예제 #1
0
def plotMCEffs(input_list, plot_name='fakerate.pdf'):
    '''input_list expects tuples with structure:
       (hist tight, hist loose, legend line, colour)
    '''

    graphs = []

    for (hist_tight, hist_loose, legend, colour, style) in input_list:
        g = TGraphAsymmErrors(hist_tight)
        g.Divide(hist_tight, hist_loose)
        g.GetYaxis().SetTitle('Fake rate')
        g.GetXaxis().SetTitle(hist_tight.GetXaxis().GetTitle())
        g.GetYaxis().SetTitleOffset(1.2)
        g.GetYaxis().SetTitleOffset(1.3)

        g.SetLineColor(colour)
        g.SetLineStyle(style)
        g.SetMarkerColor(colour)
        g.SetMarkerStyle(19+style)

        g.legend = legend

        graphs.append(g)


    ratio_graphs = []

    base_graph = graphs[0]
    for graph in graphs[1:]:

        g_vals = base_graph.GetY()
        g_data_vals = graph.GetY()

        g_ratio = graph.Clone('ratio')

        for i in xrange(graph.GetN()):
            ratio = g_data_vals[i]/g_vals[i] if g_vals[i] else 0.
            g_ratio.SetPoint(i, base_graph.GetX()[i], ratio)

            rel_y_low = math.sqrt((graph.GetErrorYlow(i)/g_data_vals[i])**2 + (base_graph.GetErrorYlow(i)/g_vals[i])**2) if g_data_vals[i] > 0.0000001 and g_vals[i] > 0.0000001 else 0.

            g_ratio.SetPointEYlow(i, rel_y_low * ratio)

            rel_y_high = math.sqrt((graph.GetErrorYhigh(i)/g_data_vals[i])**2 + (base_graph.GetErrorYhigh(i)/g_vals[i])**2) if g_data_vals[i] > 0.0000001 and g_vals[i] > 0.0000001 else 0.

            g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

        ratio_graphs.append(g_ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)
    for g_ratio in ratio_graphs:
        g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
        g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

        g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() / xtp_ratio)
        g_ratio.GetXaxis().SetTitleOffset(g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

        g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
        g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

        g_ratio.GetXaxis().SetTitle(base_graph.GetXaxis().GetTitle())


    for graph in graphs:
        graph.GetXaxis().SetLabelColor(0)
        graph.GetXaxis().SetLabelSize(0)


    maxy = 1.3 * max([gr.GetMaximum() for gr in graphs] + [1./1.25])
    for g in graphs:
        g.GetYaxis().SetRangeUser(0.0011, maxy)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    base_graph.Draw('AP')
    for graph in graphs[1:]:
        graph.Draw('P')

    legend = TLegend(0.63, 0.63, 0.93, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend2 = TLegend(0.78, 0.63, 0.93, 0.91)
    legend2.SetFillColor(0)
    legend2.SetFillStyle(0)
    legend2.SetLineColor(0)
    legend2.SetLineWidth(0)

    for graph in graphs:
        if 'opp' in graph.legend:
            legend2.AddEntry(graph.GetName(), graph.legend, 'lep')
        else:
            legend.AddEntry(graph.GetName(), graph.legend, 'lep')

    legend.Draw()
    legend2.Draw()

    padr.cd()

    for g_ratio in ratio_graphs:
        g_ratio.GetYaxis().SetRangeUser(0.01, 1.99)
        g_ratio.GetYaxis().SetTitle('Ratio to '+base_graph.legend)
        g_ratio.Draw('AP' if g_ratio == ratio_graphs[0] else 'P')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)

    g.GetYaxis().SetRangeUser(0.0001, 1)
    pad.SetLogy(True)
    cv.Print(plot_name.replace('.', '_log.'))
예제 #2
0
x.SetLabelSize(15)
'''


#create ratio plot using TGraphAsymmErrors
gPad.Modified()
ratio = TGraphAsymmErrors()
ratio.Divide(h6,h,"cl=0.683 b(1,1) mode")
ratio.SetMarkerColor(1)
ratio.SetMarkerStyle(21)
ratio.SetLineColor(1)
ratio.GetXaxis().SetTitleSize(0.1)
ratio.GetXaxis().SetLabelSize(0.1)
ratio.GetXaxis().SetRangeUser(200,1000)
ratio.GetXaxis().SetTitle("MET (GeV)")
ratio.GetYaxis().SetTitleSize(0.1)
ratio.GetYaxis().SetLabelSize(0.1)
ratio.GetYaxis().SetTitleOffset(0.4)
ratio.GetYaxis().SetTitle("ratio")
ratio.SetTitle("")

#upper histogram plot is pad1
pad1 = TPad("pad1","pad1", 0, 0.3, 1, 1.0)
pad1.SetBottomMargin(0) #joins upper and lower plot
pad1.Draw()
#lower ratio plot is pad2
c1.cd() #returns to main canvas before defining pad2
pad2 = TPad("pad2","pad2", 0, 0.05, 1, 0.3)
pad2.SetTopMargin(0) #joins upper and lower plot
pad2.SetBottomMargin(0.2)
pad2.Draw()
예제 #3
0
def limit2HDM():
    global signals
    signals = range(800, 2000 + 1, 50)
    multF = HTOBB
    THEORY = ['T1', 'T2']

    mass, val = fillValues("./combine/AZh/AZh_M%d.txt")
    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()

    massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt")
    Obs0sB = TGraph()
    Exp0sB = TGraph()
    Exp1sB = TGraphAsymmErrors()
    Exp2sB = TGraphAsymmErrors()

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)

        Obs0sB.SetPoint(n, m, valB[m][0] * multF)
        Exp0sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][2] * multF,
                             valB[m][4] * multF - valB[m][3] * multF)
        Exp2sB.SetPoint(n, m, valB[m][3] * multF)
        Exp2sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][1] * multF,
                             valB[m][5] * multF - valB[m][3] * multF)

    col = 629
    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp0s.SetLineColor(1)
    #    Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1
    #    Exp1s.SetLineColorAlpha(col, 0.4)
    #    Exp2s.SetFillColorAlpha(col, 0.2) #kOrange
    #    Exp2s.SetLineColorAlpha(col, 0.2)
    Exp1s.SetFillColor(417)
    Exp1s.SetLineColor(417)
    Exp2s.SetFillColor(800)
    Exp2s.SetLineColor(800)

    colB = 922
    Exp2sB.SetLineWidth(2)
    Obs0sB.SetLineStyle(9)
    Obs0sB.SetLineWidth(3)
    Obs0sB.SetMarkerStyle(0)
    Obs0sB.SetLineColor(colB)
    Exp0sB.SetLineStyle(8)
    Exp0sB.SetLineWidth(3)
    Exp0sB.SetLineColor(colB)
    Exp1sB.SetFillColorAlpha(colB, 0.4)  #kGreen+1
    Exp1sB.SetLineColorAlpha(colB, 0.4)
    Exp2sB.SetFillColorAlpha(colB, 0.2)  #kOrange
    Exp2sB.SetLineColorAlpha(colB, 0.2)

    Exp2s.GetXaxis().SetTitle("m_{A} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)"
    )
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Theory = {}
    #for t in THEORY:
    #    Theory[t] = TGraphAsymmErrors()
    #    for m in sorted(THDM[t]['ggA'].keys()):
    #        if m < mass[0] or m > mass[-1]: continue
    #        Xs, Xs_Up, Xs_Down = 0., 0., 0.
    #        Xs = THDM[t]['ggA'][m]
    #        Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2))
    #        Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2))
    #        n = Theory[t].GetN()
    #        Theory[t].SetPoint(n, m, Xs)
    #        Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs))

    #    Theory[t].SetLineColor(theoryLineColor[t])
    #    Theory[t].SetFillColor(theoryFillColor[t])
    #    Theory[t].SetFillStyle(theoryFillStyle[t])
    #    Theory[t].SetLineWidth(2)
    #        #Theory[t].SetLineStyle(7)

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    #    Exp2sB.Draw("SAME, 3")
    #    Exp1sB.Draw("SAME, 3")
    Exp0sB.Draw("SAME, L")
    if not options.blind:
        Obs0s.Draw("SAME, L")
        Obs0sB.Draw("SAME, L")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    #setHistStyle(Exp2s)


#    Exp2s.GetXaxis().SetTitleSize(0.045)
#    Exp2s.GetYaxis().SetTitleSize(0.04)
#    Exp2s.GetXaxis().SetLabelSize(0.04)
#    Exp2s.GetYaxis().SetLabelSize(0.04)
#    Exp2s.GetXaxis().SetTitleOffset(1)
#    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis('AZh')
    drawRegion('AZHsl', True)
    #drawCMS(LUMI, "") #Preliminary
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    leg = TLegend(0.6, 0.90, 0.99, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh",
                 "")  #"95% CL upper limits"
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    leg.AddEntry(None, "", "")
    leg.AddEntry(None, "bbA #rightarrow Zh", "")
    leg.AddEntry(Obs0sB, "Observed", "l")
    leg.AddEntry(Exp0sB, "Expected", "l")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045)
    leg.Draw()

    #    latex = TLatex()
    #    latex.SetNDC()
    #    latex.SetTextSize(0.040)
    #    latex.SetTextFont(42)
    #    latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1")

    #    legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4)
    legB = TLegend(0.15, 0.27, 0.68, 0.27)
    legB.SetBorderSize(0)
    legB.SetFillStyle(0)  #1001
    legB.SetFillColor(0)
    for t in THEORY:
        legB.AddEntry(Theory[t], theoryLabel[t], "fl")
    legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "")
    legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045)
    legB.Draw()

    c1.GetPad(0).RedrawAxis()
    leg.Draw()

    c1.Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("plotsLimit/Exclusion/THDM.png")
    c1.Print("plotsLimit/Exclusion/THDM.pdf")
예제 #4
0
def main():
   from optparse import OptionParser
   parser = OptionParser()
   parser.add_option("-i", "--inputfile", dest="inputfile")
   parser.add_option("-o", "--ouputfile", dest="outputfile")
   parser.add_option("-b", "--batch", action="store_true",\
         dest="isBatch", default=False)
   parser.add_option("--normalization", nargs=2,\
         type="float", dest="norm_range")
   parser.add_option("--fit", nargs=2,\
         type="float", dest="fit_range")
   (options, args) = parser.parse_args()

   isSaveOutput = options.outputfile is not None

   if not (options.inputfile):
      parser.error("Please specify inputfiles.")

   import configurations as config
   if options.fit_range:
      fit_range = options.fit_range
      norm_range = (fit_range[1] - 200., fit_range[1])
   else:
      fit_range = config.fit_range
      norm_range = config.norm_range

   # Override normalization range from input
   if options.norm_range:
      norm_range = options.norm_range


   from Styles import formatST, formatTemplate, formatUncertainty
   from ROOT import TFile, TF1, TH1D, TMath, TCanvas, TLegend,\
         TGraphAsymmErrors, TVectorD

   #input file name
   infile = TFile(options.inputfile, "READ")

   from HistoStore import HistoStore
   store = HistoStore()
   canvas = HistoStore()

   print "Fit range: %d - %d GeV" % fit_range
   print "Normalization range: %d - %d GeV" % norm_range

   # Fit
   for N in config.exclusive_multiplicities:
      hST = infile.Get("plots%dJets/ST" %  N)
      if not options.isBatch:
         c = TCanvas("TemplateN%d" % N, 
               "TemplateN%d" % N, 500, 500)
         canvas.book(c)
         formatST(hST)
         hST.Draw("e")
         hST.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
         hST.GetYaxis().SetRangeUser(1e-2, 2e4)
         c.SetLogy(1)

      for i,formula in enumerate(config.templates):
         if N == 2:
            f = TF1("templateN%d_%d" % (N, i), formula, 0, 10000)
         elif N == 3:
            f = store.get("templateN2_%d" % i).Clone("templateN%d_%d" % (N, i))
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
         if i == 0:
            hST.Fit(f, "Q0", "", fit_range[0], fit_range[1])

         formatTemplate(f, N, i)
         store.book(f)

         if not options.isBatch:
            f.Draw("same")

         hTemplate = hST.Clone("histoTemplateN%d_%d" % (N,i))
         hTemplate.Reset()
         hTemplate.Eval(f)
         formatTemplate(hTemplate, N, i)
         store.book(hTemplate)

         if i == 0:
            hRef = hTemplate.Clone("ReferenceTemplateN%d_0" % N)
            store.book(hRef)

         # Print Chi-squre/Ndof
         print "N = %d, Chi^2/Ndof = %0.2f/%d" %\
               (N, f.GetChisquare(), f.GetNDF())
      if not options.isBatch:
         c.Update()

   # Calculate scale/error
   from OptimizationTools import OptimizeScale
   for histoN, templateN in [[2,3]]:
      hST = store.get("ReferenceTemplateN%d_0" % histoN)
      hTemplate  = store.get("ReferenceTemplateN%d_0" % templateN)

      hlnL, scale, err = OptimizeScale(hST, hTemplate, norm_range)
      hlnL.SetName("LogLikelihood_%dto%d" % (templateN, histoN))
      store.book(hlnL)

      for i in range(len(config.templates)):
         hTemplate  = store.get("histoTemplateN%d_%d" % (templateN, i))
         hTemplate_ = hTemplate.Clone("histoTemplateN%d_%d__RescaledToN%d"
               % (templateN, i, histoN))
         hTemplate_.Scale(scale)
         store.book(hTemplate_)

   # Shape Uncertainty
   hBkgTemplate  = store.get("histoTemplateN2_0")
   hBkgTemplate.Rebin(config.rebin)
   nbins = hBkgTemplate.GetNbinsX()
   vST = TVectorD(nbins)
   vBkg = TVectorD(nbins)
   vexl = TVectorD(nbins)
   vexh = TVectorD(nbins)
   shape_el = TVectorD(nbins)
   shape_eh = TVectorD(nbins)
   rel_shape_el = TVectorD(nbins)
   rel_shape_eh = TVectorD(nbins)
   for i in range(nbins):
      vST[i] = hBkgTemplate.GetBinCenter(i+1)
      if (vST[i] < config.com):
         vBkg[i] = hBkgTemplate.GetBinContent(i+1)
      else:
         vBkg[i] = 0.0
      vexl[i] = 0.0
      vexh[i] = 0.0
      shape_el[i] = 0.0
      shape_eh[i] = 0.0
      rel_shape_el[i] = 0.0
      rel_shape_eh[i] = 0.0

   for i in range(len(config.templates)):
      for label in ["histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2"]:
         if label % i == "histoTemplateN2_0":
            continue
         h = store.get(label % i)
         h.Rebin(config.rebin)
         for ibin in range(nbins):
            diff = h.GetBinContent(ibin+1) - vBkg[ibin]
            if diff > 0 and diff > shape_eh[ibin]:
               shape_eh[ibin] = diff
            elif diff < 0 and abs(diff) > shape_el[ibin]:
               shape_el[ibin] = abs(diff)

   # Relative Shape Uncertaincy
   for i in range(nbins):
      if vBkg[i] > 0:
         #rel_shape_el[i] = rel_shape_el[i] / vBkg[i]
         #hape_eh[i] = rel_shape_eh[i] / vBkg[i]
         max_err = max(shape_el[i], shape_eh[i])
         shape_el[i] = max_err
         shape_eh[i] = max_err
         rel_shape_el[i] = max_err /vBkg[i]
         rel_shape_eh[i] = max_err /vBkg[i]
      else:
         rel_shape_el[i] = 0.0
         rel_shape_eh[i] = 0.0
      #print vST[i], vBkg[i], rel_shape_el[i], rel_shape_eh[i]
   gShapeUncertainty = TGraphAsymmErrors(vST, vBkg,
         vexl, vexh, shape_el, shape_eh)
   gShapeUncertainty.SetName("Shape_Uncertainty")
   formatUncertainty(gShapeUncertainty)
   store.book(gShapeUncertainty)

   gRelShapeUncertainty = TGraphAsymmErrors(vST, vexl,
         vexl, vexh, rel_shape_el, rel_shape_eh)
   gRelShapeUncertainty.SetName("Relative_Shape_Uncertainty")
   formatUncertainty(gRelShapeUncertainty)
   store.book(gRelShapeUncertainty)

   # Generate Backgrouds
   for N in config.label_for_data:
      hST = infile.Get("plotsN%s/ST" % N)
      rel_scale_err2 = 0.0
      scale_factor = 1.0
      for Nref in config.label_for_ref:
         if N == Nref:
            continue

         template = store.get("ReferenceTemplateN%s_0" % Nref)

         hlnL, scale, err = OptimizeScale(hST, template, norm_range)
         hlnL.SetName("LogLikelihood_%sto%s" % (Nref, N))
         store.book(hlnL)

         if Nref == "2":
            scale_factor = scale
         rel_scale_err2 += err/scale * err/scale

         print "%s/%s %.3f +/- %.3f" % (N, Nref, scale, err)

      vy = TVectorD(nbins)
      veyh = TVectorD(nbins)
      veyl = TVectorD(nbins)
      for i in range(nbins):
         vy[i] = vBkg[i] * scale_factor
         veyh[i] = vy[i] * TMath.Sqrt(rel_scale_err2 
               + rel_shape_eh[i]*rel_shape_eh[i])
         veyl[i] = vy[i] * TMath.Sqrt(rel_scale_err2 
               + rel_shape_el[i]*rel_shape_el[i])

      print "Scaling uncertainty (%s): %.2f" %\
            (N, TMath.sqrt(rel_scale_err2) * 100.0)

      gBkg = TGraphAsymmErrors(vST, vy, vexl, vexh, veyl, veyh)
      gBkg.SetName("BackgroundGraph_N%s" % N)
      formatUncertainty(gBkg)
      store.book(gBkg)

      hST.Rebin(config.rebin)
      hST.SetName("Data_N%s" % N)
      formatST(hST)
      store.book(hST)

      hBkg = hST.Clone("Background_N%s" % N)
      hBkg.Reset()
      store.book(hBkg)

      for i in range(nbins):
         ibin = hBkg.FindBin(vST[i])
         hBkg.SetBinContent(ibin, vy[i])
         hBkg.SetBinError(ibin, max(veyh[i], vexl[i]))

      from OptimizationTools import Integral
      hIntBkg = hBkg.Clone("IntegralBackground_N%s" % N)
      Integral(hIntBkg)
      store.book(hIntBkg)

      hIntData = hST.Clone("IntegralData_N%s" % N)
      Integral(hIntData)
      store.book(hIntData)

   # Plot Shape Uncertainty
   if not options.isBatch:
      legend_shape = TLegend(0.5544355,0.5741525,0.9495968,0.9152542)
      legend_shape.SetTextFont(42)
      legend_shape.SetFillColor(0)
      c = TCanvas("ShapeUncertaintyN2", "ShapeUncertaintyN2", 500, 500)
      canvas.book(c)
      gShapeUncertainty.Draw("AC3")
      gShapeUncertainty.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
      gShapeUncertainty.GetYaxis().SetRangeUser(5e-2, 1.2e6)
      legend_shape.AddEntry(store.get("Data_N2"), "Data (N = 2)", "p")
      legend_shape.AddEntry(gShapeUncertainty, "Shape Uncertainty", "f")
      for i in range(len(config.templates)):
         for label in ["histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2"]:
            h = store.get(label % i)
            h.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
            h.Draw("histcsame")
            if label == "histoTemplateN2_%d":
               N = 2
            else:
               N = 3
            legend_shape.AddEntry(h, "Parametrization %d (N = %d)" % (i, N), "l")
      store.get("Data_N2").Draw("esame")
      c.SetLogy(1)
      legend_shape.Draw("plain")
      c.Update()

   if isSaveOutput:
      store.saveAs(options.outputfile)

   if not options.isBatch:
      raw_input("Press Enter to continue...")
예제 #5
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['bstar']
    if INCLUDEACC: THEORY.append('SSM')

    suffix = "_" + BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"
    if INCLUDEACC: suffix += "_acc"

    if SY:
        filename = "./combine/limits/bstar/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/bstar/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        if SY:
            filename = filename.replace(
                BTAGGING + "/combined_run2/",
                BTAGGING + "/single_category/combined_run2/" + CATEGORY + "_")
        else:
            filename = filename.replace(
                BTAGGING + "/",
                BTAGGING + "/single_category/" + CATEGORY + "_")
        suffix += "_" + CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()
    Theory = {}

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        if INCLUDEACC:
            acc_factor = ACCEPTANCE[m]
        else:
            acc_factor = 1.

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor)
        Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][2]) * multF * acc_factor,
                            (val[m][4] - val[m][3]) * multF * acc_factor)
        Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp2s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][1]) * multF * acc_factor,
                            (val[m][5] - val[m][3]) * multF * acc_factor)
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        if 'bstar' == t:
            x = []
            y = []
            with open('bstar_deta1p1_lhc13TeV2.txt') as fin:
                for line in fin.readlines():
                    x.append(float(line.split()[0]))
                    y.append(float(line.split()[1]) * 1000)
                for ind in range(len(x)):
                    Theory[t].SetPoint(ind + 1, x[ind], y[ind])
                Theory[t].SetLineColor(theoryLineColor[t])
                Theory[t].SetFillColor(theoryFillColor[t])
                Theory[t].SetFillStyle(theoryFillStyle[t])
                Theory[t].SetLineWidth(2)
                continue
        Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t != 'SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m > 4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t != 'SSM':
                XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][
                    m]  #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m]
                XsZ_Up = XsZ * (1. +
                                math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1.,
                                           HVT['A1']['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT['A1']['Z']['QCD'][m][0],
                                             1. - HVT['A1']['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ * acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor,
                                    (XsZ_Up - XsZ) * acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    if CATEGORY == "":
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "", suppressCMS=True)
    else:
        #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)
        drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix +
                 ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m,
        print ""

    return  ##FIXME

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png")
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png")
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png")
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()