示例#1
0
 def setcanvas(self, **kwargs):
     """Make canvas and pads for ratio plots."""
     square = kwargs.get('square', False)
     double = kwargs.get('ratio', False)  # include lower panel
     width = kwargs.get('width', 900 if square else 800 if double else 800)
     height = kwargs.get('height',
                         900 if square else 750 if double else 600)
     lmargin = kwargs.get('lmargin', 1.)
     rmargin = kwargs.get('rmargin', 1.)
     tmargin = kwargs.get('tmargin', 1.)
     bmargin = kwargs.get('bmargin', 1.)
     pads = kwargs.get('pads', [])  # pass list as reference
     #if not CMSStyle.lumi_13TeV:
     #  tmargin *= 0.7
     if square:
         lmargin *= 1.15
         tmargin *= 0.90
         #rmargin *= 3.6
         #CMSStyle.relPosX = 0.15
     canvas = TCanvas('canvas', 'canvas', 100, 100, width, height)
     canvas.SetFillColor(0)
     #canvas.SetFillStyle(0)
     canvas.SetBorderMode(0)
     canvas.SetFrameBorderMode(0)
     if double:
         canvas.SetMargin(0.0, 0.0, 0.0, 0.0)  # LRBT
         canvas.Divide(2)
         canvas.cd(1)
         gPad.SetPad('pad1', 'pad1', 0.0, 0.33, 1.0, 1.0)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.029,
                        0.075 * tmargin)
         gPad.SetFillColor(0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         #gPad.SetFillStyle(0)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(2)
         gPad.SetPad('pad2', 'pad2', 0.0, 0.0, 1.0, 0.33)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.355 * bmargin,
                        0.04)
         gPad.SetFillColor(0)  #gPad.SetFillColorAlpha(0,0.0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(1)
     else:
         canvas.SetMargin(0.145 * lmargin, 0.05 * rmargin, 0.145 * bmargin,
                          0.06 * tmargin)
     return canvas
示例#2
0
def makeROC(fpr, tpr, thresholds, AUC, outfile, signal_label,
            background_label):

    c = TCanvas("c", "c", 700, 600)
    gPad.SetMargin(0.15, 0.07, 0.15, 0.05)
    gPad.SetLogy(0)
    gPad.SetGrid(1, 1)
    gStyle.SetGridColor(15)

    roc = TGraph(len(fpr), tpr, fpr)

    roc.SetLineColor(2)
    roc.SetLineWidth(2)
    roc.SetTitle(";Signal efficiency (%s); Background efficiency (%s)" %
                 (signal_label, background_label))
    roc.GetXaxis().SetTitleOffset(1.4)
    roc.GetXaxis().SetTitleSize(0.045)
    roc.GetYaxis().SetTitleOffset(1.4)
    roc.GetYaxis().SetTitleSize(0.045)
    roc.GetXaxis().SetRangeUser(0, 1)
    roc.GetYaxis().SetRangeUser(0.000, 1)
    roc.Draw("AL")

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextSize(0.05)
    latex.DrawLatexNDC(0.2, 0.88, 'AUC = %.3f' % AUC)

    c.SaveAs(outfile)
示例#3
0
def MakeOneDHist(pathToDir, distribution):

    numFittingSamples = 0

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"
    elif arguments.normalizeToData:
        NormText = "MC scaled to data"
        NormLabel.SetLabel(NormText)

    YieldsLabel = TPaveText(0.39, 0.7, 0.59, 0.9, "NDC")
    YieldsLabel.SetBorderSize(0)
    YieldsLabel.SetFillColor(0)
    YieldsLabel.SetFillStyle(0)
    YieldsLabel.SetTextAlign(12)

    RatiosLabel = TPaveText()
    RatiosLabel.SetDrawOption("NDC")
    RatiosLabel.SetBorderSize(0)
    RatiosLabel.SetFillColor(0)
    RatiosLabel.SetFillStyle(0)
    RatiosLabel.SetTextAlign(32)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    fittingIntegral = 0
    scaleFactor = 1

    HistogramsToFit = []
    TargetDataset = distribution['target_dataset']

    FittingLegendEntries = []
    DataLegendEntries = []

    FittingHistogramDatasets = []

    Stack_list = []
    Stack_list.append(THStack("stack_before", distribution['name']))
    Stack_list.append(THStack("stack_after", distribution['name']))

    fileName = condor_dir + "/" + distribution['target_dataset'] + ".root"
    if not os.path.exists(fileName):
        return
    inputFile = TFile(fileName)
    if inputFile.IsZombie() or not inputFile.GetNkeys():
        return

    Target = inputFile.Get("OSUAnalysis/" + distribution['channel'] + "/" +
                           distribution['name']).Clone()
    Target.SetDirectory(0)
    inputFile.Close()

    Target.SetMarkerStyle(20)
    Target.SetMarkerSize(0.8)
    Target.SetFillStyle(0)
    Target.SetLineColor(colors[TargetDataset])
    Target.SetLineStyle(1)
    Target.SetLineWidth(2)
    targetIntegral = Target.Integral()
    if (arguments.normalizeToUnitArea and Target.Integral() > 0):
        Target.Scale(1. / Target.Integral())
    if arguments.rebinFactor:
        RebinFactor = int(arguments.rebinFactor)
        #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
        if Target.GetNbinsX() >= RebinFactor * 5 and Target.GetName().find(
                "GenMatch") is -1:
            Target.Rebin(RebinFactor)

    ### formatting target histogram and adding to legend
    legendIndex = 0
    Legend.AddEntry(Target, labels[TargetDataset], "LEP")
    legendIndex = legendIndex + 1

    if not outputFile.Get("OSUAnalysis"):
        outputFile.mkdir("OSUAnalysis")
    if not outputFile.Get("OSUAnalysis/" + distribution['channel']):
        outputFile.Get("OSUAnalysis").mkdir(distribution['channel'])

    for sample in distribution[
            'datasets']:  # loop over different samples requested to be fit

        dataset_file = "%s/%s.root" % (condor_dir, sample)
        inputFile = TFile(dataset_file)
        HistogramObj = inputFile.Get(pathToDir + "/" +
                                     distribution['channel'] + "/" +
                                     distribution['name'])
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + pathToDir + "/" + distribution[
                'channel'] + "/" + distribution[
                    'name'] + " in file " + dataset_file + ".  Will skip it and continue."
            continue
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetName(
            ).find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(
                1)) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex]
        else:
            yAxisLabel = "Entries per bin (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"

        if not arguments.makeFancy:
            histoTitle = Histogram.GetTitle()
        else:
            histoTitle = ""

        legLabel = labels[sample]
        if (arguments.printYields):
            yieldHist = Histogram.Integral()
            legLabel = legLabel + " (%.1f)" % yieldHist
        FittingLegendEntries.append(legLabel)

        if (types[sample] == "bgMC"):

            numFittingSamples += 1
            fittingIntegral += Histogram.Integral()

            Histogram.SetLineStyle(1)
            if (arguments.noStack):
                Histogram.SetFillStyle(0)
                Histogram.SetLineColor(colors[sample])
                Histogram.SetLineWidth(2)
            else:
                Histogram.SetFillStyle(1001)
                Histogram.SetFillColor(colors[sample])
                Histogram.SetLineColor(1)
                Histogram.SetLineWidth(1)

        elif (types[sample] == "signalMC"):

            numFittingSamples += 1

            Histogram.SetFillStyle(0)
            Histogram.SetLineColor(colors[sample])
            Histogram.SetLineStyle(1)
            Histogram.SetLineWidth(2)
        if (arguments.normalizeToUnitArea and Histogram.Integral() > 0):
            Histogram.Scale(1. / Histogram.Integral())

        HistogramsToFit.append(Histogram)
        FittingHistogramDatasets.append(sample)

    #scaling histograms as per user's specifications
    if targetIntegral > 0 and fittingIntegral > 0:
        scaleFactor = targetIntegral / fittingIntegral
    for fittingHist in HistogramsToFit:
        if arguments.normalizeToData:
            fittingHist.Scale(scaleFactor)

        if arguments.normalizeToUnitArea and not arguments.noStack and fittingIntegral > 0:
            fittingHist.Scale(1. / fittingIntegral)
        elif arguments.normalizeToUnitArea and arguments.noStack and fittingHist.Integral(
        ) > 0:
            fittingHist.Scale(1. / fittingHist.Integral())

    def fitf(x, par):
        xBin = HistogramsToFit[0].FindBin(x[0])
        value = 0.0

        for i in range(0, len(HistogramsToFit)):
            value += par[i] * HistogramsToFit[i].GetBinContent(xBin) + par[
                i +
                len(HistogramsToFit)] * HistogramsToFit[i].GetBinError(xBin)

        return value

    lowerLimit = Target.GetBinLowEdge(1)
    upperLimit = Target.GetBinLowEdge(Target.GetNbinsX()) + Target.GetBinWidth(
        Target.GetNbinsX())
    if 'lowerLimit' in distribution:
        lowerLimit = distribution['lowerLimit']
    if 'upperLimit' in distribution:
        upperLimit = distribution['upperLimit']
    func = TF1("fit", fitf, lowerLimit, upperLimit, 2 * len(HistogramsToFit))

    for i in range(0, len(HistogramsToFit)):
        if 'fixed_datasets' in distribution and distribution['datasets'][
                i] in distribution['fixed_datasets']:
            func.FixParameter(i, 1.0)
        else:
            func.SetParameter(i, 1.0)
#            func.SetParLimits (i, 0.0, 1.0e2) # comment this out so we don't have to pre-normalize the QCD input sample
        func.SetParName(i, labels[FittingHistogramDatasets[i]])

    shiftedScaleFactors = []
    if arguments.parametricErrors:
        # loop over all input histograms and shift them +- 1 sigma
        for i in range(0, len(HistogramsToFit)):
            sfs = []

            # -1 => -1 sigma, +1 => +1 sigma
            for j in [-1, 1]:
                # loop over the parameters holding the errors for each dataset, fixing all to 0
                for k in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
                    func.FixParameter(k, 0)
                # fix the error of the dataset of interest to +-1
                func.FixParameter(i + len(HistogramsToFit), j)

                # perform new fit
                for k in range(0, distribution['iterations'] - 1):
                    if j == -1:
                        print "Scale down " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    if j == 1:
                        print "Scale up " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    Target.Fit("fit", "QEMR0")
                Target.Fit("fit", "VEMR0")

                # save the new scale factors for each dataset
                for k in range(0, len(HistogramsToFit)):
                    sfs.append(func.GetParameter(k))

            shiftedScaleFactors.append(sfs)

    # reset the parameters with the errors of each dataset to 0
    for i in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
        func.FixParameter(i, 0)
    # do the fit to get the central values
    for i in range(0, distribution['iterations'] - 1):
        print "Iteration " + str(i + 1) + "..."
        Target.Fit("fit", "QEMR0")
    Target.Fit("fit", "VEMR0")

    if arguments.parametricErrors:
        # make a list of the largest errors on each contribution by shifting any other contribution
        parErrors = []
        # loop over all the datasets
        for i in range(0, len(HistogramsToFit)):
            centralValue = func.GetParameter(i)
            maxError = 0
            # find the maximum deviation from the central value and save that
            for shiftedScaleFactor in shiftedScaleFactors[i]:
                currentError = abs(shiftedScaleFactor - centralValue)
                if currentError > maxError:
                    maxError = currentError

            parErrors.append(maxError)

    finalMax = 0
    if not arguments.noStack:
        for fittingHist in HistogramsToFit:
            finalMax += fittingHist.GetMaximum()
        else:
            for fittingHist in HistogramsToFit:
                if (fittingHist.GetMaximum() > finalMax):
                    finalMax = fittingHist.GetMaximum()
    if (Target.GetMaximum() > finalMax):
        finalMax = Target.GetMaximum()

    Target.SetMaximum(1.1 * finalMax)
    Target.SetMinimum(0.0001)

    Canvas = TCanvas(distribution['name'] + "_FitFunction")
    Canvas.cd(1)
    Target.Draw()
    func.Draw("same")

    outputFile.cd("OSUAnalysis/" + distribution['channel'])
    Canvas.Write()
    if arguments.savePDFs:
        if histogram == input_histograms[0]:
            Canvas.Print(pdfFileName + "(", "pdf")
        else:
            Canvas.Print(pdfFileName, "pdf")
    Target.SetStats(0)

    ### formatting bgMC histograms and adding to legend
    legendIndex = numFittingSamples - 1
    for Histogram in reversed(HistogramsToFit):
        if (arguments.noStack):
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "L")
        else:
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "F")
        legendIndex = legendIndex - 1

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    ### Draw everything to the canvases !!!!

    for i in range(0, 2):  # 0 => before, 1 => after

        integrals = []
        ratios = []
        errors = []

        if i == 1:
            # loop over each dataset, saving it's yield and the errors on it
            for j in range(0, len(HistogramsToFit)):

                integrals.append(HistogramsToFit[j].Integral())
                HistogramsToFit[j].Scale(func.GetParameter(j))
                ratios.append(func.GetParameter(j))
                errors.append(func.GetParError(j))

        for fittingHist in HistogramsToFit:
            if not arguments.noStack:
                Stack_list[i].Add(fittingHist)

        #creating the histogram to represent the statistical errors on the stack
        if not arguments.noStack:
            ErrorHisto = HistogramsToFit[0].Clone("errors")
            ErrorHisto.SetFillStyle(3001)
            ErrorHisto.SetFillColor(13)
            ErrorHisto.SetLineWidth(0)
            if i == 1:
                Legend.AddEntry(ErrorHisto, "Stat. Errors", "F")
            for Histogram in HistogramsToFit:
                if Histogram is not HistogramsToFit[0]:
                    ErrorHisto.Add(Histogram)

        if i == 0:
            Canvas = TCanvas(distribution['name'] + "_Before")
        if i == 1:
            Canvas = TCanvas(distribution['name'] + "_After")

        if makeRatioPlots or makeDiffPlots:
            Canvas.SetFillStyle(0)
            Canvas.Divide(1, 2)
            Canvas.cd(1)
            gPad.SetPad(0, 0.25, 1, 1)
            gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
            gPad.SetFillStyle(0)
            gPad.Update()
            gPad.Draw()
            if arguments.setLogY:
                gPad.SetLogy()
            Canvas.cd(2)
            gPad.SetPad(0, 0, 1, 0.25)
            # format: gPad.SetMargin(l,r,b,t)
            gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
            gPad.SetFillStyle(0)
            gPad.SetGridy(1)
            gPad.Update()
            gPad.Draw()

            Canvas.cd(1)

        ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
        finalMax = 0
        if numFittingSamples is not 0 and not arguments.noStack:
            finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError(
                ErrorHisto.GetMaximumBin())
        else:
            for bgMCHist in HistogramsToFit:
                if (bgMCHist.GetMaximum() > finalMax):
                    finalMax = bgMCHist.GetMaximum()
        if (Target.GetMaximum() > finalMax):
            finalMax = Target.GetMaximum() + Target.GetBinError(
                Target.GetMaximumBin())
        finalMax = 1.15 * finalMax
        if arguments.setYMax:
            finalMax = float(arguments.setYMax)

        if not arguments.noStack:  # draw stacked background samples
            Stack_list[i].SetTitle(histoTitle)
            Stack_list[i].Draw("HIST")
            Stack_list[i].GetXaxis().SetTitle(xAxisLabel)
            Stack_list[i].GetYaxis().SetTitle(yAxisLabel)
            Stack_list[i].SetMaximum(finalMax)
            Stack_list[i].SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                Stack_list[i].GetHistogram().GetXaxis().SetLabelSize(0)
            #draw shaded error bands
            ErrorHisto.Draw("A E2 SAME")

        else:  #draw the unstacked backgrounds
            HistogramsToFit[0].SetTitle(histoTitle)
            HistogramsToFit[0].Draw("HIST")
            HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel)
            HistogramsToFit[0].GetYaxis().SetTitle(yAxisLabel)
            HistogramsToFit[0].SetMaximum(finalMax)
            HistogramsToFit[0].SetMinimum(yAxisMin)
            for bgMCHist in HistogramsToFit:
                bgMCHist.Draw("A HIST SAME")

        Target.Draw("A E X0 SAME")

        #legend coordinates, empirically determined :-)
        x_left = 0.6761745
        x_right = 0.9328859
        x_width = x_right - x_left
        y_max = 0.9
        entry_height = 0.05

        if (numFittingSamples is not 0):  #then draw the data & bgMC legend

            numExtraEntries = 2  # count the target and (lack of) title
            Legend.SetX1NDC(x_left)
            numExtraEntries = numExtraEntries + 1  # count the stat. errors entry

            Legend.SetY1NDC(y_max - entry_height *
                            (numExtraEntries + numFittingSamples))
            Legend.SetX2NDC(x_right)
            Legend.SetY2NDC(y_max)
            Legend.Draw()

            RatiosLabel.SetX1NDC(x_left - 0.1)
            RatiosLabel.SetX2NDC(x_right)
            RatiosLabel.SetY2NDC(Legend.GetY1NDC() - 0.1)
            RatiosLabel.SetY1NDC(RatiosLabel.GetY2NDC() - entry_height *
                                 (numFittingSamples))

            # Deciding which text labels to draw and drawing them
            drawLumiLabel = False
            drawNormLabel = False
            offsetNormLabel = False
            drawHeaderLabel = False

            if not arguments.normalizeToUnitArea:  #don't draw the lumi label if there's no data and it's scaled to unit area
                drawLumiLabel = True
                # move the normalization label down before drawing if we drew the lumi. label
                offsetNormLabel = True
            if arguments.normalizeToUnitArea or arguments.normalizeToData:
                drawNormLabel = True
            if arguments.makeFancy:
                drawHeaderLabel = True
                drawLumiLabel = False

            # now that flags are set, draw the appropriate labels

            if drawLumiLabel:
                LumiLabel.Draw()

            if drawNormLabel:
                if offsetNormLabel:
                    NormLabel.SetY1NDC(topLeft_y_bottom - topLeft_y_offset)
                    NormLabel.SetY2NDC(topLeft_y_top - topLeft_y_offset)
                else:
                    NormLabel.SetY1NDC(topLeft_y_bottom)
                    NormLabel.SetY2NDC(topLeft_y_top)
                NormLabel.Draw()

            if drawHeaderLabel:
                HeaderLabel.Draw()

            YieldsLabel.Clear()
            mcYield = Stack_list[i].GetStack().Last().Integral()
            dataYield = Target.Integral()
            if i == 0:
                YieldsLabel.AddText("Before Fit to Data")
            if i == 1:
                YieldsLabel.AddText("After Fit to Data")
            YieldsLabel.AddText("data yield: " + '%.1f' % dataYield)
            YieldsLabel.AddText("bkgd yield: " + '%.1f' % mcYield)
            YieldsLabel.AddText("data/bkgd: " + '%.2f' % (dataYield / mcYield))
            if i == 1:
                for j in range(0, len(FittingLegendEntries)):
                    if abs(ratios[j] - 1) < 0.001 and abs(
                            errors[j]
                    ) < 0.001:  #then it probably was held fixed
                        continue
                    if arguments.showFittedYields:
                        yield_ = ratios[j] * integrals[j]
                        yielderror_ = errors[j] * yield_
                        text = FittingLegendEntries[
                            j] + " yield: " + '%.0f' % yield_ + ' #pm %.0f' % yielderror_
                    else:
                        text = FittingLegendEntries[
                            j] + " ratio: " + '%.2f' % ratios[
                                j] + ' #pm %.2f' % errors[j]
                    text = text + " (fit)"
                    if arguments.parametricErrors:
                        yield_ = ratios[j] * integrals[j]
                        yieldParError_ = parErrors[j] * yield_
                        if arguments.showFittedYields:
                            text += ' #pm %.2f' % yieldParError_
                        else:
                            text += ' #pm %.2f' % parErrors[j]
                        text = text + " (sys)"
                    RatiosLabel.AddText(text)
            YieldsLabel.Draw()
            RatiosLabel.Draw()

        # drawing the ratio or difference plot if requested
        if (makeRatioPlots or makeDiffPlots):
            Canvas.cd(2)
            BgSum = Stack_list[i].GetStack().Last()
            if makeRatioPlots:
                if arguments.ratioRelErrMax:
                    Comparison = ratioHistogram(Target, BgSum,
                                                arguments.ratioRelErrMax)
                else:
                    Comparison = ratioHistogram(Target, BgSum)
            elif makeDiffPlots:
                Comparison = Target.Clone("diff")
                Comparison.Add(BgSum, -1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("Data-Bkgd")
            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)
            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange,
                                                   RatioYRange)
            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
                else:  #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMax, 1.2 * YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMin, 1.2 * YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparison.Draw("E0")

        if i == 0:
            Canvas.Write(distribution['name'] + "_Before")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_Before.pdf")

        if i == 1:
            Canvas.Write(distribution['name'] + "_After")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_After.pdf")
示例#4
0
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    width = 0.25
    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.65, 0.88
    x2, y2 = x1 + width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
def MakeOneHist(histogramName):

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources:  # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],
                                              source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get("OSUAnalysis/" +
                                        source['num_channel'] + "/" +
                                        histogramName)
        if 'condor_dir_den' in source:  # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],
                                                     source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get("OSUAnalysis/" +
                                               source['den_channel'] + "/" +
                                               histogramName)
        else:  # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get("OSUAnalysis/" +
                                            source['den_channel'] + "/" +
                                            histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'num_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'den_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetTitle(
            ).find("GenMatch") is -1 and not Histogram.Class().InheritsFrom(
                    "TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)
            ) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj)
        if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            Histogram = TGraphAsymmErrors(Histogram, DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1. / histogram.Integral())

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram, LegendEntries[legendIndex], "LEP")
        legendIndex = legendIndex + 1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    if arguments.noTGraph:
        for histogram in Histograms:
            currentMax = histogram.GetMaximum() + histogram.GetBinError(
                histogram.GetMaximumBin())
            if (currentMax > finalMax):
                finalMax = currentMax
    finalMax = 1.5 * finalMax
    if finalMax is 0:
        finalMax = 1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1, 2)
        Canvas.cd(1)
        gPad.SetPad(0, 0.25, 1, 1)
        gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0, 0, 1, 0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[
                DatasetName.rfind('__') +
                2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom,
                                      topLeft_x_right, topLeft_y_top,
                                      DatasetName, "NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()
            if arguments.makeFancy:
                HeaderLabel.Draw()

        else:
            if histogram.InheritsFrom("TGraph") and histCounter == 0:
                plotting_options = "AP"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)
            histogram.GetXaxis().SetTitle(xAxisLabel)
            histogram.GetYaxis().SetTitle(yAxisLabel)
            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    if arguments.makeFancy:
        HeaderLabel.Draw()

    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            Comparison = ratioHistogram(Histograms[0], Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1], -1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
            else:  #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMax, 1.2 * YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 1.2 * YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
示例#6
0
outputFile = TFile(arguments.outputDir + "/output.root", "RECREATE")

for pt in pts_to_test:
    for variable in variables_to_test:
        for plot in plots:

            plot_name = plot['name'] + "_" + variable + "_" + pt
            canvas = TCanvas(plot_name, "", 0, 0, 700, 800)

            canvas.Divide(1, 2)

            canvas.cd(1)
            gPad.SetLogy()
            gPad.SetPad(0, 0.25, 1, 1)
            gPad.SetMargin(0.15, 0.05, 0.0, 0.07)
            gPad.SetFillStyle(0)
            gPad.SetTickx(1)
            gPad.SetTicky(1)
            gPad.Update()
            gPad.Draw()

            canvas.cd(2)
            gPad.SetPad(0, 0, 1, 0.25)
            gPad.SetMargin(0.15, 0.05, 0.4, 0.0)
            gPad.SetFillStyle(0)
            gPad.SetTickx(1)
            gPad.SetTicky(1)
            gPad.Update()
            gPad.Draw()
示例#7
0
def MakeOneDHist(histogramDirectory, histogramName,integrateDir):

    if arguments.verbose:
        print "Creating histogram", histogramName, "in directory", histogramDirectory

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    canvasName = histogramName
    if integrateDir is "left":
        canvasName += "_CumulativeLeft"
    elif integrateDir is "right":
        canvasName += "_CumulativeRight"
    Canvas = TCanvas(canvasName)
    Histograms = []
    RefIndex = -99
    LegendEntries = []

    colorIndex = 0
    markerStyleIndex = 0
    fillIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)


        if arguments.generic:
            if histogramDirectory == "":
                histPath = histogramName
            else:
                histPath = histogramDirectory + "/" + histogramName
            HistogramObj = inputFile.Get(histPath)
        else:
            HistogramObj = inputFile.Get(source['channel'] + "Plotter/" + histogramDirectory + "/" + histogramName)
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        Histogram.Sumw2()
        if arguments.verbose:
            print "  Got histogram", Histogram.GetName(), "from file", dataset_file
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        # correct bin contents of object multiplcity plots
        if Histogram.GetName().startswith("num") and "PV" not in Histogram.GetName():
            # include overflow bin
            for bin in range(2,Histogram.GetNbinsX()+2):
                content = Histogram.GetBinContent(bin)
                Histogram.SetBinContent(bin, content/float(bin-1))


        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")
        xAxisLabelVar = xAxisLabel

        if "_pfx" in Histogram.GetName() or "_pfy" in Histogram.GetName() or "_sigma" in Histogram.GetName():
            yAxisLabel = Histogram.GetYaxis().GetTitle()
        else:

            if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
                yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex]
                xAxisLabelVar = xAxisLabel[0:unitBeginIndex]
            else:
                yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
            if arguments.normalizeToUnitArea:
                yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

            if arguments.normalizeToUnitArea and arguments.makeSignificancePlots:
                unit = "Efficiency"
            else:
                unit = "Yield"
            if integrateDir is "left":
                yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
            if integrateDir is "right":
                yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"


        nbins = Histogram.GetNbinsX()
        if not noOverFlow:
            Histogram.SetBinContent(nbins, Histogram.GetBinContent(nbins) + Histogram.GetBinContent(nbins+1)) # Add overflow
            Histogram.SetBinError(nbins, math.sqrt(math.pow(Histogram.GetBinError(nbins),2) + math.pow(Histogram.GetBinError(nbins+1),2))) # Set the errors to be the sum in quadrature
        if not noUnderFlow:
            Histogram.SetBinContent(1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) # Add underflow
            Histogram.SetBinError(1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) # Set the errors to be the sum in quadrature

        if not arguments.makeFancy and not arguments.generic:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
                markerStyleIndex = markerStyleIndex + 1
                if markerStyleIndex is len(markerStyleList):
                    markerStyleIndex = 0
                    fillIndex = fillIndex + 1


        if 'scale' in source:
            Histogram.Scale(source['scale'])

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        else:
            markerStyle = markers[markerStyleList[markerStyleIndex]]

        fillStyle = 0
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        else:
            markerStyle = markerStyle + fills[fillList[fillIndex]]

        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(0.5)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        if arguments.normalizeToUnitArea and Histogram.Integral() > 0:
            Histogram.Scale(1./Histogram.Integral())

        Histogram = MakeIntegralHist(Histogram, integrateDir)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        if 'reference' in source:
            if source['reference']:
                RefIndex = len(Histograms)-1

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.generic:
        plotting_options = "p,e"
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        histogram.SetTitle(histoTitle)
        if arguments.verbose:
            print "  Drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor())
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        histogram.SetMaximum(finalMax)

        if "_pfx" not in Histogram.GetName() and "_pfy" not in Histogram.GetName() and "_sigma" not in Histogram.GetName():
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            plotting_options = plotting_options + " SAME"
        histCounter = histCounter + 1

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()


    # Deciding which text labels to draw and drawing them
    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()




    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Comparisons = []
        Canvas.cd(2)
        if RefIndex == -99:
            Reference = Histograms[0]
        else:
            Reference = Histograms[RefIndex]

        for Histogram in Histograms:
            if Histogram is Reference:
                continue

            if makeRatioPlots:
                makeRatio = functools.partial (ratioHistogram,Histogram, Reference)
                if arguments.ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                    makeRatio =  functools.partial (makeRatio, relErrMax = float(arguments.ratioRelErrMax))
                if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                    makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
                Comparison = makeRatio()
            elif makeDiffPlots:
                Comparison = Reference.Clone("diff")
                Comparison.Add(Histograms[1],-1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("X-ref")

            Comparison.SetLineColor(Histogram.GetLineColor())
            Comparison.SetFillColor(Histogram.GetFillColor())
            Comparison.SetFillStyle(Histogram.GetFillStyle())
            Comparison.SetMarkerColor(Histogram.GetMarkerColor())
            Comparison.SetMarkerStyle(Histogram.GetMarkerStyle())

            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)

            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)

            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
                else: #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparisons.append(Comparison)

        option = "E0"
        for index,Comparison in enumerate(Comparisons):
            if index == 0:
                option += " SAME"
            Comparison.Draw(option)

    outputFile.cd(histogramDirectory)
    Canvas.Write()
    if arguments.verbose:
        print "  Finished writing canvas: ", Canvas.GetName()

    if arguments.savePDFs:
        Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")
def MakeOneHist(dirName, histogramName):

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    #legend coordinates, empirically determined :-)
    x_left = 0.4
    x_right = 0.7
    y_min = 0.15
    y_max = 0.3

    Legend = TLegend(x_left,y_min,x_right,y_max)
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    HistogramClones = []
    NBins = []
    MaxXValues = []
    MinXValues = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get(source['num_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if 'condor_dir_den' in source:   # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        else:   # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source['num_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source['den_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        nbinsN = Histogram.GetNbinsX()
        nbinsD = DenHistogram.GetNbinsX()
        if not noOverFlow:
            # Add overflow
            Histogram.SetBinContent(   nbinsN,    Histogram.GetBinContent(nbinsN) +    Histogram.GetBinContent(nbinsN+1))
            DenHistogram.SetBinContent(nbinsD, DenHistogram.GetBinContent(nbinsD) + DenHistogram.GetBinContent(nbinsD+1))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(  nbinsN,     math.sqrt(math.pow(Histogram.GetBinError(nbinsN),2) +    math.pow(Histogram.GetBinError(nbinsN+1),2)))
            DenHistogram.SetBinError(nbinsD, math.sqrt(math.pow(DenHistogram.GetBinError(nbinsD),2) + math.pow(DenHistogram.GetBinError(nbinsD+1),2)))

        if not noUnderFlow:
            # Add underflow
            Histogram.SetBinContent(   1,    Histogram.GetBinContent(1) +    Histogram.GetBinContent(0))
            DenHistogram.SetBinContent(1, DenHistogram.GetBinContent(1) + DenHistogram.GetBinContent(0))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(   1,    math.sqrt(math.pow(Histogram.GetBinError(1), 2) +    math.pow(Histogram.GetBinError(0), 2)))
            DenHistogram.SetBinError(1, math.sqrt(math.pow(DenHistogram.GetBinError(1), 2) + math.pow(DenHistogram.GetBinError(0), 2)))

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1 and not Histogram.Class().InheritsFrom("TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #check if bin content is consistent
        TEfficiency.CheckConsistency(Histogram,DenHistogram)
        for i in range(1,Histogram.GetNbinsX()+1):
            if Histogram.GetBinContent(i) > DenHistogram.GetBinContent(i):
                DenHistogram.SetBinContent(i,Histogram.GetBinContent(i))

        #HistogramClone and HistogramClones only used for ratio plot
        HistogramClone = Histogram.Clone()
        HistogramClone.SetDirectory(0)
        HistogramClone.Divide(DenHistogram)
        Nbins = HistogramClone.GetNbinsX()
        MaxXValue = HistogramClone.GetXaxis().GetBinLowEdge(Nbins+1)
        MinXValue = HistogramClone.GetXaxis().GetBinLowEdge(1)

        #this Histogram becomes the main TEfficiency
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            #using default methods (which give correct uncertainties)
            #see https://root.cern.ch/doc/master/classTEfficiency.html (c.f. section IV)
            Histogram = TEfficiency(Histogram,DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        HistogramClones.append(HistogramClone)
        NBins.append(Nbins)
        MaxXValues.append(MaxXValue)
        MinXValues.append(MinXValue)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1./histogram.Integral())


    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 1.1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    dontRebinRatio = -1
    if arguments.dontRebinRatio:
        dontRebinRatio = arguments.dontRebinRatio

    ratioRelErrMax = -1
    if arguments.ratioRelErrMax:
        ratioRelErrMax = arguments.ratioRelErrMax

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    h = TH2F("h1","",NBins[0],MinXValues[0],MaxXValues[0],110,0.,finalMax)
    h.SetTitle(";"+xAxisLabel+";"+yAxisLabel)
    h.Draw()

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[DatasetName.rfind('__')+2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,DatasetName,"NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()

        else:
            if histogram.InheritsFrom("TEfficiency") and histCounter==0:
                plotting_options = "P SAME"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)

            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)

        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TEfficiency"):
                plotting_options = "P" + " SAME"

        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    Legend.Draw()


    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()



    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            makeRatio = functools.partial (ratioHistogram,HistogramClones[0],HistogramClones[1])
            if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
            if ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, relErrMax = float (ratioRelErrMax))
            if dontRebinRatio is True:
                makeRatio = functools.partial (makeRatio, dontRebinRatio)
            Comparison = makeRatio ()
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
            else:
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd(dirName)
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
示例#9
0
def main(program, type, event, phase, event_n):
    CM_data = np.transpose(
        np.loadtxt('results_phase%.4f_%d/B0_CM_variables_factor%s%.1f_%d.txt' %
                   (phase, event_n, type, event, event_n)))
    CM_data_conj = np.transpose(
        np.loadtxt(
            'results_phase%.4f_%d/B0_CM_variables_factor%s%.1f_%d_conj.txt' %
            (phase, event_n, type, event, event_n)))

    mDDbar = CM_data[1]
    mDDbar_conj = CM_data_conj[1]
    mKpi = CM_data[2]
    mKpi_conj = CM_data_conj[2]

    bin = 400
    A1, A2, A3 = 10, 10, 10

    c0 = ROOT.TCanvas("c0", "B0 decay invmass", 1420, 710)
    c0.Divide(2, 1)
    c0.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h0_1 = pltini("h0_1", bin, mDDbar, '\ m(D^0\\bar{D}^0)\\;[GeV/c^2]',
                  ROOT.kBlack)
    f0_1 = fit1(min(mDDbar), max(mDDbar), 3.770, 0.0272, A1, 4.039, 0.080, A2,
                4.191, 0.070, A3)
    h0_1.Fit(f0_1, "R+")
    leg0_1 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg0_1.AddEntry(h0_1, "\ B^0 \\; data \\;(MC)", "lf")
    leg0_1.AddEntry(f0_1, "\ BW \\; fit", "l")
    legset(leg0_1)
    h0_1.SetMaximum(1.8 * h0_1.GetMaximum())
    h0_1.Draw()
    leg0_1.Draw()

    c0.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h0_2 = pltini("h0_2", bin, mDDbar_conj, '\ m(\\bar{D}^0 D^0)\\;[GeV/c^2]',
                  ROOT.kBlack)
    f0_2 = fit1(min(mDDbar_conj), max(mDDbar_conj), 3.770, 0.0272, A1, 4.039,
                0.080, A2, 4.191, 0.070, A3)
    h0_2.Fit(f0_2, "R+")
    leg0_2 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg0_2.AddEntry(h0_2, "\  \\bar{B}^0  \\; data \\;(MC)", "lf")
    leg0_2.AddEntry(f0_2, "\ BW \\; fit", "l")
    legset(leg0_2)
    h0_2.SetMaximum(h0_1.GetMaximum())
    h0_2.Draw()
    leg0_2.Draw()
    c0.SaveAs("results_phase%.4f_%d/invmass_D0Dbar0_fit_factor%s%.1f_%d.png" %
              (phase, event_n, type, event, event_n))

    c00 = ROOT.TCanvas("c00", "Bbar0 decay invmass", 1420, 710)
    c00.Divide(2, 1)
    c00.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h00_1 = pltini("h00_1", bin, mKpi, '\ m(K^+\pi^-)\\;[GeV/c^2]',
                   ROOT.kBlack)
    f00_1 = fit(min(mKpi), max(mKpi), 0.89555, 0.0473)
    h0_2.Fit(f0_2, "R+")
    h00_1.Fit(f00_1, "R+")
    leg00_1 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg00_1.AddEntry(h00_1, "\ B^0 \\; data \\;(MC)", "lf")
    leg00_1.AddEntry(f00_1, "\ BW \\; fit", "l")
    legset(leg00_1)
    h00_1.SetMaximum(1.8 * h00_1.GetMaximum())
    h00_1.Draw()
    leg00_1.Draw()

    c00.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h00_2 = pltini("h00_2", bin, mKpi_conj, '\ m(K^-\pi^+)\\;[GeV/c^2]',
                   ROOT.kBlack)
    f00_2 = fit(min(mKpi_conj), max(mKpi_conj), 0.89555, 0.0473)
    h00_2.Fit(f00_2, "R+")
    leg00_2 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg00_2.AddEntry(h00_2, "\ \\bar{B}^0 \\; data \\;(MC)", "lf")
    leg00_2.AddEntry(f00_2, "\ BW \\; fit", "l")
    legset(leg00_2)
    h00_2.SetMaximum(h00_1.GetMaximum())
    h00_2.Draw()
    leg00_2.Draw()
    c00.SaveAs("results_phase%.4f_%d/invmass_Kpi_fit_factor%s%.1f_%d.png" %
               (phase, event_n, type, event, event_n))

    with open(
            'results_phase%.4f_%d/invmass_fit_parameters_factor%s%.1f_%d.txt' %
        (phase, event_n, type, event, event_n),
            mode='a') as f:
        f.write("bin=%d A1=%d A2=%d A3=%d" % (bin, A1, A2, A3) + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(3770)", f0_1.GetParameters()[0], f0_1.GetParError(0),
                 f0_1.GetParameters()[1], f0_1.GetParError(1),
                 f0_1.GetChisquare(), "B0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(3770)", f0_2.GetParameters()[0], f0_2.GetParError(0),
                 f0_2.GetParameters()[1], f0_2.GetParError(1),
                 f0_2.GetChisquare(), "Bbar0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(4040)", f0_1.GetParameters()[3], f0_1.GetParError(3),
                 f0_1.GetParameters()[4], f0_1.GetParError(4),
                 f0_1.GetChisquare(), "B0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(4040)", f0_2.GetParameters()[3], f0_2.GetParError(3),
                 f0_2.GetParameters()[4], f0_2.GetParError(4),
                 f0_2.GetChisquare(), "Bbar0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(4160)", f0_1.GetParameters()[6], f0_1.GetParError(6),
                 f0_1.GetParameters()[7], f0_1.GetParError(7),
                 f0_1.GetChisquare(), "B0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("psi(4160)", f0_2.GetParameters()[6], f0_2.GetParError(6),
                 f0_2.GetParameters()[7], f0_2.GetParError(7),
                 f0_2.GetChisquare(), "Bbar0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("K*0(892)", f00_1.GetParameters()[0], f00_1.GetParError(0),
                 f00_1.GetParameters()[1], f00_1.GetParError(1),
                 f00_1.GetChisquare(), "B0") + "\n")
        f.write("%s %.4f %.4f %.4f %.4f %.4f %s" %
                ("K*0(892)", f00_2.GetParameters()[0], f00_2.GetParError(0),
                 f00_2.GetParameters()[1], f00_2.GetParError(1),
                 f00_2.GetChisquare(), "Bbar0") + "\n")
示例#10
0
def drawTrainingCurve(input,output):
    hist = pickle.load(open(input,"rb"))
    tr_acc = hist["acc"]
    tr_loss = hist["loss"]
    val_acc = hist["val_acc"]
    val_loss = hist["val_loss"]
    epochs = range(len(tr_acc))
    
    c = TCanvas("c","c",800,500)
    #c.SetFillStyle(4000)
    #c.SetFrameFillStyle(4000)
    gStyle.SetOptStat(0)
    uppad = TPad("u","u",0.,0.55,1.,1.)
    downpad = TPad("d","d",0.,0.,1.,0.55)
    uppad.Draw()
    #uppad.SetFillStyle(4000)
    #uppad.SetFrameFillStyle(4000)
    downpad.Draw()
    #downpad.SetFillStyle(4000)
    #downpad.SetFrameFillStyle(4000)
    uppad.cd()
    gPad.SetMargin(0.15,0.05,0.02,0.15)
    gPad.SetGrid(1,1)
    gStyle.SetGridColor(13)
    
    gr_acc_train = TGraph(len(epochs),array('d',epochs),array('d',tr_acc))
    gr_acc_train.SetLineColor(2)
    gr_acc_train.SetLineWidth(2)
    gr_acc_test = TGraph(len(epochs),array('d',epochs),array('d',val_acc))
    gr_acc_test.SetLineColor(4)
    gr_acc_test.SetLineWidth(2)
    
    mgup = TMultiGraph("mgup",";number of epochs;accuracy")
    mgup.Add(gr_acc_train,"l")
    mgup.Add(gr_acc_test,"l")
    mgup.Draw("AL")
    mgup.GetXaxis().SetRangeUser(min(epochs),max(epochs))
    mgup.GetXaxis().SetLabelSize(0)
    mgup.GetYaxis().CenterTitle()
    mgup.GetYaxis().SetTitleSize(0.12)
    mgup.GetYaxis().SetTitleOffset(0.5)
    mgup.GetYaxis().SetLabelSize(0.105)
    mgup.GetYaxis().SetNdivisions(8)
    
    l = TLegend(0.6,0.15,0.88,0.6)
    l.SetTextSize(0.14)
    l.AddEntry(gr_acc_train,"training","l")
    l.AddEntry(gr_acc_test,"validation","l")
    l.Draw("same")
    
    downpad.cd()
    gPad.SetMargin(0.15,0.05,0.25,0.02)
    gPad.SetGrid(1,1)
    gStyle.SetGridColor(13)
    
    gr_loss_train = TGraph(len(epochs),array('d',epochs),array('d',tr_loss))
    gr_loss_train.SetLineColor(2)
    gr_loss_train.SetLineWidth(2)
    gr_loss_test = TGraph(len(epochs),array('d',epochs),array('d',val_loss))
    gr_loss_test.SetLineColor(4)
    gr_loss_test.SetLineWidth(2)
    
    mgdown = TMultiGraph("mgdown",";number of epochs;loss")
    mgdown.Add(gr_loss_train,"l")
    mgdown.Add(gr_loss_test,"l")
    mgdown.Draw("AL")
    mgdown.GetXaxis().SetRangeUser(min(epochs),max(epochs))
    mgdown.GetXaxis().SetLabelSize(0.085)
    mgdown.GetXaxis().SetTitleSize(0.11)
    mgdown.GetXaxis().SetTitleOffset(0.9)
    mgdown.GetXaxis().CenterTitle()
    mgdown.GetYaxis().CenterTitle()
    mgdown.GetYaxis().SetTitleSize(0.11)
    mgdown.GetYaxis().SetTitleOffset(0.55)
    mgdown.GetYaxis().SetLabelSize(0.085)
    mgdown.GetYaxis().SetNdivisions(8)
    
    c.SaveAs(output)
示例#11
0
def MakeOneHist(varXaxis, varConst, xvalues, constval):

    if len(xvalues)<=1:
        return # Do not make plot if there is only 1 xvalue
    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)
    Canvas = TCanvas("sigEff_"+varConst+str(constval)+"_vs_"+varXaxis)
    Histograms = []
    LegendEntries = []
    colorIndex = 0
    for source in input_sources: # loop over different input sources in config file
#        print "Debug:  running over input_source from: ", source['condor_dir'], " for varXaxis=", varXaxis, ", varConst=", varConst

        # Create histogram of efficiencies with appropriate binning
        xAxisBins = array('d')
        xBinWidth = xvalues[1] - xvalues[0]
        for xval in xvalues:
            xAxisBins.append(xval - xBinWidth/2.0)
        xAxisBins.append(xvalues[-1] + xBinWidth/2.0)   # add an extra bin boundary for the last bin.

        Histogram = TH1F("Histogram", ";x title;signal efficiency", len(xvalues), xAxisBins)
        Histogram.SetDirectory(0)

        # Now fill the histogram of efficiencies:
        for xval in xvalues:
            if   varXaxis=="mass" and varConst=="lifetime":
                mass = xval
                lifetime = constval
            elif varXaxis=="lifetime" and varConst=="mass":
                lifetime = xval
                mass = constval
            else:
                print "Unrecognized value of varXaxis=", varXaxis
                return
            dataset_file = "condor/%s/%s.root" % (source['condor_dir'],dataset)
            dataset_file = dataset_file.replace("MASS",     str(mass))
            dataset_file = dataset_file.replace("LIFETIME", str(lifetime))
            inputFile = TFile(dataset_file)
            HistCutflow = inputFile.Get("OSUAnalysis/" + source['channel'] + "CutFlow")
            if not HistCutflow:
                print "WARNING: Could not find histogram OSUAnalysis/" + source['channel'] + "CutFlow in file " + dataset_file + ". Will skip it and continue."
                return

            # calculate efficiency
            nbinsCutflow = HistCutflow.GetNbinsX()
            if arguments.xsecFile:
                xsec = float(signal_cross_sections[str(mass)]['value'])
                denom = xsec * intLumi
            else:
                denom = HistCutflow.GetBinContent(1)  # denominator is the first entry in the cutflow histogram
            eff    = HistCutflow.GetBinContent(nbinsCutflow) / denom
            effErr = HistCutflow.GetBinError  (nbinsCutflow) / denom
            ibin = Histogram.FindBin(xval)
            Histogram.SetBinContent(ibin, eff)
            Histogram.SetBinError  (ibin, effErr)
            print "Setting bin content for varConst = ", varConst, " = ", constval, " in ibin=", ibin, ", xval=", xval, ", eff=", eff, " +- ", effErr, ", fractional error =", effErr/eff, " numerator = ", HistCutflow.GetBinContent(nbinsCutflow), " denom = ", denom, " from file: ", dataset_file
            inputFile.Close()

        if varXaxis=="mass":
            xAxisLabel = "chargino mass [GeV]"
        elif varXaxis=="lifetime":
            xAxisLabel = "chargino c#tau [cm]"
        else:
            print "Unrecognized value of varXaxis=", varXaxis
            return

        yAxisLabel = "efficiency"

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(1)
#        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)
        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    # Finish loop over input_sources

    # formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
#        print "Adding entry to legend:  ", LegendEntries[legendIndex]
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    # finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
#        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        currentMax = histogram.GetMaximum()
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if finalMax is 0:
        finalMax = 1
##         if arguments.setYMax:
##             finalMax = float(arguments.setYMax)

    # Drawing histograms to canvas
    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    yAxisMin = 0.0
##         if arguments.setYMin:
##             yAxisMin = float(arguments.setYMin)
    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
##             if arguments.setLogY:
##                 gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()
        Canvas.cd(1)

    histCounter = 0
    plotting_options = "pe, x0"   # x0 suppresses the error bar along x
##         if arguments.plot_hist:
##             plotting_options = "HIST"

    for histogram in Histograms:
        #            histogram.SetTitle(histoTitle)
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        if histogram.InheritsFrom("TH1"):
            histogram.SetMaximum(finalMax)
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    x_left = 0.15
    x_right = 0.55
    y_min = 0.6
    y_max = 0.8
    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    customText = "chargino " + varConst + " " + str(constval)
    if varConst == "mass":
        customText += " GeV"
    elif varConst == "lifetime":
        customText += " cm"
    customText = customText.replace("lifetime", "c#tau")

    CustomLabel = TPaveLabel(x_left, 0.8, x_right, 0.9, customText, "NDC")
    CustomLabel.SetBorderSize(0)
    CustomLabel.SetFillColor(0)
    CustomLabel.SetFillStyle(0)
    CustomLabel.Draw()

    #drawing the ratio or difference plot if requested
    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
#            Comparison = ratioHistogram(Histograms[0],Histograms[1], 1000)
            Comparison = Histograms[0].Clone()
            Comparison.Divide(Histograms[1])
            Comparison.GetYaxis().SetTitle("ratio")
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
#            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(0.7, 1.3)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
        Comparison.GetYaxis().SetNdivisions(205)
#        Comparison.Draw("E0")
        Comparison.Draw("PE, X0")  # X0 suppresses error bar in x direction

    outputFile.cd()
    Canvas.Write()
    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
示例#12
0
def main():

    CatHist_elel = TH1D("hist_elel","",6,-1.5,4.5)
    CatHist_mumu = TH1D("hist_mumu","",6,-1.5,4.5)
    CatHist_elmu = TH1D("hist_elmu","",6,-1.5,4.5)
    CatHist_incl = TH1D("hist_incl","",6,-1.5,4.5)

    workingdir = os.getcwd()
    infile = TFile("/user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/analyse/SELECTED_Full2017DataMC/TTJets_TuneCP5_13TeV-amcatnloFXFX-pythia8.root")
    intree = infile.Get("tree")
    
    hweight = infile.Get("hweight")
    orig_nevents = hweight.GetBinContent(1)
    xsec = 831*1000 #[fb]
    int_lumi = 41.5#27.3 #[fb-1]
    expected_nevents = xsec*int_lumi
    factor = float(expected_nevents)/float(orig_nevents)
    print factor
    #factor = factor*24/63.

    if not os.path.isdir(workingdir+"/inclusive"): os.mkdir(workingdir+"/inclusive")
    
    nEvents = intree.GetEntries()
    for evt in range(nEvents):
        intree.GetEntry(evt)
        
        weight = intree.weight_btag_iterativefit*intree.weight_electron_id*intree.weight_electron_reco*intree.weight_electron_trig*intree.weight_muon_id*intree.weight_muon_iso*intree.weight_muon_trig*intree.pu_weight*intree.mc_weight
        

        lept_channel = intree.lepton_Category
        if lept_channel == 0: # elel
            CatHist_elel.Fill(intree.event_Category,factor*weight)
        if lept_channel == 1: # mumu
            CatHist_mumu.Fill(intree.event_Category,factor*weight)
        if lept_channel == 2: # elmu
            CatHist_elmu.Fill(intree.event_Category,factor*weight)
        
        CatHist_incl.Fill(intree.event_Category,factor*weight)
    
#     CatHistNorm=CatHist.Clone()
#     CatHistNorm.Scale(100./CatHist.Integral())
#     CatHistNorm.SetLineWidth(0)
#     CatHistNorm.SetFillColor(0)
    c1 = TCanvas("c1","c1",1200,800)
    leftpad = TPad("u","u",0.,0.,0.7,1.)
    rightpad = TPad("d","d",0.7,0.0,1.,1.)
    leftpad.Draw()
    rightpad.Draw()

    leftpad.cd()
    gPad.SetLogy(1)
    gPad.SetMargin(0.15,0.05,0.1,0.1)
    CatHist_elmu.SetTitle("")
    CatHist_elmu.SetFillColor(2)
    CatHist_elmu.SetLineColor(2)
    CatHist_elmu.SetLineWidth(0)
    CatHist_elmu.SetBarWidth(0.2)
    CatHist_elmu.SetBarOffset(0.1)
    CatHist_elmu.SetMarkerStyle(0)
    #CatHist_elmu.Scale(100./CatHist_elmu.Integral())
    CatHist_elmu.GetXaxis().SetBinLabel(1,"other")
    CatHist_elmu.GetXaxis().SetBinLabel(2,"ttbb")
    #CatHist_elmu.GetXaxis().SetBinLabel(3,"ttbc")
    CatHist_elmu.GetXaxis().SetBinLabel(3,"ttbj")
    CatHist_elmu.GetXaxis().SetBinLabel(4,"ttcc")
    CatHist_elmu.GetXaxis().SetBinLabel(5,"ttcj")
    CatHist_elmu.GetXaxis().SetBinLabel(6,"ttjj")
    CatHist_elmu.GetXaxis().SetLabelSize(0.06)
    #CatHist_elmu.GetYaxis().SetTitle("Percentage of events [%]")
    CatHist_elmu.GetYaxis().SetTitle("# events (%.1f fb-1)"%int_lumi)
    CatHist_elmu.GetYaxis().SetTitleOffset(1.4)
    CatHist_elmu.GetYaxis().SetTitleSize(0.05)
    CatHist_elmu.GetYaxis().SetRangeUser(1,500000)
    #CatHist_elmu.GetYaxis().SetRangeUser(0.1,500)
    CatHist_elmu.Draw("barTEXT")
    #CatHist_elmuNorm.Draw("TEXT")
    
    CatHist_elel.SetTitle("")
    CatHist_elel.SetFillColor(4)
    CatHist_elel.SetLineColor(4)
    CatHist_elel.SetLineWidth(0)
    CatHist_elel.SetBarWidth(0.2)
    CatHist_elel.SetBarOffset(0.3)
    CatHist_elel.SetMarkerStyle(0)
    CatHist_elel.Draw("barTEXT same")  
    
    CatHist_mumu.SetTitle("")
    CatHist_mumu.SetFillColor(3)
    CatHist_mumu.SetLineColor(3)
    CatHist_mumu.SetLineWidth(0)
    CatHist_mumu.SetBarWidth(0.2)
    CatHist_mumu.SetBarOffset(0.5)
    CatHist_mumu.SetMarkerStyle(0)
    CatHist_mumu.Draw("barTEXT same")   
    
    CatHist_incl.SetTitle("")
    CatHist_incl.SetFillColor(14)
    CatHist_incl.SetLineColor(14)
    CatHist_incl.SetLineWidth(0)
    CatHist_incl.SetBarWidth(0.2)
    CatHist_incl.SetBarOffset(0.7)
    CatHist_incl.SetMarkerStyle(0)
    CatHist_incl.Draw("barTEXT same")  
    
    
    l_1 = TLegend(0.18,0.7,0.5,0.89)
    l_1.SetFillStyle(0)
    l_1.SetBorderSize(0)
    l_1.AddEntry(CatHist_elmu,"e^{#pm}#mu^{#mp} channel","f")
    l_1.AddEntry(CatHist_elel,"e^{+}e^{-} channel","f")
    l_1.AddEntry(CatHist_mumu,"#mu^{+}#mu^{-} channel","f")
    l_1.AddEntry(CatHist_incl,"inclusive","f")
    l_1.Draw("same")
      
    #c1.cd(2)
    #FlavHist.Draw("colzTEXT")

    c1.SaveAs(workingdir+"/inclusive/categories.png")
    c1.SaveAs(workingdir+"/inclusive/categories.pdf")
示例#13
0
def main(program, name):
    #0.phi, 1. mddbar, 2. mkpi, 3. costhetaddbar, 4. costhetakpi, 5.C_T
    CM_data = np.transpose(
        np.loadtxt('results_%s/B0_CM_variables.txt' % (name)))
    CM_data_conj = np.transpose(
        np.loadtxt('results_%s/B0_CM_variables_conj.txt' % (name)))

    mDDbar = CM_data[1]
    mDDbar_conj = CM_data_conj[1]
    mKpi = CM_data[2]
    mKpi_conj = CM_data_conj[2]
    C_T = CM_data[5]
    C_T_conj = CM_data_conj[5]
    phi_p = CM_data[0][(C_T > 0)]
    phi_p_conj = CM_data_conj[0][(C_T_conj > 0)]
    mDDbar_p = CM_data[1][(C_T > 0)]
    mDDbar_p_conj = CM_data_conj[1][(C_T_conj > 0)]
    mKpi_p = CM_data[2][(C_T > 0)]
    mKpi_p_conj = CM_data_conj[2][(C_T_conj > 0)]
    costhetaD_p = CM_data[3][(C_T > 0)]
    costhetaD_p_conj = CM_data_conj[3][(C_T_conj > 0)]
    costhetaK_p = CM_data[4][(C_T > 0)]
    costhetaK_p_conj = CM_data_conj[4][(C_T_conj > 0)]
    sWeight_p = CM_data[6][(C_T > 0)]
    sWeight_p_conj = CM_data_conj[6][(C_T_conj > 0)]
    mB0_p = CM_data[7][(C_T > 0)]
    mB0_p_conj = CM_data_conj[7][(C_T_conj > 0)]
    phi_n = CM_data[0][(C_T < 0)]
    phi_n_conj = CM_data_conj[0][(C_T_conj < 0)]
    mDDbar_n = CM_data[1][(C_T < 0)]
    mDDbar_n_conj = CM_data_conj[1][(C_T_conj < 0)]
    mKpi_n = CM_data[2][(C_T < 0)]
    mKpi_n_conj = CM_data_conj[2][(C_T_conj < 0)]
    costhetaD_n = CM_data[3][(C_T < 0)]
    costhetaD_n_conj = CM_data_conj[3][(C_T_conj < 0)]
    costhetaK_n = CM_data[4][(C_T < 0)]
    costhetaK_n_conj = CM_data_conj[4][(C_T_conj < 0)]
    sWeight_n = CM_data[6][(C_T < 0)]
    sWeight_n_conj = CM_data_conj[6][(C_T_conj < 0)]
    mB0_n = CM_data[7][(C_T < 0)]
    mB0_n_conj = CM_data_conj[7][(C_T_conj < 0)]

    bin = 100

    #*****************************************************************************************
    #invariant mass  -  m(D0 Dbar0)
    #*****************************************************************************************
    c1 = ROOT.TCanvas("c1", "B0 decay invmass", 1420, 710)
    c1.Divide(2, 1)
    c1.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h1_1 = pltini("h1_1", bin, mDDbar_p, sWeight_p,
                  '\ m(D^0\\bar{D}^0)\\;[GeV/c^2]', ROOT.kAzure + 2)
    h1_2 = pltini("h1_2", bin, mDDbar_n, sWeight_n,
                  '\ m(D^0\\bar{D}^0)\\;[GeV/c^2]', ROOT.kRed)
    leg1 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg1.AddEntry(h1_1, "\ B^0(C_T > 0)", "lf")
    leg1.AddEntry(h1_2, "\ B^0(C_T < 0)", "lf")
    legset(leg1)
    h1_1.SetMaximum(1.8 * h1_1.GetMaximum())
    h1_1.Draw("HIST")
    h1_2.Draw("HIST same")
    leg1.Draw()

    c1.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h11_1 = pltini("h11_1", bin, mDDbar_p_conj, sWeight_p_conj,
                   '\ m(\\bar{D}^0D^0)\\;[GeV/c^2]', ROOT.kAzure + 2)
    h11_2 = pltini("h11_2", bin, mDDbar_n_conj, sWeight_n_conj,
                   '\ m(\\bar{D}^0D^0)\\;[GeV/c^2]', ROOT.kRed)
    leg11 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg11.AddEntry(h11_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg11.AddEntry(h11_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg11)
    h11_1.SetMaximum(h1_1.GetMaximum())
    h11_1.Draw("HIST")
    h11_2.Draw("HIST same")
    leg11.Draw()
    c1.SaveAs("results_%s/invmass_D0Dbar0.png" % (name))

    #*****************************************************************************************
    #invariant mass  -  m(K pi)
    #*****************************************************************************************
    c2 = ROOT.TCanvas("c2", "B0 decay invmass", 1420, 710)
    c2.Divide(2, 1)
    c2.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h2_1 = pltini("h2_1", bin, mKpi_p, sWeight_p, '\ m(K^+\pi^-)\\;[GeV/c^2]',
                  ROOT.kAzure + 2)
    h2_2 = pltini("h2_2", bin, mKpi_n, sWeight_n, '\ m(K^+\pi^-)\\;[GeV/c^2]',
                  ROOT.kRed)
    leg2 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg2.AddEntry(h2_1, "\ B^0(C_T > 0)", "lf")
    leg2.AddEntry(h2_2, "\ B^0(C_T < 0)", "lf")
    legset(leg2)
    h2_1.SetMaximum(1.8 * h2_1.GetMaximum())
    h2_1.Draw("HIST")
    h2_2.Draw("HIST same")
    leg2.Draw()

    c2.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h22_1 = pltini("h22_1", bin, mKpi_p_conj, sWeight_p_conj,
                   '\ m(K^-\pi^+)\\;[GeV/c^2]', ROOT.kAzure + 2)
    h22_2 = pltini("h22_2", bin, mKpi_n_conj, sWeight_n_conj,
                   '\ m(K^-\pi^+)\\;[GeV/c^2]', ROOT.kRed)
    leg22 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg22.AddEntry(h22_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg22.AddEntry(h22_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg22)
    h22_1.SetMaximum(h2_1.GetMaximum())
    h22_1.Draw("HIST")
    h22_2.Draw("HIST same")
    leg22.Draw()
    c2.SaveAs("results_%s/invmass_KpPim.png" % (name))

    #*****************************************************************************************
    #helicity angle  -  cos(theta_D)
    #*****************************************************************************************
    c3 = ROOT.TCanvas("c3", "B0 decay helicity anlge", 1420, 710)
    c3.Divide(2, 1)
    c3.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h3_1 = pltini("h3_1", bin, costhetaD_p, sWeight_p, '\ \cos(\\theta_D)',
                  ROOT.kAzure + 2)
    h3_2 = pltini("h3_2", bin, costhetaD_n, sWeight_n, '\ \cos(\\theta_D)',
                  ROOT.kRed)
    leg3 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg3.AddEntry(h3_1, "\ B^0(C_T > 0)", "lf")
    leg3.AddEntry(h3_2, "\ B^0(C_T < 0)", "lf")
    legset(leg3)
    h3_1.SetMaximum(1.8 * h3_1.GetMaximum())
    h3_1.Draw("HIST")
    h3_2.Draw("HIST same")
    leg3.Draw()

    c3.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h33_1 = pltini("h33_1", bin, costhetaD_p_conj, sWeight_p_conj,
                   '\ \cos(\\theta_D)', ROOT.kAzure + 2)
    h33_2 = pltini("h33_2", bin, costhetaD_n_conj, sWeight_n_conj,
                   '\ \cos(\\theta_D)', ROOT.kRed)
    leg33 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg33.AddEntry(h33_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg33.AddEntry(h33_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg33)
    h33_1.SetMaximum(h3_1.GetMaximum())
    h33_1.Draw("HIST")
    h33_2.Draw("HIST same")
    leg33.Draw()
    c3.SaveAs("results_%s/helangle_D0Dbar0.png" % (name))

    #*****************************************************************************************
    #helicity angle  -  cos(theta_K)
    #*****************************************************************************************
    c4 = ROOT.TCanvas("c4", "B0 decay helicity anlge", 1420, 710)
    c4.Divide(2, 1)
    c4.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h4_1 = pltini("h4_1", bin, costhetaK_p, sWeight_p, '\ \cos(\\theta_K)',
                  ROOT.kAzure + 2)
    h4_2 = pltini("h4_2", bin, costhetaK_n, sWeight_n, '\ \cos(\\theta_K)',
                  ROOT.kRed)
    leg4 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg4.AddEntry(h4_1, "\ B^0(C_T > 0)", "lf")
    leg4.AddEntry(h4_2, "\ B^0(C_T < 0)", "lf")
    legset(leg4)
    h4_1.SetMaximum(1.8 * h4_1.GetMaximum())
    h4_1.Draw("HIST")
    h4_2.Draw("HIST same")
    leg4.Draw()

    c4.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h44_1 = pltini("h44_1", bin, costhetaK_p_conj, sWeight_p_conj,
                   '\ \cos(\\theta_K)', ROOT.kAzure + 2)
    h44_2 = pltini("h44_2", bin, costhetaK_n_conj, sWeight_n_conj,
                   '\ \cos(\\theta_K)', ROOT.kRed)
    leg44 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg44.AddEntry(h44_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg44.AddEntry(h44_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg44)
    h44_1.SetMaximum(h4_1.GetMaximum())
    h44_1.Draw("HIST")
    h44_2.Draw("HIST same")
    leg44.Draw()
    c4.SaveAs("results_%s/helangle_KpPim.png" % (name))

    #*****************************************************************************************
    #plane angle  -  phi
    #*****************************************************************************************
    c5 = ROOT.TCanvas("c5", "B0 decay plane angle", 1420, 710)
    c5.Divide(2, 1)
    c5.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h5_1 = pltini("h5_1", bin, phi_p, sWeight_p, '\ \phi\\;[rad]',
                  ROOT.kAzure + 2)
    h5_2 = pltini("h5_2", bin, phi_n, sWeight_n, '\ \phi\\;[rad]', ROOT.kRed)
    leg5 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg5.AddEntry(h5_1, "\ B^0(C_T > 0)", "lf")
    leg5.AddEntry(h5_2, "\ B^0(C_T < 0)", "lf")
    legset(leg5)
    h5_1.SetMaximum(1.8 * h5_1.GetMaximum())
    h5_1.Draw("HIST")
    h5_2.Draw("HIST same")
    leg5.Draw()

    c5.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h55_1 = pltini("h55_1", bin, phi_p_conj, sWeight_p_conj, '\ \phi\\;[rad]',
                   ROOT.kAzure + 2)
    h55_2 = pltini("h55_2", bin, phi_n_conj, sWeight_n_conj, '\ \phi\\;[rad]',
                   ROOT.kRed)
    leg55 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg55.AddEntry(h55_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg55.AddEntry(h55_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg55)
    h55_1.SetMaximum(h5_1.GetMaximum())
    h55_1.Draw("HIST")
    h55_2.Draw("HIST same")
    leg55.Draw()
    c5.SaveAs("results_%s/planeangle.png" % (name))

    #*****************************************************************************************
    #invariant mass  -  m(D0 Dbar0 K pi)
    #*****************************************************************************************
    c6 = ROOT.TCanvas("c6", "B0 decay invmass", 1420, 710)
    c6.Divide(2, 1)
    c6.cd(1)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h6_1 = pltini("h6_1", bin, mB0_p, sWeight_p,
                  '\ m(D^0\\bar{D}^0K^+\pi^-)\\;[GeV/c^2]', ROOT.kAzure + 2)
    h6_2 = pltini("h6_2", bin, mB0_n, sWeight_n,
                  '\ m(D^0\\bar{D}^0K^+\pi^-)\\;[GeV/c^2]', ROOT.kRed)
    leg6 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg6.AddEntry(h6_1, "\ B^0(C_T > 0)", "lf")
    leg6.AddEntry(h6_2, "\ B^0(C_T < 0)", "lf")
    legset(leg6)
    h6_1.SetMaximum(1.8 * h6_1.GetMaximum())
    h6_1.Draw("HIST")
    h6_2.Draw("HIST same")
    leg6.Draw()

    c6.cd(2)
    gPad.SetMargin(0.2, 0.05, 0.15, 0.1)
    h66_1 = pltini("h66_1", bin, mB0_p_conj, sWeight_p_conj,
                   '\ m(\\bar{D}^0D^0K^-\pi^+)\\;[GeV/c^2]', ROOT.kAzure + 2)
    h66_2 = pltini("h66_2", bin, mB0_n_conj, sWeight_n_conj,
                   '\ m(\\bar{D}^0D^0K^-\pi^+)\\;[GeV/c^2]', ROOT.kRed)
    leg66 = ROOT.TLegend(0.6, 0.74, 0.89, 0.89)
    leg66.AddEntry(h66_1, "\ \\bar{B}^0(-\\bar{C}_T > 0)", "lf")
    leg66.AddEntry(h66_2, "\ \\bar{B}^0(-\\bar{C}_T < 0)", "lf")
    legset(leg66)
    h66_1.SetMaximum(h6_1.GetMaximum())
    h66_1.Draw("HIST")
    h66_2.Draw("HIST same")
    leg66.Draw()
    c6.SaveAs("results_%s/invmass_B0.png" % (name))

    #combined figure
    img1 = mpimg.imread("results_%s/invmass_D0Dbar0.png" % (name))
    img2 = mpimg.imread("results_%s/invmass_KpPim.png" % (name))
    img3 = mpimg.imread("results_%s/helangle_D0Dbar0.png" % (name))
    img4 = mpimg.imread("results_%s/helangle_KpPim.png" % (name))
    img5 = mpimg.imread("results_%s/planeangle.png" % (name))

    fig1, axs1 = plt.subplots(2, 1, figsize=(60, 50))
    (ax1), (ax2) = axs1

    fig2, axs2 = plt.subplots(3, 1, figsize=(60, 75))
    (ax3), (ax4), (ax5) = axs2

    fig3, axs3 = plt.subplots(5, 1, figsize=(60, 125))
    (ax1_1), (ax2_1), (ax3_1), (ax4_1), (ax5_1) = axs3

    ax1.imshow(img1)
    ax1.set_axis_off()
    ax2.imshow(img2)
    ax2.set_axis_off()
    ax3.imshow(img3)
    ax3.set_axis_off()
    ax4.imshow(img4)
    ax4.set_axis_off()
    ax5.imshow(img5)
    ax5.set_axis_off()

    ax1_1.imshow(img1)
    ax1_1.set_axis_off()
    ax2_1.imshow(img2)
    ax2_1.set_axis_off()
    ax3_1.imshow(img3)
    ax3_1.set_axis_off()
    ax4_1.imshow(img4)
    ax4_1.set_axis_off()
    ax5_1.imshow(img5)
    ax5_1.set_axis_off()

    fig1.tight_layout()
    fig2.tight_layout()
    fig3.tight_layout()
    fig1.savefig("results_%s/CM_variable_invariant_mass.png" % (name))
    fig2.savefig("results_%s/CM_variable_angles.png" % (name))
    fig3.savefig("results_%s/CM_variable_all.png" % (name))
示例#14
0
def MakeOneDHist(histogramName,integrateDir): 

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)
    
    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)
    
    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)
    
    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"
        
    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    canvasName = histogramName
    if integrateDir is "left":
        canvasName += "_CumulativeLeft"
    elif integrateDir is "right":
        canvasName += "_CumulativeRight"
    Canvas = TCanvas(canvasName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0
    
    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)
        if arguments.generic:
            HistogramObj = inputFile.Get(source['channel'] + "/" +histogramName)  
        else: 
            HistogramObj = inputFile.Get("OSUAnalysis/" + source['channel'] + "/" +histogramName)
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."  
            return 
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")
        xAxisLabelVar = xAxisLabel
        
        if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
            yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex]
            xAxisLabelVar = xAxisLabel[0:unitBeginIndex]
        else:
            yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        if arguments.normalizeToUnitArea and arguments.makeSignificancePlots:
            unit = "Efficiency"
        else:
            unit = "Yield"
        if integrateDir is "left":
            yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
        if integrateDir is "right":
            yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
                                                        
        
        if not arguments.makeFancy and not arguments.generic:  
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
        
        markerStyle = 20 
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)
        
        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        if arguments.normalizeToUnitArea and Histogram.Integral() > 0:
            Histogram.Scale(1./Histogram.Integral())

        Histogram = MakeIntegralHist(Histogram, integrateDir)
            
        LegendEntries.append(source['legend_entry']) 
        Histograms.append(Histogram)

            
    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if arguments.setYMax:  
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    #makeSignifPlots = arguments.makeSignificancePlots
    
    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.generic:
        plotting_options = "p,e" 
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        histogram.SetTitle(histoTitle)
        if arguments.verbose:
            print "Debug:  drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor())    
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        histogram.SetMaximum(finalMax)
        histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            plotting_options = plotting_options + " SAME"
        histCounter = histCounter + 1

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()


    # Deciding which text labels to draw and drawing them
    drawHeaderLabel = False

    if arguments.makeFancy:
        drawHeaderLabel = True

    #now that flags are set, draw the appropriate labels

    if drawHeaderLabel:
        HeaderLabel.Draw()




    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            if arguments.ratioRelErrMax:
                Comparison = ratioHistogram(Histograms[0],Histograms[1],float(arguments.ratioRelErrMax))
            else:
                Comparison = ratioHistogram(Histograms[0],Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
                         
        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()
    
    if arguments.savePDFs:
        Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")