Ejemplo n.º 1
0
def createPaveLabel(x1, y1, x2, y2, text,
                    fillColor=1, textColor=0,
                    textSize=None):

    label = TPaveLabel(0.80, 0.80, 0.97, 0.88,
                           'Peak Fit')
    label.SetFillColor(fillColor)
    label.SetTextColor(textColor)
    label.SetTextFont(52)
    if (textSize != None):
        label.SetTextSize(textSize)

    label.Draw()
    return label
Ejemplo n.º 2
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):
    #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")
    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    xPointsForErrors = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
        xPointsForErrors.append(0)
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    xPointsErrors = numpy.array(xPointsForErrors)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig

    GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected2SigLow),
                                               numpy.array(expected2SigHigh))
    GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected1SigLow),
                                               numpy.array(expected1SigHigh))

    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)
    #cCL=TCanvas("cCL", "cCL",0,0,567,384)
    cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450)
    gStyle.SetOptStat(0)
    gStyle.SetPadRightMargin(0.063)
    gStyle.SetPadLeftMargin(0.14)
    gStyle.SetPadBottomMargin(0.12)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    if SPIN2:
        signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"]
    elif GUT:
        signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"]
    else:
        signals = ["ssm", "psi"]

    xSecCurves = []
    for signal in signals:
        xSecCurves.append(getXSecCurve(signal, kFacs[signal]))
        #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True))

#Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if SPIN2:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z"
        )
    else:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(200, 5500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(1e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.055)
    DummyGraph.GetXaxis().SetTitleSize(0.055)
    DummyGraph.GetXaxis().SetTitleOffset(1.05)
    DummyGraph.GetYaxis().SetLabelSize(0.055)
    DummyGraph.GetYaxis().SetTitleSize(0.055)
    DummyGraph.GetYaxis().SetTitleOffset(1.3)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")

    plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    if "2017" in output or "Combination" in output:
        plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   Default
    leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
    if SPIN2:
        leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.0425)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l")
        leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC")
    leg1.SetTextSize(0.05)
    if GUT:
        leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC")
    if SPIN2:
        leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC")
        leg1.SetTextSize(0.045)
    for index, signal in enumerate(signals):
        xSecCurves[index].SetName(labels[signal])
        xSecCurves[index].Write(labels[signal])
        leg1.AddEntry(xSecCurves[index], labels[signal], "l")
    leg1.SetBorderSize(0)

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")

    elif "2017" in output or "Combination" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "41.4 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

#GraphErr2SigForHEPData.SetName("graph2Sig")
#GraphErr2SigForHEPData.Write("graph2Sig")

#GraphErr1SigForHEPData.SetName("graph1Sig")
#GraphErr1SigForHEPData.Write("graph1Sig")

#GraphExp.SetName("graphExp")
#GraphExp.Write("graphExp")

#GraphObs.SetName("graphObs")
#GraphObs.Write("graphObs")

#fileForHEPData.Write()
#fileForHEPData.Close()
    cCL.Update()
    printPlots(cCL, output)
Ejemplo n.º 3
0
pad3 = TPad('pad3', 'The pad with the histogram', 0.03, 0.02, 0.97, 0.57, 21)
pad1.Draw()
pad2.Draw()
pad3.Draw()
#
# We connect the ROOT file generated in a previous tutorial
# see begin_html <a href="hsimple.C.html">An example creating/filling/saving histograms/ntuples on file</a> end_html
#
example = TFile('py-hsimple.root')
example.ls()

# Draw a global picture title
title = TPaveLabel(0.1, 0.94, 0.9, 0.98,
                   'Drawing options for one dimensional histograms')
title.SetFillColor(16)
title.SetTextFont(52)
title.Draw()
#
# Draw histogram hpx in first pad with the default option.
pad1.cd()
pad1.GetFrame().SetFillColor(18)
hpx = gROOT.FindObject('hpx')
hpx.SetFillColor(45)
hpx.DrawCopy()
label1 = TPaveLabel(-3.5, 700, -1, 800, 'Default option')
label1.SetFillColor(42)
label1.Draw()
#
# Draw hpx as a lego. Clicking on the lego area will show
# a "transparent cube" to guide you rotating the lego in real time.
pad2.cd()
Ejemplo n.º 4
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)
    smoother = TGraphSmooth("normal")
    smoother2 = TGraphSmooth("normal")

    zprimeX = []
    zprimeY = []
    fileZPrime = open('tools/xsec_SSM.txt', 'r')
    for entries in fileZPrime:
        entry = entries.split()
        zprimeX.append(float(entry[0]))
        zprimeY.append(float(entry[1]) * 1.3 / 1928)
    zpX = numpy.array(zprimeX)
    zpY = numpy.array(zprimeY)
    GraphZPrime = TGraph(481, zpX, zpY)
    GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear")
    GraphZPrimeSmooth.SetLineWidth(3)
    GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3)
    GraphZPrimeSmooth.SetLineStyle(2)

    zprimePsiX = []
    zprimePsiY = []
    fileZPrimePsi = open('tools/xsec_PSI.txt', 'r')
    for entries in fileZPrimePsi:
        entry = entries.split()
        zprimePsiX.append(float(entry[0]))
        zprimePsiY.append(float(entry[1]) * 1.3 / 1928)
    zpPsiX = numpy.array(zprimePsiX)
    zpPsiY = numpy.array(zprimePsiY)
    GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY)
    GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear")
    GraphZPrimePsiSmooth.SetLineWidth(3)
    GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    plotPad.SetLogy()
    if "Moriond" in output:
        DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500)
    else:
        DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)"
        )
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)"
        )

    gStyle.SetOptStat(0)
    if "Moriond" in output:
        DummyGraph.GetXaxis().SetRangeUser(120, 4500)
    else:
        DummyGraph.GetXaxis().SetRangeUser(400, 4500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(4e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")

    GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    if not SPIN2:
        GraphZPrimeSmooth.Draw("lsame")
        GraphZPrimePsiSmooth.Draw("lsame")

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")

        leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l")
        leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0],
                     "l")

    else:
        leg.AddEntry(GraphObs, "Observed 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f")
            leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f")

    leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC")
    leg1.SetTextSize(0.032)

    if not SPIN2:
        leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l")
        leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(400, 1, 4500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
Ejemplo n.º 5
0
    jbessel.SetTitle("")
    jbessel.SetLineStyle(1)
    jbessel.SetLineWidth(3)
    jbessel.SetLineColor(nu + 1)
    JBessel.append(jbessel)

# Setting x axis for JBessel
xaxis = JBessel[0].GetXaxis()
xaxis.SetTitle("x")
xaxis.SetTitleSize(0.06)
xaxis.SetTitleOffset(.7)

# setting the title in a label style
p1 = TPaveLabel(.0, .90, .0 + .50, .90 + .10, "Bessel J functions", "NDC")
p1.SetFillColor(0)
p1.SetTextFont(22)
p1.SetTextColor(kBlack)

# setting the legend
leg.AddEntry(JBessel[0].DrawCopy(), " J_0(x)", "l")
leg.AddEntry(JBessel[1].DrawCopy("same"), " J_1(x)", "l")
leg.AddEntry(JBessel[2].DrawCopy("same"), " J_2(x)", "l")
leg.AddEntry(JBessel[3].DrawCopy("same"), " J_3(x)", "l")
leg.AddEntry(JBessel[4].DrawCopy("same"), " J_4(x)", "l")

leg.Draw()
p1.Draw()

# Set canvas 2
DistCanvas.cd(2)
gPad.SetGrid()
Ejemplo n.º 6
0
def makeBiasPlot(output,
                 muFile,
                 chan,
                 interference,
                 printStats=False,
                 obs2="",
                 ratioLabel=""):

    mu = open(muFile, 'r')

    limits = {}
    mux = []
    muy = []
    mu1SigLow = []
    mu1SigHigh = []
    mu2SigLow = []
    mu2SigHigh = []
    for entry in mu:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        mux.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        muy.append(limits[massPoint][medianNr])
        mu1SigLow.append(limits[massPoint][lower1Sig])
        mu1SigHigh.append(limits[massPoint][upper1Sig])
        mu2SigLow.append(limits[massPoint][lower2Sig])
        mu2SigHigh.append(limits[massPoint][upper2Sig])

    muX = numpy.array(mux)
    muY = numpy.array(muy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of mux: ", len(mux)
    if printStats: print "length of mu1SigLow: ", len(mu1SigLow)
    if printStats: print "length of mu1SigHigh: ", len(mu1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(mux)):
        values2.append(mu2SigLow[x])
        xPointsForValues2.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values2.append(mu2SigHigh[x])
        xPointsForValues2.append(mux[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(mux)):
        values.append(mu1SigLow[x])
        xPointsForValues.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values.append(mu1SigHigh[x])
        xPointsForValues.append(mux[x])
    if printStats: print "length of values: ", len(values)

    mu2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    mu1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "mu2Sig: ", mu2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "mu1Sig: ", mu1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, mu2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, mu1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    muX = numpy.array(mux)
    muY = numpy.array(muy)
    GraphMU = TGraph(len(muX), muX, muY)
    GraphMU.SetLineWidth(3)
    GraphMU.SetLineStyle(2)
    GraphMU.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 40)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    DummyGraph.GetYaxis().SetTitle("#hat{#mu}")
    gStyle.SetOptStat(0)
    if "Des" in output:
        DummyGraph.GetXaxis().SetRangeUser(10, 28)
    else:
        DummyGraph.GetXaxis().SetRangeUser(10, 40)

    DummyGraph.SetMinimum(-2)
    DummyGraph.SetMaximum(10)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    DummyGraph.SetLineColor(ROOT.kWhite)
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphMU.Draw("lpsame")
    else:
        GraphMU.Draw("lp")
    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    leg.AddEntry(GraphMU, "median value", "l")
    if (FULL):
        leg.AddEntry(GraphErr1Sig, "1#sigma quantile", "f")
        leg.AddEntry(GraphErr2Sig, "2#sigma quantile", "f")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()
    maxX = 40
    if "Des" in output:
        maxX = 28
    line = ROOT.TLine(10, 0, maxX, 0)
    if "mu1" in output:
        line = ROOT.TLine(10, 1, maxX, 1)
    line.SetLineStyle(ROOT.kDashed)
    line.Draw("same")

    plotPad.RedrawAxis()

    cCL.Update()
    printPlots(cCL, output)
Ejemplo n.º 7
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  interference,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    xSecs = getFittedXSecCurve("CI_%s" % interference, 1.3)
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1]) * xSecs.Eval(
                int(float(entry.split()[0])))
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    xSecCurves = []
    xSecCurves.append(getFittedXSecCurve("CI_%s" % interference, 1.3))

    #Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 46)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#mu#mu +X) [pb]"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowee +X) [pb]")
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#font[12]{ll}) [pb]"
        )

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(10, 46)

    DummyGraph.SetMinimum(5e-4)
    DummyGraph.SetMaximum(1)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        print curve.Eval(28)
        #curve.Draw()
        curve.Draw("sameR")

    plCMS = TPaveLabel(.15, .81, .25, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.15, .76, .275, .82, "Supplementary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    #plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.440517, 0.523051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Observed 95%% CL limit" % ratioLabels[1],
                     "l")
        leg.AddEntry(GraphObs2, "%s Observed 95%% CL limit" % ratioLabels[0],
                     "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg.AddEntry(xSecCurves[0], labels[interference], "l")
    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    elif "2017" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "42.1 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "41.5 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "41.5 fb^{-1} (13 TeV, ee) + 42.1 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
Ejemplo n.º 8
0
def makeLimitPlot(output, obs, exp, chan, printStats=False):

    obsLimits = {}

    for obsFile in obs:
        if 'width' in obsFile:
            width = obsFile.split('width')[-1].split('_')[0]
        else:
            width = '0.006'
        obsLimits[width] = createObsGraph(obsFile)

    if SMOOTH:
        for width, obsGraph in obsLimits.iteritems():
            smooth_obs = TGraphSmooth("normal")
            GraphObs_nonSmooth = obsGraph
            obsLimits[width] = copy.deepcopy(
                smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005))
            obsLimits[width].SetLineWidth(3)

    expLimits = {}

    for expFile in exp:
        if 'width' in expFile:
            width = expFile.split('width')[-1].split('_')[0]
        else:
            width = '0.006'
        expLimits[width] = createExpGraph(expFile)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    smoother = TGraphSmooth("normal")
    smoother2 = TGraphSmooth("normal")

    zprimeX = []
    zprimeY = []
    fileZPrime = open('tools/xsec_ssm.txt', 'r')
    for entries in fileZPrime:
        entry = entries.split()
        zprimeX.append(float(entry[0]))
        zprimeY.append(float(entry[1]) * 1.3 / 1928)
    zpX = numpy.array(zprimeX)
    zpY = numpy.array(zprimeY)
    GraphZPrime = TGraph(481, zpX, zpY)
    GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear")
    GraphZPrimeSmooth.SetLineWidth(3)
    GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3)
    GraphZPrimeSmooth.SetLineStyle(2)

    zprimePsiX = []
    zprimePsiY = []
    fileZPrimePsi = open('tools/xsec_psi.txt', 'r')
    for entries in fileZPrimePsi:
        entry = entries.split()
        zprimePsiX.append(float(entry[0]))
        zprimePsiY.append(float(entry[1]) * 1.3 / 1928)
    zpPsiX = numpy.array(zprimePsiX)
    zpPsiY = numpy.array(zprimePsiY)
    GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY)
    GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear")
    GraphZPrimePsiSmooth.SetLineWidth(3)
    GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    plotPad.SetLogy()
    if "Moriond" in output:
        DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    else:
        DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)"
        )
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)"
        )

    gStyle.SetOptStat(0)
    if "Moriond" in output:
        DummyGraph.GetXaxis().SetRangeUser(200, 5500)
    else:
        DummyGraph.GetXaxis().SetRangeUser(400, 4500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(4e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    leg = TLegend(0.430517, 0.623051, 0.734885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    colors = {
        '01': ROOT.kBlue,
        '03': ROOT.kRed,
        '05': ROOT.kGreen + 3,
        '10': ROOT.kOrange
    }
    for width in sorted(obsLimits):
        obsGraph = obsLimits[width]
        if colors.has_key(width):
            obsGraph.SetLineColor(colors[width])
        obsGraph.Draw("lsame")
        if width == '0.006':
            leg.AddEntry(obsGraph, "Observed 95% CL limit width 0.6%", "l")
        else:
            leg.AddEntry(obsGraph,
                         "Observed 95%% CL limit width %d%%" % int(width), "l")

    for width in sorted(expLimits):
        expGraph = expLimits[width]
        if colors.has_key(width):
            expGraph.SetLineColor(colors[width])
        expGraph.Draw("lsame")
        if width == '0.006':
            leg.AddEntry(expGraph, "Expected 95% CL limit width 0.6%, median",
                         "l")
        else:
            leg.AddEntry(
                expGraph,
                "Expected 95%% CL limit width %d%%, median" % (int(width)),
                "l")

#    	if not SPIN2:
#        	GraphZPrimeSmooth.Draw("lsame")
#        	GraphZPrimePsiSmooth.Draw("lsame")

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    cCL.Update()
    printPlots(cCL, output)
Ejemplo n.º 9
0
def getAvgHist(infile):
    global outRootFile

    inputFile = TFile(infile, "READ")
    canOrig = inputFile.Get(arguments.canName).Clone()
    can     = inputFile.Get(arguments.canName).Clone()
    if not can:
        print "Could not find TCanvas " + can + " in " + inputFile

    isFirstHist = True
    for obj in can.GetListOfPrimitives():
        if arguments.verbose:
            print "Reading: ", obj.GetName()
        if obj.InheritsFrom("TH1"):
            if isFirstHist:
                isFirstHist = False
                havg = obj.Clone()
                hwts = obj.Clone()
                havg.SetDirectory(0)
                havg.Reset()
                hwts.Reset()
                # Define average efficiency as weighted arithmetic mean:
                # (See http://en.wikipedia.org/wiki/Weighted_arithmetic_mean)
                # <eff> = (1/N) * Sum_i (eff_i   / sigma_i^2)
                # <err> = sqrt(1/N)
                # weight_i = 1 / sigma_i^2
                # normalization: N = Sum_i (1 / sigma_i^2)
            for i in range(1,obj.GetNbinsX()+1):
                eff = obj.GetBinContent(i)
                err = obj.GetBinError(i)
                if arguments.verbose:
                    print "Debug:  bin ", i, ": eff=", eff, ", err=", err
                # If error is 0, then reset to be very large value, so that it does not contribute much to the sum
                if err == 0:
                    err = 9.E9
                hwts.SetBinContent(i, hwts.GetBinContent(i) + 1.0 / math.pow(err,2))
                havg.SetBinContent(i, havg.GetBinContent(i) + eff / math.pow(err,2))
                havg.SetBinError  (i, havg.GetBinError  (i) + err / math.pow(err,2))
            if arguments.verbose:
                print "Found TH1: ", obj.GetName()
                print "yield: ", obj.GetBinContent(2), " +- ", obj.GetBinError(2)

    # After looping over all hists, calculate average
    for i in range(1,havg.GetNbinsX()+1):
        havg.SetBinContent(i, havg.GetBinContent(i) / hwts.GetBinContent(i))
        havg.SetBinError  (i, math.sqrt(        1.0 / hwts.GetBinContent(i)))
        if arguments.verbose:
            print "Bin ", i, ": range: (", havg.GetBinLowEdge(i), ", ", havg.GetBinLowEdge(i+1), "): value=", havg.GetBinContent(i), ", error=", havg.GetBinError(i)

    outRootFile.cd()
    canOrig.SetName(canOrig.GetName() + "_orig")
    canOrig.Write()
    can.cd()
    can.Clear("D")
    canNew = TCanvas("canNew", "canNew", can.GetWw(), can.GetWh())
    canNew.SetBottomMargin(can.GetBottomMargin())
    canNew.SetLeftMargin  (can.GetLeftMargin())
    havg.SetMaximum(1.1)
    if arguments.canName == "totalMcparticleStatus3SusyIdPt":
        havg.GetXaxis().SetTitle(havg.GetXaxis().GetTitle().replace("#sum", ""))
    if arguments.canName == "stopDecayVxyZoom":
        #        print "Debug:  setting max to 0.8"
        havg.SetMaximum(0.8)
    havg.GetYaxis().SetTitleOffset(1.4)
    havg.GetXaxis().SetTitleOffset(1.4)
    havg.GetXaxis().SetNdivisions(509)
    havg.Draw("P, E")


    #LumiLabel = TPaveLabel(0.7063758,0.8321678,0.9765101,0.9318182,"CMS","NDC")
    #LumiLabel = TPaveLabel(0.1641611,0.80,0.4463087,0.90,"CMS","NDC")
    LumiLabel = TPaveLabel(0.1858108,0.7904412,0.5084459,0.8897059,"CMS","NDC")
    LumiLabel.SetTextFont(62)
    LumiLabel.SetTextAlign(12)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)
    LumiLabel.Draw()

    #HeaderLabel = TPaveLabel(0.03187919, 0.9440559, 0.9110738, 0.9947552,"19.5 fb^{-1} (8 TeV)","NDC") # from makePlots.py
    HeaderLabel = TPaveLabel(0.02702703,0.9117647,0.9070946,0.9632353,"19.5 fb^{-1} (8 TeV)","NDC") # from makePlots.py
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)
    HeaderLabel.SetTextFont(42);
    HeaderLabel.Draw()

    outputPdf = arguments.outfile[:arguments.outfile.rfind("/")]
#    outputPdf += "/" + canNew.GetName() + ".pdf"
    outputPdf += "/" + havg.GetName() + "_avgEff.pdf"
    canNew.SaveAs(outputPdf)
    canNew.Write()
    print "Saving pdf: ", outputPdf
    inputFile.Close()

    return havg
Ejemplo n.º 10
0
def main():

    import argparse
    parser = argparse.ArgumentParser(
        usage="makePValuePlot.py [options] -o OUTPUTFILE --card CARD1",
        description="plots pvalue scans for Z' analysis'",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--card",
                        dest="cards",
                        default=[],
                        action="append",
                        help='add datacard to list of curves to plot')
    parser.add_argument("--smooth",
                        dest="smooth",
                        action="store_true",
                        default=False,
                        help="Smooth observed values")
    parser.add_argument("-c",
                        "--config",
                        dest="config",
                        default='',
                        help="config name")
    parser.add_argument("-t",
                        "--tag",
                        dest="tag",
                        default='',
                        help="limit tag")
    parser.add_argument("--ratioLabel",
                        dest="ratioLabel",
                        default='',
                        help="label for ratio")
    args = parser.parse_args()

    canv = ROOT.TCanvas("c1", "c1", 600, 450)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1)
    ROOT.gStyle.SetPadLeftMargin(0.12)
    ROOT.gStyle.SetPadBottomMargin(0.12)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetTitleXSize(0.055)
    ROOT.gStyle.SetLabelSize(0.055, "X")
    ROOT.gStyle.SetLabelSize(0.055, "Y")
    ROOT.gStyle.SetTitleXOffset(1.05)
    #ROOT.gStyle.SetLabelYSize(0.04)
    ROOT.gStyle.SetTitleYSize(0.055)
    ROOT.gStyle.SetTitleYOffset(1.1)

    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    plotPad.DrawFrame(200, 1e-4, 4000, 10, ";M [GeV]; local p-Value")
    plotPad.SetLogy()
    #ROOT.gStyle.SetLabelXSize(0.04)
    leg = ROOT.TLegend(0.32, 0.72, 0.9, 0.875, "", "brNDC")
    leg.SetFillColor(10)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetTextSize(0.06)
    graphs = []

    name = "pValues_%s_%s" % (args.config, args.tag)
    fileForHEPData = TFile("plots/" + name + "_forHEPData.root", "RECREATE")
    for index, card in enumerate(args.cards):
        if 'width' in card:
            width = "signif" + card.split('width')[-1].split('_')[0]
        else:
            width = 'signif'

        masses, pValues = getPValues(card)
        minPVal, minPValMass = getMinPValue(card)
        print card, minPVal, minPValMass
        graphs.append(
            ROOT.TGraph(len(masses), numpy.array(masses),
                        numpy.array(pValues)))
        label = card.split("_")[-1].split(".")[0]
        if args.smooth:
            smoother = ROOT.TGraphSmooth("normal")
            graphs[index] = deepcopy(
                smoother.SmoothSuper(graphs[index], "linear", 0, 0.005))

        graphs[index].SetLineColor(lineColors[width])
        graphs[index].SetLineStyle(lineStyles[width])
        leg.AddEntry(graphs[index], labels[width], "l")
        graphs[index].Draw("Lsame")
        graphs[index].SetLineWidth(2)
        graphs[index].SetName("graphPVal%s" % width)
        graphs[index].Write("graphPVal%s" % width)

    leg.Draw()
    leg.SetTextSize(0.045)
    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.03)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(62)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    configName = "scanConfiguration_%s" % args.config

    config = __import__(configName)
    chan = config.leptons

    if (chan == "mumu"):
        plLumi = TPaveLabel(.65, .885, .9, .99,
                            "139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC")
    elif (chan == "elel"):
        plLumi = TPaveLabel(.65, .885, .9, .99, "136.8 fb^{-1} (13 TeV, ee)",
                            "NBNDC")
    elif (chan == "elmu"):
        plLumi = TPaveLabel(
            .27, .885, .9, .99,
            "136.8 fb^{-1} (13 TeV, ee) + 139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
            "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.14, 0.81, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.78
    else:
        yLabelPos = 0.78

    latexCMSExtra.DrawLatex(0.14, yLabelPos, "%s" % (cmsExtra))

    ZeroSigmaLine = ROOT.TLine(200, 0.5, 4000, 0.5)
    ZeroSigmaLine.SetLineStyle(ROOT.kDashed)
    ZeroSigmaLine.Draw("same")

    OneSigmaLine = ROOT.TLine(200, 0.317 / 2, 4000, 0.317 / 2)
    OneSigmaLine.SetLineStyle(ROOT.kDashed)
    OneSigmaLine.Draw("same")

    TwoSigmaLine = ROOT.TLine(200, 0.0455 / 2, 4000, 0.0455 / 2)
    TwoSigmaLine.SetLineStyle(ROOT.kDashed)
    TwoSigmaLine.Draw("same")

    ThreeSigmaLine = ROOT.TLine(200, 0.0027 / 2, 4000, 0.0027 / 2)
    ThreeSigmaLine.SetLineStyle(ROOT.kDashed)
    ThreeSigmaLine.Draw("same")

    FourSigmaLine = ROOT.TLine(200, 0.00006 / 2, 4000, 0.00006 / 2)
    FourSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FourSigmaLine.Draw("same")

    FiveSigmaLine = ROOT.TLine(200, 3e-07, 4000, 3e-07)
    FiveSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FiveSigmaLine.Draw("same")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    #~ latex.SetNDC(Tru78
    latex.DrawLatex(4150, 0.5, "0#sigma")
    latex.DrawLatex(4150, 0.317 / 2, "1#sigma")
    latex.DrawLatex(4150, 0.0455 / 2, "2#sigma")
    latex.DrawLatex(4150, 0.0027 / 2, "3#sigma")
    #~ latex.DrawLatex(4200, 0.00006/2, "4#sigma")
    #~ latex.DrawLatex(4200, 3e-7, "5#sigma")

    #~ ROOT.gPad.WaitPrimitive()
    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()
    if args.smooth:
        name += "_smoothed"
    #name = name+".pdf"
    canv.Print("plots/" + name + ".pdf")
    canv.Print("plots/" + name + ".root")

    plotPad.RedrawAxis()

    fileForHEPData.Write()
    fileForHEPData.Close()
Ejemplo n.º 11
0
    h1 = f1.Get(plot["name"])
    h2 = f2.Get(plot["name"])
    h1.GetXaxis().SetNdivisions(5)  
    h1.GetYaxis().SetNdivisions(5)  
    h1.GetXaxis().SetTitleSize(0.05)
    h1.GetYaxis().SetTitleSize(0.05)
    h1.GetZaxis().SetTitleSize(0.05)
    h1.GetXaxis().SetLabelSize(0.05)
    h1.GetYaxis().SetLabelSize(0.05)
    h1.GetZaxis().SetLabelSize(0.05)
    h1.GetXaxis().SetTitleOffset(1.0) 
    h1.GetYaxis().SetTitleOffset(1.6) 

    HeaderLabel = TPaveLabel(0.2, 0.92, 0.8, 0.98,title,"NDC")
    # HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.8) 
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    if h1.Class().InheritsFrom("TH2"):
        is2D = True
    else:
        is2D = False  

    if is2D:
        c.SetRightMargin(0.15)  
        c.SetLogz(True)  
        HeaderLabel.SetTextSize(0.7) 
Ejemplo n.º 12
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")
Ejemplo n.º 13
0
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")
Ejemplo n.º 14
0
def makeLimitPlot(output,obs,exp,chan,printStats=False):

	fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")

	obsLimits = {}
	
	for obsFile in obs:
		if 'width' in obsFile:
			width = obsFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'
		obsLimits[width] = createObsGraph(obsFile)	

        if  SMOOTH:
		for width,obsGraph in obsLimits.iteritems():
                	smooth_obs=TGraphSmooth("normal")
                	GraphObs_nonSmooth=obsGraph
                	obsLimits[width]=copy.deepcopy(smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005))
                	obsLimits[width].SetLineWidth(3)


	expLimits = {}
	
	for expFile in exp:
		if 'width' in expFile:
			width = expFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'	
		expLimits[width] = createExpGraph(expFile)	

    	cCL=TCanvas("cCL", "cCL",0,0,600,450)
    	gStyle.SetOptStat(0)
	gStyle.SetPadRightMargin(0.063)
	gStyle.SetPadLeftMargin(0.14)
	gStyle.SetPadBottomMargin(0.12)
	
    	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    	plotPad.Draw()	
    	plotPad.cd()


     	smoother=TGraphSmooth("normal")
    	smoother2=TGraphSmooth("normal")
	   

    
    	zprimeX=[]
    	zprimeY=[]
    	fileZPrime=open('tools/xsec_ssm.txt','r')
    	for entries in fileZPrime:
        	entry=entries.split()
        	zprimeX.append(float(entry[0]))
        	zprimeY.append(float(entry[1])/1928)
    	zpX=numpy.array(zprimeX)
    	zpY=numpy.array(zprimeY)
    	GraphZPrime=TGraph(len(zprimeX),zpX,zpY)
    	GraphZPrimeSmooth=smoother2.SmoothSuper(GraphZPrime,"linear")
    	GraphZPrimeSmooth.SetLineWidth(3)
    	GraphZPrimeSmooth.SetLineColor(ROOT.kGreen+3)
    	GraphZPrimeSmooth.SetLineStyle(2)

    	zprimePsiX=[]
    	zprimePsiY=[]
    	fileZPrimePsi=open('tools/xsec_psi.txt','r')
    	for entries in fileZPrimePsi:
        	entry=entries.split()
        	zprimePsiX.append(float(entry[0]))
        	zprimePsiY.append(float(entry[1])/1928)

   	zpPsiX=numpy.array(zprimePsiX)
	zpPsiY=numpy.array(zprimePsiY)
    	GraphZPrimePsi=TGraph(len(zprimePsiX),zpPsiX,zpPsiY)
    	GraphZPrimePsiSmooth=smoother.SmoothSuper(GraphZPrimePsi,"linear")
   	GraphZPrimePsiSmooth.SetLineWidth(3)
    	GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

#Draw the graphs:
    	plotPad.SetLogy()
    	DummyGraph=TH1F("DummyGraph","",100,200,5500)
    	DummyGraph.GetXaxis().SetTitle("M [GeV]")
	if SPIN2:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] G_{KK} / #sigma#upoint#font[12]{B}] Z")
	else:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")



    	gStyle.SetOptStat(0)
    	DummyGraph.GetXaxis().SetRangeUser(200,5500)

    	DummyGraph.SetMinimum(1e-8)
    	DummyGraph.SetMaximum(3e-4)
    	DummyGraph.GetXaxis().SetLabelSize(0.055)
    	DummyGraph.GetXaxis().SetTitleSize(0.055)
   	DummyGraph.GetXaxis().SetTitleOffset(1.05)
    	DummyGraph.GetYaxis().SetLabelSize(0.055)
    	DummyGraph.GetYaxis().SetTitleSize(0.055)
    	DummyGraph.GetYaxis().SetTitleOffset(1.3)

    	DummyGraph.Draw()

    	plCMS=TPaveLabel(.16,.76,.27,.83,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.16,.76,.27,.82,"Preliminary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetBorderSize(0)
#    	plPrelim.Draw()

    	leg=TLegend(0.420517,0.7,0.85,0.878644,"","brNDC")   
    	legWidth=TLegend(0.625,0.5,0.9,0.7,"width","brNDC")   
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.0425)
    	legWidth.SetTextSize(0.0425)
	colors = {'01':ROOT.kBlue,'03':ROOT.kRed,'05':ROOT.kGreen+3,'10':ROOT.kOrange}
#	for width in sorted(obsLimits):
#		obsGraph = obsLimits[width]
#		if colors.has_key(width):
#			obsGraph.SetLineColor(colors[width])
#		obsGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(obsGraph,"Observed 95% CL limit width 0.6%","l")
#		else:	
#			leg.AddEntry(obsGraph,"Observed 95%% CL limit width %d%%"%int(width),"l")
#
#	for width  in sorted(expLimits):
#		expGraph = expLimits[width]
#		if colors.has_key(width):
#			expGraph.SetLineColor(colors[width])
#		expGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(expGraph,"Expected 95% CL limit width 0.6%, median","l")
#		else:	
#			leg.AddEntry(expGraph,"Expected 95%% CL limit width %d%%, median"%(int(width)),"l")

	
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		obsGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(obsGraph,"Obs. 95% CL limit","l")

	for width  in sorted(expLimits):
		expGraph = expLimits[width]
		if colors.has_key(width):
			expGraph.SetLineColor(colors[width])
		expGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(expGraph,"Exp. 95% CL limit, median","l")
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		if width == '0.006':
			legWidth.AddEntry(obsGraph,"0.6%","l")
		else:	
			legWidth.AddEntry(obsGraph,"%d%%"%int(width),"l")


    	if not SPIN2:
        	GraphZPrimeSmooth.Draw("lsame")
        	GraphZPrimePsiSmooth.Draw("lsame")

	leg1=TLegend(0.625,0.35,0.825,0.5,"","brNDC")
	leg1.SetTextSize(0.0375)
	leg1.AddEntry(GraphZPrimeSmooth,"Z'_{SSM} (width 2.97%)","l")	
	leg1.AddEntry(GraphZPrimePsiSmooth,"Z'_{#Psi} (width 0.53%)","l")	
	
    	leg1.SetLineWidth(0)
    	leg1.SetLineStyle(0)
    	leg1.SetLineColor(0)
    	leg1.SetFillStyle(0)
    	leg1.SetBorderSize(0)

	leg1.Draw()

    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#plCMS.Draw()
  	plotPad.SetTicks(1,1)
	plotPad.RedrawAxis()	

	

    	leg.SetLineWidth(0)
    	leg.SetLineStyle(0)
    	leg.SetLineColor(0)
    	leg.Draw("hist")
    	legWidth.SetLineWidth(0)
    	legWidth.SetLineStyle(0)
    	legWidth.SetLineColor(0)
    	legWidth.SetFillStyle(0)
	legWidth.SetNColumns(2)
    	legWidth.Draw("hist")


	if "Moriond" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.885,.9,.99,"36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.27,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
	else:
 	      	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"2.7 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")

    	plLumi.SetTextSize(0.5)
    	plLumi.SetTextFont(42)
    	plLumi.SetFillColor(0)
    	plLumi.SetBorderSize(0)
    	plLumi.Draw()
    

	plotPad.RedrawAxis()
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		obsGraph.SetName("graphObs%s"%width)
		obsGraph.Write("graphObs%s"%width)
	for width in sorted(expLimits):
		expGraph = expLimits[width]
		expGraph.SetName("graphExp%s"%width)
		expGraph.Write("graphExp%s"%width)


   	fileForHEPData.Write()
	fileForHEPData.Close() 


    
    	cCL.Update()
    	printPlots(cCL,output)
Ejemplo n.º 15
0
def report():
    global freed_file
    print'    HeapMonReport.report(): heapmon_file=', freed_file
    
    #findStaticHoles()
          
    tfile = TFile(freed_file, "READ")
    print "   root compression factor = ", tfile.GetCompressionFactor()
   
    mem_canvas = TCanvas("HeapMon_report", "Memory Holes Statistics", 10, 10, 800, 1034);
    mem_canvas.SetFillColor(17);
    mem_canvas.cd()
    
    pad1 = TPad("pad1","pad1",0.01,0.57,0.50,0.93,33);
    pad2 = TPad("pad2","pad2",0.51,0.57,0.99,0.93,33);
    pad3 = TPad("pad3","pad3",0.01,0.01,0.99,0.50,33);
    pad3.SetPhi(210);
    pad3.SetTheta(25);

    pad1.Draw(); pad2.Draw(); pad3.Draw();
    memTree = tfile.Get("holeTree")
    infoTree = tfile.Get("infoTree")
    mallocTree = tfile.Get("mallocTree")
    #holesm_th1i =   TH1I('holesm_th1i', 'Holes size evolution', fcount, 0, fcount)    
    #holesn_th1i =   TH1I('holesn_th1i', 'Holes number evolution', fcount, 0, fcount)  
    #total_th1i  =   TH1I('total_th1i', 'Total memory size evolution', fcount, 0, fcount)
    
    max_hole_size = memTree.GetMaximum("hole_size")
    print "    max_hole_size=", max_hole_size, "    min_hole_size", memTree.GetMinimum("hole_size")
    max_scan_number = memTree.GetMaximum("scan_number")
    print "     max_scan_number=", max_scan_number
    
    memHist1  = TH2I("mem2d","Hole-sizes distribution evolution", 128, -0.5, max_hole_size - 0.5, 50, 0, max_scan_number) 
    memTree.Project("mem2d", "scan_number:hole_size"); 
    
    multiGraph1 = TMultiGraph();
    multiGraph2 = TMultiGraph();

    print " memHist.GetMaximum() = ",    memHist1.GetMaximum();
    
    # Working on a Report
    gStyle.SetOptStat(0);
    gStyle.SetPalette(1);
    gStyle.SetCanvasColor(33);
    gStyle.SetFrameFillColor(18);
    
    memHist1.SetFillColor(30);
    memHist1.SetFillStyle(0);
    memHist1.GetXaxis().SetTitle("Size of holes, kb");
    memHist1.GetXaxis().SetLabelOffset(0.02);
    memHist1.GetXaxis().SetLabelSize(0.02);
    memHist1.GetXaxis().SetTitleSize(0.04);
    memHist1.GetXaxis().SetTitleColor(2);
    memHist1.GetYaxis().SetTitle("Event number");
    memHist1.GetYaxis().SetLabelSize(0.04);
    memHist1.GetXaxis().SetLabelOffset(0.04);
    memHist1.GetYaxis().SetTitleSize(0.04);
    memHist1.GetYaxis().SetTitleColor(2);
    memHist1.GetZaxis().SetTitle("Number of holes");
    memHist1.GetZaxis().SetLabelSize(0.02);
    memHist1.GetZaxis().SetTitleSize(0.04);
    memHist1.GetZaxis().SetTitleColor(2);
    
    title = TPaveLabel(0.1,0.95,0.9,0.99, "Job Memory Usage Plots");
    title.SetFillColor(42);
    title.SetTextFont(42);
    title.Draw();
    
    text_box = TPaveText(0.1,0.51,0.9,0.54);
    text_box.AddText("Malloc freed ('marked') Heap Memory Profile");
    text_box.SetFillColor(42);
    text_box.SetTextAlign(12);
    text_box.SetTextFont(42);
    text_box.Draw();
    
    x1=0.2; y1=0.91; x2=0.8; y2=0.98;

#Drawing upper-left corner Pad1 of the report
    pad1.cd();
    pad1.SetGridx();pad1.SetGridy();
    infoTree.Draw("total_maps_memory:scan_number","", "goff")
    mapsGraph=TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(), infoTree.GetV1());    
    mapsGraph.SetLineColor(1); mapsGraph.SetLineWidth(1); #mapsGraph.SetFillStyle(3001); mapsGraph.SetFillColor(2);
    mapsGraph.SetName("total_maps_memory");
    #VmSize, VmLck, VmRSS, VmData, VmStk, VmExe, VmLib;
    infoTree.Draw("VmSize:scan_number", "","goff"); 
    vmsizeGraph=TGraph(int(infoTree.GetSelectedRows()), infoTree.GetV2(), infoTree.GetV1());    
    vmsizeGraph.SetLineColor(2); vmsizeGraph.SetLineWidth(1); #vmsizeGraph.SetFillStyle(3002); vmsizeGraph.SetFillColor(3);
    vmsizeGraph.SetName("VmSize");
    
    infoTree.Draw("VmRSS:scan_number", "", "goff"); 
    vmrssGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmrssGraph.SetLineColor(3); vmrssGraph.SetLineWidth(1); #vmrssGraph.SetFillStyle(3003); vmrssGraph.SetFillColor(4);
    vmrssGraph.SetName("VmRSS"); 
    
    infoTree.Draw("VmData:scan_number", "", "goff"); 
    vmdataGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmdataGraph.SetLineColor(4); vmdataGraph.SetLineWidth(1); #vmdataGraph.SetFillStyle(3004); vmdataGraph.SetFillColor(4);
    vmdataGraph.SetName("VmData"); 
    
    infoTree.Draw("VmStk:scan_number", "", "goff"); 
    vmstkGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmstkGraph.SetLineColor(5); vmstkGraph.SetLineWidth(1); #vmstkGraph.SetFillStyle(3005); vmstkGraph.SetFillColor(4);
    vmstkGraph.SetName("VmStk")
    
    infoTree.Draw("VmExe:scan_number", "", "goff"); 
    vmexeGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmexeGraph.SetLineColor(6); vmexeGraph.SetLineWidth(1); #vmexeGraph.SetFillStyle(3003); vmexeGraph.SetFillColor(4);
    vmexeGraph.SetName("VmExe");
    
    infoTree.Draw("VmLib:scan_number", "", "goff"); 
    vmlibGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmlibGraph.SetLineColor(7); vmlibGraph.SetLineWidth(1); #vmlibGraph.SetFillStyle(3003); vmlibGraph.SetFillColor(4);
    vmlibGraph.SetName("VmLib");
  
    infoTree.Draw("VmLck:scan_number", "", "goff"); 
    vmlckGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1());
    vmlckGraph.SetLineColor(8); vmlckGraph.SetLineWidth(1); #vmlckGraph.SetFillStyle(3003); vmlckGraph.SetFillColor(4);
    vmlckGraph.SetName("VmLck");

    infoTree.Draw("total_hole_memory:scan_number", "", "goff");
    holeGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1())    
    holeGraph.SetLineColor(9); holeGraph.SetLineWidth(1); #holeGraph.SetFillStyle(3004); holeGraph.SetFillColor(5);
    holeGraph.SetName("HolesSize"); 
        
    mallocTree.Draw("malloc_free:scan_number", "", "goff"); 
    freeGraph=TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1())    
    freeGraph.SetLineColor(11); freeGraph.SetLineWidth(1); freeGraph.SetFillStyle(3003); freeGraph.SetFillColor(4);
    freeGraph.SetName("malloc_free");
    
    mallocTree.Draw("malloc_inuse:scan_number", "", "goff"); 
    inuseGraph=TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1())    
    inuseGraph.SetLineColor(21); inuseGraph.SetLineWidth(1); inuseGraph.SetFillStyle(3003); inuseGraph.SetFillColor(4);
    inuseGraph.SetName("malloc_inuse");

    mallocTree.Draw("malloc_sbrk:scan_number", "", "goff"); 
    sbrkGraph=TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1())    
    sbrkGraph.SetLineColor(31); sbrkGraph.SetLineWidth(1); sbrkGraph.SetFillStyle(3003); sbrkGraph.SetFillColor(4);
    sbrkGraph.SetName("malloc_sbrk");
    
    mallocTree.Draw("malloc_mmap:scan_number", "", "goff"); 
    mmapGraph=TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1())    
    mmapGraph.SetLineColor(41); mmapGraph.SetLineWidth(1); mmapGraph.SetFillStyle(3003); mmapGraph.SetFillColor(4);
    mmapGraph.SetName("malloc_mmap");
    
    pad1.cd();
    multiGraph1.Add(mapsGraph);multiGraph1.Add(vmsizeGraph);
    multiGraph1.Add(vmrssGraph);multiGraph1.Add(vmdataGraph);
    multiGraph1.Add(vmlckGraph);multiGraph1.Add(vmexeGraph);
    multiGraph1.Add(vmstkGraph);#multiGraph1.Add(vmlibGraph);
    multiGraph1.Add(inuseGraph);
    multiGraph1.Add(sbrkGraph);multiGraph1.Add(mmapGraph);
    multiGraph1.Add(holeGraph);multiGraph1.Add(freeGraph);


    
    #multiGraph1.SetTitle("PROCESS VM and Malloc MEMORY USAGE"); 
    title.DrawPaveLabel(x1,y1,x2,y2,"PROCESS VM and Malloc MEMORY USAGE","brNDC");

    multiGraph1.Draw("ALg")
    hist = multiGraph1.GetHistogram(); hist.SetXTitle("Event Number"); hist.SetYTitle("Memory, kb");
    legend1 = TLegend(0.84,0.20,0.99,0.90);
    legend1.AddEntry(mapsGraph,  "Maps",            "l");
    legend1.AddEntry(vmsizeGraph,"VmSize",          "l");
    legend1.AddEntry(vmrssGraph, "VmRSS",           "l");
    legend1.AddEntry(vmdataGraph,"VmData",          "l");

    legend1.AddEntry(sbrkGraph,  "MallocSbrk",      "l");
    legend1.AddEntry(inuseGraph, "MallocInuse",     "l");    
    #legend1.AddEntry(vmlibGraph, "VmLib",          "l");
    legend1.AddEntry(mmapGraph,  "MallocMmap",      "l");    
    legend1.AddEntry(freeGraph,  "MallocFree",      "l");
    legend1.AddEntry(holeGraph,  "Freed-Holes",     "l");     
    legend1.AddEntry(vmstkGraph, "VmStk",           "l");
    legend1.AddEntry(vmexeGraph, "VmExe",           "l");
    legend1.AddEntry(vmlckGraph, "VmLck",           "l");
    legend1.Draw();

    #multiGraph1.Draw("ALg")    
    #title.DrawPaveLabel(x1,y1,x2,y2,"Process Memory Usage Charts","brNDC");
    
    
#Drawing upper-left corner Pad1 of the report
    pad2.cd();
    pad2.SetGridx(); pad2.SetGridy();

    infoTree.Draw("total_hole_memory:scan_number", "", "goff");
    holeGraph=TGraph(infoTree.GetSelectedRows(), infoTree.GetV2(), infoTree.GetV1())    
    holeGraph.SetLineColor(9); holeGraph.SetLineWidth(1); holeGraph.SetFillStyle(3004); holeGraph.SetFillColor(5);
    holeGraph.SetName("total_hole_memory"); 

    mallocTree.Draw("malloc_free:scan_number", "", "goff");
    freeGraph=TGraph(mallocTree.GetSelectedRows(), mallocTree.GetV2(), mallocTree.GetV1())    
    freeGraph.SetLineColor(11); freeGraph.SetLineWidth(1); freeGraph.SetFillStyle(3004); freeGraph.SetFillColor(5);
    freeGraph.SetName("malloc_free");
    
    pad2.cd();
    multiGraph2.Add(holeGraph);
    multiGraph2.Add(freeGraph);
    #multiGraph2.Add(sbrkGraph);
    #multiGraph2.Add(mmapGraph);
    
    #multiGraph2.SetTitle("Free and Marked Holes Memory Graph"); 
    title.DrawPaveLabel(x1,y1,x2,y2,"Malloc Free and Marked Holes Memory","brNDC");
    
    multiGraph2.Draw("ALg")    
    hist = multiGraph2.GetHistogram(); hist.SetXTitle("Event Number"); hist.SetYTitle("Memory, kb");
    
    legend2 = TLegend(0.9,0.30,0.99,0.90);
    legend2.AddEntry(freeGraph,  "Free",   "l");
    legend2.AddEntry(holeGraph,  "Holes",  "l");
    #legend2.AddEntry(inuseGraph, "Inuse",  "l");
    #legend2.AddEntry(mmapGraph,  "Mmap",  "l");
    #legend2.AddEntry(sbrkGraph,  "Sbrk",  "l");

    legend2.Draw()
    #multiGraph2.Draw("ALg")    
    #title.DrawPaveLabel(x1,y1,x2,y2,"Malloc Memory Usage and Deallocation Charts","brNDC");  
  
  #PAD3
    pad3.cd()
    pad3.SetLogz()
    memHist1.Draw("lego2");
    #title.DrawPaveLabel(x1,y1,x2,y2,"TH2I-LEGO2","brNDC");

    mem_canvas.SetBorderSize(1);
    #mem_canvas.Modified()
    mem_canvas.Update()
    mem_canvas.Print(".pdf")
    mem_canvas.Print(".C")