コード例 #1
0
def plotUpperLimits(resultdicts, scanlabels, xlabel, ylabel, outpath):
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/
    tgraphs = []
    tgraphs_observed = []
    up2s = []
    colors = [
        ROOT.kBlack, ROOT.kBlue, ROOT.kRed, 41, ROOT.kGray + 1,
        ROOT.kMagenta + 2, ROOT.kOrange + 7, ROOT.kCyan + 2
    ]
    markers = [20, 21, 22, 23, 24, 25, 26, 32]
    if len(resultdicts) == 2:
        markers = [23, 24]
    for k, r in enumerate(resultdicts):
        values = []
        for key in r.keys():
            values.append(int(key))
        N = len(values)
        values = sorted(values)
        median = ROOT.TGraph(N)  # median line
        observed = ROOT.TGraph(N)  # observed line
        i = 0
        for v in values:
            limit = r[str(v)]
            if unblind and len(limit) < 6:
                raise Exception("Not enougth entries in limit to unblind")
            up2s.append(limit[2])
            if unblind:
                observed.SetPoint(i, values[i], limit[5])  # observed
            median.SetPoint(i, values[i], limit[2])  # median
            i = i + 1
        tgraphs.append(median)
        if unblind: tgraphs_observed.append(observed)
    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = ROOT.TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetYaxis().SetTitle(
        "95% upper limit on #sigma (#Chi#rightarrow HH) [pb]")
    frame.GetXaxis().SetTitle(xlabel)
    frame.SetMinimum(miny)
    frame.SetMaximum(max(up2s) * 1.05)
    if logy:
        frame.SetMaximum(max(up2s) * 15)
    frame.GetXaxis().SetLimits(min(values), max(values))
    if logy:
        c.SetLogy()
    if (maxy > 0.): frame.SetMaximum(maxy)
    tgraphs[0].Draw()
    for i, g in enumerate(tgraphs):
        g.SetLineColor(colors[i])
        print scanlabels.split(":")[i], markers[i]
        g.SetMarkerColor(colors[i])
        g.SetMarkerStyle(markers[i])
        g.SetMarkerSize(1.2)
        if not unblind:
            g.SetLineWidth(2)
            g.Draw("PLSame")
        else:
            g.SetLineStyle(2)
            g.SetLineWidth(1)
            g.Draw("LSame")
    for i, g in enumerate(tgraphs_observed):
        g.SetLineColor(colors[i])
        print scanlabels.split(":")[i], markers[i]
        g.SetMarkerColor(colors[i])
        g.SetMarkerStyle(markers[i])
        g.SetMarkerSize(1.2)
        g.SetLineWidth(2)
        g.Draw("PLSame")

    CMS_lumi.lumi_sqrtS = ylabel
    CMS_lumi.CMS_lumi(c, 0, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    #x1 = 0.459
    x1 = 0.3
    x2 = 0.959
    y2 = 0.9175
    y1 = 0.6675
    legend = ROOT.TLegend(x1, y1, x2, y2)
    #legend.SetFillStyle(0)
    #legend.SetFillColor(1)
    legend.SetNColumns(3)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    if unblind:
        for i, g in enumerate(tgraphs_observed):
            legend.AddEntry(g, scanlabels.split(":")[i], 'PL')
        legend.AddEntry(tgraphs[0], 'expected', 'L')
    else:
        for i, g in enumerate(tgraphs):
            legend.AddEntry(g, scanlabels.split(":")[i], 'PL')
    legend.Draw()
    print " "
    c.SaveAs(outpath)
    c.Close()
コード例 #2
0
  mg_data.Draw("Ape0")
  # histolist[0].Draw("HIST E")
 #  for h in histolist:
 #    h.Draw("HIST E same)")
  # if(histolist[0]):histolist[0].Draw("pe0")
  mg_data.SetMaximum(histolist[0].GetMaximum()*1.3)
  mg_data.GetXaxis().SetNdivisions(405)
  mg_data.GetXaxis().SetTitleSize(0.06)
  mg_data.GetXaxis().SetTitleOffset(0.95)
  mg_data.GetYaxis().SetTitleOffset(1.3)
  mg_data.GetXaxis().SetLabelSize(0.05)
  mg_data.GetYaxis().SetTitleSize(0.06)
  mg_data.GetYaxis().SetLabelSize(0.04)
  mg_data.GetXaxis().SetTitle("Diboson invariant mass [GeV]")
  mg_data.GetYaxis().SetTitle("Mistagging rate")
  CMS_lumi.CMS_lumi(canvas, iPeriod, iPos)
  SetOwnership( l, 1 )
  # l.Draw()
  l2.Draw()
  addInfo.Draw("same")

  cname =" all-hadronic-plots/BkgEff/QCD_" +cat+"_VV_MistaggingRateEff.pdf"
  print "saving canvas %s" %cname
  canvas.SaveAs(cname)
  cname =outdir +"/QCD_" +cat+"_VV_MistaggingRateEff.pdf"
  print "saving canvas %s" %cname
  canvas.SaveAs(cname)
  
  cname =" all-hadronic-plots/BkgEff/QCD_" +cat+"_VV_MistaggingRateEff.C"
  print "saving canvas %s" %cname
  canvas.SaveAs(cname)
コード例 #3
0
ファイル: prettifier.py プロジェクト: EJDomi/CMSDAS-boostedZ
hist2.GetYaxis().SetTitleOffset(0.8)

hist1.SetMarkerStyle(24)
hist2.SetMarkerStyle(24)
hist2.SetMarkerColor(kRed)
hist2.Draw()
#hist3.SetLineColor(kBlue)
#hist3.Draw('SAME')
hist1.SetMarkerColor(kBlue)
hist1.Draw('SAME')

#############################################

leg = TLegend(0.7, 0.7, 0.89, 0.89)
leg.SetFillColor(kWhite)
leg.AddEntry(hist1, 'Z prime 2 TeV', 'P')
leg.AddEntry(hist2, 'Z prime 3 TeV ', 'P')
#leg.AddEntry(hist3,'Down Variation', 'l')
#leg.SetLineColor(kWhite)
#leg.SetHeader('Legend')
leg.Draw()

CMS_lumi.CMS_lumi(c1, 4, iPos)

c1.cd()
c1.Update()

#c1.SaveAs(keyn[0][0]+'.png')
#c1.Write()
############################################
def plot_all(w, ch="el", reg='sig'):

    # These things just have to be kept in memory so that ROOT does not make them disappear in the next loop
    pads = []
    paveTexts = []
    legendsMWV = []

    canvas = TCanvas(ch, ch, 800, 572)
    pad1 = TPad('pad', 'pad', 0., 0., 1., 1.)
    pads.append(pad1)
    # Main MWV plot
    p = plot(w, fitres, normset, ch, reg)
    p.GetXaxis().SetTitle('m_{WV} (GeV)')
    p.GetXaxis().SetTitleSize(0.07)
    p.GetXaxis().SetTitleOffset(0.8)
    p.GetXaxis().SetLabelSize(0.05)
    p.GetYaxis().SetRangeUser(7e-2, 1e4)
    p.GetYaxis().SetTitle('Events / 100 GeV')
    p.GetYaxis().SetTitleSize(0.07)
    p.GetYaxis().SetTitleOffset(0.7)
    p.GetYaxis().SetLabelSize(0.05)

    canvas.cd()
    pad1.Draw()

    pad1.cd()
    pad1.SetLogy()
    pad1.SetTicky()
    pad1.SetBottomMargin(0.13)
    p.Draw()

    # Lumi text and channel
    pad1.cd()
    #if reg=='sb_lo':
    CMS_lumi.lumiTextSize = 0.0
    CMS_lumi.writeExtraText = True
    CMS_lumi.extraText = "Simulation"
    CMS_lumi.cmsTextSize = 0.75
    CMS_lumi.extraOverCmsTextSize = 0.57
    CMS_lumi.relPosY = -0.09
    CMS_lumi.relExtraDX = 0.15
    CMS_lumi.relExtraDY = 0.4
    CMS_lumi.CMS_lumi(pad1, 4, 11)
    #elif reg=='sb_hi':
    CMS_lumi.cmsTextSize = 0.0
    CMS_lumi.writeExtraText = False
    CMS_lumi.lumiTextSize = 0.65
    CMS_lumi.lumiTextOffset = 0.2
    CMS_lumi.CMS_lumi(pad1, 4, 11)

    # Legend
    legMWV = TLegend(0.5, 0.4625, 0.88, 0.9)
    legMWV.SetFillColor(0)
    legMWV.SetFillStyle(0)
    legMWV.SetBorderSize(0)
    legMWV.SetLineColor(0)
    legMWV.SetLineWidth(0)
    legMWV.SetLineStyle(0)
    legMWV.SetTextFont(42)
    legMWV.AddEntry(p.getObject(11), "Signal c_{WWW}/#Lambda^{2}=3.6 TeV^{-2}",
                    "L")
    legMWV.AddEntry(p.getObject(0), "W+jets", "F")
    legMWV.AddEntry(p.getObject(1), "t#bar{t}", "F")
    legMWV.AddEntry(p.getObject(4), "WW", "F")
    legMWV.AddEntry(p.getObject(5), "WZ", "F")
    legMWV.AddEntry(p.getObject(8), "Single t", "F")
    legMWV.AddEntry(p.getObject(10), "Uncertainty", "F")
    legMWV.Draw()
    legendsMWV.append(legMWV)

    canvas.Update()
    canvas.SaveAs('prefit_%s_mWV_%s.pdf' % (ch, reg))
    raw_input(ch)

    for i in pads:
        i.Delete()
コード例 #5
0
ファイル: smsPlotABS.py プロジェクト: susy2015/Limits
    def DrawText(self):
        #redraw axes
        self.c.RedrawAxis()
        # white background
        graphWhite = rt.TGraph(5)
        graphWhite.SetName("white")
        graphWhite.SetTitle("white")
        graphWhite.SetFillColor(rt.kWhite)
        graphWhite.SetFillStyle(1001)
        graphWhite.SetLineColor(rt.kBlack)
        graphWhite.SetLineStyle(1)
        graphWhite.SetLineWidth(3)
        graphWhite.SetPoint(0, self.model.Xmin, self.model.Ymax)
        graphWhite.SetPoint(1, self.model.Xmax, self.model.Ymax)
        graphWhite.SetPoint(2, self.model.Xmax, self.model.Ymax * 0.82)
        graphWhite.SetPoint(3, self.model.Xmin, self.model.Ymax * 0.82)
        #graphWhite.SetPoint(2,self.model.Xmax, self.model.Ymax*0.8)
        #graphWhite.SetPoint(3,self.model.Xmin, self.model.Ymax*0.8)
        graphWhite.SetPoint(4, self.model.Xmin, self.model.Ymax)
        graphWhite.Draw("FSAME")
        graphWhite.Draw("LSAME")
        self.c.graphWhite = graphWhite
        CMS_lumi.writeExtraText = 1
        CMS_lumi.extraText = "Preliminary"
        #CMS_lumi.lumi_13TeV="2.3 fb^{-1}"
        CMS_lumi.lumi_13TeV = "12.9 fb^{-1}"

        CMS_lumi.lumi_sqrtS = "13 TeV"
        iPos = 0
        CMS_lumi.CMS_lumi(self.c, 4, iPos)
        # CMS LABEL
        textCMS = rt.TLatex(0.25, 0.96, "  %s " % (self.preliminary))
        textCMS.SetNDC()
        textCMS.SetTextAlign(13)
        textCMS.SetTextFont(52)
        textCMS.SetTextSize(0.038)
        #textCMS.Draw()
        self.c.textCMS = textCMS
        # MODEL LABEL
        if self.model.extraText:
            textModelLabel = rt.TLatex(0.17, 0.91, "%s" % self.model.label)
        else:
            textModelLabel = rt.TLatex(0.17, 0.91, "%s" % self.model.label)
        textModelLabel.SetNDC()
        textModelLabel.SetTextAlign(13)
        textModelLabel.SetTextFont(42)
        textModelLabel.SetTextSize(0.035)
        #textModelLabel.SetTextSize(0.03)
        textModelLabel.Draw()
        self.c.textModelLabel = textModelLabel
        # NLO NLL XSEC
        textNLONLL = rt.TLatex(0.15, 0.8625, "NLO+NLL exclusion")
        textNLONLL.SetNDC()
        textNLONLL.SetTextAlign(13)
        textNLONLL.SetTextFont(42)
        textNLONLL.SetTextSize(0.035)
        #         if self.model.extraText :
        #             textNLONLL.Draw()
        self.c.textNLONLL = textNLONLL

        if self.model.extraText:
            xRange = self.model.Xmax - self.model.Xmin
            yRange = self.model.Ymax - self.model.Ymin

            textExtra1 = rt.TLatex(0.17, 0.81, self.model.extratext1)
            textExtra1.SetNDC()
            textExtra1.SetTextFont(42)
            textExtra1.SetTextSize(0.030)
            textExtra1.Draw()
            self.c.textExtra1 = textExtra1

            textExtra2 = rt.TLatex(0.17, 0.7, self.model.extratext2)
            textExtra2.SetNDC()
            textExtra2.SetTextFont(42)
            textExtra2.SetTextSize(0.030)
            textExtra2.Draw()
            self.c.textExtra2 = textExtra2
コード例 #6
0
def loopIntoIt(files, key, outputFolder):
    #############################################
    if (key.IsA().InheritsFrom("TDirectory")):
        #print key.GetName(), "is a directory in ",key.GetPath()
        here = key.GetPath().split(":", 1)[1]
        #print here
        ROOT.gSystem.MakeDirectory(outputFolder + here)
        files[0].cd(str(key.GetPath()))
        the_dir = ROOT.gDirectory
        dirList = ROOT.gDirectory.GetListOfKeys()
        for k in dirList:
            obj_array = []
            obj1 = k.ReadObj()
            if (obj1.IsA().InheritsFrom("TH1")
                ):  #and "h2_" not in obj1.GetName()):
                if (obj1.IsA().InheritsFrom("TH2")):
                    continue

                increment_count()
                print "processed ", nplots, " histograms"
                #if (nplots>10):
                #    return

                #print obj1.GetName()," is an histogram in ",key.GetPath()

                listOfAcceptedHistograms = ["Residuals"]

                searchpath = key.GetPath().split(":/", 1)[1]
                if (listOfAcceptedHistograms[0]
                        in key.GetPath()):  #obj1.GetName()):
                    continue

                for the_file in files:
                    the_file.cd(searchpath)
                    kf = ROOT.gDirectory.GetListOfKeys().FindObject(
                        obj1.GetName())
                    objf = kf.ReadObj()
                    obj_array.append(objf)

                arr = []
                for h1 in obj_array:
                    if (h1.GetSumOfWeights() !=
                            0):  #and ("p_" not in obj1.GetName())):
                        ##h1.Scale(100/h1.GetSumOfWeights())
                        ##h1.Scale(1/1000.)
                        arr.append(h1)

                the_extrema = getExtrema(arr)
                for h1 in obj_array:
                    if thetypes[obj_array.index(h1)]:
                        doFill = False
                    else:
                        #if (obj_array.index(h1)>0):
                        doFill = True
                        #print "themarker is :",themarkers[obj_array.index(h1)]
                    makeNicePlotStyle(h1, thecolors[obj_array.index(h1)],
                                      themarkers[obj_array.index(h1)],
                                      the_extrema, doFill)

                compound = str(obj1.GetName()) + "_" + str(key.GetName())

                #####################################
                ##
                ## Standard plot canvas
                ##
                #####################################

                c1 = ROOT.TCanvas("c1_" + compound, "c1_" + compound, 800, 800)
                c1.cd()

                if ("prof_" not in obj1.GetName()):
                    for h1 in obj_array:
                        if thetypes[obj_array.index(h1)]:
                            if obj_array.index(h1) == 0:
                                h1.Draw("PE1")
                            else:
                                h1.Draw("PE1sames")
                        else:
                            if obj_array.index(h1) == 0:
                                h1.Draw("HIST")
                            else:
                                h1.Draw("HISTsames")
                else:
                    obj_array[0].Draw("PE1")
                    for h1 in obj_array:
                        h1.Draw("PE1sames")

                CMS_lumi.CMS_lumi(c1, iPeriod, iPos)
                c1.Draw()

                clones = []
                for h1 in obj_array:
                    clone = h1.Clone()
                    clones.append(clone)

                    #stats = h1.FindObject("stats")
                    #makeNiceStats(stats,obj_array.index(h1))
                    #stats.Draw("same")

                myleg = makeNiceTLegend(obj_array, thelabels)
                myleg.Draw("same")
                (p1, p2, p3) = makeNicePaveTest()
                #p1.Draw("same")
                #p2.Draw("same")
                #p3.Draw("same")

                #c1.Print()
                #c1.RedrawAxis()
                #frame = c1.GetFrame()
                #frame.Draw()

                c1.SaveAs(outputFolder + here + "/c1_" + compound + ".png")
                c1.SaveAs(outputFolder + here + "/c1_" + compound + ".pdf")
                #c1.SaveAs(outputFolder+here+"/c1_"+compound+".root")

                #####################################
                ##
                ## ratio plot canvas
                ##
                #####################################

                c1ratio = ROOT.TCanvas("c1_ratio_%s" % c1.GetName(),
                                       "c1_ratio_%s" % c1.GetName(), 800, 800)
                # upper pad
                pad = ROOT.TPad("mainPad_%s" % c1.GetName(),
                                "mainPad_%s" % c1.GetName(), 0., 0.17, 1., 1.)
                pad.SetFillStyle(4000)
                ## lower pad
                pad_ratio = ROOT.TPad('ratioPad_%s' % c1.GetName(),
                                      'ratioPad_%s' % c1.GetName(), 0., 0., 1.,
                                      0.29)
                pad_ratio.SetFillStyle(4000)
                pad_ratio.SetBottomMargin(0.45)
                pad.Draw()
                pad_ratio.Draw()

                pad.cd()

                ratio_hists = []
                denom_hists = []
                for clone in clones:
                    ratio = clone.Clone(clone.GetName() +
                                        "_%s" % clones.index(clone))
                    if ("prof_" in obj1.GetName()
                            and obj1.IsA().InheritsFrom("TProfile")):
                        ratio = ratio.ProjectionX()

                        #### old logic
                        # if (clones.index(clone)!=0):
                        #     ratio_hists.append(ratio)
                        #     if ("p_" not in obj1.GetName()):
                        #         clone.Draw("HISTsames")
                        #     else:
                        #         clone.Draw("HISTsames")
                        # else:
                        #     denom_hists.append(ratio)
                        #     if ("p_" not in obj1.GetName()):
                        #         clone.Draw("PE1")
                        #     else:
                        #         clone.Draw("PE1")

                    if thetypes[clones.index(clone)]:
                        # if this is data
                        if clones.index(clone) == 0:
                            denom_hists.append(ratio)
                            clone.Draw("PE1")
                        else:
                            ratio_hists.append(ratio)
                            clone.Draw("PE1same")
                    else:
                        # if this is mc
                        if clones.index(clone) == 0:
                            denom_hists.append(ratio)
                            clone.Draw("HIST")
                        else:
                            ratio_hists.append(ratio)
                            clone.Draw("HISTsame")

                    #stats = clone.FindObject("stats")
                    #makeNiceStats(stats,clones.index(clone))
                    #stats.Draw("same")

                    clone.GetXaxis().SetLabelSize(0.)

                myleg.Draw("same")
                (p1r, p2r, p3r) = makeNicePaveTest(True)
                #p1r.Draw("same")
                #p2r.Draw("same")
                #p3r.Draw("same")

                pad_ratio.cd()

                nbins = obj1.GetNbinsX()
                flatline = ROOT.TH1F("flatline_%s" % c1.GetName(),
                                     "flatline_%s" % c1.GetName(), nbins,
                                     obj1.GetXaxis().GetBinLowEdge(1),
                                     obj1.GetXaxis().GetBinLowEdge(nbins + 1))

                flatline.SetMarkerSize(0)
                makeNicePlotStyle(flatline, ROOT.kBlue, 20, (0., 2.))
                flatline.SetLineColor(ROOT.kBlue)
                flatline.SetLineStyle(9)
                flatline.SetFillStyle(0)
                flatline.SetLineWidth(2)
                flatline.SetTitle("")

                for i in xrange(1, nbins + 1):
                    flatline.SetBinContent(i, 1)
                    flatline.SetBinError(i, 0)

                for ratio in ratio_hists:
                    ratio.Divide(denom_hists[0])
                    ratio.SetTitle("")
                    makeNicePlotStyle(ratio,
                                      thecolors[ratio_hists.index(ratio) + 1],
                                      themarkers[ratio_hists.index(ratio) + 1],
                                      (0., 2.))
                    ratio.SetLineColor(thecolors[ratio_hists.index(ratio) + 1])
                    ratio.GetXaxis().SetTitleSize(0.19)
                    ratio.GetYaxis().SetTitleSize(0.19)
                    ratio.GetXaxis().SetTitleOffset(1.0)
                    ratio.GetYaxis().SetTitleOffset(0.45)
                    ratio.GetXaxis().SetLabelFont(42)
                    ratio.GetYaxis().SetLabelFont(42)
                    ratio.GetXaxis().SetLabelOffset(0.009)
                    ratio.GetYaxis().SetLabelOffset(0.009)
                    ratio.GetYaxis().SetLabelSize(0.16)
                    ratio.GetXaxis().SetLabelSize(0.16)
                    ratio.GetYaxis().SetNdivisions(505)
                    ratio.GetYaxis().SetRangeUser(0., 1.89)
                    ratio.GetYaxis().SetTitle("ratio")
                    if (ratio_hists.index(ratio) == 0):
                        ratio.Draw("P")
                    else:
                        ratio.Draw("Psames")
                    ratio.Draw("e1sames")
                    ratio.SetStats(ROOT.kFALSE)

                flatline.Draw("e1same")
                flatline.SetStats(ROOT.kFALSE)

                # #stack_ratio.GetYaxis().SetNdivisions(507) # Avoids crowded labels
                CMS_lumi.CMS_lumi(c1ratio, iPeriod, iPos)
                c1ratio.Draw()
                c1ratio.Update()

                c1ratio.SaveAs(outputFolder + here + "/c1_ratio_" + compound +
                               ".png")
                c1ratio.SaveAs(outputFolder + here + "/c1_ratio_" + compound +
                               ".pdf")
                #c1ratio.SaveAs(outputFolder+here+"/c1_ratio"+compound+".root")

                #####################################
                ##
                ## log scale plot canvas
                ##
                #####################################

                c1log = ROOT.TCanvas("c1log_" + compound, "c1log_" + compound,
                                     800, 800)
                c1log.cd().SetLogy()

                #print "min1:",obj1.GetMinimum()," min2:",obj2.GetMinimum()
                for h1 in obj_array:
                    #print "min:",the_extrema[1],"max:",the_extrema[0]
                    dr = the_extrema[1] - the_extrema[0]

                    #log(max+ov) = 5/4*log(max)  ---> max+ov = 10^{5/4*log(max)}

                    if ((h1.GetMinimum() > 0.)):
                        h1.GetYaxis().SetRangeUser(
                            the_extrema[0],
                            the_extrema[1] + ROOT.TMath.Power(10, dr))
                        #h1.GetYaxis().UnZoom()
                    else:
                        h1.GetYaxis().SetRangeUser(
                            0.01,
                            ROOT.TMath.Power(
                                10,
                                1.3 * ROOT.TMath.Log10(10 * the_extrema[1])))
                        #h1.GetYaxis().SetRangeUser(0.01,the_extrema[1]+ROOT.TMath.Power(10,dr))
                        #h1.GetYaxis().UnZoom()

                    if ("prof_" not in obj1.GetName()):
                        if thetypes[obj_array.index(h1)]:
                            if obj_array.index(h1) == 0:
                                h1.Draw("PE1")
                            else:
                                h1.Draw("PE1sames")
                        else:
                            if obj_array.index(h1) == 0:
                                h1.Draw("HIST")
                            else:
                                h1.Draw("HISTsames")
                    else:
                        if obj_array.index(h1) == 0:
                            h1.Draw("PE1")
                        else:
                            h1.Draw("PE1sames")

                    #stats = h1.FindObject("stats")
                    #makeNiceStats(stats,obj_array.index(h1))
                    #stats.Draw("same")

                CMS_lumi.CMS_lumi(c1log, iPeriod, iPos)
                c1log.Draw()
                myleg.Draw("same")
                #p1.Draw("same")
                #p2.Draw("same")
                #p3.Draw("same")

                c1log.SaveAs(outputFolder + here + "/c1_log_" + compound +
                             ".png")
                c1log.SaveAs(outputFolder + here + "/c1_log_" + compound +
                             ".pdf")
                #c1log.SaveAs(outputFolder+here+"/c1log_"+compound+".root")

            elif (obj1.IsA().InheritsFrom("TDirectory")):
                print "here: ", ROOT.gDirectory.GetName()
                loopIntoIt(files, obj1, outputFolder)

    elif (key.IsA().InheritsFrom("TH1")):
        print key.GetName(), " is an histogram"
        increment_count()
        #print "processed ",nplots," histograms"
        #if (nplots>100):
        #    return

        #print obj1.GetName()," is an histogram in ",key.GetPath()
        searchpath = key.GetPath().split(":/", 1)[1]

        files[0].cd(searchpath)
        k2 = ROOT.gDirectory.GetListOfKeys().FindObject(obj1.GetName())
        obj2 = k2.ReadObj()

        arr = []
        arr.append(obj1)
        arr.append(obj2)

        the_extrema = getExtrema(arr)
        makeNicePlotStyle(obj1, ROOT.kBlue, 20, the_extrema)
        makeNicePlotStyle(obj2, ROOT.kRed, 20, the_extrema)

        compound = str(obj1.GetName()) + "_" + str(key.GetName())
        c1 = ROOT.TCanvas("c1_" + compound, "c1_" + compound, 800, 600)
        c1.cd()
        if ("prof_" not in obj1.GetName()):
            obj1.Draw("HIST")
        else:
            obj1.Draw("CP")
            obj2.Draw("CPsames")

        c1.Draw()
        ## syntax obj1,obj2,label1,label2
        myleg = makeNiceTLegend(obj1, obj2, obj3, "53X", "70X_PESS", "70X_OPT")
        myleg.Draw("same")

        #st1 = obj1.FindObject("stats")
        #st2 = obj2.FindObject("stats")
        #makeNiceStats(st1,ROOT.kBlue,st2,ROOT.kRed,st3,ROOT.kBlack)
        #st1.Draw("same")
        #st2.Draw("same")

        c1.SaveAs(outputFolder + here + "/c1_" + compound + ".pdf")
コード例 #7
0
for i in range(0, 10):
    gForward.Fit(g2, "EX0FRU")

gForward.Draw("PEsame")

# sF = TSpline3("SPLINE_massResolution_1v3eta2v5",gForward,"",fitmin,fitmax)
# sF.SetLineColor(kBlue)
# s2.Draw("same")
# gForward.Draw("PEsame")
massReso_central = gCentral.GetFunction("massResolution_0eta1v3")
massReso_forward = gForward.GetFunction("massResolution_1v3eta2v5")

filename = "weights/puppiSoftdropResol"
f = TFile("%s.root" % filename, "UPDATE")
print "Writing to file ", f.GetName()
massReso_central.Write("", TObject.kOverwrite)
massReso_forward.Write("", TObject.kOverwrite)
# sC.Write("",TObject.kOverwrite)
# sF.Write("",TObject.kOverwrite)
canv.Write("", TObject.kOverwrite)
f.Close()

l.Draw("same")
CMS_lumi.CMS_lumi(canv, iPeriod, iPos)
canv.RedrawAxis()
canv.Update()
canvname = "puppiSoftdropResol_fit.pdf"
canv.SaveAs(canvname, "pdf")
canv.SaveAs(canvname.replace("pdf", "root"), "pdf")
time.sleep(205)
コード例 #8
0
ファイル: etaDistro.py プロジェクト: adeyta/RPC
def eta_plot(X0W, Y0W, X1W, Y1W, X2W, Y2W, X3W, Y3W, X4W, Y4W, X5W, Y5W, X6W,
             Y6W, X7W, Y7W, X8W, Y8W, X9W, Y9W, X10W, Y10W, X11W, Y11W, X12W,
             Y12W, X13W, Y13W, X0E, Y0E, X1E, Y1E, X2E, Y2E, X3E, Y3E, X4E,
             Y4E, X5E, Y5E, X6E, Y6E, X7E, Y7E, X8E, Y8E, X9E, Y9E, X10E, Y10E,
             X11E, Y11E, X12E, Y12E, X13E, Y13E):
    print "------ Setting Up Format ----------"
    tdrstyle.setTDRStyle()
    #change the CMS_lumi variables (see CMS_lumi.py)
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    CMS_lumi.extraText2 = "2018 pp data"
    CMS_lumi.lumi_sqrtS = "13 TeV"  # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
    CMS_lumi.writeTitle = 1
    CMS_lumi.textTitle = 'title'

    iPos = 11
    if (iPos == 0): CMS_lumi.relPosX = 0.12

    H_ref = 600
    W_ref = 800
    W = W_ref
    H = H_ref
    iPeriod = 0
    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    print "------ Creating Wheel TGraph ----------"
    n0W = len(X0W)
    gr0W = TGraph(n0W, X0W, Y0W)
    gr0W.SetMarkerColor(kRed)
    gr0W.SetMarkerStyle(20)
    gr0W.SetMarkerSize(1.5)
    gr0W.SetTitle('RB1 in')
    gr0W.GetXaxis().SetTitle('#eta')
    gr0W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n1W = len(X1W)
    gr1W = TGraph(n1W, X1W, Y1W)
    gr1W.SetLineColor(2)
    gr1W.SetLineWidth(4)
    gr1W.SetMarkerColor(kBlue)
    gr1W.SetMarkerStyle(29)
    gr1W.SetMarkerSize(1.7)
    gr1W.SetTitle('Layer 1 Wheel')
    gr1W.GetXaxis().SetTitle('#eta')
    gr1W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n2W = len(X2W)
    gr2W = TGraph(n2W, X2W, Y2W)
    gr2W.SetLineColor(3)
    gr2W.SetLineWidth(5)
    gr2W.SetMarkerColor(kRed + 2)
    gr2W.SetMarkerStyle(21)
    gr2W.SetMarkerSize(1.5)
    gr2W.SetTitle('Layer 2 Wheel')
    gr2W.GetXaxis().SetTitle('#eta')
    gr2W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n3W = len(X3W)
    gr3W = TGraph(n3W, X3W, Y3W)
    gr3W.SetLineColor(4)
    gr3W.SetLineWidth(6)
    gr3W.SetMarkerColor(kRed)
    gr3W.SetMarkerStyle(21)
    gr3W.SetMarkerSize(1.5)
    gr3W.SetTitle('Layer 3 Wheel')
    gr3W.GetXaxis().SetTitle('#eta')
    gr3W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n4W = len(X4W)
    gr4W = TGraph(n4W, X4W, Y4W)
    gr4W.SetLineColor(5)
    gr4W.SetLineWidth(7)
    gr4W.SetMarkerColor(kBlue)
    gr4W.SetMarkerStyle(23)
    gr4W.SetMarkerSize(1.5)
    gr4W.SetTitle('Layer 4 Wheel')
    gr4W.GetXaxis().SetTitle('#eta')
    gr4W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    print "------ Creating Endcap TGraph ----------"
    n0E = len(X0E)
    gr0E = TGraph(n0E, X0E, Y0E)
    gr0E.SetLineColor(2)
    gr0E.SetLineWidth(4)
    gr0E.SetMarkerColor(kRed)
    gr0E.SetMarkerStyle(24)
    gr0E.SetMarkerSize(1.5)
    gr0E.SetTitle('Layer 1 Endcap')
    gr0E.GetXaxis().SetTitle('#eta')
    gr0E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n1E = len(X1E)
    gr1E = TGraph(n1E, X1E, Y1E)
    gr1E.SetLineColor(2)
    gr1E.SetLineWidth(4)
    gr1E.SetMarkerColor(kBlue)
    gr1E.SetMarkerStyle(30)
    gr1E.SetMarkerSize(1.5)
    gr1E.SetTitle('Layer 1 Endcap')
    gr1E.GetXaxis().SetTitle('#eta')
    gr1E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n2E = len(X2E)
    gr2E = TGraph(n2E, X2E, Y2E)
    gr2E.SetLineColor(3)
    gr2E.SetLineWidth(5)
    gr2E.SetMarkerColor(kRed + 2)
    gr2E.SetMarkerStyle(25)
    gr2E.SetMarkerSize(1.5)
    gr2E.SetTitle('Layer 2 Endcap')
    gr2E.GetXaxis().SetTitle('#eta')
    gr2E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n3E = len(X3E)
    gr3E = TGraph(n3E, X3E, Y3E)
    gr3E.SetLineColor(4)
    gr3E.SetLineWidth(6)
    gr3E.SetMarkerColor(kRed)
    gr3E.SetMarkerStyle(25)
    gr3E.SetMarkerSize(1.5)
    gr3E.SetTitle('Layer 3 Endcap')
    gr3E.GetXaxis().SetTitle('#eta')
    gr3E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n4E = len(X4E)
    gr4E = TGraph(n4E, X4E, Y4E)
    gr4E.SetLineColor(5)
    gr4E.SetLineWidth(7)
    gr4E.SetMarkerColor(kBlue)
    gr4E.SetMarkerStyle(32)
    gr4E.SetMarkerSize(1.5)
    gr4E.SetTitle('Layer 4 Endcap')
    gr4E.GetXaxis().SetTitle('#eta')
    gr4E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    print "------ Creating Wheel TGraph ----------"
    n5W = len(X5W)
    gr5W = TGraph(n5W, X5W, Y5W)
    gr5W.SetLineColor(2)
    gr5W.SetLineWidth(4)
    gr5W.SetMarkerColor(6)
    gr5W.SetMarkerStyle(22)
    gr5W.SetMarkerSize(1.5)
    gr5W.SetTitle('Layer 1 Wheel')
    gr5W.GetXaxis().SetTitle('#eta')
    gr5W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n6W = len(X6W)
    gr6W = TGraph(n6W, X6W, Y6W)
    gr6W.SetLineColor(3)
    gr6W.SetLineWidth(5)
    gr6W.SetMarkerColor(28)
    gr6W.SetMarkerStyle(23)
    gr6W.SetMarkerSize(1.7)
    gr6W.SetTitle('Layer 2 Wheel')
    gr6W.GetXaxis().SetTitle('#eta')
    gr6W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n7W = len(X7W)
    gr7W = TGraph(n7W, X7W, Y7W)
    gr7W.SetLineColor(4)
    gr7W.SetLineWidth(6)
    gr7W.SetMarkerColor(kRed)
    gr7W.SetMarkerStyle(20)
    gr7W.SetMarkerSize(1.5)
    gr7W.SetTitle('Layer 3 Wheel')
    gr7W.GetXaxis().SetTitle('#eta')
    gr7W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n8W = len(X8W)
    gr8W = TGraph(n8W, X8W, Y8W)
    gr8W.SetLineColor(5)
    gr8W.SetLineWidth(7)
    gr8W.SetMarkerColor(kBlue)
    gr8W.SetMarkerStyle(29)
    gr8W.SetMarkerSize(1.5)
    gr8W.SetTitle('Layer 4 Wheel')
    gr8W.GetXaxis().SetTitle('#eta')
    gr8W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n9W = len(X9W)
    gr9W = TGraph(n9W, X9W, Y9W)
    gr9W.SetLineColor(5)
    gr9W.SetLineWidth(7)
    gr9W.SetMarkerColor(kRed + 2)
    gr9W.SetMarkerStyle(21)
    gr9W.SetMarkerSize(1.5)
    gr9W.SetTitle('Layer 4 Wheel')
    gr9W.GetXaxis().SetTitle('#eta')
    gr9W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n10W = len(X10W)
    gr10W = TGraph(n10W, X10W, Y10W)
    gr10W.SetLineColor(5)
    gr10W.SetLineWidth(7)
    gr10W.SetMarkerColor(kRed)
    gr10W.SetMarkerStyle(21)
    gr10W.SetMarkerSize(1.5)
    gr10W.SetTitle('Layer 4 Wheel')
    gr10W.GetXaxis().SetTitle('#eta')
    gr10W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n11W = len(X11W)
    gr11W = TGraph(n11W, X11W, Y11W)
    gr11W.SetLineColor(5)
    gr11W.SetLineWidth(7)
    gr11W.SetMarkerColor(kBlue)
    gr11W.SetMarkerStyle(23)
    gr11W.SetMarkerSize(1.5)
    gr11W.SetTitle('Layer 4 Wheel')
    gr11W.GetXaxis().SetTitle('#eta')
    gr11W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n12W = len(X12W)
    gr12W = TGraph(n12W, X12W, Y12W)
    gr12W.SetLineColor(5)
    gr12W.SetLineWidth(7)
    gr12W.SetMarkerColor(6)
    gr12W.SetMarkerStyle(22)
    gr12W.SetMarkerSize(1.5)
    gr12W.SetTitle('Layer 4 Wheel')
    gr12W.GetXaxis().SetTitle('#eta')
    gr12W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n13W = len(X13W)
    gr13W = TGraph(n13W, X13W, Y13W)
    gr13W.SetLineColor(5)
    gr13W.SetLineWidth(7)
    gr13W.SetMarkerColor(28)
    gr13W.SetMarkerStyle(23)
    gr13W.SetMarkerSize(1.5)
    gr13W.SetTitle('Layer 4 Wheel')
    gr13W.GetXaxis().SetTitle('#eta')
    gr13W.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    print "------ Creating Endcap TGraph ----------"
    n5E = len(X5E)
    gr5E = TGraph(n5E, X5E, Y5E)
    gr5E.SetLineColor(2)
    gr5E.SetLineWidth(4)
    gr5E.SetMarkerColor(6)
    gr5E.SetMarkerStyle(26)
    gr5E.SetMarkerSize(1.5)
    gr5E.SetTitle('Layer 1 Endcap')
    gr5E.GetXaxis().SetTitle('#eta')
    gr5E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n6E = len(X6E)
    gr6E = TGraph(n6E, X6E, Y6E)
    gr6E.SetLineColor(3)
    gr6E.SetLineWidth(5)
    gr6E.SetMarkerColor(28)
    gr6E.SetMarkerStyle(32)
    gr6E.SetMarkerSize(1.5)
    gr6E.SetTitle('Layer 2 Endcap')
    gr6E.GetXaxis().SetTitle('#eta')
    gr6E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n7E = len(X7E)
    gr7E = TGraph(n7E, X7E, Y7E)
    gr7E.SetLineColor(4)
    gr7E.SetLineWidth(6)
    gr7E.SetMarkerColor(kRed)
    gr7E.SetMarkerStyle(24)
    gr7E.SetMarkerSize(1.5)
    gr7E.SetTitle('Layer 3 Endcap')
    gr7E.GetXaxis().SetTitle('#eta')
    gr7E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n8E = len(X8E)
    gr8E = TGraph(n8E, X8E, Y8E)
    gr8E.SetLineColor(5)
    gr8E.SetLineWidth(7)
    gr8E.SetMarkerColor(kBlue)
    gr8E.SetMarkerStyle(30)
    gr8E.SetMarkerSize(1.5)
    gr8E.SetTitle('Layer 4 Endcap')
    gr8E.GetXaxis().SetTitle('#eta')
    gr8E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n9E = len(X9E)
    gr9E = TGraph(n9E, X9E, Y9E)
    gr9E.SetLineColor(5)
    gr9E.SetLineWidth(7)
    gr9E.SetMarkerColor(kRed + 2)
    gr9E.SetMarkerStyle(25)
    gr9E.SetMarkerSize(1.5)
    gr9E.SetTitle('Layer 4 Endcap')
    gr9E.GetXaxis().SetTitle('#eta')
    gr9E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n10E = len(X10E)
    gr10E = TGraph(n10E, X10E, Y10E)
    gr10E.SetLineColor(5)
    gr10E.SetLineWidth(7)
    gr10E.SetMarkerColor(kRed)
    gr10E.SetMarkerStyle(25)
    gr10E.SetMarkerSize(1.5)
    gr10E.SetTitle('Layer 4 Endcap')
    gr10E.GetXaxis().SetTitle('#eta')
    gr10E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n11E = len(X11E)
    gr11E = TGraph(n11E, X11E, Y11E)
    gr11E.SetLineColor(5)
    gr11E.SetLineWidth(7)
    gr11E.SetMarkerColor(kBlue)
    gr11E.SetMarkerStyle(32)
    gr11E.SetMarkerSize(1.5)
    gr11E.SetTitle('Layer 4 Endcap')
    gr11E.GetXaxis().SetTitle('#eta')
    gr11E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n12E = len(X12E)
    gr12E = TGraph(n12E, X12E, Y12E)
    gr12E.SetLineColor(5)
    gr12E.SetLineWidth(7)
    gr12E.SetMarkerColor(6)
    gr12E.SetMarkerStyle(26)
    gr12E.SetMarkerSize(1.5)
    gr12E.SetTitle('Layer 4 Endcap')
    gr12E.GetXaxis().SetTitle('#eta')
    gr12E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    n13E = len(X13E)
    gr13E = TGraph(n13E, X13E, Y13E)
    gr13E.SetLineColor(5)
    gr13E.SetLineWidth(7)
    gr13E.SetMarkerColor(28)
    gr13E.SetMarkerStyle(32)
    gr13E.SetMarkerSize(1.5)
    gr13E.SetTitle('Layer 4 Endcap')
    gr13E.GetXaxis().SetTitle('#eta')
    gr13E.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')

    print "----- Creating TCanvas -----"
    H = 800
    W = 1600
    canv = TCanvas("c1", "Canvas", 50, 50, W, H)
    canv.SetFillColor(0)
    canv.SetBorderMode(0)
    canv.SetFrameFillStyle(0)
    canv.SetFrameBorderMode(0)
    canv.SetLeftMargin(L / W)
    canv.SetRightMargin(R / W)
    canv.SetTopMargin(T / H)
    canv.SetBottomMargin(B / H)
    canv.SetTickx(0)
    canv.SetTicky(0)
    canv.Divide(3, 2, 0.001, 0.001)
    CMS_lumi.CMS_lumi(canv, iPeriod, iPos)
    canv.cd()
    canv.Update()
    maxY = 1000

    canv.cd(1)
    gPad.SetLogy()
    print " ------------ Creating TMultiGraph -----------"
    mg1 = TMultiGraph()
    #graphAxis(mg1)
    mg1.Add(gr0E, "AP")
    mg1.Add(gr0W, "AP")
    mg1.Add(gr7E, "AP")
    mg1.Add(gr7W, "AP")
    mg1.Draw("a")
    mg1.SetTitle('RB1in')
    mg1.GetXaxis().SetTitle('#eta')
    mg1.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg1.SetMaximum(maxY)
    mg1.GetXaxis().SetLabelFont(42)
    mg1.GetXaxis().SetLabelOffset(0.007)
    mg1.GetXaxis().SetLabelSize(0.043)
    mg1.GetXaxis().SetTitleSize(0.05)
    mg1.GetXaxis().SetTitleOffset(1.06)
    mg1.GetXaxis().SetTitleFont(42)
    mg1.GetYaxis().SetLabelFont(42)
    mg1.GetYaxis().SetLabelOffset(0.008)
    mg1.GetYaxis().SetLabelSize(0.05)
    mg1.GetYaxis().SetTitleSize(0.06)
    mg1.GetYaxis().SetTitleOffset(0.87)
    mg1.GetYaxis().SetTitleFont(42)

    pvtxt = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvtxt.AddText('CMS Preliminary')
    pvtxt.SetFillStyle(0)
    pvtxt.SetBorderSize(0)
    pvtxt.SetTextSize(0.03)
    pvtxt.Draw()
    pvtxt100 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvtxt100.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvtxt100.SetFillStyle(0)
    pvtxt100.SetBorderSize(0)
    pvtxt100.SetTextSize(0.03)
    pvtxt100.Draw()

    canv.cd(2)
    gPad.SetLogy()
    gr00 = TGraph()
    gr00.SetMarkerColor(kBlack)
    gr00.SetMarkerStyle(20)
    gr00.SetMarkerSize(1.5)
    gr01 = TGraph()
    gr01.SetMarkerColor(kBlack)
    gr01.SetMarkerStyle(24)
    gr01.SetMarkerSize(1.5)

    legend0 = TLegend(0.2, 0.7, .8, .9)
    legend0.SetNColumns(1)
    legend0.AddEntry(gr00, "Barrel", "p")
    legend0.AddEntry(gr01, "Endcaps", "p")
    legend0.Draw("a same")

    legendi = TLegend(0.2, 0.2, .8, .6)
    legendi.SetNColumns(1)
    legendi.AddEntry(gr7W, "RB1in  + RE1", "p")
    legendi.AddEntry(gr8W, "RB1out + RE1", "p")
    legendi.AddEntry(gr9W, "RB2 + RE2", "p")
    #  legendi.AddEntry(gr10W, "RB2in  + RE2" , "p")
    #  legendi.AddEntry(gr11W, "RB2out + RE2" , "p")
    legendi.AddEntry(gr12W, "RB3 + RE3", "p")
    legendi.AddEntry(gr13W, "RB4 + RE4", "p")
    legendi.SetTextSize(0.05)
    legendi.Draw("a")

    canv.cd(3)
    gPad.SetLogy()
    mg2 = TMultiGraph()
    mg2.Add(gr1E, "AP")
    mg2.Add(gr1W, "AP")
    mg2.Add(gr8E, "AP")
    mg2.Add(gr8W, "AP")
    mg2.Draw("a")
    mg2.SetTitle('RB1out')
    mg2.GetXaxis().SetTitle('#eta')
    mg2.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg2.SetMaximum(maxY)
    mg2.GetXaxis().SetLabelFont(42)
    mg2.GetXaxis().SetLabelOffset(0.007)
    mg2.GetXaxis().SetLabelSize(0.043)
    mg2.GetXaxis().SetTitleSize(0.05)
    mg2.GetXaxis().SetTitleOffset(1.06)
    mg2.GetXaxis().SetTitleFont(42)
    mg2.GetYaxis().SetLabelFont(42)
    mg2.GetYaxis().SetLabelOffset(0.008)
    mg2.GetYaxis().SetLabelSize(0.05)
    mg2.GetYaxis().SetTitleSize(0.06)
    mg2.GetYaxis().SetTitleOffset(0.87)
    mg2.GetYaxis().SetTitleFont(42)

    pvtxt3 = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvtxt3.AddText('CMS Preliminary')
    pvtxt3.SetFillStyle(0)
    pvtxt3.SetBorderSize(0)
    pvtxt3.SetTextSize(0.03)
    pvtxt3.Draw()
    pvtxt4 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvtxt4.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvtxt4.SetFillStyle(0)
    pvtxt4.SetBorderSize(0)
    pvtxt4.SetTextSize(0.03)
    pvtxt4.Draw()

    canv.cd(4)
    gPad.SetLogy()
    mg3 = TMultiGraph()
    #graphAxis(mg3)
    mg3.Add(gr2E, "AP")
    mg3.Add(gr2W, "AP")
    mg3.Add(gr9E, "AP")
    mg3.Add(gr9W, "AP")
    mg3.Draw("a")
    mg3.SetTitle('RB2')
    mg3.GetXaxis().SetTitle('#eta')
    mg3.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg3.SetMaximum(maxY)
    mg3.GetXaxis().SetLabelFont(42)
    mg3.GetXaxis().SetLabelOffset(0.007)
    mg3.GetXaxis().SetLabelSize(0.043)
    mg3.GetXaxis().SetTitleSize(0.05)
    mg3.GetXaxis().SetTitleOffset(1.06)
    mg3.GetXaxis().SetTitleFont(42)
    mg3.GetYaxis().SetLabelFont(42)
    mg3.GetYaxis().SetLabelOffset(0.008)
    mg3.GetYaxis().SetLabelSize(0.05)
    mg3.GetYaxis().SetTitleSize(0.06)
    mg3.GetYaxis().SetTitleOffset(0.87)
    mg3.GetYaxis().SetTitleFont(42)

    pvtxt5 = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvtxt5.AddText('CMS Preliminary')
    pvtxt5.SetFillStyle(0)
    pvtxt5.SetBorderSize(0)
    pvtxt5.SetTextSize(0.03)
    pvtxt5.Draw()
    pvtxt6 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvtxt6.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvtxt6.SetFillStyle(0)
    pvtxt6.SetBorderSize(0)
    pvtxt6.SetTextSize(0.03)
    pvtxt6.Draw()

    canv.cd(5)
    gPad.SetLogy()
    mg4 = TMultiGraph()
    #graphAxis(mg4)
    mg4.Add(gr5E, "AP")
    mg4.Add(gr5W, "AP")
    mg4.Add(gr12E, "AP")
    mg4.Add(gr12W, "AP")
    mg4.Draw("a")
    mg4.SetTitle('RB3')
    mg4.GetXaxis().SetTitle('#eta')
    mg4.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg4.SetMaximum(maxY)
    mg4.GetXaxis().SetLabelFont(42)
    mg4.GetXaxis().SetLabelOffset(0.007)
    mg4.GetXaxis().SetLabelSize(0.043)
    mg4.GetXaxis().SetTitleSize(0.05)
    mg4.GetXaxis().SetTitleOffset(1.06)
    mg4.GetXaxis().SetTitleFont(42)
    mg4.GetYaxis().SetLabelFont(42)
    mg4.GetYaxis().SetLabelOffset(0.008)
    mg4.GetYaxis().SetLabelSize(0.05)
    mg4.GetYaxis().SetTitleSize(0.06)
    mg4.GetYaxis().SetTitleOffset(0.87)
    mg4.GetYaxis().SetTitleFont(42)

    pvtxt7 = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvtxt7.AddText('CMS Preliminary')
    pvtxt7.SetFillStyle(0)
    pvtxt7.SetBorderSize(0)
    pvtxt7.SetTextSize(0.03)
    pvtxt7.Draw()
    pvtxt8 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvtxt8.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvtxt8.SetFillStyle(0)
    pvtxt8.SetBorderSize(0)
    pvtxt8.SetTextSize(0.03)
    pvtxt8.Draw()

    canv.cd(6)
    gPad.SetLogy()
    mg5 = TMultiGraph()
    #graphAxis(mg5)
    mg5.Add(gr6E, "AP")
    mg5.Add(gr6W, "AP")
    mg5.Add(gr13E, "AP")
    mg5.Add(gr13W, "AP")
    mg5.Draw("a")
    mg5.SetTitle('RB4')
    mg5.GetXaxis().SetTitle('#eta')
    mg5.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg5.SetMaximum(maxY)
    mg5.GetXaxis().SetLabelFont(42)
    mg5.GetXaxis().SetLabelOffset(0.007)
    mg5.GetXaxis().SetLabelSize(0.043)
    mg5.GetXaxis().SetTitleSize(0.05)
    mg5.GetXaxis().SetTitleOffset(1.06)
    mg5.GetXaxis().SetTitleFont(42)
    mg5.GetYaxis().SetLabelFont(42)
    mg5.GetYaxis().SetLabelOffset(0.008)
    mg5.GetYaxis().SetLabelSize(0.05)
    mg5.GetYaxis().SetTitleSize(0.06)
    mg5.GetYaxis().SetTitleOffset(0.87)
    mg5.GetYaxis().SetTitleFont(42)

    pvtxt10 = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvtxt10.AddText('CMS Preliminary')
    pvtxt10.SetFillStyle(0)
    pvtxt10.SetBorderSize(0)
    pvtxt10.SetTextSize(0.03)
    pvtxt10.Draw()
    pvtxt9 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvtxt9.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvtxt9.SetFillStyle(0)
    pvtxt9.SetBorderSize(0)
    pvtxt9.SetTextSize(0.03)
    pvtxt9.Draw()

    canv.SaveAs("etaDistro.gif")
    canv.SaveAs("etaDistro.png")
    canv.SaveAs("etaDistro.pdf")
    canv.SaveAs("etaDistro.C")

    canv.Close()

    print "----- Creating Second TCanvas -----"
    H = 800
    W = 800
    c = TCanvas("c1", "Canvas", 50, 50, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    gPad.SetLogy()

    print " ------------ Creating TMultiGraph -----------"
    mg = TMultiGraph()
    mg.Add(gr0E, "AP")
    mg.Add(gr0W, "AP")
    mg.Add(gr7E, "AP")
    mg.Add(gr7W, "AP")
    mg.Add(gr1W, "AP")
    mg.Add(gr8W, "AP")
    mg.Draw("a")
    mg.SetTitle('RB1in')
    mg.GetXaxis().SetTitle('#eta')
    mg.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mg.SetMaximum(maxY)
    mg.GetXaxis().SetLabelFont(42)
    mg.GetXaxis().SetLabelOffset(0.007)
    mg.GetXaxis().SetLabelSize(0.043)
    mg.GetXaxis().SetTitleSize(0.05)
    mg.GetXaxis().SetTitleOffset(1.06)
    mg.GetXaxis().SetTitleFont(42)
    mg.GetYaxis().SetLabelFont(42)
    mg.GetYaxis().SetLabelOffset(0.008)
    mg.GetYaxis().SetLabelSize(0.05)
    mg.GetYaxis().SetTitleSize(0.06)
    mg.GetYaxis().SetTitleOffset(0.87)
    mg.GetYaxis().SetTitleFont(42)

    pvt = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pvt.AddText('CMS Preliminary')
    pvt.SetFillStyle(0)
    pvt.SetBorderSize(0)
    pvt.SetTextSize(0.03)
    pvt.Draw()
    pvt1 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pvt1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pvt1.SetFillStyle(0)
    pvt1.SetBorderSize(0)
    pvt1.SetTextSize(0.03)
    pvt1.Draw()

    legenda = TLegend(0.4, 0.7, .7, .9)
    legenda.SetNColumns(1)
    legenda.AddEntry(gr0E, "RE1", "p")
    legenda.AddEntry(gr0W, "RB1in", "p")
    legenda.AddEntry(gr1W, "RB1out", "p")
    legenda.SetTextSize(0.05)
    legenda.Draw("a")

    c.SaveAs("etaDistroDetailRB1.png")
    c.SaveAs("etaDistroDetailRB1.gif")
    c.SaveAs("etaDistroDetailRB1.pdf")
    c.SaveAs("etaDistroDetailRB1.C")

    c.Close()

    print "----- Creating Second TCanvas -----"
    c1 = TCanvas("c1", "Canvas", 50, 50, W, H)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetFrameFillStyle(0)
    c1.SetFrameBorderMode(0)
    c1.SetLeftMargin(L / W)
    c1.SetRightMargin(R / W)
    c1.SetTopMargin(T / H)
    c1.SetBottomMargin(B / H)
    c1.SetTickx(0)
    c1.SetTicky(0)
    gPad.SetLogy()

    print " ------------ Creating TMultiGraph -----------"
    mgd2 = TMultiGraph()
    mgd2.Add(gr3E, "AP")
    mgd2.Add(gr3W, "AP")
    mgd2.Add(gr10E, "AP")
    mgd2.Add(gr10W, "AP")
    mgd2.Add(gr4W, "AP")
    mgd2.Add(gr11W, "AP")
    mgd2.Draw("a")
    mgd2.SetTitle('RB1in')
    mgd2.GetXaxis().SetTitle('#eta')
    mgd2.GetYaxis().SetTitle('RPC single hit rate (Hz/cm^{2})')
    mgd2.SetMaximum(maxY)
    mgd2.GetXaxis().SetLabelFont(42)
    mgd2.GetXaxis().SetLabelOffset(0.007)
    mgd2.GetXaxis().SetLabelSize(0.043)
    mgd2.GetXaxis().SetTitleSize(0.05)
    mgd2.GetXaxis().SetTitleOffset(1.06)
    mgd2.GetXaxis().SetTitleFont(42)
    mgd2.GetYaxis().SetLabelFont(42)
    mgd2.GetYaxis().SetLabelOffset(0.008)
    mgd2.GetYaxis().SetLabelSize(0.05)
    mgd2.GetYaxis().SetTitleSize(0.06)
    mgd2.GetYaxis().SetTitleOffset(0.87)
    mgd2.GetYaxis().SetTitleFont(42)

    pv = TPaveText(.1, 0.97, .55, 0.97, "NDC")  #(.06,.4,.55,.73)
    pv.AddText('CMS Preliminary')
    pv.SetFillStyle(0)
    pv.SetBorderSize(0)
    pv.SetTextSize(0.03)
    pv.Draw()
    pv1 = TPaveText(.7, 0.97, .9, 0.97, "NDC")
    pv1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)')
    pv1.SetFillStyle(0)
    pv1.SetBorderSize(0)
    pv1.SetTextSize(0.03)
    pv1.Draw()

    legendd2 = TLegend(0.4, 0.6, .7, .8)
    legendd2.SetNColumns(1)
    legendd2.AddEntry(gr3E, "RE2", "p")
    legendd2.AddEntry(gr3W, "RB2in", "p")
    legendd2.AddEntry(gr4W, "RB2out", "p")
    legendd2.SetTextSize(0.05)
    legendd2.Draw("a")

    c1.SaveAs("etaDistroDetailRB2.png")
    c1.SaveAs("etaDistroDetailRB2.pdf")
    c1.SaveAs("etaDistroDetailRB2.gif")
    c1.SaveAs("etaDistroDetailRB2.C")

    c1.Close()

    print "is there an error here?"
コード例 #9
0
def plotUpperLimits(model, lambdas, helicity, Mmin):

    N = len(lambdas)
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    up2s = []
    xseclist = [1.0] * N

    for i in range(N):
        file_name = "./%sshapeCards/ee_limit_min%d%s/higgsCombineTest.AsymptoticLimits.mH%d.root" % (
            model, Mmin, helicity, lambdas[i])
        limit = getLimits(file_name)
        up2s.append(limit[4])
        if model == "ADD":
            yellow.SetPoint(i, lambdas[i] / 1000,
                            limit[4] * xseclist[i])  # + 2 sigma
            green.SetPoint(i, lambdas[i] / 1000,
                           limit[3] * xseclist[i])  # + 1 sigma
            median.SetPoint(i, lambdas[i] / 1000,
                            limit[2] * xseclist[i])  # median
            green.SetPoint(2 * N - 1 - i, lambdas[i] / 1000,
                           limit[1] * xseclist[i])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, lambdas[i] / 1000,
                            limit[0] * xseclist[i])  # - 2 sigma
        else:
            yellow.SetPoint(i, lambdas[i], limit[4] * xseclist[i])  # + 2 sigma
            green.SetPoint(i, lambdas[i], limit[3] * xseclist[i])  # + 1 sigma
            median.SetPoint(i, lambdas[i], limit[2] * xseclist[i])  # median
            green.SetPoint(2 * N - 1 - i, lambdas[i],
                           limit[1] * xseclist[i])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, lambdas[i],
                            limit[0] * xseclist[i])  # - 2 sigma
        print "Lambda = %d, Median = %f" % (lambdas[i], limit[2])

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    if model == "ADD": frame = c.DrawFrame(4, 0.01, 10, 10)
    else: frame = c.DrawFrame(16, 0.1, 40, 8)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{}")
    if model == "ADD":
        frame.GetYaxis().SetTitle("95% CL limit on #sigma / #sigma_{ADD}")
        frame.GetXaxis().SetTitle("#Lambda_{T} [ADD]")
    else:
        frame.GetYaxis().SetTitle("95% CL limit on #sigma / #sigma_{CI}")
        frame.GetXaxis().SetTitle("#Lambda [CI]")
    frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    #frame.GetXaxis().SetLimits(min(values),max(values))

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 13, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median,
                    "Asymptotic CL_{s} expected %s%s" % (model, helicity), 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    legend.Draw()

    c.SaveAs("%slimits/%sLimit_ee_ShapeMin%d%s_201678.png" %
             (model, model, Mmin, helicity))
    c.Close()
コード例 #10
0
    def saveCanvas(self, corner, suffix='', leg=True):
        if self.doRatio: self.canvas.cd(1)
        else: self.canvas.cd()

        # Draw legend
        textSize = 0.022
        legWidth = 0.13
        height = (.18 + textSize * max(len(self.objectsInLeg) - 3, 0))
        if corner == "TR":
            (x1, y1, x2,
             y2) = (0.93 - legWidth if self.doWide else .85 - legWidth,
                    .93 - height, .865, .93)
        elif corner == "TC":
            (x1, y1, x2, y2) = (.5, .93 - height, .55 + legWidth, .93)
        elif corner == "TL":
            (x1, y1, x2, y2) = (.18, .835 - height, .18 + legWidth, .835)
        elif corner == "BR":
            (x1, y1, x2, y2) = (.85 - legWidth, .16 + height, .90, .16)
        elif corner == "BC":
            (x1, y1, x2, y2) = (.5, .16 + height, .5 + legWidth, .16)
        elif corner == "BL":
            (x1, y1, x2, y2) = (.2, .16 + height, .2 + legWidth, .16)

        if leg:
            leg = r.TLegend(x1, y1, x2, y2)
            leg.SetTextFont(42)
            leg.SetTextSize(textSize)
            leg.SetBorderSize(0)
            leg.SetFillColor(10)
            for obj, name, opt, idnam in self.objectsInLeg:
                if opt:
                    leg.AddEntry(obj, name, opt)
            leg.Draw('same')

        if not hasattr(self, 'noCMS'):
            CMS_lumi.lumi_13TeV = "%.1f fb^{-1}" % (vl.Lumi)
            CMS_lumi.extraText = 'Preliminary'
            CMS_lumi.lumi_sqrtS = '#sqrt{s} = 13 TeV'
            CMS_lumi.CMS_lumi(
                r.gPad, 4, 10, -0.005 if self.doWide and self.doRatio else
                0.01 if self.doWide else 0.05)

        # Draw ratio if needed
        if self.doRatio:
            print '> Plotting ratio between prediction(s) and results'
            if 'data' not in [it[3] for it in self.objectsInLeg]:
                raise RuntimeError(
                    'There is not data to make a ratio plot as demanded.')
            if [it[3] for it in self.objectsInLeg].count('data') > 1:
                raise RuntimeError(
                    'There are more than one data histograms attached: multiple ratios are not implemented.'
                )
            if 'mc' not in [it[3] for it in self.objectsInLeg]:
                raise RuntimeError(
                    'There is not (at least) one prediction to make a ratio plot as demanded.'
                )
            if 'unc' not in [it[3] for it in self.objectsInLeg]:
                raise RuntimeError(
                    'There is not histogram with the total uncertainties to make a ratio plot as demanded.'
                )
            if [it[3] for it in self.objectsInLeg].count('unc') > 1:
                raise RuntimeError(
                    'There are more than one total uncertainty histograms attached. Please add only one.'
                )
            # Obtaining resources
            ratiohistos = []
            totalunc = None

            datavalues = copy.deepcopy(
                [it[0] for it in self.objectsInLeg if it[3] == 'data'][0])
            fitunc = copy.deepcopy(datavalues.Clone('fitunc'))

            for bin in range(1, datavalues.GetNbinsX() + 1):
                datavalues.SetBinError(bin, 0.)
            for it in self.objectsInLeg:
                if it[3] == 'mc':
                    ratiohistos.append(copy.deepcopy(it[0].Clone(it[1])))
                    ratiohistos[-1].Divide(datavalues)
                if it[3] == 'unc':
                    totalunc = copy.deepcopy(it[0].Clone(it[1]))
            xtemp = r.Double(0.)
            ytemp = r.Double(0.)
            for bin in range(1, datavalues.GetNbinsX() + 1):
                fitunc.SetBinError(
                    bin,
                    fitunc.GetBinError(bin) / fitunc.GetBinContent(bin))
                fitunc.SetBinContent(bin, 1.)
                totalunc.GetPoint(bin - 1, xtemp, ytemp)
                totalunc.SetPointEYhigh(
                    bin - 1,
                    totalunc.GetErrorYhigh(bin - 1) / ytemp)
                totalunc.SetPointEYlow(bin - 1,
                                       totalunc.GetErrorYlow(bin - 1) / ytemp)
                totalunc.SetPoint(bin - 1, xtemp, 1.)

            # Setting options
            fitunc.SetFillColorAlpha(r.kAzure, 0.35)
            fitunc.SetLineColor(r.kBlack)
            fitunc.SetFillStyle(1001)
            fitunc.SetLineWidth(1)
            fitunc.SetMarkerSize(0.)

            totalunc.SetLineColor(r.kBlack)
            totalunc.SetFillStyle(1001)
            totalunc.SetLineWidth(1)

            #if self.doFit: totalunc.GetXaxis().SetRangeUser(fitunc.GetXaxis().GetBinLowEdge(1), fitunc.GetXaxis().GetBinUpEdge(fitunc.GetNbinsX()))
            totalunc.GetXaxis().SetRangeUser(
                fitunc.GetXaxis().GetBinLowEdge(1),
                fitunc.GetXaxis().GetBinUpEdge(fitunc.GetNbinsX()))
            #else:          totalunc.GetXaxis().SetRangeUser(datavalues.GetXaxis().GetBinLowEdge(1), datavalues.GetXaxis().GetBinUpEdge(datavalues.GetNbinsX()))

            totalunc.GetXaxis().SetTitle(vl.varList[self.name.replace(
                '_folded', '').replace('_asimov', '')]['xaxis'])
            totalunc.GetXaxis().SetTitleFont(43)
            totalunc.GetXaxis().SetTitleSize(22)
            totalunc.GetXaxis().SetTitleOffset(4)
            totalunc.GetXaxis().SetLabelFont(43)
            totalunc.GetXaxis().SetLabelSize(22)
            totalunc.GetXaxis().SetLabelOffset(0.007)
            totalunc.GetXaxis().SetNdivisions(510, True)

            totalunc.GetYaxis().SetRangeUser(0, 2.5)
            totalunc.GetYaxis().SetTitle('Pred./Data')
            totalunc.GetYaxis().SetTitleFont(43)
            totalunc.GetYaxis().SetTitleSize(22)
            totalunc.GetYaxis().SetTitleOffset(0.5 if self.doWide else 1.8)
            totalunc.GetYaxis().CenterTitle(True)
            totalunc.GetYaxis().SetLabelFont(43)
            totalunc.GetYaxis().SetLabelSize(22)
            totalunc.GetYaxis().SetLabelOffset(0.007)
            totalunc.GetYaxis().SetNdivisions(510, True)

            # Drawing
            self.canvas.cd(2)
            totalunc.Draw('a2')
            fitunc.Draw('E2,L,same')
            for el in ratiohistos:
                el.Draw('L,same')

        # Save results
        self.canvas.SaveAs(self.plotspath + self.name + suffix + '.pdf')
        self.canvas.SaveAs(self.plotspath + self.name + suffix + '.png')
        self.canvas.SaveAs(self.plotspath + self.name + suffix + '.eps')
        self.canvas.SaveAs(self.plotspath + self.name + suffix + '.root')

        self.canvas.IsA().Destructor(self.canvas)
コード例 #11
0
    def DrawText(self):
        #redraw axes
        self.c.RedrawAxis()
        # white background
        graphWhite = rt.TGraph(5)
        graphWhite.SetName("white")
        graphWhite.SetTitle("white")
        graphWhite.SetFillColor(rt.kWhite)
        graphWhite.SetFillStyle(1001)
        graphWhite.SetLineColor(rt.kBlack)
        graphWhite.SetLineStyle(1)
        graphWhite.SetLineWidth(3)
        graphWhite.SetPoint(0, self.model.Xmin, self.model.Ymax)
        graphWhite.SetPoint(1, self.model.Xmax, self.model.Ymax)

        # if(self.model.label2 == ""):
        #     graphWhite.SetPoint(2,self.model.Xmax, self.model.Ymax*0.75)
        #     graphWhite.SetPoint(3,self.model.Xmin, self.model.Ymax*0.75)
        # else:
        #     graphWhite.SetPoint(2,self.model.Xmax, self.model.Ymax*0.69)
        #     graphWhite.SetPoint(3,self.model.Xmin, self.model.Ymax*0.69)
        graphWhite.SetPoint(2, self.model.Xmax, self.model.Ymax * 0.75)
        graphWhite.SetPoint(3, self.model.Xmin, self.model.Ymax * 0.75)

        graphWhite.SetPoint(4, self.model.Xmin, self.model.Ymax)
        graphWhite.Draw("FSAME")
        graphWhite.Draw("LSAME")
        self.c.graphWhite = graphWhite
        CMS_lumi.writeExtraText = 0
        CMS_lumi.extraText = self.preliminary
        CMS_lumi.lumi_13TeV = self.lumi + " fb^{-1}"

        CMS_lumi.lumi_sqrtS = self.energy + " TeV"
        iPos = 0
        CMS_lumi.CMS_lumi(self.c, 4, iPos)
        # CMS LABEL
        textCMS = rt.TLatex(0.25, 0.96, "  %s " % (self.preliminary))
        textCMS.SetNDC()
        textCMS.SetTextAlign(13)
        textCMS.SetTextFont(52)
        textCMS.SetTextSize(0.038)
        textCMS.Draw()
        self.c.textCMS = textCMS
        exclusion_text = "Approx. NNLO+NNLL exclusion"
        if "rpvMonoPhi" in self.model.modelname:
            exclusion_text = "    LO exclusion"
        # MODEL LABEL
        if (self.model.label2 == ""):
            textModelLabel = rt.TLatex(
                0.15, 0.90, "%s  %s" % (self.model.label, exclusion_text))
            textModelLabel.SetNDC()
            textModelLabel.SetTextAlign(13)
            textModelLabel.SetTextFont(42)
            textModelLabel.SetTextSize(0.030 if "rpvMonoPhi" not in
                                       self.model.modelname else 0.037)
            textModelLabel.Draw()
            self.c.textModelLabel = textModelLabel
        else:
            textModelLabel = rt.TLatex(0.15, 0.910, "%s" % self.model.label)
            textModelLabel.SetNDC()
            textModelLabel.SetTextAlign(13)
            textModelLabel.SetTextFont(42)
            textModelLabel.SetTextSize(0.032)
            textModelLabel.Draw()
            self.c.textModelLabel = textModelLabel
            textModelLabel2 = rt.TLatex(0.15, 0.860, exclusion_text)
            textModelLabel2.SetNDC()
            textModelLabel2.SetTextAlign(13)
            textModelLabel2.SetTextFont(42)
            textModelLabel2.SetTextSize(0.032)
            textModelLabel2.Draw()
            self.c.textModelLabel2 = textModelLabel2
            self.c.otherLabels = []
            for i, text in enumerate(self.model.label2.split(r"\\")):
                tl = rt.TLatex(0.58, 0.855 - i * 0.044, text)
                tl.SetNDC()
                tl.SetTextAlign(13)
                tl.SetTextFont(42)
                tl.SetTextSize(0.027)
                tl.Draw()
                self.c.otherLabels.append(tl)

            self.c.SaveAs("~/public_html/test.pdf")

        # NLO NLL XSEC
        textNLONLL = rt.TLatex(0.16, 0.32, "NLO-NLL exclusion")
        textNLONLL.SetNDC()
        textNLONLL.SetTextAlign(13)
        textNLONLL.SetTextFont(42)
        textNLONLL.SetTextSize(0.04)
        textNLONLL.Draw()
コード例 #12
0
def plotHists(binname='incl', inclTemplate=False, mcData=True, addHists=True):

    # frame
    frame = _varStore['Lp'].frame(
        RooFit.Title('Lp distributions and fit in bin ' + binname))

    _dhStore['data_' + binname].plotOn(
        frame, RooFit.Name('data'),
        RooFit.DataError(RooAbsData.SumW2))  #,RooLinkedList())

    # plot full template fit
    _pdfStore['pdfTemplate'].plotOn(frame, RooFit.LineColor(2),
                                    RooFit.Name('FullFit'))
    # plot only QCD component
    if not inclTemplate:
        argset = RooArgSet(_pdfStore['pdfQCDanti_' +
                                     binname])  # hack to keep arguments alive
    else:
        import re
        incName = re.sub('LT[0-9]', 'LTi',
                         binname)  # use LTi as inclusive template
        if 'pdfQCDanti_' + incName not in _pdfStore:
            incName = re.sub('LT[0-9]_', '',
                             binname)  # remove LTx to get incl template
        argset = RooArgSet(_pdfStore['pdfQCDanti_' +
                                     incName])  # hack to keep arguments alive
    _pdfStore['pdfTemplate'].plotOn(frame, RooFit.Components(argset),
                                    RooFit.LineColor(kCyan),
                                    RooFit.LineStyle(5), RooFit.Name('QCDfit'))
    # plot only EWK
    argset2 = RooArgSet(_pdfStore['pdfEWKsel_' +
                                  binname])  # hack to keep arguments alive
    _pdfStore['pdfTemplate'].plotOn(frame, RooFit.Components(argset2),
                                    RooFit.LineColor(4), RooFit.LineStyle(2),
                                    RooFit.Name('EWKfit'))

    # PLOT
    canv = TCanvas("cQCDfit_" + binname, "canvas for bin " + binname, cwidth,
                   cheigth)

    if cheigth == cwidth:
        frame.GetYaxis().SetTitleOffset(1.3)

    frame.Draw()

    if addHists:

        doTransp = True

        if doTransp:
            alpha = 0.35
            _hStore['EWKsel_' + binname].SetFillColorAlpha(
                _hStore['EWKsel_' + binname].GetFillColor(), alpha)
            _hStore['QCDsel_' + binname].SetFillColorAlpha(
                _hStore['QCDsel_' + binname].GetFillColor(), alpha)
        else:
            _hStore['EWKsel_' + binname].SetFillStyle(3001)
            _hStore['QCDsel_' + binname].SetFillStyle(3002)

        stack = THStack('hs', 'hstack')
        stack.Add(_hStore['QCDsel_' + binname])
        stack.Add(_hStore['EWKsel_' + binname])
        stack.Draw("histsame")
        #_hStore['QCDsel_'+binname].Draw("histsame")

        SetOwnership(stack, 0)
        #SetOwnership( _hStore['QCDsel_'+binname], 0 )
        #SetOwnership( _hStore['EWKsel_'+binname], 0 )
        #hData.Draw('histsame')

    frame.Draw("same")

    # LEGEND
    leg = doLegend()

    # set legend header = bin name
    #leg.SetHeader("Bin: " + binname.replace("_",", "))
    leg.SetHeader("Bin: " + decryptBinName(binname))

    if mcData:
        leg.AddEntry(frame.findObject('data'), 'Pseudo Data', 'lp')
    else:
        leg.AddEntry(frame.findObject('data'), 'Data', 'lp')

    leg.AddEntry(frame.findObject('FullFit'), 'Full fit', 'l')
    leg.AddEntry(frame.findObject('QCDfit'), 'QCD fit (Data)', 'l')
    leg.AddEntry(frame.findObject('EWKfit'), 'EWK fit (MC)', 'l')

    if addHists:
        leg.AddEntry(0, "From MC:", "")
        leg.AddEntry(_hStore['EWKsel_' + binname], 'EWK selected', 'f')
        leg.AddEntry(_hStore['QCDsel_' + binname], 'QCD selected', 'f')

    leg.Draw()

    SetOwnership(leg, 0)

    #for prim in  canv.GetListOfPrimitives(): print prim

    # Draw CMS Lumi
    CMS_lumi.CMS_lumi(canv, 4, iPos)

    gPad.Update()

    if '-b' not in sys.argv:
        # wait for input
        answ = ['c']
        while 'c' not in answ:
            answ.append(raw_input("Enter 'c' to continue: "))

    _canvStore[canv.GetName()] = canv

    return canv
コード例 #13
0
canvas = ROOT.TCanvas("col", "col", 50, 50, W, H)
canvas.SetFillColor(0)
canvas.SetBorderMode(0)
canvas.SetFrameFillStyle(0)
canvas.SetFrameBorderMode(0)
canvas.SetLeftMargin(L / W)
canvas.SetRightMargin(R / W)
canvas.SetTopMargin(T / H)
canvas.SetBottomMargin(B / H)
canvas.SetTickx(0)
canvas.SetTicky(0)
#canvas.SetGrid()

matrixByCol.Draw("colz text")

CMS_lumi.CMS_lumi(canvas, 4, iPos)

ROOT.gPad.RedrawAxis()
canvas.SaveAs("confusionmatrix_bycol_2018_1p2.png")

canvas2 = ROOT.TCanvas("row", "row", 50, 50, W, H)
canvas2.SetFillColor(0)
canvas2.SetBorderMode(0)
canvas2.SetFrameFillStyle(0)
canvas2.SetFrameBorderMode(0)
canvas2.SetLeftMargin(L / W)
canvas2.SetRightMargin(R / W)
canvas2.SetTopMargin(T / H)
canvas2.SetBottomMargin(B / H)
canvas2.SetTickx(0)
canvas2.SetTicky(0)
コード例 #14
0
ファイル: wtag-cut-flow.py プロジェクト: vscheurer/scipts
  h.GetYaxis().SetTitle('Efficiency')
  h.SetName(fname.GetName())
  histolist.append(h)  
  j += 1

canvas.cd()
for j in range(1,len(histolist)+1):  
  hs.Add( histolist[len(histolist)-j],"HIST")

histolist[0].Draw()  
histolist[0].SetMaximum(histolist[0].GetMaximum()*1.2)
for j in range(0,len(histolist)):  
  histolist[j].Draw("same")  
  legend.Draw()
canvas.Update()
CMS_lumi.CMS_lumi(canvas, 4, 0)
canvas.cd()
canvas.Update()
canvas.RedrawAxis()
canvas.cd()
canvas.Update()
#
# l1 = TLatex()
# l1.SetTextAlign(13)
# l1.SetTextFont(42)
# l1.SetNDC()
# l1.SetTextSize(0.04)
# l1.DrawLatex(0.14+0.03,0.25, 'Run 2015D')
#
# l1.SetTextAlign(12)
# l1.SetTextSize(0.045)
コード例 #15
0
def easyPlot(name,
             tag,
             histlist,
             bkglist=[],
             signals=[],
             colors=[],
             titles=[],
             logy=False,
             rootfile=False,
             xtitle='',
             ytitle='',
             dataOff=False,
             datastyle='pe'):
    # histlist is just the generic list but if bkglist is specified (non-empty)
    # then this function will stack the backgrounds and compare against histlist as if
    # it is data. The important bit is that bkglist is a list of lists. The first index
    # of bkglist corresponds to the index in histlist (the corresponding data).
    # For example you could have:
    #   histlist = [data1, data2]
    #   bkglist = [[bkg1_1,bkg2_1],[bkg1_2,bkg2_2]]

    if len(histlist) == 1:
        width = 800
        height = 700
        padx = 1
        pady = 1
    elif len(histlist) == 2:
        width = 1200
        height = 700
        padx = 2
        pady = 1
    elif len(histlist) == 3:
        width = 1600
        height = 700
        padx = 3
        pady = 1
    elif len(histlist) == 4:
        width = 1200
        height = 1000
        padx = 2
        pady = 2
    elif len(histlist) == 6 or len(histlist) == 5:
        width = 1600
        height = 1000
        padx = 3
        pady = 2
    else:
        raise ValueError('histlist of size ' + str(len(histlist)) +
                         ' not currently supported')

    tdrstyle.setTDRStyle()

    myCan = TCanvas(name, name, width, height)
    myCan.Divide(padx, pady)

    # Just some colors that I think work well together and a bunch of empty lists for storage if needed
    default_colors = [kRed, kMagenta, kGreen, kCyan, kBlue]
    if len(colors) == 0:
        colors = default_colors
    stacks = []
    tot_hists = []
    legends = []
    mains = []
    subs = []
    pulls = []
    logString = ''

    # For each hist/data distribution
    for hist_index, hist in enumerate(histlist):
        # Grab the pad we want to draw in
        myCan.cd(hist_index + 1)
        # if len(histlist) > 1:
        thisPad = myCan.GetPrimitive(name + '_' + str(hist_index + 1))
        thisPad.cd()

        # If this is a TH2, just draw the lego
        if hist.ClassName().find('TH2') != -1:
            if logy == True:
                gPad.SetLogy()
            gPad.SetLeftMargin(0.2)
            hist.GetXaxis().SetTitle(xtitle)
            hist.GetYaxis().SetTitle(ytitle)
            hist.GetXaxis().SetTitleOffset(1.5)
            hist.GetYaxis().SetTitleOffset(2.3)
            hist.GetZaxis().SetTitleOffset(1.8)
            if len(titles) > 0:
                hist.SetTitle(titles[hist_index])

            hist.Draw('lego')
            if len(bkglist) > 0:
                print(
                    'ERROR: It seems you are trying to plot backgrounds with data on a 2D plot. This is not supported since there is no good way to view this type of distribution.'
                )

        # Otherwise it's a TH1 hopefully
        else:
            alpha = 1
            if dataOff:
                alpha = 0
            hist.SetLineColorAlpha(kBlack, alpha)
            if 'pe' in datastyle.lower():
                hist.SetMarkerColorAlpha(kBlack, alpha)
                hist.SetMarkerStyle(8)
            if 'hist' in datastyle.lower():
                hist.SetFillColorAlpha(0, 0)

            # If there are no backgrounds, only plot the data (semilog if desired)
            if len(bkglist) == 0:
                hist.GetXaxis().SetTitle(xtitle)
                hist.GetYaxis().SetTitle(ytitle)
                if len(titles) > 0:
                    hist.SetTitle(titles[hist_index])
                hist.Draw(datastyle)

            # Otherwise...
            else:
                # Create some subpads, a legend, a stack, and a total bkg hist that we'll use for the error bars
                if not dataOff:
                    mains.append(
                        TPad(hist.GetName() + '_main',
                             hist.GetName() + '_main', 0, 0.3, 1, 1))
                    subs.append(
                        TPad(hist.GetName() + '_sub',
                             hist.GetName() + '_sub', 0, 0, 1, 0.3))

                else:
                    mains.append(
                        TPad(hist.GetName() + '_main',
                             hist.GetName() + '_main', 0, 0.1, 1, 1))
                    subs.append(
                        TPad(hist.GetName() + '_sub',
                             hist.GetName() + '_sub', 0, 0, 0, 0))

                legends.append(TLegend(0.65, 0.6, 0.95, 0.93))
                stacks.append(
                    THStack(hist.GetName() + '_stack',
                            hist.GetName() + '_stack'))
                tot_hist = hist.Clone(hist.GetName() + '_tot')
                tot_hist.Reset()
                tot_hist.SetTitle(hist.GetName() + '_tot')
                tot_hist.SetMarkerStyle(0)
                tot_hists.append(tot_hist)

                # Set margins and make these two pads primitives of the division, thisPad
                mains[hist_index].SetBottomMargin(0.0)
                mains[hist_index].SetLeftMargin(0.16)
                mains[hist_index].SetRightMargin(0.05)
                mains[hist_index].SetTopMargin(0.1)

                subs[hist_index].SetLeftMargin(0.16)
                subs[hist_index].SetRightMargin(0.05)
                subs[hist_index].SetTopMargin(0)
                subs[hist_index].SetBottomMargin(0.3)
                mains[hist_index].Draw()
                subs[hist_index].Draw()

                # Build the stack
                for bkg_index, bkg in enumerate(
                        bkglist[hist_index]):  # Won't loop if bkglist is empty
                    # bkg.Sumw2()
                    tot_hists[hist_index].Add(bkg)
                    bkg.SetLineColor(kBlack)
                    if logy:
                        bkg.SetMinimum(1e-3)

                    if bkg.GetName().find('qcd') != -1:
                        bkg.SetFillColor(kYellow)

                    else:
                        if colors[bkg_index] != None:
                            bkg.SetFillColor(colors[bkg_index])
                        else:
                            bkg.SetFillColor(default_colors[bkg_index])

                    stacks[hist_index].Add(bkg)

                    legends[hist_index].AddEntry(bkg,
                                                 bkg.GetName().split('_')[0],
                                                 'f')

                # Go to main pad, set logy if needed
                mains[hist_index].cd()

                # Set y max of all hists to be the same to accomodate the tallest
                histList = [stacks[hist_index], tot_hists[hist_index], hist]

                yMax = histList[0].GetMaximum()
                maxHist = histList[0]
                for h in range(1, len(histList)):
                    if histList[h].GetMaximum() > yMax:
                        yMax = histList[h].GetMaximum()
                        maxHist = histList[h]
                for h in histList:
                    h.SetMaximum(yMax * 1.1)
                    if logy == True:
                        h.SetMaximum(yMax * 10)

                mLS = 0.06
                # Now draw the main pad
                data_leg_title = hist.GetTitle()
                if len(titles) > 0:
                    hist.SetTitle(titles[hist_index])
                hist.SetTitleOffset(1.5, "xy")
                hist.GetYaxis().SetTitle('Events')
                hist.GetYaxis().SetLabelSize(mLS)
                hist.GetYaxis().SetTitleSize(mLS)
                if logy == True:
                    hist.SetMinimum(1e-3)
                hist.Draw(datastyle)

                stacks[hist_index].Draw('same hist')

                # Do the signals
                if len(signals) > 0:
                    signals[hist_index].SetLineColor(kBlue)
                    signals[hist_index].SetLineWidth(2)
                    if logy == True:
                        signals[hist_index].SetMinimum(1e-3)
                    legends[hist_index].AddEntry(
                        signals[hist_index],
                        signals[hist_index].GetName().split('_')[0], 'L')
                    signals[hist_index].Draw('hist same')

                tot_hists[hist_index].SetFillColor(kBlack)
                tot_hists[hist_index].SetFillStyle(3354)

                tot_hists[hist_index].Draw('e2 same')
                # legends[hist_index].Draw()

                if not dataOff:
                    legends[hist_index].AddEntry(hist, 'data', datastyle)
                    hist.Draw(datastyle + ' same')

                gPad.RedrawAxis()

                # Draw the pull
                subs[hist_index].cd()
                # Build the pull
                pulls.append(Make_Pull_plot(hist, tot_hists[hist_index]))
                pulls[hist_index].SetFillColor(kBlue)
                pulls[hist_index].SetTitle(";" + hist.GetXaxis().GetTitle() +
                                           ";(Data-Bkg)/#sigma")
                pulls[hist_index].SetStats(0)

                LS = .13

                pulls[hist_index].GetYaxis().SetRangeUser(-2.9, 2.9)
                pulls[hist_index].GetYaxis().SetTitleOffset(0.4)
                pulls[hist_index].GetXaxis().SetTitleOffset(0.9)

                pulls[hist_index].GetYaxis().SetLabelSize(LS)
                pulls[hist_index].GetYaxis().SetTitleSize(LS)
                pulls[hist_index].GetYaxis().SetNdivisions(306)
                pulls[hist_index].GetXaxis().SetLabelSize(LS)
                pulls[hist_index].GetXaxis().SetTitleSize(LS)

                pulls[hist_index].GetXaxis().SetTitle(xtitle)
                pulls[hist_index].GetYaxis().SetTitle("(Data-Bkg)/#sigma")
                pulls[hist_index].Draw('hist')

                if logy == True:
                    mains[hist_index].SetLogy()

                CMS_lumi.CMS_lumi(thisPad, 4, 11)

    if rootfile:
        myCan.Print(tag + 'plots/' + name + '.root', 'root')
    else:
        myCan.Print(tag + 'plots/' + name + '.png', 'png')
コード例 #16
0
ファイル: plotFits.py プロジェクト: DryRun/StatisticalTools
        leg.AddEntry(background, "B Fit", "L")
        #leg.AddEntry(background_f6,"B Fit","L")
        #leg.AddEntry(background_f6_SplusB,"B component","L")
        leg.AddEntry(h_s_plus_b, "S+B Fit", "L")

        pave_fit.Draw("same")
        #pave_fit1.Draw("same")
        leg.Draw("same")

        #redraw axis
        p11_1.RedrawAxis()
        p11_1.Update()
        #cout << "MIN: " << p11_1.GetUxmin() << endl
        #cout << "MAX: " << p11_1.GetUxmax() << endl
        #draw the lumi text on the canvas
        CMS_lumi.CMS_lumi(p11_1, iPeriod, iPos)

        #
        #---- Next PAD

        c.cd(2)
        p11_2 = c.GetPad(2)
        p11_2.SetPad(0.01, 0.02, 0.99, 0.27)
        p11_2.SetBottomMargin(0.35)
        p11_2.SetRightMargin(0.05)
        p11_2.SetGridx()
        p11_2.SetGridy()

        vFrame2 = p11_2.DrawFrame(p11_1.GetUxmin(), -3.5, p11_1.GetUxmax(),
                                  3.5)
コード例 #17
0
def plot_mJ(canvas,xlo,xhi,reg,w,fitres,normset,ch,pads,medianLines,paveTexts,legends):


    canvas.cd()
    pad     = TPad(reg,reg,xlo,0.25,xhi,1.0)
    if reg=='sb_lo':
        pad2    = TPad(reg+"_pull",reg+"_pull",xlo,0.0,xhi,0.31)
        pad.SetMargin(0.25,0,0.1,0.1)
        pad2.SetMargin(0.25,0.0,0.4,0)
    elif reg=='sb_hi':
        pad2    = TPad(reg+"_pull",reg+"_pull",xlo,0.0,xhi,0.31)
        pad.SetMargin(0,0.1,0.1,0.1)
        pad2.SetMargin(0,0.1,0.4,0)
    else:
        pad2    = TPad(reg+"_pull",reg+"_pull",xlo-0.00445,0.0,xhi+0.001,0.31)
        pad.SetMargin(0,0,0.1,0.1)
        pad2.SetMargin(0.022,0,0.4,0)
    pad.Draw()
    pad2.Draw()

    pad.cd()
    # Main MJ plot
    p       = plot(w,fitres,normset,ch,reg)
    #p.GetXaxis().SetTitleSize(0.0575)
    #p.GetXaxis().SetTitleOffset(0.7)
    p.GetXaxis().SetTitleSize(0)
    p.GetXaxis().SetLabelSize(0)
    p.GetYaxis().SetRangeUser(0,1450)
    p.GetYaxis().SetLabelSize(0.05)
    p.GetYaxis().SetTitle('Events / 5 GeV')
    p.GetYaxis().SetTitleSize(0.08)
    p.GetYaxis().SetTitleOffset(1.1)
    if reg=='sb_lo':
        p.GetYaxis().SetRangeUser(0,1535)
        p.GetXaxis().SetTitle('')
    elif reg=='sb_hi':
        p.GetYaxis().SetTitle('')
        p.GetYaxis().SetLabelSize(0)
    else:
        p.GetXaxis().SetTitle('')
        p.GetYaxis().SetTitle('')
        p.GetYaxis().SetLabelSize(0)
    p.Draw()

    # Lumi text and channel
    if reg=='sb_lo':
       CMS_lumi.lumiTextSize=0.0
       #CMS_lumi.writeExtraText=True
       CMS_lumi.cmsTextSize=0.75
       CMS_lumi.relPosY    = -0.09
       CMS_lumi.relExtraDX = 0.3
       CMS_lumi.relExtraDY = 0.24
       CMS_lumi.CMS_lumi(pad,4,11)
    elif reg=='sb_hi':
       CMS_lumi.cmsTextSize=0.0
       #CMS_lumi.writeExtraText=False
       CMS_lumi.lumiTextSize=0.65
       CMS_lumi.lumiTextOffset=0.2
       CMS_lumi.CMS_lumi(pad,4,11)

    # Channel text
    if reg=='sig':
        pt = TPaveText(0.375,0.8,0.625,0.97, "blNDC")
        pt.SetFillStyle(0)
        pt.SetBorderSize(0)
        pt.SetTextAlign(23)
        pt.SetTextSize(0.09)
        if ch=="el":
            pt.AddText("Electron channel")
        else:
            pt.AddText("Muon channel")
        pt.Draw()
        paveTexts.append(pt)

    # Legend
    if reg=='sb_hi':
        legMJ=TLegend(0.625,0.39,0.875,0.875)
        legMJ.SetFillColor(0)
        legMJ.SetFillStyle(0)
        legMJ.SetBorderSize(0)
        legMJ.SetLineColor(0)
        legMJ.SetLineWidth(0)
        legMJ.SetLineStyle(0)
        legMJ.SetTextFont(42)
        if ch=='el':
            #legMJ.AddEntry(p.getObject(11),"CMS data, WV#rightarrow e#nuqq","P")
            legMJ.AddEntry(p.getObject(11),"Data","PE")
        else:
            #legMJ.AddEntry(p.getObject(11),"CMS data, WV#rightarrow #mu#nuqq","P")
            legMJ.AddEntry(p.getObject(11),"Data","PE")
        #legMJ.AddEntry(p.getObject(10),"Signal","L")
        legMJ.AddEntry(p.getObject(0),"W+jets","F")
        legMJ.AddEntry(p.getObject(1),"t#bar{t}","F")
        legMJ.AddEntry(p.getObject(4),"WW","F")
        legMJ.AddEntry(p.getObject(5),"WZ","F")
        legMJ.AddEntry(p.getObject(8),"Single top","F")
        legMJ.AddEntry(p.getObject(10),"Post-fit unc.","F")
        legMJ.Draw()
    else:
        legMJ=[]

    pad2.cd()

    # MJ pull histograms
    if reg=='sb_lo':
        pullhist    = p.pullHist("data","WJets")
        pullhist.SetMaximum(4.9)
        pullhist.SetMinimum(-5)
        pullhist.GetXaxis().SetRangeUser(40,65)
        pullhist.GetXaxis().SetNdivisions(505)
        pullhist.GetXaxis().SetLabelSize(0.14)
        pullhist.GetYaxis().SetNdivisions(7)
        pullhist.GetYaxis().SetTitle('#frac{Data-Fit}{#sigma_{Data}}')
        pullhist.GetYaxis().SetLabelSize(0.125)
        pullhist.GetYaxis().SetTitleSize(0.2)
        pullhist.GetYaxis().SetTitleOffset(0.35)
        pullhist.SetMarkerStyle(20)
        #pullhist.SetMarkerSize(1.5)
        pullhist.SetLineColor(kBlack)
        pullhist.SetMarkerColor(kBlack)
        pullhist.Draw("AP")
        medianLine = TLine(pullhist.GetXaxis().GetXmin(),0.,pullhist.GetXaxis().GetXmax(),0.); medianLine.SetLineWidth(1); medianLine.SetLineColor(kBlue); medianLine.Draw();
        pullhist.Draw("Psame")

    elif reg=='sig':
        pullhist    = p.pullHist("data","WJets")
        pullhist.SetMaximum(4.9)
        pullhist.SetMinimum(-5)
        pullhist.GetXaxis().SetRangeUser(65,105)
        pullhist.GetXaxis().SetLabelSize(0.14)
        pullhist.GetYaxis().SetNdivisions(7)
        pullhist.GetYaxis().SetLabelSize(0)
        pullhist.GetYaxis().SetTitleSize(0.2)
        pullhist.GetYaxis().SetTitleOffset(0.32)
        pullhist.SetMarkerStyle(20)
        #pullhist.SetMarkerSize(1.5)
        pullhist.SetLineColor(kBlack)
        pullhist.SetMarkerColor(kBlack)
        pullhist.Draw("AP")
        medianLine = TLine(65.,0.,105.,0.); medianLine.SetLineWidth(1); medianLine.SetLineColor(kBlue); medianLine.Draw();
        pullhist.Draw("Psame")
    else:
        pullhist    = p.pullHist("data","WJets")
        pullhist.SetMaximum(4.9)
        pullhist.SetMinimum(-5)
        pullhist.GetXaxis().SetRangeUser(105,150)
        pullhist.GetXaxis().SetLabelSize(0.14)
        pullhist.GetXaxis().SetTitle('m_{SD} (GeV)')
        pullhist.GetXaxis().SetTitleSize(0.2)
        pullhist.GetXaxis().SetTitleOffset(0.85)
        pullhist.GetYaxis().SetNdivisions(7)
        pullhist.GetYaxis().SetLabelSize(0)
        pullhist.GetYaxis().SetTitleSize(0.2)
        pullhist.GetYaxis().SetTitleOffset(0.32)
        pullhist.SetMarkerStyle(20)
        #pullhist.SetMarkerSize(1.5)
        pullhist.SetLineColor(kBlack)
        pullhist.SetMarkerColor(kBlack)
        pullhist.Draw("AP")
        medianLine = TLine(105.,0.,150.,0.); medianLine.SetLineWidth(1); medianLine.SetLineColor(kBlue); medianLine.Draw();
        pullhist.Draw("Psame")

    canvas.Update()

    pads.append(pad)
    pads.append(pad2)
    medianLines.append(medianLine)
    legends.append(legMJ)
コード例 #18
0
ファイル: utility.py プロジェクト: yongbinfeng/cmgtools-lite
def drawCorrelationPlot(h2D,
                        labelXtmp="xaxis", labelYtmp="yaxis", labelZtmp="zaxis",
                        canvasName="default", plotLabel="", outdir="./",
                        rebinFactorY=0,
                        rebinFactorX=0,
                        smoothPlot=True,
                        drawProfileX=True,
                        scaleToUnitArea=True,
                        draw_both0_noLog1_onlyLog2=0,
                        leftMargin=0.16,
                        rightMargin=0.20,
                        nContours=50,
                        palette=57,
                        canvasSize="700,625"):


    # if h2D.GetName() == "scaleFactor_origBinPt":
    #     print "="*20
    #     print "Check: hist %s: Z axis title = %s" % (h2D.GetName(),labelZtmp)
    #     print "="*20

    ROOT.TH1.SetDefaultSumw2()

    if (rebinFactorX): 
        if isinstance(rebinFactorX, int): h2D.RebinY(rebinFactorX)
        else:                             h2D.RebinY(len(rebinFactorX)-1,"",array('d',rebinFactorX)) # case in which rebinFactorX is a list of bin edges

    if (rebinFactorY): 
        if isinstance(rebinFactorY, int): h2D.RebinY(rebinFactorY)
        else:                             h2D.RebinY(len(rebinFactorY)-1,"",array('d',rebinFactorY)) # case in which rebinFactorX is a list of bin edges

    ROOT.gStyle.SetPalette(palette)  # 55:raibow palette ; 57: kBird (blue to yellow, default) ; 107 kVisibleSpectrum ; 77 kDarkRainBow 
    ROOT.gStyle.SetNumberContours(nContours) # default is 20 

    labelX,setXAxisRangeFromUser,xmin,xmax = getAxisRangeFromUser(labelXtmp)
    labelY,setYAxisRangeFromUser,ymin,ymax = getAxisRangeFromUser(labelYtmp)
    labelZ,setZAxisRangeFromUser,zmin,zmax = getAxisRangeFromUser(labelZtmp)
    
    cw,ch = canvasSize.split(',')
    #canvas = ROOT.TCanvas("canvas",h2D.GetTitle() if plotLabel == "ForceTitle" else "",700,625)
    canvas = ROOT.TCanvas("canvas","",int(cw),int(ch))
    canvas.SetLeftMargin(leftMargin)
    canvas.SetRightMargin(rightMargin)
    canvas.cd()

    addStringToEnd(outdir,"/",notAddIfEndswithMatch=True)
    createPlotDirAndCopyPhp(outdir)
    # normalize to 1
    if (scaleToUnitArea): h2D.Scale(1./h2D.Integral())

    h2DGraph = 0

    h2DPlot = 0
    if (not smoothPlot): h2DPlot = h2D
    else:
        h2DGraph = ROOT.TGraph2D()
        h2DGraph.SetNpx(300)
        h2DGraph.SetNpy(300)
        nPoint = 0
        for iBinX in range (1,1+h2D.GetNbinsX()):
            for iBinY in range(1,1+h2D.GetNbinsY()):
                h2DGraph.SetPoint(nPoint,h2D.GetXaxis().GetBinCenter(iBinX),h2D.GetYaxis().GetBinCenter(iBinY),h2D.GetBinContent(iBinX,iBinY))
                nPoint += 1
            

        h2DPlot = h2DGraph.GetHistogram()
  
    h2DPlot.GetXaxis().SetTitle(labelX)
    h2DPlot.GetYaxis().SetTitle(labelY)
    h2DPlot.GetXaxis().SetTitleSize(0.05)
    h2DPlot.GetXaxis().SetLabelSize(0.04)
    h2DPlot.GetXaxis().SetTitleOffset(1.1)
    h2DPlot.GetYaxis().SetTitleSize(0.05)
    h2DPlot.GetYaxis().SetLabelSize(0.04)
    h2DPlot.GetYaxis().SetTitleOffset(1.1)
    h2DPlot.GetZaxis().SetTitleSize(0.05)
    h2DPlot.GetZaxis().SetLabelSize(0.04)
    h2DPlot.GetZaxis().SetTitleOffset(1.2)

    h2DPlot.GetZaxis().SetTitle(labelZ) 
    h2DPlot.Draw("colz")
    if (setXAxisRangeFromUser): h2DPlot.GetXaxis().SetRangeUser(xmin,xmax)
    if (setYAxisRangeFromUser): h2DPlot.GetYaxis().SetRangeUser(ymin,ymax)
    if (setZAxisRangeFromUser): h2DPlot.GetZaxis().SetRangeUser(zmin,zmax)


    # if h2D.GetName() == "scaleFactor_origBinPt":
    #     print "="*20
    #     print "Check: hist %s: Z axis title = %s" % (h2DPlot.GetName(),h2DPlot.GetZaxis().GetTitle())
    #     print "="*20

    # attempt to make Z axis title farther depending on how many digits are printed
    maxZaxisVal = h2DPlot.GetBinContent(h2DPlot.GetMaximumBin())
    if (setZAxisRangeFromUser): maxZaxisVal = zmax

    if maxZaxisVal >= 1.0:
        rootYear = int(str(ROOT.gROOT.GetVersionDate())[:4])        
        if (rootYear > 2016):
            h2DPlot.GetZaxis().SetMaxDigits(3)
        else:
            print "Warning in drawCorrelationPlot: TAxis::SetMaxDigits() not implemented for ROOT versions before 2017 (rough estimate)"
            print "Will not exit, but instruction will be neglected"
        if maxZaxisVal > 9999.:
            h2DPlot.GetZaxis().SetTitleOffset(h2DPlot.GetZaxis().GetTitleOffset()+0.15)
            print "Changing title offset by 0.15"
    else:
        i = 1
        tryNext = True
        while tryNext:
            tmpVal = maxZaxisVal * pow(10,i)
            if tmpVal >= 1.0: tryNext = False 
            else: i += 1
        if i > 1:            
            print "Max Z axis < 1, will try to adjust distance of Z axis title to Z axis"
            print "i = %d: will move Z axis offset by 0.45" % i
            # for numbers like 0.025 or with more 0 after ., make increase distance between Z axis title and the Z axis
            h2DPlot.GetZaxis().SetTitleOffset(h2DPlot.GetZaxis().GetTitleOffset()+0.45)

    h2DProfile = 0
    if drawProfileX:
        h2DProfile = h2D.ProfileX("%s_pfx" %h2D.GetName())
        h2DProfile.SetMarkerColor(ROOT.kBlack)
        h2DProfile.SetMarkerStyle(20)
        h2DProfile.SetMarkerSize(1)
        h2DProfile.Draw("EPsame")
        
    # not yet implemented
    if not plotLabel == "ForceTitle": CMS_lumi(canvas,"",True,False)
    setTDRStyle()
    #print ">>>>>>>>>>>>>> check <<<<<<<<<<<<<<<<<<<"

    if plotLabel == "ForceTitle":
        ROOT.gStyle.SetOptTitle(1)        

    #h2DPlot.GetZaxis().SetMaxDigits(1)  #for N>99, should use scientific notation, I'd like to make it work only with negative exponential but haven't succeeded yet
    # canvas.Modified()
    # canvas.Update()

    leg = ROOT.TLegend(0.39,0.75,0.89,0.95)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(62)
    if plotLabel not in ["", "ForceTitle"]: leg.AddEntry(0,plotLabel,"")
    if drawProfileX: leg.AddEntry(0,"Correlation = %.2f" % h2DPlot.GetCorrelationFactor(),"")
    leg.Draw("same")

    if (draw_both0_noLog1_onlyLog2 == 0 or draw_both0_noLog1_onlyLog2 == 1):
        for ext in ['png', 'pdf']:
            canvas.SaveAs('{od}/{cn}.{ext}'.format(od=outdir, cn=canvasName, ext=ext))
        
    if (draw_both0_noLog1_onlyLog2 == 0 or draw_both0_noLog1_onlyLog2 == 2):
        canvas.SetLogz()
        for ext in ['png', 'pdf']:
            canvas.SaveAs('{od}/{cn}_logZ.{ext}'.format(od=outdir, cn=canvasName, ext=ext))
        canvas.SetLogz(0)
コード例 #19
0
def Estimate_QCD(config,
                 sysname='',
                 direction='',
                 is_weight=False,
                 processlist=[],
                 trees={},
                 is_overflow=True):
    fname = config.get('GENERAL', 'hfile')
    verbose = config.getboolean('GENERAL', 'verbose')
    calc_qwfac = config.getboolean('GENERAL', 'calc_qwfac')
    apply_qwfac = config.getboolean('GENERAL', 'apply_qwfac')
    setQCD0error = config.getboolean('GENERAL', 'setQCD0error')
    weight = config.get('GENERAL', 'weight')
    test_nominal = config.getboolean('GENERAL', 'test_nominal')
    use_bin_opt = config.getboolean('GENERAL', 'use_bin_opt')
    interest_var = ast.literal_eval(config.get('GENERAL', 'var'))
    hname = OrderedDict(sorted(dnames.items(), key=lambda t: t[0]))
    bkgs_ = list(filter(lambda x: x not in ['QCD', 'data'], processlist))
    hvar = []
    hlist = []
    #CR_add_cut = '(top1_m < 150 ||top1_m > 200)'
    SR_add_cut = '(1==1)'
    CR_add_cut = '(1==1)'
    if 'shape' in sysname:
        is_shape = True
        shapelist = ast.literal_eval(config.get('SYSTEMATICS', 'shapelist'))
    else:
        is_shape = False
    if 'lN' in sysname:
        is_lN = True
        lNlist = ast.literal_eval(config.get('SYSTEMATICS', 'lNlist'))
    else:
        is_lN = False
    if is_weight:
        print 'is_weight'
        weight_name = sysname[1:].partition('_')[0]  #btagweight
        if 'top' not in weight_name and 'LHE' not in weight_name:
            weight = weight.replace(weight_name, sysname[1:] + '_' + direction)
            topweight = weight + '*topweight'
            #+'*topweight'
        else:
            print 'LHE or top'
            if 'top' in weight_name:
                topweight = weight + '*topweight_' + direction
            else:
                topweight = weight + '*topweight*{0}_{1}*{2}'.format(
                    sysname[1:], direction, LHE_fac[sysname + '_' + direction])
                print topweight
                print '*' * 80

    else:
        topweight = weight + '*topweight'
    #+'*topweight'

    if verbose: print 'weight: ', weight

    interest_var = ast.literal_eval(config.get('GENERAL', 'var'))
    control_var = ast.literal_eval(config.get('QCD_ESTIMATION',
                                              'control_vars'))
    plot_control = config.getboolean('QCD_ESTIMATION', 'plot_control')
    qcd_first = config.getboolean('QCD_ESTIMATION', 'qcd_first')
    plot_data = config.getboolean('QCD_ESTIMATION', 'plot_data')
    save_plots = config.getboolean('QCD_ESTIMATION', 'save_plots')

    if plot_control:
        interest_var += control_var
        print interest_var, 'interest_vars'

    fout = rt.TFile(fname, "UPDATE")
    xdist = -0.35
    add_cut = ''
    regcuts = []
    add_cut_nom = ''
    regcutsnom = []
    for item, cut in config.items('CUT'):
        if item not in ast.literal_eval(config.get('QCD_ESTIMATION',
                                                   'CR_vars')):
            add_cut += item + sysname + direction + cut + '&&'
            add_cut_nom += item + cut + '&&'
        else:
            if 'qgLR' not in item:
                add_cut += item + sysname + direction + '>=-1&&'
                add_cut_nom += item + '>=-1&&'
            else:
                add_cut += item + sysname + direction + '>0&&'
                add_cut_nom += item + '>0&&'
            if '>' in cut or '>=' in cut: SRdir = 0
            else: SRdir = 1
            regcuts.append([
                item + sysname + direction,
                [s for s in re.findall(r'-?\d+\.?\d*', cut)][0], SRdir
            ])
            regcutsnom.append(
                [item, [s for s in re.findall(r'-?\d+\.?\d*', cut)][0], SRdir])

    add_cut_nom = add_cut_nom[:-2]  #Remove last &&
    add_cut = add_cut[:-2]  #Remove last &&

    if verbose:
        print add_cut, add_cut_nom, 'cuts for qcd est'
        print regcuts, regcutsnom, 'regcuts'
    #print 'other cuts: ',add_cut

    regions = OrderedDict()
    regionsnom = OrderedDict()

    # regions["CR1"]={'cut':'(jet_CSV[0]<0.9535||jet_CSV[1]<0.9535 && (jet_CSV[0]>=0.8484 && jet_CSV[1]>=0.8484))','data':None,'bkg':None,'QCD':None}
    # regions["CR2"]={'cut':'((jet_CSV[0]<0.8484 || jet_CSV[1]<0.8484) && qgLR<0.722416)','data':None,'bkg':None,'QCD':None}
    # regions["VR"]={'cut':'((jet_CSV[0]<0.8484 || jet_CSV[1]<0.8484) && qgLR>0.722416)','data':None,'bkg':None,'QCD':None}
    # regions["SR"]={'cut':'(jet_CSV[0]>=0.9535 && jet_CSV[1]>=0.9535 )','data':None,'bkg':None,'QCD':None}

    regions["CR1"] = {
        'cut':
        '(' + regcuts[0][0] + ('<' if regcuts[0][2] else '>') + regcuts[0][1] +
        '&&' + regcuts[1][0] + ('>' if regcuts[1][2] else '<') +
        regcuts[1][1] + ')' + '&&' + CR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regions["CR2"] = {
        'cut':
        '(' + regcuts[0][0] + ('>' if regcuts[0][2] else '<') + regcuts[0][1] +
        '&&' + regcuts[1][0] + ('>' if regcuts[1][2] else '<') +
        regcuts[1][1] + ')' + '&&' + CR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regions["VR"] = {
        'cut':
        '(' + regcuts[0][0] + ('>' if regcuts[0][2] else '<') + regcuts[0][1] +
        '&&' + regcuts[1][0] + ('<' if regcuts[1][2] else '>') +
        regcuts[1][1] + ')' + '&&' + SR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regions["SR"] = {
        'cut':
        '(' + regcuts[0][0] + ('<' if regcuts[0][2] else '>') + regcuts[0][1] +
        '&&' + regcuts[1][0] + ('<' if regcuts[1][2] else '>') +
        regcuts[1][1] + ')' + '&&' + SR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }

    regionsnom["CR1"] = {
        'cut':
        '(' + regcutsnom[0][0] + ('<' if regcutsnom[0][2] else '>') +
        regcutsnom[0][1] + '&&' + regcutsnom[1][0] +
        ('>' if regcutsnom[1][2] else '<') + regcutsnom[1][1] + ')' + '&&' +
        CR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regionsnom["CR2"] = {
        'cut':
        '(' + regcutsnom[0][0] + ('>' if regcutsnom[0][2] else '<') +
        regcutsnom[0][1] + '&&' + regcutsnom[1][0] +
        ('>' if regcutsnom[1][2] else '<') + regcutsnom[1][1] + ')' + '&&' +
        CR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regionsnom["VR"] = {
        'cut':
        '(' + regcutsnom[0][0] + ('>' if regcutsnom[0][2] else '<') +
        regcutsnom[0][1] + '&&' + regcutsnom[1][0] +
        ('<' if regcutsnom[1][2] else '>') + regcutsnom[1][1] + ')' + '&&' +
        SR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }
    regionsnom["SR"] = {
        'cut':
        '(' + regcutsnom[0][0] + ('<' if regcutsnom[0][2] else '>') +
        regcutsnom[0][1] + '&&' + regcutsnom[1][0] +
        ('<' if regcutsnom[1][2] else '>') + regcutsnom[1][1] + ')' + '&&' +
        SR_add_cut,
        'data':
        None,
        'bkg':
        None,
        'QCD':
        None
    }

    if is_weight or test_nominal or is_lN or is_shape:
        regions = regionsnom
        add_cut = add_cut_nom

    print 'Doing QCD Estimate'
    for reg in regions:
        print reg, regions[reg]['cut']

    t_data = trees['data']

    scaleSR = scaleVR = 0

    for ivar, var in enumerate(interest_var):
        rt.gDirectory.GetList().Delete()
        varnom = var
        if is_weight == False and sysname != '' and is_lN == False and is_shape == False:
            var += sysname + direction
        for proc in hname:
            if sysname != '':
                if is_weight:
                    if 'btag' in sysname:
                        nuis_name = sysname.replace('btagweight',
                                                    'CMS_btag') + direction
                    else:
                        nuis_name = '_CMS' + sysname.replace(
                            'weight', '_Weight') + direction
                elif is_lN:
                    nuis_name = sysname.replace('lN', '')
                elif is_shape:
                    nuis_name = sysname.replace('shape', '')
                else:
                    nuis_name = '_CMS' + sysname + '_j' + direction
            else:
                nuis_name = sysname + direction
        #print nuis_name
        #print is_lN
        for reg in regions:
            if verbose: print reg
            if not fout.GetDirectory(reg):
                fout.mkdir(reg)
            fout.cd(reg)

            if verbose: print 'doing ', reg, 'scaleVR = ', scaleVR
            if use_bin_opt:
                hopt = rt.TH1F('hdata' + reg + varnom + sysname,
                               'hdata' + reg + varnom + sysname,
                               len(opt_bin) - 1, opt_bin)
                t_data.Draw(varnom + '>>' + 'hdata' + reg + varnom + sysname,
                            "(" + add_cut_nom + ")*" + regionsnom[reg]['cut'])

                hdata = hopt.Clone('data_obs')
            else:
                t_data.Draw(
                    varnom + '>>' + 'hdata' + reg + varnom + sysname +
                    str(vartitle[varnom][1]),
                    "(" + add_cut_nom + ")*" + regionsnom[reg]['cut'])
                print varnom + '>>' + 'hdata' + reg + varnom + sysname + str(
                    vartitle[varnom]
                    [1]), "(" + add_cut_nom + ")*" + regionsnom[reg]['cut']
                #print reg, varnom + '>>'+ 'hdata'+reg+varnom+sysname+ str(vartitle[varnom][1]),"("+add_cut_nom+")*"+regionsnom[reg]['cut']
                #print 'data: ',"("+add_cut_nom+")*"+regionsnom[reg]['cut']
                hdata = rt.gDirectory.Get('hdata' + reg + varnom +
                                          sysname).Clone('data_obs')

            if is_overflow: AddOverflow(hdata)
            if sysname == '': hdata.Write()

            if verbose:
                print var.partition('_')[0] + '>>' + 'hdata' + reg + str(
                    vartitle[varnom]
                    [1]), "(" + add_cut_nom + ")*" + regions[reg]['cut']
            hdata.Sumw2()

            hbkg = hdata.Clone('bkg' + reg)
            hbkg.Reset()
            for process in bkgs_:
                #print process
                if process in processgroup and process != 'QCD':
                    for isub, subprocess in enumerate(processgroup[process]):
                        #print subprocess
                        if use_bin_opt:
                            hopt = rt.TH1F('h' + reg + subprocess + sysname,
                                           'h' + reg + subprocess + sysname,
                                           len(opt_bin) - 1, opt_bin)
                            trees[subprocess].Draw(
                                var + '>>' + 'h' + reg + subprocess + sysname,
                                weight + "*(" + add_cut + "&&" +
                                regions[reg]['cut'] + ')')
                        else:
                            trees[subprocess].Draw(
                                var + '>>' + 'h' + reg + subprocess + sysname +
                                str(vartitle[varnom][1]), weight + "*(" +
                                add_cut + "&&" + regions[reg]['cut'] + ')')

                        if isub == 0:
                            if use_bin_opt:
                                h = hopt.Clone(hname[process] + nuis_name)
                            else:
                                h = rt.gDirectory.Get(
                                    'h' + reg + subprocess +
                                    sysname).Clone(hname[process] + nuis_name)

                            if calc_qwfac and (reg == 'SR'):
                                Calculate_qwfrac(trees[subprocess],
                                                 weight + "*(" + add_cut + ')',
                                                 subprocess)
                            if is_overflow: AddOverflow(h)
                            h.Sumw2()
                            h.Scale(dscale[subprocess])
                            if apply_qwfac: h.Scale(qwfac[subprocess])
                            # if calc_qwfac:Calculate_qwfrac(tree[subprocess],weight,subprocess)
                            # else: h.Scale(qwfac[subprocess])
                        else:
                            if use_bin_opt:
                                hsub = hopt.Clone(hname[process] + nuis_name)
                            else:
                                hsub = rt.gDirectory.Get(
                                    'h' + reg + subprocess +
                                    sysname).Clone(hname[process] + nuis_name)

                            if calc_qwfac and (reg == 'SR'):
                                Calculate_qwfrac(trees[subprocess],
                                                 weight + "*(" + add_cut + ')',
                                                 subprocess)
                            if is_overflow: AddOverflow(hsub)
                            # if calc_qwfac:Calculate_qwfrac(tree[subprocess],weight,subprocess)
                            # else:h.Scale(qwfac[subprocess])
                            hsub.Sumw2()
                            hsub.Scale(dscale[subprocess])
                            if apply_qwfac: hsub.Scale(qwfac[subprocess])
                            h.Add(hsub)
                        if verbose:
                            print 'subprocess: ', var + '>>' + 'h' + reg + subprocess + str(
                                vartitle[varnom]
                                [1]), weight + "*(" + add_cut + "&&" + regions[
                                    reg]['cut'] + ')'
                        #print type(hbkg),type(h)
                    if is_lN:
                        #print nuis_name[1:]
                        #print dnames[process]
                        if lNlist[dnames[process]].has_key(nuis_name[1:]):
                            if direction == 'Up':
                                h.Scale(
                                    lNlist[dnames[process]][nuis_name[1:]][0])
                                h.SetName(h.GetName() + direction)
                            elif direction == 'Down':
                                h.Scale(
                                    lNlist[dnames[process]][nuis_name[1:]][1])
                                h.SetName(h.GetName() + direction)
                            else:
                                print 'wtf mate'
                    hbkg.Add(h)
                    if direction in h.GetName() or sysname == '':
                        #print h.GetName()
                        #print reg
                        h.Write()

                elif 'ttbar' in process:
                    for tproc in ttCls:
                        if use_bin_opt:
                            hopt = rt.TH1F('h' + reg + tproc + var + sysname,
                                           'h' + reg + tproc + var + sysname,
                                           len(opt_bin) - 1, opt_bin)
                            trees[tproc].Draw(
                                var + '>>' + 'h' + reg + tproc + var + sysname,
                                topweight + "*(" + add_cut + "&&" +
                                ttCls[tproc] + "&&" + regions[reg]['cut'] +
                                ')')
                        else:
                            trees[tproc].Draw(
                                var + '>>' + 'h' + reg + tproc + var +
                                sysname + str(vartitle[varnom][1]), topweight +
                                "*(" + add_cut + "&&" + ttCls[tproc] + "&&" +
                                regions[reg]['cut'] + ')')
                            print var + '>>' + 'h' + reg + tproc + var + sysname + str(
                                vartitle[varnom][1]
                            ), topweight + "*(" + add_cut + "&&" + ttCls[
                                tproc] + "&&" + regions[reg]['cut'] + ')'

                        #print var + '>>'+ 'h'+reg+tproc+var+sysname+ str(vartitle[varnom][1]),topweight+"*("+add_cut+"&&"+ttCls[tproc]+"&&"+regions[reg]['cut']+')'
                        if verbose:
                            print 'ttbar options: ', var + '>>' + 'h' + reg + tproc + var + sysname + str(
                                vartitle[varnom][1]
                            ), topweight + "*(" + add_cut + "&&" + ttCls[
                                tproc] + "&&" + regions[reg]['cut'] + ')'
                        if use_bin_opt:
                            h = hopt.Clone(hname[tproc] + nuis_name)
                        else:
                            h = rt.gDirectory.Get('h' + reg + tproc + var +
                                                  sysname).Clone(hname[tproc] +
                                                                 nuis_name)
                        if calc_qwfac and (reg == 'SR'):
                            Calculate_qwfrac(
                                trees[tproc], topweight + "*(" + add_cut +
                                "&&" + ttCls[tproc] + ')', tproc)
                        if is_overflow: AddOverflow(h)
                        #print h.Integral()
                        if verbose:
                            print 'tproc before: ', tproc, ' ntproc:', h.Integral(
                            )
                        h.Sumw2()
                        h.Scale(dscale[process])
                        if apply_qwfac: h.Scale(qwfac[tproc])
                        if is_lN:
                            if lNlist[tproc].has_key(nuis_name[1:]):
                                if direction == 'Up':
                                    h.Scale(lNlist[tproc][nuis_name[1:]][0])
                                    h.SetName(h.GetName() + direction)
                                elif direction == 'Down':
                                    h.Scale(lNlist[tproc][nuis_name[1:]][1])
                                    h.SetName(h.GetName() + direction)
                                else:
                                    print 'wtf mate'

                        #if not is_weight and direction == 'Up':
                        #h.SetBinContent(1,h.GetBinContent(1)*1.02)

                        #rint 'tproc: ',tproc,' ntproc:', h.Integral()
                        #if reg in ['SR','VR']:h.Scale(qwfac[tproc])
                        if verbose:
                            print 'tproc: ', tproc, ' ntproc:', h.Integral()
                        hbkg.Add(h)
                        if direction in h.GetName() or sysname == '':
                            h.Write()

                else:
                    if use_bin_opt:
                        hopt = rt.TH1F('h' + reg + process + sysname,
                                       'h' + reg + process + sysname,
                                       len(opt_bin) - 1, opt_bin)
                        trees[process].Draw(
                            var + '>>' + 'h' + reg + process + sysname,
                            weight + "*(" + add_cut + "&&" +
                            regions[reg]['cut'] + ')')
                        h = hopt.Clone(hname[process] + nuis_name)
                    else:
                        trees[process].Draw(
                            var + '>>' + 'h' + reg + process + sysname +
                            str(vartitle[varnom][1]), weight + "*(" + add_cut +
                            "&&" + regions[reg]['cut'] + ')')

                        h = rt.gDirectory.Get('h' + reg + process +
                                              sysname).Clone(hname[process] +
                                                             nuis_name)
                    if calc_qwfac and (reg == 'SR'):
                        Calculate_qwfrac(trees[process],
                                         weight + "*(" + add_cut + ')',
                                         process)
                    if is_overflow: AddOverflow(h)
                    h.Sumw2()
                    h.Scale(dscale[process])
                    if apply_qwfac: h.Scale(qwfac[process])
                    if is_lN:
                        if lNlist[dnames[process]].has_key(nuis_name[1:]):
                            if direction == 'Up':
                                h.Scale(
                                    lNlist[dnames[process]][nuis_name[1:]][0])
                                h.SetName(h.GetName() + direction)
                            elif direction == 'Down':
                                h.Scale(
                                    lNlist[dnames[process]][nuis_name[1:]][1])
                                h.SetName(h.GetName() + direction)
                            else:
                                print 'wtf mate'
                    #if reg in ['SR','VR']:h.Scale(qwfac[process])
                    if h.Integral() < 0: print process
                    if verbose: print 'before: ', hbkg.Integral()
                    if verbose:
                        print 'process ', process, ' integral: ', h.Integral()
                    hbkg.Add(h)
                    if verbose: print 'after: ', hbkg.Integral()
                    if direction in h.GetName() or sysname == '':
                        h.Write()

            hres = hdata.Clone("hbkgsub" + reg)
            print 'Data evts: ', hdata.Integral()
            print 'background evts without QCD: ', hbkg.Integral()
            hres.Add(hbkg, -1)
            #Set_Zero(hres)
            regions[reg]['QCD'] = hres
            if verbose: print 'QCD estimate ', hres.Integral()
            regions[reg]['bkg'] = hbkg
            regions[reg]['data'] = hdata.Clone('Data' + reg)

            if "CR" not in reg:
                if reg == 'SR':
                    if regions['CR1']['QCD'] == None:
                        print 'Do CRs first!'
                        continue
                    elif scaleVR == 0:
                        print 'Do VR first!'
                        continue
                    else:

                        if ivar == 0:
                            nqcd = regions['CR1']['QCD'].Integral()
                            scaleSR = hres.Integral() / nqcd
                            # nqcd = regions['CR1']['QCD'].GetBinContent(1)
                            # scaleSR = hres.GetBinContent(1)/nqcd
                            #scaleSR = scaleVR
                        print 'SR/CR1: ', scaleSR, 'nqcd CR1: ', nqcd

                        hSR = regions['CR1']['QCD'].Clone('QCD' + nuis_name)
                        hSR.Scale(scaleSR)
                        if is_shape:  #hot fix for shape extrapolation uncertainty
                            correction = shapelist['QCD']['bkg_extrap']
                            if direction == 'Down':
                                correction = [
                                    2 - bin
                                    for bin in shapelist['QCD']['bkg_extrap']
                                ]
                            for bin, corr in enumerate(correction):
                                hSR.SetBinContent(
                                    bin + 1,
                                    hSR.GetBinContent(bin + 1) * corr)
                            hSR.SetName('QCD' + nuis_name + direction)

                        regions[reg]['QCD'] = hSR
                        if is_lN: hSR.SetName('QCD' + nuis_name + direction)
                        hSR.Write()

                if reg == 'VR':
                    if regions['CR2']['QCD'] == None:
                        print 'Do CRs first!'
                        continue

                    else:
                        if ivar == 0:
                            nqcd = regions['CR2']['QCD'].Integral()
                            scaleVR = hres.Integral() / nqcd
                            # nqcd = regions['CR2']['QCD'].GetBinContent(1)
                            # scaleVR = hres.GetBinContent(1)/nqcd
                            print 'VR/CR2: ', scaleVR, 'nqcd CR2: ', nqcd
                        hSR = regions['CR2']['QCD'].Clone('QCD' + nuis_name)
                        hSR.Scale(scaleVR)
                        regions[reg]['QCD'] = hSR
                        if is_lN: hSR.SetName('QCD' + nuis_name + direction)
                        hSR.Write()
            else:
                hres.SetName('QCD' + nuis_name)
                if is_lN: hres.SetName('QCD' + nuis_name + direction)
                hres.Write()
            fout.cd("../")

        if plot_control:
            for reg in regions:
                colors = {
                    'ttbar': ['#2c7fb8', 't#bar{t} + Minor Bkgs.'],
                    'Multijet': ['#31a354', 'Multijet']
                }
                if plot_data:
                    regions[reg]['data'].SetMarkerColor(1)
                    regions[reg]['data'].SetMarkerStyle(20)
                    regions[reg]['data'].SetMarkerSize(1.0)
                regions[reg]['bkg'].SetFillColor(
                    rt.TColor.GetColor(colors['ttbar'][0]))
                regions[reg]['QCD'].SetFillColor(
                    rt.TColor.GetColor(colors['Multijet'][0]))
                hstack = rt.THStack(vartitle[varnom][0] + reg,
                                    vartitle[varnom][0] + reg)
                if qcd_first:
                    hstack.Add(regions[reg]['bkg'])
                    hstack.Add(regions[reg]['QCD'])
                else:
                    hstack.Add(regions[reg]['QCD'])
                    hstack.Add(regions[reg]['bkg'])

                c = rt.TCanvas(var + reg + weight, var + reg + weight, 5, 30,
                               W_ref, H_ref)
                pad1 = rt.TPad("pad1", "pad1", 0.0, 0.15 if plot_data else 0.0,
                               1, 1.0)
                pad1.Draw()
                pad1.cd()
                SetupCanvas(pad1, vartitle[varnom][2])
                if use_bin_opt:
                    hframe = rt.TH1F(
                        var + reg,
                        "h; {0}; Events ".format(vartitle[varnom][0]),
                        len(opt_bin) - 1, opt_bin)
                else:
                    hframe = rt.TH1F(
                        var + reg,
                        "h; {0}; Events ".format(vartitle[varnom][0]),
                        vartitle[varnom][1][0], vartitle[varnom][1][1],
                        vartitle[varnom][1][2])
                hframe.SetAxisRange(
                    0.1, regions[reg]['data'].GetMaximum() *
                    1e4 if vartitle[varnom][2] == 1 else
                    regions[reg]['data'].GetMaximum() * 1.8, "Y")
                xAxis = hframe.GetXaxis()
                xAxis.SetNdivisions(6, 5, 0)
                yAxis = hframe.GetYaxis()
                yAxis.SetNdivisions(6, 5, 0)
                yAxis.SetTitleOffset(1)
                hframe.Draw()
                c.Update()
                c.Modified()
                hstack.Draw("sameaxis")
                hstack.Draw('histsame')
                herr = regions[reg]['QCD'].Clone('stat.err')
                herr.Add(regions[reg]['bkg'])
                herr.SetFillColor(rt.kBlack)
                herr.SetMarkerStyle(0)
                herr.SetFillStyle(3354)
                rt.gStyle.SetHatchesLineWidth(1)
                rt.gStyle.SetHatchesSpacing(2)
                if plot_data: regions[reg]['data'].Draw("esamex0")
                herr.Draw('e2same')
                CMS_lumi.CMS_lumi(c, iPeriod, iPos)

                pad1.cd()
                pad1.Update()
                pad1.RedrawAxis()
                frame = c.GetFrame()

                latex = rt.TLatex()

                legend = rt.TPad("legend_0", "legend_0", x0_l - 0.15, y0_l,
                                 x1_l, y1_l)

                legend.Draw()
                legend.cd()

                if plot_data:
                    gr_l = rt.TGraphErrors(1, x_l, y_l, ex_l, ey_l)
                    rt.gStyle.SetEndErrorSize(0)
                    gr_l.SetMarkerSize(0.9)
                    gr_l.Draw("0P")

                latex.SetTextFont(42)
                latex.SetTextAngle(0)
                latex.SetTextColor(rt.kBlack)
                latex.SetTextSize(0.12)
                latex.SetTextAlign(12)
                yy_ = y_l[0]
                if plot_data:
                    latex.DrawLatex(xx_ + 1. * bwx_, yy_, "Data")
                latex.DrawLatex(xx_ + 1. * bwx_, yy_ - gap_, reg)
                for hist in colors:
                    box_ = rt.TBox()
                    SetupBox(box_, yy_, rt.TColor.GetColor(colors[hist][0]))
                    box_.DrawBox(xx_ - bwx_ / 2 - xdist, yy_ - bwy_ / 2,
                                 xx_ + bwx_ / 2 - xdist, yy_ + bwy_ / 2)
                    box_.SetFillStyle(0)
                    box_.DrawBox(xx_ - bwx_ / 2 - xdist, yy_ - bwy_ / 2,
                                 xx_ + bwx_ / 2 - xdist, yy_ + bwy_ / 2)
                    latex.DrawLatex(xx_ + 1. * bwx_ - xdist, yy_,
                                    colors[hist][1])
                    yy_ -= gap_

                box_ = rt.TBox()
                SetupBox(box_, yy_)
                box_.SetFillStyle(3354)
                box_.DrawBox(xx_ - bwx_ / 2 - xdist, yy_ - bwy_ / 2,
                             xx_ + bwx_ / 2 - xdist, yy_ + bwy_ / 2)
                latex.DrawLatex(xx_ + 1. * bwx_ - xdist, yy_, 'Stat. Uncert.')
                yy_ -= gap_
                c.Update()
                c.cd()
                if plot_data:
                    p1r = rt.TPad("p4", "", 0, 0, 1, 0.26)

                    p1r.SetRightMargin(0.04)
                    p1r.SetLeftMargin(0.12)
                    p1r.SetTopMargin(0.0)
                    p1r.SetBottomMargin(0.42)
                    p1r.SetTicks()
                    p1r.Draw()
                    p1r.cd()

                    xmin = float(herr.GetXaxis().GetXmin())
                    xmax = float(herr.GetXaxis().GetXmax())
                    one = rt.TF1("one", "1", xmin, xmax)
                    one.SetLineColor(1)
                    one.SetLineStyle(2)
                    one.SetLineWidth(1)

                    nxbins = herr.GetNbinsX()
                    hratio = regions[reg]['data'].Clone()

                    he = herr.Clone()
                    he.SetFillColor(16)
                    he.SetFillStyle(1001)
                    print reg
                    for b in range(nxbins):
                        nbkg = herr.GetBinContent(b + 1)
                        ebkg = herr.GetBinError(b + 1)

                        ndata = regions[reg]['data'].GetBinContent(b + 1)
                        edata = regions[reg]['data'].GetBinError(b + 1)
                        r = ndata / nbkg if nbkg > 0 else 0

                        #print 'bin: ',b+1,  ' r: ',r
                        #print str(r) + '\t'
                        rerr = edata / nbkg if nbkg > 0 else 0

                        hratio.SetBinContent(b + 1, r)
                        hratio.SetBinError(b + 1, rerr)

                        he.SetBinContent(b + 1, 1)
                        he.SetBinError(b + 1, ebkg / nbkg if nbkg > 0 else 0)

                    hratio.GetYaxis().SetRangeUser(0.0, 2.0)

                    hratio.SetTitle("")

                    hratio.GetXaxis().SetTitle(vartitle[varnom][0])
                    hratio.GetXaxis().SetTitleSize(0.156)
                    hratio.GetXaxis().SetLabelSize(0.171)
                    #hratio.GetXaxis().SetTickLength(0.09)

                    #for b in range(hratio.GetNbinsX()):
                    #    hratio.GetXaxis().SetBinLabel(b+1, str(int(hratio.GetBinLowEdge(b+1))) )

                    hratio.GetXaxis().SetLabelOffset(0.02)

                    hratio.GetYaxis().SetTitleSize(0.196)
                    hratio.GetYaxis().SetLabelSize(0.171)
                    hratio.GetYaxis().SetTitleOffset(0.30)
                    hratio.GetYaxis().SetTitle("      Data/MC")
                    hratio.GetYaxis().SetDecimals(1)
                    hratio.GetYaxis().SetNdivisions(3, 2, 0,
                                                    rt.kTRUE)  #was 402
                    hratio.GetXaxis().SetNdivisions(6, 5, 0)

                    hratio.Draw("pe")
                    #    setex2.Draw()
                    he.Draw("e2same")
                    one.Draw("SAME")
                    #turn off horizontal error bars
                    #    setex1.Draw()
                    hratio.Draw("PEsame")
                    hratio.Draw("PE0X0same")
                    hratio.Draw("sameaxis")  #redraws the axes
                    p1r.Update()
                if save_plots:
                    if not os.path.exists(destination + "/QCD Estimation"):
                        os.makedirs(destination + "/QCD Estimation")
                    else:
                        print "WARNING: directory already exists. Will overwrite existing files..."
                        c.SaveAs(destination + "/QCD Estimation/" + reg + var +
                                 ".pdf")

        # fout.cd()
        # for reg in regions:
        #     regions[reg]['data'].Write()
        #     regions[reg]['bkg'].Write()
        #     regions[reg]['QCD'].Write()
        #     if verbose:
        #         regions[reg]['data'].GetName()
        #         print regions[reg]['bkg'].GetName()
        #         print regions[reg]['QCD'].GetName()

    fout.Close()
コード例 #20
0
ファイル: fitbkg.py プロジェクト: hbprosper/monoHZZ4LRun2016
def main():
    if len(sys.argv) > 1:
        fstate = sys.argv[1]
    else:
        fstate = ''
    decor = fstate
    if decor != '':
        decor += '_'

    sources = ('%s/fig_%sbkg.root' % (PATH, decor), 'bkg', kMagenta + 1)

    # ---------------------------------------
    # get data histogram
    # ---------------------------------------
    filename = '%s/fig_%sdata.root' % (PATH, decor)
    fdata = TFile(filename)
    if not fdata.IsOpen():
        sys.exit("** can't open file %s" % filename)
    hdata = fdata.Get(HNAME)
    if not hdata: sys.exit("** can't find hbnn")

    # ---------------------------------------
    # get source histogram
    # ---------------------------------------
    filename, hname, color = sources
    fsrc = TFile(filename)
    if not fsrc.IsOpen():
        sys.exit("** can't open file %s" % fsrc)
    hsrc = fsrc.Get(HNAME).Clone(hname)
    if not hsrc: sys.exit("** can't find histogram")

    # ---------------------------------------
    # set up some standard graphics style
    # ---------------------------------------
    tdrstyle.setTDRStyle()
    #gStyle.SetCanvasPreferGL(True)
    gStyle.SetPadRightMargin(0.12)
    #gStyle.SetOptStat('ei')
    gStyle.SetOptStat('i')
    gStyle.SetStatFont(42)
    gStyle.SetStatFontSize(0.03)
    gStyle.SetStatBorderSize(1)
    gStyle.SetStatH(0.2)
    gStyle.SetStatW(0.3)
    gStyle.SetStatX(0.83)
    gStyle.SetStatY(0.93)

    # change the CMS_lumi variables (see CMS_lumi.py)
    iPeriod = 4
    iPos = 0
    CMS_lumi.relPosX = 0.12
    CMS_lumi.lumi_13TeV = "36.0 fb^{-1}"
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    vdouble = vector("double")

    # ---------------------------------------
    # plot data
    # ---------------------------------------
    ymax = 1.2 * hdata.GetMaximum()
    ii = int(ymax / 10)
    ymax = (ii + 1) * 10

    hdata.SetMaximum(ymax)
    hdata.SetNdivisions(505, 'X')

    xbins = int(hdata.GetNbinsX())
    width = hdata.GetXaxis().GetBinWidth(1)
    xmin = int(hdata.GetXaxis().GetBinLowEdge(1))
    xmax = int(hdata.GetXaxis().GetBinLowEdge(xbins) + width)

    postfix = "_%s_%3.3d_%3.3d" % (HNAME, xmin, xmax)

    cname = "fig_%sdata_%s" % (decor, postfix)
    canvas = TCanvas(cname, cname, 10, 10, 500, 500)
    canvas.cd()
    hdata.Draw("ep gl")
    canvas.Update()
    canvas.SaveAs('.png')
    gSystem.ProcessEvents()
    sleep(1)
    del canvas

    # ---------------------------------------
    # plot source
    # ---------------------------------------
    cname = "fig_%s%s%s" % (decor, hname, postfix)
    canvas = TCanvas(cname, cname, 10, 10, 500, 500)
    canvas.cd()
    hsrc.SetNdivisions(505, 'X')
    hsrc.Draw("hist gl")
    canvas.Update()
    canvas.SaveAs('.png')
    gSystem.ProcessEvents()
    sleep(1)
    del canvas

    # get counts
    datum = 0.0
    bkg = 0.0

    fb = []
    D = []
    for ii in xrange(xbins):
        bkg += hsrc.GetBinContent(ii + 1)
        datum += hdata.GetBinContent(ii + 1)

        if bkg > 10:
            fb.append(bkg)
            D.append(datum)

            print '%4d\t%10.2f\t%10.0f' % (len(D), bkg, datum)
            bkg = 0.0
            datum = 0.0

    # ---------------------------------------
    # fit
    # ---------------------------------------
    t = []
    bguess = sum(fb)
    fb = map(lambda x: x / bguess, fb)

    def Func(npar, grad, fval, xval, flag):
        fval[0] = 0.0
        B = xval[0]
        for i in xrange(len(D)):
            theory = B * fb[i]
            x = D[i] - theory
            fval[0] += x * x / theory

    minuit = TMinuit(1)
    minuit.SetPrintLevel(1)
    minuit.SetFCN(Func)
    minuit.SetErrorDef(1)

    # Find mode of posterior density
    # make some reasonable guesses for fit
    total = sum(D)
    status = Long()

    bstep = bguess / 1000
    bmin = 0.0
    bmax = 2 * total
    minuit.mnparm(0, "B", bguess, bstep, bmin, bmax, status)
    if status != 0:
        sys.exit("** mnparam status code: %d" % status)

    args = array('d')
    args.append(MAXITER)
    args.append(TOLERANCE)
    minuit.mnexcm(METHOD, args, 2, status)
    if status != 0:
        sys.exit("** mnexcm %s failed" % METHOD)

    # Print results
    print "-" * 80
    print "total observed count: %d" % total
    print "%-10s\t%10s" % ('source', "    estimated count")
    value = Double()
    dvalue = Double()
    minuit.GetParameter(0, value, dvalue)
    mode = value
    error = dvalue
    print "%-10s\t%10.1f +/-%- 10.1f" % \
      ("", mode, error)

    color = sources[-1]
    hsrc.SetLineColor(color + 2)
    hsrc.SetFillColor(color)
    hsrc.Scale(mode / hsrc.Integral())
    hsrc.SetMaximum(ymax)

    # compute GOF measure
    chisq = 0.0
    for i in xrange(len(D)):
        theory = mode * fb[i]
        x = D[i] - theory
        chisq += x * x / theory
    ndf = len(D) - 1

    print '\nchisq/NDF = %10.1f/%d = %10.2f\n' % (chisq, ndf, chisq / ndf)

    lg = mklegend(0.35, 0.72, 0.25, 0.2)
    lg.SetHeader('events(%s)' % FINALSTATES[fstate])

    lg.SetTextSize(0.04)
    lg.AddEntry(hdata, 'data  %4.0f' % hdata.Integral(), 'p')
    fname, src, color = sources
    src = capitalize(src)
    lg.AddEntry(hsrc,  '%-5s   %6.1f #pm %-6.1f (#color[4]{%6.1f})' \
                    % (src, mode, error, bguess), 'f')

    scribe = Scribe(0.43, 0.68)

    cname = "fig_%sresult%s" % (decor, postfix)
    cfit = TCanvas(cname, cname, 520, 10, 500, 500)
    cfit.cd()
    gStyle.SetOptStat('')

    hdata.SetMaximum(ymax)
    hdata.Draw('ep')
    hsrc.Draw('histsame')
    hdata.Draw('epsame')

    lg.Draw()
    scribe.write('#chi^{2}/NDF = %5.1f / %d = %5.2f\n' % \
                     (chisq, ndf, chisq/ndf))
    scribe.write('#font[12]{m}_{4#font[12]{l}} #in [%d, %d] GeV' %
                 (xmin, xmax))

    CMS_lumi.CMS_lumi(cfit, iPeriod, iPos)
    cfit.SaveAs('.png')
    cfit.Update()
    gSystem.ProcessEvents()

    sleep(5)
コード例 #21
0
def drawHist(histName, plotInfo, plotDirectory, _file):

    canvas.cd()
    canvas.ResetDrawn()
    stack = THStack(histName, histName)
    for sample in stackList:
        #        print sample
        _dir = sample
        if "QCD" in sample:
            continue
            if useQCDMC: _dir = "QCDMu"
            if useQCDDD: _dir = "QCD_DD"
        hist = _file.Get("%s/%s_%s" % (_dir, histName, sample)).Clone(sample)
        hist.SetFillColor(mcList[sample][0])
        hist.SetLineColor(mcList[sample][0])
        hist.Rebin(plotInfo[2])
        stack.Add(hist)
    dataHist = _file.Get("DataMu/%s_DataMu" % (histName))
    dataHist.Rebin(plotInfo[2])

    #histograms list has flag whether it's log or not
    canvas.SetLogy(plotInfo[-1])

    if not plotInfo[-1]:
        stack.SetMaximum(1.45 * max(dataHist.GetMaximum(), stack.GetMaximum()))
    else:
        stack.SetMaximum(100. * max(dataHist.GetMaximum(), stack.GetMaximum()))

    stack.Draw("hist")
    # histograms list has x-axis title
    stack.GetHistogram().GetXaxis().SetTitle(plotInfo[0])
    if not -1 in plotInfo[3]:
        stack.GetHistogram().GetXaxis().SetRangeUser(plotInfo[3][0],
                                                     plotInfo[3][1])
        dataHist.GetXaxis().SetRangeUser(plotInfo[3][0], plotInfo[3][1])
    stack.GetHistogram().GetYaxis().SetTitle(plotInfo[1])

    dataHist.Draw("e,X0,same")
    legend.Draw("same")

    CMS_lumi.channelText = _channelText + plotInfo[4]
    CMS_lumi.CMS_lumi(canvas, 4, 11)
    canvas.Print("%s/%s.pdf" % (plotDirectory, histName), ".pdf")

    ratio = dataHist.Clone("temp")
    ratio.Add(stack.GetStack().Last(), -1)

    pad1.Clear()
    pad2.Clear()

    canvasRatio.cd()
    canvasRatio.ResetDrawn()

    pad1.Clear()
    pad2.Clear()

    pad1.cd()

    pad1.SetLogy(plotInfo[-1])
    stack.Draw('HIST')
    #    pad1.Update()
    y2 = pad1.GetY2()

    stack.SetMinimum(1)
    #    pad1.Update()
    stack.GetXaxis().SetTitle('')
    #    stack.GetYaxis().SetTitle(dataHist.GetYaxis().GetTitle())

    stack.SetTitle('')
    stack.GetXaxis().SetLabelSize(0)
    stack.GetYaxis().SetLabelSize(gStyle.GetLabelSize() /
                                  (1. - padRatio + padOverlap))
    stack.GetYaxis().SetTitleSize(gStyle.GetTitleSize() /
                                  (1. - padRatio + padOverlap))
    stack.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() *
                                    (1. - padRatio + padOverlap))
    dataHist.Draw('E,X0,SAME')
    legendR.Draw()
    ratio.SetTitle('')

    ratio.GetXaxis().SetLabelSize(gStyle.GetLabelSize() /
                                  (padRatio + padOverlap))
    ratio.GetYaxis().SetLabelSize(gStyle.GetLabelSize() /
                                  (padRatio + padOverlap))
    ratio.GetXaxis().SetTitleSize(gStyle.GetTitleSize() /
                                  (padRatio + padOverlap))
    ratio.GetYaxis().SetTitleSize(gStyle.GetTitleSize() /
                                  (padRatio + padOverlap))
    ratio.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() *
                                    (padRatio + padOverlap - padGap))
    #    ratio.GetYaxis().SetRangeUser(0.75,1.25)
    ratio.SetMaximum(1.15 * ratio.GetMaximum())
    ratio.GetYaxis().SetNdivisions(504)
    ratio.GetXaxis().SetTitle(plotInfo[0])
    ratio.GetYaxis().SetTitle("#splitline{QCD}{Template}")
    ratio.GetYaxis().SetTitleOffset(0.4)

    pad2.cd()
    ratio.SetMarkerStyle(dataHist.GetMarkerStyle())
    ratio.SetMarkerSize(dataHist.GetMarkerSize())
    ratio.SetLineColor(dataHist.GetLineColor())
    ratio.SetLineWidth(dataHist.GetLineWidth())

    oneLine = TF1("oneline", "1", -9e9, 9e9)
    oneLine.SetLineColor(kBlack)
    oneLine.SetLineWidth(1)
    oneLine.SetLineStyle(2)
    TGaxis.SetExponentOffset(-0.075, 0.0, "y")
    ratio.SetFillColor(kGreen + 3)
    ratio.SetLineColor(kGreen + 3)
    ratio.SetMarkerSize(0)

    ratio.Draw('h')
    #    oneLine.Draw("same")

    #    pad2.Update()
    CMS_lumi.CMS_lumi(pad1, 4, 11)
    canvasRatio.Update()
    canvasRatio.RedrawAxis()

    canvasRatio.SaveAs("%s/%s_ratio.pdf" % (plotDirectory, histName))
    canvasRatio.SetLogy(0)
コード例 #22
0
    rp.GetYaxis().SetTitleSize(20)
    rp.GetYaxis().SetTitleFont(43)
    rp.GetYaxis().SetTitleOffset(1.55)
    rp.GetYaxis().SetLabelFont(43)
    rp.GetYaxis().SetLabelSize(15)

    rp.GetXaxis().SetTitleSize(20)
    rp.GetXaxis().SetTitleFont(43)
    rp.GetXaxis().SetTitleOffset(4.)
    rp.GetXaxis().SetLabelFont(43)
    rp.GetXaxis().SetLabelSize(15)

    rp.Draw("ep")

    #draw CMS and lumi text
    CMS_lumi.writeExtraText = True
    CMS_lumi.extraText = "Preliminary"
    CMS_lumi.lumi_sqrtS = lumiText + " (13 TeV)"
    CMS_lumi.cmsTextSize = 0.6
    CMS_lumi.lumiTextSize = 0.46
    CMS_lumi.extraOverCmsTextSize = 0.75
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(pad1, 0, 0)

    canvas.Update()

    canvas.SaveAs(outputDir + "/" + DATA_list[i].GetTitle() + ".pdf")
    canvas.SaveAs(outputDir + "/" + DATA_list[i].GetTitle() + ".png")

print "plots done"
コード例 #23
0
legend = TLegend(0.638778, 0.640577, 1.0005, 0.879506, "", "brNDC")
#legend = TLegend(gPad.GetUxmax()-3.5, gPad.GetUymax()-3.5,gPad.GetUxmax()+0.1,gPad.GetUymax()-0.3,"","br")
legend.AddEntry(graph_comb, "Combination", "lf")
legend.AddEntry(sm, "SM", "l")
legend.SetFillStyle(0)
legend.SetBorderSize(0)

extraLabel = TLatex()
extraLabel.SetTextSize(0.03)
extraLabel.SetTextAngle(0)
extraLabel.SetTextAlign(32)
extraLabel.SetTextFont(22)

graph_comb.Draw("E2same")
sm.Draw()
if not comb_text == "": comb_line.Draw()
graph.Draw("P")
comb.DrawLatex(4.88747, 6.10814, comb_text)
#comb.DrawLatex(gPad.GetUxmax()-0.5,gPad.GetUymax()*2/3.,comb_text)
extraLabel.DrawLatex(gPad.GetUxmax() - 0.1,
                     gPad.GetUymax() - 0.2, "H#rightarrowWW")
#legend.Draw()

CMS_lumi.CMS_lumi(canvas, 4, iPos)

gPad.RedrawAxis()
canvas.Update()
canvas.SaveAs("signalstrength2018_1.png")
a = raw_input()
コード例 #24
0
c.cd()
leg = TLegend(0.45, 0.7, 0.85, 0.9)
leg.SetLineColor(0)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.AddEntry(h_mjjQCD, "QCD", "l")
leg.AddEntry(h_mjjSB, "QCD + q* (4 TeV, 0.06 pb^{-1})", "l")
leg.AddEntry(g_eff[1], "data", "p")

h_mjjQCD.Draw("hist")
#g_eff[0].Draw("al")
h_mjjSB.Draw("hist same")
g_eff[1].Draw("pe0 same")
leg.Draw()
#draw the lumi text on the canvas
CMS_lumi.CMS_lumi(c, iPeriod, iPos)

c.SaveAs(outputDir + "/deltaeta_check_" + tag + ".png")
c.SaveAs(outputDir + "/deltaeta_check_" + tag + ".pdf")
c.Write()
h_mjjQCD.Write()
g_eff[0].Write()
g_eff[1].Write()

#-----------  with ratio -----------
c2 = TCanvas('c2', 'c2', 600, 650)
c2.cd()
#----- pad 1 -----------
pad1 = TPad("pad1", "pad1", 0, 0.15, 1, 1)
#pad1.SetRightMargin(0.1)
コード例 #25
0
sig_.Draw('hist,same')
bkg_.Draw('hist,same')
CMS_lumi.channelText = _channelText
legend.Draw("same")
ratio.GetXaxis().SetLabelSize(gStyle.GetLabelSize() / (padRatio + padOverlap))
ratio.GetYaxis().SetLabelSize(gStyle.GetLabelSize() / (padRatio + padOverlap))
ratio.GetXaxis().SetTitleSize(gStyle.GetTitleSize() / (padRatio + padOverlap))
ratio.GetYaxis().SetTitleSize(gStyle.GetTitleSize() / (padRatio + padOverlap))
ratio.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() *
                                (padRatio + padOverlap - padGap))
ratio.GetYaxis().SetRangeUser(0.5, 1.5)
ratio.GetYaxis().SetNdivisions(504)
if finalState == "mu":
    ratio.GetXaxis().SetTitle("(#mu^{+},#mu^{-}) invariant mass (GeV)")
else:
    ratio.GetXaxis().SetTitle("(e^{+},e^{-}) invariant mass (GeV)")

ratio.GetYaxis().SetTitle("Data/MC")
CMS_lumi.CMS_lumi(pad1, 4, 11)

pad2.cd()

ratio.Draw('e,x0')
oneLine.Draw("same")

canvasRatio.Update()
canvasRatio.RedrawAxis()
CMS_lumi.channelText = _channelText
canvasRatio.SaveAs("DilepMass_prefit_%s_%s%s_ratio.pdf" %
                   (finalState, ext, zjets))
コード例 #26
0
def EffiGraph1D(effDataList,
                effMCList,
                sfList,
                nameout,
                xAxis='pT',
                yAxis='eta'):

    W = 800
    H = 800
    yUp = 0.45
    canName = 'toto' + xAxis

    c = rt.TCanvas(canName, canName, 50, 50, H, W)
    c.SetTopMargin(0.055)
    c.SetBottomMargin(0.10)
    c.SetLeftMargin(0.12)

    p1 = rt.TPad(canName + '_up', canName + '_up', 0, yUp, 1, 1, 0, 0, 0)
    p2 = rt.TPad(canName + '_do', canName + '_do', 0, 0, 1, yUp, 0, 0, 0)
    p1.SetBottomMargin(0.0075)
    p1.SetTopMargin(c.GetTopMargin() * 1 / (1 - yUp))
    p2.SetTopMargin(0.0075)
    p2.SetBottomMargin(c.GetBottomMargin() * 1 / yUp)
    p1.SetLeftMargin(c.GetLeftMargin())
    p2.SetLeftMargin(c.GetLeftMargin())
    firstGraph = True
    leg = rt.TLegend(0.5, 0.80, 0.95, 0.92)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)

    igr = 0
    listOfTGraph1 = []
    listOfTGraph2 = []
    listOfMC = []

    xMin = 10
    xMax = 120
    if 'pT' in xAxis or 'pt' in xAxis:
        p1.SetLogx()
        p2.SetLogx()
        xMin = 10
        xMax = 120
    elif 'vtx' in xAxis or 'Vtx' in xAxis or 'PV' in xAxis:
        xMin = 3
        xMax = 42
    elif 'eta' in xAxis or 'Eta' in xAxis:
        xMin = -2.60
        xMax = +2.60

    if 'abs' in xAxis or 'Abs' in xAxis:
        xMin = 0.0

    effminmax = findMinMax(effDataList)
    effiMin = effminmax[0]
    effiMax = effminmax[1]

    sfminmax = findMinMax(sfList)
    #    sfMin = sfminmax[0]
    sfMin = 0.8
    sfMax = 1.2

    for key in sorted(effDataList.keys()):
        grBinsEffData = effUtil.makeTGraphFromList(effDataList[key], 'min',
                                                   'max')
        grBinsSF = effUtil.makeTGraphFromList(sfList[key], 'min', 'max')
        grBinsEffMC = None
        if not effMCList is None:
            grBinsEffMC = effUtil.makeTGraphFromList(effMCList[key], 'min',
                                                     'max')
            grBinsEffMC.SetLineStyle(rt.kDashed)
            grBinsEffMC.SetLineColor(graphColors[igr])
            grBinsEffMC.SetMarkerSize(0)
            grBinsEffMC.SetLineWidth(2)

        grBinsSF.SetMarkerColor(graphColors[igr])
        grBinsSF.SetLineColor(graphColors[igr])
        grBinsSF.SetLineWidth(2)
        grBinsEffData.SetMarkerColor(graphColors[igr])
        grBinsEffData.SetLineColor(graphColors[igr])
        grBinsEffData.SetLineWidth(2)

        grBinsEffData.GetHistogram().SetMinimum(effiMin)
        grBinsEffData.GetHistogram().SetMaximum(effiMax)

        grBinsEffData.GetHistogram().GetXaxis().SetLimits(xMin, xMax)
        grBinsSF.GetHistogram().GetXaxis().SetLimits(xMin, xMax)
        grBinsSF.GetHistogram().SetMinimum(sfMin)
        grBinsSF.GetHistogram().SetMaximum(sfMax)

        grBinsSF.GetHistogram().GetXaxis().SetTitleOffset(1)
        if 'eta' in xAxis or 'Eta' in xAxis:
            grBinsSF.GetHistogram().GetXaxis().SetTitle("SuperCluster #eta")
        elif 'pt' in xAxis or 'pT' in xAxis:
            grBinsSF.GetHistogram().GetXaxis().SetTitle("p_{T}  [GeV]")
        elif 'vtx' in xAxis or 'Vtx' in xAxis or 'PV' in xAxis:
            grBinsSF.GetHistogram().GetXaxis().SetTitle("N_{vtx}")

        grBinsSF.GetHistogram().GetYaxis().SetTitle("Data / MC ")
        grBinsSF.GetHistogram().GetYaxis().SetTitleOffset(1)

        grBinsEffData.GetHistogram().GetYaxis().SetTitleOffset(1)
        grBinsEffData.GetHistogram().GetYaxis().SetTitle("Data efficiency")
        grBinsEffData.GetHistogram().GetYaxis().SetRangeUser(effiMin, effiMax)

        ### to avoid loosing the TGraph keep it in memory by adding it to a list
        listOfTGraph1.append(grBinsEffData)
        listOfTGraph2.append(grBinsSF)
        listOfMC.append(grBinsEffMC)
        if 'eta' in yAxis or 'Eta' in yAxis:
            leg.AddEntry(
                grBinsEffData, '%1.3f #leq | #eta | #leq  %1.3f' %
                (float(key[0]), float(key[1])), "PL")
        elif 'pt' in yAxis or 'pT' in yAxis:
            leg.AddEntry(
                grBinsEffData, '%3.0f #leq p_{T} #leq  %3.0f GeV' %
                (float(key[0]), float(key[1])), "PL")
        elif 'vtx' in yAxis or 'Vtx' in yAxis or 'PV' in yAxis:
            leg.AddEntry(
                grBinsEffData,
                '%3.0f #leq nVtx #leq  %3.0f' % (float(key[0]), float(key[1])),
                "PL")

    for igr in range(len(listOfTGraph1) + 1):

        option = "P"
        if igr == 1:
            option = "AP"

        use_igr = igr
        if use_igr == len(listOfTGraph1):
            use_igr = 0

        listOfTGraph1[use_igr].SetLineColor(graphColors[use_igr])
        listOfTGraph1[use_igr].SetMarkerColor(graphColors[use_igr])
        if not listOfMC[use_igr] is None:
            listOfMC[use_igr].SetLineColor(graphColors[use_igr])

        listOfTGraph1[use_igr].GetHistogram().SetMinimum(effiMin)
        listOfTGraph1[use_igr].GetHistogram().SetMaximum(effiMax)
        p1.cd()
        listOfTGraph1[use_igr].Draw(option)
        if not listOfMC[use_igr] is None:
            listOfMC[use_igr].Draw("ez")

        p2.cd()
        listOfTGraph2[use_igr].SetLineColor(graphColors[use_igr])
        listOfTGraph2[use_igr].SetMarkerColor(graphColors[use_igr])
        listOfTGraph2[use_igr].GetHistogram().SetMinimum(sfMin)
        listOfTGraph2[use_igr].GetHistogram().SetMaximum(sfMax)
        if 'pT' in xAxis or 'pt' in xAxis:
            listOfTGraph2[use_igr].GetHistogram().GetXaxis().SetMoreLogLabels()
        listOfTGraph2[use_igr].GetHistogram().GetXaxis().SetNoExponent()
        listOfTGraph2[use_igr].Draw(option)

    lineAtOne = rt.TLine(xMin, 1, xMax, 1)
    lineAtOne.SetLineStyle(rt.kDashed)
    lineAtOne.SetLineWidth(2)

    p2.cd()
    lineAtOne.Draw()

    c.cd()
    p2.Draw()
    p1.Draw()

    leg.Draw()
    CMS_lumi.CMS_lumi(c, 4, 10)

    c.Print(nameout)

    return listOfTGraph2
コード例 #27
0
def plotUpperLimits(model, lambdas, helicity):

    N = len(lambdas)
    #yellow = TGraph(2*N)    # yellow band
    #green = TGraph(2*N)     # green band
    #median = TGraph(N)      # median line

    Mmin = [100 + i * 100 for i in range(40)]
    graphs = []
    for i in range(N):
        thislam = TGraph(len(Mmin))
        thislimit = []
        for mm in range(len(Mmin)):
            file_name = "./%sdataCards/ee_signif%s/higgsCombine%d.Significance.mH%d.root" % (
                model, helicity, Mmin[mm], lambdas[i])
            limit = getLimits(file_name)
            thislam.SetPoint(mm, Mmin[mm], limit[0])
            thislam.SetLineColor(i + 2)
            thislam.SetLineWidth(2)
            thislimit.append(limit[0])
        graphs.append(thislam.Clone())
        print "this minimum mass cut is %d" % Mmin[mm]
        print thislimit

        #yellow.SetPoint(    i,    values[i], limit[4] ) # + 2 sigma
        #green.SetPoint(     i,    values[i], limit[3] ) # + 1 sigma
        #median.SetPoint(    i,    labels[i], limit[0] ) # median
        #green.SetPoint(  2*N-1-i, values[i], limit[1] ) # - 1 sigma
        #yellow.SetPoint( 2*N-1-i, values[i], limit[0] ) # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    if model == "ADD": frame = c.DrawFrame(100, 0.01, 4000, 22)
    elif "Con" in helicity: frame = c.DrawFrame(100, 0.01, 4000, 15)
    else: frame = c.DrawFrame(100, 0.01, 4000, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetYaxis().SetTitle("Significance")
    frame.GetXaxis().SetTitle("M_{min} [GeV]")
    frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    #frame.GetXaxis().SetLimits(min(values),max(values))

    for gf in graphs:
        gf.Draw('Lsame')
    '''
    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')
 
    green.SetFillColor(ROOT.kGreen+1)
    green.SetLineColor(ROOT.kGreen+1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')
    
    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')'''

    CMS_lumi.CMS_lumi(c, 13, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    x1 = 0.75
    x2 = x1 + 0.24
    y2 = 0.86
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    for i in range(N):
        legend.AddEntry(graphs[i], "#Lambda = %d" % lambdas[i], 'l')
    #legend.AddEntry(median, "Asymptotic CL_{s} expected",'L')
    #legend.AddEntry(green, "#pm 1 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
    #legend.AddEntry(yellow,"#pm 2 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    print " "
    c.SaveAs("%slimits/%sSignificance_ee%s.png" % (model, model, helicity))
    c.Close()
コード例 #28
0
def plotSignificance(masses,
                     models,
                     cat="all",
                     doUnblind=False,
                     doPValue=True):

    directory = "/afs/cern.ch/work/l/lviliani/LatinosFramework13TeV_highmass/CMSSW_8_0_5/src/LatinoAnalysis/ShapeAnalysis/PlotsConfigurations/Configurations/EXO/WWlvlv_VBF/2015/combine2015_nocprime/"

    leg1 = TLegend(0.6, 0.65, 0.9, 0.9)
    leg1.SetBorderSize(0)
    leg1.SetFillStyle(0)

    xcentral = array("d")  # masses
    ycentral = array("d")  # limits
    obseved = array("d")
    xerr = array("d")

    c1 = makeCanvas("c1")
    c1.cd()
    mg = TMultiGraph()

    count = 0
    for model in models:
        count += 1
        xcentral = array("d")  # masses
        ycentral = array("d")  # limits
        observed = array("d")
        xerr = array("d")

        #            modelName = model.replace("c","c'= ").replace("0","0.").replace("brn"," BR_{new} = ").replace("0.0.","0.0").replace("10.","1.0")
        #            modelName = model.replace("brn00","").replace("c","c'= ").replace("0","0.").replace("10.","1.0")

        cp2 = float(model[1] + "." + model[2])
        gamma = str(cp2 * cp2)

        if gamma == "1.0":
            modelName = "#Gamma = #Gamma_{SM}"
        else:
            modelName = "#Gamma = " + gamma + " * #Gamma_{SM}"

        if cat == "all":
            CMS_lumi.extraText2 = "0+1+2 jets "
        else:
            CMS_lumi.extraText2 = cat.replace("jet", " jet ")

        for m in masses:

            if cat == "all":
                fitfile = directory + "Significance.ICHEP2016.mH" + m + "_" + model + ".txt"
                fitfileObs = directory + "Significance.ICHEP2016.unblind.mH" + m + "_" + model + ".txt"
            else:
                fitfile = directory + "Significance." + cat + ".ICHEP2016.mH" + m + "_" + model + ".txt"
                fitfileObs = directory + "Significance." + cat + ".ICHEP2016.unblind.mH" + m + "_" + model + ".txt"

            fitFile = open(
                fitfile
            )  #"/afs/cern.ch/work/l/lviliani/LatinosFramework13TeV_clean/CMSSW_7_6_3/src/LatinoAnalysis/ShapeAnalysis/PlotsConfigurations/Configurations/EXO/WWlvlv_VBF/combine/Limit.Moriond2016.2jet.mH"+m+".txt")
            sig = extract(fitFile, doPValue)
            fitFile.close()

            fitFileObs = open(fitfileObs)
            print fitFileObs
            sigObs = extract(fitFileObs, doPValue)
            fitFileObs.close()

            xcentral.append(float(m))
            xerr.append(0)
            ycentral.append(float(sig))
            observed.append(float(sigObs))
            print m, sigObs

        graph = TGraph(len(xcentral), xcentral, ycentral)
        graphObs = TGraph(len(xcentral), xcentral, observed)
        graph.SetLineStyle(2)
        graphObs.SetLineStyle(1)
        graph.SetLineWidth(2)
        graphObs.SetLineWidth(2)
        graph.SetLineColor(kBlue - 2 * count)
        graphObs.SetLineColor(kBlue - 2 * count)

        #            leg1.AddEntry(graph,modelName+" Expected","l")
        leg1.AddEntry(graphObs, modelName, "l")
        #            mg.Add(graph,"l")
        if doUnblind: mg.Add(graphObs, "l")

    mg.Draw("A")
    mg.GetYaxis().SetTitle("Significance (standard deviations)")
    mg.GetXaxis().SetTitle("M_{X} [GeV]")
    mg.GetXaxis().SetRangeUser(200, 1000)
    if doPValue:
        gPad.SetLogy()
        mg.GetYaxis().SetTitle("p-value")
        mg.GetYaxis().SetRangeUser(0.001, 2)
    else:
        mg.GetYaxis().SetRangeUser(0, 4)
    leg1.Draw()
    CMS_lumi.CMS_lumi(c1, 4, iPos)
    gPad.RedrawAxis()

    a = raw_input()
コード例 #29
0
legend.SetFillColor(0)
legend.SetFillStyle(0)
legend.SetMargin(0.35)
#legend.AddEntry(sigdists[8],legends[2],"l")
legend.AddEntry(sigdists[0], legends[0], "l")
#legend.AddEntry(sigdists[4],legends[1],"l")

jj = -1
for h in sigdists:
    jj += 1
    h.Draw("sameHISTC")

legend.Draw("same")

addInfo = rt.TPaveText(0.6728188, 0.5681818, 0.9295302, 0.6433566, "NDC")
# addInfo.AddText(labels[ii])
addInfo.SetFillColor(0)
addInfo.SetLineColor(0)
addInfo.SetFillStyle(0)
addInfo.SetBorderSize(0)
addInfo.SetTextFont(42)
addInfo.SetTextSize(0.040)
addInfo.SetTextAlign(12)
addInfo.Draw()
CMS_lumi.CMS_lumi(c1, iPeriod, iPos)
c1.Update()
c1.SaveAs("DiBosonInvMass_AllSignals.pdf")
c1.SaveAs("DiBosonInvMass_AllSignals.root")
time.sleep(100)
infileS.Close()
コード例 #30
0
leg.AddEntry(Hbb.Fit.ErrUp, "fit errors", "L")
C2 = TCanvas("C2", "", 800, 800)
C2.cd()
Hbb.G.SetTitle("")
Hbb.G.Draw("AP")
Hbb.G.GetXaxis().SetTitle("m_{J} - m_{H} (GeV)")
Hbb.G.GetYaxis().SetTitle("R_{p/f}")
Hbb.G.GetYaxis().SetTitleOffset(1.3)
#Hbb.truthG.Draw("P same")
Hbb.Fit.fit.Draw("same")
Hbb.Fit.ErrUp.SetLineStyle(2)
Hbb.Fit.ErrUp.Draw("same")
Hbb.Fit.ErrDn.SetLineStyle(2)
Hbb.Fit.ErrDn.Draw("same")
leg.Draw()
CMS_lumi.CMS_lumi(C2, iPeriod, iPos)
C2.SaveAs("outputs/SR_Fit.pdf")

variable = "dijetmass_corr"

binBoundaries = [
    800, 838, 890, 944, 1000, 1058, 1118, 1181, 1246, 1313, 1383, 1455, 1530,
    1607, 1687, 1770, 1856, 1945, 2037, 2132, 2231, 2332, 2438, 2546, 2659,
    2775, 2895, 3019, 3147, 3279, 3416, 3558, 3704, 3854, 4010, 4171, 4337,
    4509
]

Hbb.MakeEstVariable(variable, binBoundaries, antitag, tag)
FILE = TFile("outputs/SR_output.root", "RECREATE")
FILE.cd()
V = TH1F("data_obs", "", len(binBoundaries) - 1, array('d', binBoundaries))