def plotEfficiencies2D(filename, prefix, workingpoint, label=""):
    print ">>>\n>>> plotEfficiencies2D - %s" % (filename)

    file = TFile(filename, 'READ')
    dirname = "bTagEff"
    histnames = [
        "%s_%s_%s_eff" % (prefix, "udsg", workingpoint),
        "%s_%s_%s_eff" % (prefix, "b", workingpoint),
    ]

    for histname in histnames:
        print ">>>   %s" % (histname)

        flavor = "b"
        if "udsg" in histname: flavor = "light"
        if "_c_" in histname: flavor = "c"

        range = [0.25, 0.70]
        if flavor == "light": range = [0.0, 0.10]

        hist = file.Get("%s/%s" % (dirname, histname))

        canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
        canvas.SetBottomMargin(0.12)
        canvas.SetRightMargin(0.11)
        canvas.SetLeftMargin(0.10)
        canvas.SetTopMargin(0.08)
        hist.Draw("colz")
        hist.SetTitle("")
        hist.GetZaxis().SetRangeUser(*range)
        #hist.GetXaxis().SetRangeUser(0,100)
        #hist.GetYaxis().SetRangeUser(0,200)
        hist.GetXaxis().SetTitle("%s jet p_{T}" % (flavor))
        hist.GetYaxis().SetTitle("%s jet #eta" % (flavor))
        hist.GetYaxis().CenterTitle()
        hist.GetXaxis().SetLabelSize(0.042)
        hist.GetYaxis().SetLabelSize(0.042)
        hist.GetXaxis().SetTitleSize(0.05)
        hist.GetYaxis().SetTitleSize(0.05)
        hist.GetXaxis().SetTitleOffset(1.10)
        hist.GetYaxis().SetTitleOffset(0.99)
        gStyle.SetOptStat(0)
        CMS_lumi.CMS_lumi(canvas, 13, 0)
        canvas.SaveAs("%s/%s%s.png" % (OUT_DIR, histname, label))
        canvas.Close()

    file.Close()
Esempio n. 2
0
def plotCorrelation(channel,var,DM,year,*parameters,**kwargs):
    """Calculate and plot correlation between parameters."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotCorrelation %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    
    title       = kwargs.get('title',     ""                )
    name        = kwargs.get('name',      ""                )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""                )
    plotlabel   = kwargs.get('plotlabel', ""                )
    order       = kwargs.get('order',     False             )
    era         = "%d-13TeV"%year
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    print '>>>   file "%s"'%(filename)
    
    # HISTOGRAM
    parlist = getParameters(filename,parameters)
    if order:
      parlist.sort(key=lambda x: -x.sigma)
    N       = len(parlist)     
    hist    = TH2F("corr","corr",N,0,N,N,0,N)
    
    for i in xrange(N): # diagonal
      hist.SetBinContent(i+1,N-i,1.0)
      hist.GetXaxis().SetBinLabel(1+i,parlist[i].title)
      hist.GetYaxis().SetBinLabel(N-i,parlist[i].title)
    for xi, yi in combinations(range(N),2): # off-diagonal
      r = parlist[xi].corr(parlist[yi])
      hist.SetBinContent(1+xi,N-yi,r)
      hist.SetBinContent(1+yi,N-xi,r)
      #print "%20s - %20s: %5.3f"%(par1,par2,r)
      #hist.Fill(par1.title,par2.title,r)
      #hist.Fill(par2.title,par1.title,r)
    
    # SCALE
    canvasH  = 160+64*max(10,N)
    canvasW  = 300+70*max(10,N)
    scaleH   =  800./canvasH
    scaleW   = 1000./canvasW
    scaleF   = 640./(canvasH-160)
    tmargin  = 0.06
    bmargin  = 0.14
    lmargin  = 0.22
    rmargin  = 0.12
    
    canvas = TCanvas('canvas','canvas',100,100,canvasW,canvasH)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  tmargin ); canvas.SetBottomMargin( bmargin )
    canvas.SetLeftMargin( lmargin ); canvas.SetRightMargin( rmargin )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    frame = hist
    frame.GetXaxis().SetLabelSize(0.054*scaleF)
    frame.GetYaxis().SetLabelSize(0.072*scaleF)
    frame.GetZaxis().SetLabelSize(0.034)
    frame.GetXaxis().SetLabelOffset(0.005)
    frame.GetYaxis().SetLabelOffset(0.003)
    frame.GetXaxis().SetNdivisions(508)
    #gStyle.SetPalette(kBlackBody)
    #frame.SetContour(3);
    gStyle.SetPaintTextFormat(".2f")
    frame.SetMarkerSize(1.5*scaleF)
    #frame.SetMarkerColor(kRed)
    
    hist.Draw('COLZ TEXT')
    
    # TEXT
    if title:
      latex = TLatex()
      latex.SetTextSize(0.045)
      latex.SetTextAlign(33)
      latex.SetTextFont(42)
      latex.DrawLatexNDC(0.96*lmargin,0.80*bmargin,title)
    
    CMS_lumi.relPosX = 0.14
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvasname = "%s/postfit-correlation_%s_%s%s%s"%(outdir,var,DM,tag,plotlabel)
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
Esempio n. 3
0
def plotPostFitValues(channel,var,DM,year,*parameters,**kwargs):
    """Draw post-fit values for parameter using MultiDimFit and FitDiagnostics output."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotPostFitValues %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    title       = kwargs.get('title',     ""    )
    name        = kwargs.get('name',      ""    )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""    )
    plotlabel   = kwargs.get('plotlabel', ""    )
    compareFD   = kwargs.get('compareFD', False ) and N==1
    era         = "%d-13TeV"%year
    isBBB       = any("_bin_" in p for p in parameters)
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    filenamesFD = '%s/fitDiagnostics.%s_%s-%s%s-%s_TES*p*.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    if not name:
      name = formatParameter(parameters[0]).replace('_'+DM,'')
    if len(parameters)>1:
      name = "comparison_%s"%(name) #re.sub(r"bin_\d+","bin",name)
    canvasname = "%s/postfit-%s_%s_%s%s%s"%(outdir,name,var,DM,tag,plotlabel)
    print '>>>   file "%s"'%(filename)
    
    
    graphs      = [ ]
    graphsFD    = [ ]
    tvals       = [ ]
    pvals       = [ -2.2, +2.2 ]
    tes         = measureTES(filename)
    for parameter in parameters[:]:
      graph = getTGraphOfParameter(filename,'tes',parameter,xvals=tvals,yvals=pvals)
      if graph:
        graphs.append(graph)
      else:
        parameters.remove(parameter)
      if compareFD:
        graphFD = getTGraphOfParameter_FD(filenamesFD,parameter,xvals=tvals,yvals=pvals)
        if graphFD: graphsFD.append(graphFD)
    if len(parameters)!=len(graphs):
      warning("plotPostFitValues: len(parameters) = %d != %d = len(graphs)"%(len(parameters),len(graphs)))
      exit(1)
    N           = len(parameters)
    compareFD   = compareFD and len(graphsFD)>0
    parameters  = [formatParameter(p).replace('_'+DM,'') for p in parameters]
    graphsleg   = columnize(graphs,3)     if N>6 else columnize(graphs,2)     if N>3 else graphs # reordered for two columns
    paramsleg   = columnize(parameters,3) if N>6 else columnize(parameters,2) if N>3 else parameters # reordered for two columns
    
    xtitle  = 'tau energy scale'
    ytitle  = "%s post-fit value"%(parameters[0] if N==1 else "MultiDimFit")
    xmin, xmax = min(tvals), max(tvals)
    ymin, ymax = min(pvals), max(pvals)
    colors  = [ kBlack, kBlue, kRed, kGreen, kMagenta, kOrange, kTeal, kAzure+2, kYellow-3 ]
    
    canvas = TCanvas("canvas","canvas",100,100,800,650)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  0.07 ); canvas.SetBottomMargin( 0.13 )
    canvas.SetLeftMargin( 0.11 ); canvas.SetRightMargin(  0.05 )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    maxmargin = 0.18*abs(ymax-ymin)
    minmargin = 0.20*abs(ymax-ymin) #(0.20 if N<5 else 0.10*ceil(N/2))
    ymin   = 0.0 if ymin>=0 else ymin-minmargin
    ymax   = ymax + minmargin
    
    textsize   = 0.045 if N==1 else 0.036
    lineheight = 0.055 if N==1 else 0.045
    x1, width  = 0.42, 0.25
    y1, height = 0.15, lineheight*(ceil(N/3.) if N>6 else ceil(N/2.) if N>3 else N)
    if title:     height += lineheight
    if compareFD: height += lineheight
    if   N>6:
      if isBBB: width = 0.62; x1 = 0.25
      else:     width = 0.70; x1 = 0.20
    elif N>3:   width = 0.52; x1 = 0.36
    legend = TLegend(x1,y1,x1+width,y1+height)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    if title:
      legend.SetTextFont(62)
      legend.SetHeader(title) 
    legend.SetTextFont(42)
    if N>6:
      legend.SetNColumns(3)
      legend.SetColumnSeparation(0.02)
    elif N>3:
      legend.SetNColumns(2)
      legend.SetColumnSeparation(0.03)
    
    frame = canvas.DrawFrame(xmin,ymin,xmax,ymax)
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetLabelSize(0.050)
    frame.GetYaxis().SetLabelSize(0.050)
    frame.GetXaxis().SetLabelOffset(0.01)
    frame.GetYaxis().SetLabelOffset(0.01)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(0.84)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    
    for i, (parameter,graph) in enumerate(zip(parameters,graphs)):
      graph.SetLineColor(colors[i%len(colors)])
      graph.SetLineWidth(2)
      graph.SetLineStyle(1)
      graph.Draw('LSAME')
    
    for parameter,graph in zip(paramsleg,graphsleg):
      if N==1:
        legend.AddEntry(graph, "MultiDimFit", 'l')
      else:
        legend.AddEntry(graph, parameter, 'l')
    
    line = TLine(tes, ymin, tes, ymax)
    #line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw('SAME')
    latex = TLatex()
    latex.SetTextSize(0.045)
    latex.SetTextAlign(13)
    latex.SetTextFont(42)
    latex.DrawLatex(tes+0.02*(xmax-xmin),ymax-0.04*(ymax-ymin),"tes = %.3f"%tes)
    
    if compareFD:
      graphFD.SetLineColor(kBlue)
      graphFD.SetLineWidth(2)
      graphFD.SetLineStyle(2)
      graphFD.Draw('LSAME')
      legend.AddEntry(graphFD, "FitDiagnostics", 'l')
    
    legend.Draw()
    
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()
Esempio n. 4
0
def plotPValues(labels, masses0, **kwargs):
    print color("plotPValues()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    bins = kwargs.get('bins', [])
    ymin = 0.00005

    # LOOP over LABELS
    for label in labels:
        print color("plotPValues - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        masses = array('d', [])
        zeros = array('d', [])
        limitObs = array('d', [])
        limitExps = []

        up2s = []
        for i, mass in enumerate(masses0):
            bin = -1
            if bins: bin = bins[i]
            filename = getOutputFilename(label,
                                         mass,
                                         method="ProfileLikelihood",
                                         bin=bin,
                                         extralabel=".SignifObs")
            limitObs.append(getLimits(filename, brazilian=False))
            masses.append(mass)
            zeros.append(0.0)

        v_masses = TVectorD(len(masses), masses)
        v_zeros = TVectorD(len(zeros), zeros)
        v_limitObs = TVectorD(len(limitObs), limitObs)
        v_limitExps = []
        for limitExp in limitExps:
            v_limitExps.append(TVectorD(len(limitExp), limitExp))

        W = 800
        H = 600
        T = 0.08 * H
        B = 0.12 * H
        L = 0.12 * W
        R = 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, 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()
        canvas.SetLogy()  # log
        canvas.cd()

        frame = canvas.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(1.14)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(False)
        frame.GetYaxis().SetTitle("local p-value")
        #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
        frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]")
        frame.SetMinimum(ymin)
        frame.SetMaximum(1.5)
        frame.GetXaxis().SetLimits(min(masses), max(masses))

        latex = TLatex()
        latex.SetTextSize(0.4 * canvas.GetTopMargin())
        latex.SetTextColor(2)
        f1 = TF1("f1", "0.15866", min(masses), max(masses))
        f1.SetLineColor(2)
        f1.SetLineWidth(2)
        f1.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma")
        f2 = TF1("f2", "0.02275", min(masses), max(masses))
        f2.SetLineColor(2)
        f2.SetLineWidth(2)
        f2.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma")
        f3 = TF1("f3", "0.0013499", min(masses), max(masses))
        f3.SetLineColor(2)
        f3.SetLineWidth(2)
        f3.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma")

        graph_limitExps = []
        colors = [4, 2, 3, 6, 7, 8]
        for i, v_limitExp in enumerate(v_limitExps):
            graph_limitExps.append(
                TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros,
                                  v_zeros, v_zeros))
            graph_limitExps[-1].SetLineColor(colors[i])
            graph_limitExps[-1].SetLineWidth(2)
            graph_limitExps[-1].SetLineStyle(2)
            graph_limitExps[-1].Draw("Lsame")

        graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros,
                                           v_zeros, v_zeros, v_zeros)
        graph_limitObs.SetLineColor(1)
        graph_limitObs.SetLineWidth(2)
        graph_limitObs.Draw("Csame")

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        frame.Draw('sameaxis')

        x1 = 0.62
        x2 = x1 + 0.24
        y1 = 0.15
        y2 = y1 + 0.20
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(42)
        legend.SetHeader("%s" % (label_dict[label]))
        legend.AddEntry(graph_limitObs, "observed", 'L')  #p-value
        legend.Draw("same")
        gPad.RedrawAxis()

        print " "
        canvas.SaveAs("%s/p-value-local-%s.png" % (PLOTS_DIR, label))
        canvas.SaveAs("%s/p-value-local-%s.pdf" % (PLOTS_DIR, label))
        canvas.Close()
Esempio n. 5
0
def compareUpperLimits(labels, masses, filelabels, **kwargs):
    print color("compareUpperLimits()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")
    plotlabel = kwargs.get('plotlabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        ymax = -99999
        ymin = 99999
        medians = []

        for filelabel, title in filelabels:
            N = len(masses)
            median = TGraph(N)  # median line
            median.SetTitle(title)
            medians.append(median)
            for i, mass in enumerate(masses):
                filename = getOutputFilename(label, mass, extralabel=filelabel)
                limits = getLimits(filename)
                median.SetPoint(i, mass, limits[2])  # median
                if limits[2] > ymax: ymax = limits[2]
                if limits[2] < ymin: ymin = limits[2]

        median0 = medians[0]
        doLog = ymin and ymax / ymin > 6
        ymax = ymax * 1.40
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in filelabels[0][0]:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 800
        T, B = 0.10 * H, 0.16 * H
        L, R = 0.12 * W, 0.04 * W

        # MAIN plot
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.Divide(2)
        canvas.cd(1)
        gPad.SetPad("pad1", "pad1", 0, 0.37, 1, 1, 0, -1, 0)
        gPad.SetTopMargin(T / H)
        gPad.SetBottomMargin(0.01)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)
        gPad.SetTickx(0)
        gPad.SetTicky(0)
        gPad.SetGrid()
        if doLog:
            ymin = 10**(floor(log(ymin, 10)))
            ymax = 10**(ceil(log(ymax, 10)))
            gPad.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        width = 0.25
        height = 0.05 + len(medians) * 0.05
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.70
        x1 = x2 - width  # Right
        x2 = x1 + width
        y1 = 0.86
        y2 = y1 - height
        legend = TLegend(x1, y1, x2, y2)

        frame = gPad.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.058)
        frame.GetXaxis().SetLabelSize(0.050 * 0)
        frame.GetYaxis().SetLabelSize(0.053)
        frame.GetXaxis().SetLabelOffset(0.012)
        frame.GetXaxis().SetTitleOffset(1.02)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        option = 'L'
        for i, median in enumerate(medians):
            median.SetLineColor(colors[i % len(colors)])
            median.SetLineStyle(styles[i % len(styles)])
            median.SetLineWidth(2 if styles[i % len(styles)] != kDotted else 3)
            median.Draw('L')
            legend.AddEntry(median, median.GetTitle(), 'L')
            if i == 0: option += ' SAME'

        CMS_lumi.CMS_lumi(gPad, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.Draw()

        # RATIO plot
        canvas.cd(2)
        gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.36, 0, -1, 0)
        gPad.SetTopMargin(0.05)
        gPad.SetBottomMargin(0.24)
        gPad.SetLeftMargin(L / W)
        gPad.SetRightMargin(R / W)

        frame_ratio = gPad.DrawFrame(min(masses), 0.36, max(masses), 1.20)
        frame_ratio.GetYaxis().CenterTitle()
        frame_ratio.GetYaxis().SetTitleSize(0.055 * 1.79)
        frame_ratio.GetXaxis().SetTitleSize(0.058 * 1.79)
        frame_ratio.GetXaxis().SetLabelSize(0.052 * 1.79)
        frame_ratio.GetYaxis().SetLabelSize(0.050 * 1.79)
        frame_ratio.GetXaxis().SetLabelOffset(0.012)
        frame_ratio.GetXaxis().SetTitleOffset(1.00)
        frame_ratio.GetYaxis().SetTitleOffset(0.63)
        frame_ratio.GetXaxis().SetNdivisions(508)
        frame_ratio.GetYaxis().CenterTitle(True)
        frame_ratio.GetYaxis().SetTitle("ratio")
        frame_ratio.GetXaxis().SetTitle(xtitle)
        frame_ratio.GetYaxis().SetNdivisions(5)

        option = 'L'
        ratios = []
        for i, median in enumerate(medians):
            ratio = makeRatioTGraphs(median, median0)
            ratio.SetLineColor(median.GetLineColor())
            ratio.SetLineStyle(median.GetLineStyle())
            ratio.SetLineWidth(median.GetLineWidth())
            ratio.Draw('L')
            ratios.append(ratio)
            if i == 1: option += ' SAME'

        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame_ratio.Draw('sameaxis')

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s_compare.png" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.SaveAs("%s/upperLimit-%s%s_compare.pdf" %
                      (PLOTS_DIR, label, plotlabel))
        canvas.Close()
Esempio n. 6
0
def plotUpperLimits(labels, masses, **kwargs):
    print color("plotUpperLimits()", color="magenta", prepend=">>>\n>>> ")
    # https://raw.githubusercontent.com/nucleosynthesis/HiggsAnalysis-CombinedLimit/combine_tutorial_SWAN/combine_tutorials_2016/combine_intro/plotPvalue.py

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

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

        up2s = []
        down2s = []
        for i, mass in enumerate(masses):
            filename = getOutputFilename(label, mass, extralabel=extralabel)
            limits = getLimits(filename)
            yellow.SetPoint(i, mass, limits[4])  # + 2 sigma
            green.SetPoint(i, mass, limits[3])  # + 1 sigma
            median.SetPoint(i, mass, limits[2])  # median
            green.SetPoint(2 * N - 1 - i, mass, limits[1])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, mass, limits[0])  # - 2 sigma
            down2s.append(limits[0])
            up2s.append(limits[4])

        ymax = max(up2s) * 1.20
        ymin = min(down2s)
        doLog = ymin and ymax / min(down2s) > 4
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in extralabel:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 600
        T, B = 0.08 * H, 0.12 * H
        L, R = 0.12 * W, 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.cd()
        if doLog:
            ymin = 0.1  #10**(floor(log(ymin,10))-1)
            ymax = 1000  #10**(ceil(log(ymax,10))+1)
            #ymin, ymax = 0.1, 1000
            canvas.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        frame = canvas.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetLabelSize(0.044)
        frame.GetYaxis().SetLabelSize(0.044)
        frame.GetXaxis().SetLabelOffset(0.010)
        frame.GetXaxis().SetTitleOffset(1.04)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

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

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

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

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        width = 0.28
        height = 0.20
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.80
        x1 = x2 - width  # Right
        x2 = x1 + width

        y1 = 0.68
        y2 = y1 + height
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.040)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        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 " "
        canvas.SaveAs("%s/upperLimit-%s%s.png" %
                      (PLOTS_DIR, label, extralabel))
        canvas.SaveAs("%s/upperLimit-%s%s%s.pdf" %
                      (PLOTS_DIR, label, extralabel))
        canvas.Close()
Esempio n. 7
0
def plotBoxes(labels, **kwargs):
    '''Plot boxes.'''
    print color("plotBoxes()", color="magenta", prepend=">>>\n>>> ")
    # https://wiki.physik.uzh.ch/cms/limits:brazilianplotexample
    # https://root.cern.ch/doc/master/classTHistPainter.html#HP07
    # text label https://root.cern.ch/root/roottalk/roottalk98/0616.html
    #            https://root.cern.ch/phpBB3/viewtopic.php?t=18534
    #            https://root.cern.ch/doc/master/classTGaxis.html#GA10a
    # boxes https://root.cern.ch/doc/master/classTGraphPainter.html#GP03b

    # MASS
    mass = kwargs.get('mass', 28)
    green = TGraphAsymmErrors()
    yellow = TGraphAsymmErrors()
    limit = TGraphAsymmErrors()
    labels = labels[::-1]  # reverse order: top to bottom
    width = 0.2

    (down, up) = (1000, 0)
    labels = [
        "mt-2",
        "mt-2",
        "mt-1",
        "mt-1",
    ]
    extralabels = [
        "_noOpt",
        "_Opt",
        "_noOpt",
        "_Opt",
    ]
    for i, (label, extralabel) in enumerate(zip(labels, extralabels)):
        filename = getOutputFilename(label, mass, extralabel=extralabel)
        limits = getLimits(filename)
        limit.SetPoint(i, limits[2], i + 1)
        green.SetPoint(i, limits[2], i + 1)  # -/+ 1 sigma
        yellow.SetPoint(i, limits[2], i + 1)  # -/+ 2 sigma
        limit.SetPointError(i, 0, 0, width, width)  # -/+ 1 sigma
        green.SetPointError(i, limits[2] - limits[1], limits[3] - limits[2],
                            width, width)  # -/+ 1 sigma
        yellow.SetPointError(i, limits[2] - limits[0], limits[4] - limits[2],
                             width, width)  # -/+ 2 sigma
        if down > limits[0]: down = limits[0]
        if up < limits[4]: up = limits[4]
    labels = [
        "mt-2_label",
        "mt-2",
        "mt-1_label",
        "mt-1",
    ]

    N = len(labels)
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    canvas.SetTopMargin(0.08)
    canvas.SetBottomMargin(0.12)
    canvas.SetLeftMargin(0.14)
    canvas.SetRightMargin(0.04)
    canvas.SetGrid(1, 0)
    #canvas.SetTicks(1,0)
    #canvas.SetLogx()
    green.SetFillColor(kGreen + 1)
    yellow.SetFillColor(kOrange)
    limit.SetLineWidth(2)

    frame = TH2F("frame", "frame", 200, down - (up * 0.1), up * 1.1,
                 2 * (N + 1), 0, N + 1)  #canvas.DrawFrame(0.001,0,10,N+1)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetYaxis().SetLabelSize(0.0)  #8)
    frame.GetXaxis().SetLabelSize(0.045)
    frame.GetXaxis().SetTitleOffset(1.14)
    frame.GetYaxis().SetNdivisions(N + 1, 0, 0,
                                   False)  # ndiv = N1 + 100*N2 + 10000*N3
    #frame.GetXaxis().CenterTitle(True)
    xtitle = "95% upper limit on #sigma#timesBR(X#rightarrow#tau#tau) [pb]"
    frame.GetXaxis().SetTitle(xtitle)

    #frame.GetXaxis().SetRangeUser(0,up*1.10)
    #frame.SetMinimum(0)
    #frame.SetMaximum(up*1.10) #ymax)
    #frame.GetYaxis().SetLimits(0,N+1)
    frame.Draw("AXIS")
    yellow.Draw("2 SAME")
    green.Draw("2 SAME")
    limit.Draw("P SAME")

    labelfontsize = 0.042
    text = TLatex()
    text.SetTextSize(labelfontsize)
    text.SetTextAlign(23)
    text.SetTextFont(42)

    #labelfontwidth = labelfontsize*stringWidth(*[label_dict_split[k] for k in label_dict_split])
    #xtext = frame.GetXaxis().GetXmin()-frame.GetXaxis().GetXmax()*0.04 # manual
    xtext = marginCenter(canvas, frame.GetXaxis())  # automatic
    for i, label in enumerate(labels):
        bin = frame.GetYaxis().FindBin(i + 1)
        ytext = frame.GetYaxis().GetBinCenter(bin)
        #print "(x,y)=(%s,%s)"%(xtext,ytext)
        text.DrawLatex(xtext, ytext, label_dict_split[label] + "  ")
        # limit.GetYaxis().SetBinLabel(bin-1,label_dict_split[label])

    #frame.GetYaxis().LabelsOption('H') # draw horizontal
    #gPad.Modified()
    #gPad.Update()
    CMS_lumi.CMS_lumi(canvas, 13, 0)

    print " "
    canvas.SaveAs("%s/upperLimitBoxes.png" % (PLOTS_DIR))
    canvas.SaveAs("%s/upperLimitBoxes.pdf" % (PLOTS_DIR))
    canvas.Close()
def compareProjectedEfficiencies(filename1, filename2, prefix, workingpoint,
                                 **kwargs):
    print ">>>\n>>> compareProjectedEfficiencies"
    print ">>>   %s vs. %s" % (filename1, filename2)

    file1 = TFile(filename1, 'READ')  # old file
    file2 = TFile(filename2, 'READ')  # new file

    label = kwargs.get('label', "")
    dirname = kwargs.get('dirname', "bTagEff")
    compare = kwargs.get('compare', "")

    title1 = "VH #rightarrow #tau#taubb analysis"
    title2 = "X #rightarrow #tau#tau analysis"
    dirname1 = dirname
    dirname2 = dirname

    if compare == "mutau-etau":
        title1 = "#mu#tau"
        title2 = "e#tau"
        dirname1 = "%s_mutau" % (dirname)
        dirname2 = "%s_etau" % (dirname)
        label += "_mutau-etau"

    histnames = [
        "%s_%s_%s_eff" % (prefix, "udsg", workingpoint),
        "%s_%s_%s_eff" % (prefix, "b", workingpoint),
    ]

    etabins_dict = {
        "central": ["|#eta|<1.5", 2, 3],
        "forward": ["1.5<|#eta|<2.5", 1, 4],
    }

    for histname in histnames:
        for etarange in ["central", "forward"]:
            print ">>>   %s - %s" % (histname, etarange)

            etabins = etabins_dict[etarange]
            flavor = "b"
            if "udsg" in histname: flavor = "light"
            if "_c_" in histname: flavor = "c"

            range = [0.10, 0.80]
            legendCoordinates = [0.52, 0.72, 0.90, 0.86]
            if flavor == "light":
                range = [0.0, 0.10]
                legendCoordinates = [0.20, 0.65, 0.60, 0.80]

            hist1_2D = file1.Get("%s/%s" % (dirname1, histname))
            hist2_2D = file2.Get("%s/%s" % (dirname2, histname))  # old first
            hist1 = None
            hist2 = None
            if etarange == "central":
                hist1 = hist1_2D.ProjectionX("%s_1" % (histname), etabins[1],
                                             etabins[2])  # ProfileX
                hist2 = hist2_2D.ProjectionX("%s_2" % (histname), etabins[1],
                                             etabins[2])
            else:
                hist1 = hist1_2D.ProjectionX("%s_11" % (histname), 1,
                                             1)  # ProfileX
                hist2 = hist2_2D.ProjectionX("%s_21" % (histname), 4, 4)
                hist1.Add(hist1_2D.ProjectionX("%s_12" % (histname), 1, 1))
                hist2.Add(hist2_2D.ProjectionX("%s_22" % (histname), 4, 4))

            hist1.Scale(0.5)
            hist2.Scale(0.5)
            #print ">>>   hist1_2D.GetNbinsY() - %s" % (hist1_2D.GetNbinsY())
            #print ">>>   hist2_2D.GetNbinsY() - %s" % (hist2_2D.GetNbinsY())

            canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
            canvas.SetBottomMargin(0.12)
            canvas.SetRightMargin(0.04)
            canvas.SetLeftMargin(0.10)
            canvas.SetTopMargin(0.08)
            hist1.SetLineWidth(3)
            hist1.SetLineStyle(1)
            hist1.SetLineColor(kAzure + 4)
            hist2.SetLineWidth(3)
            hist2.SetLineStyle(2)
            hist2.SetLineColor(kRed + 3)
            hist1.Draw("histE")
            hist2.Draw("histsameE")
            hist1.SetTitle("")
            hist1.GetXaxis().SetTitle("%s jet p_{T}" % (flavor))
            hist1.GetYaxis().SetTitle("b tagging efficiency of %s jet" %
                                      (flavor))
            hist1.GetXaxis().SetLabelSize(0.042)
            hist1.GetYaxis().SetLabelSize(0.040)
            hist1.GetXaxis().SetTitleSize(0.05)
            hist1.GetYaxis().SetTitleSize(0.05)
            hist1.GetXaxis().SetTitleOffset(1.10)
            hist1.GetYaxis().SetTitleOffset(0.99)
            hist1.GetYaxis().SetRangeUser(*range)
            legend = TLegend(*legendCoordinates)
            legend.SetHeader(etabins[0])
            legend.AddEntry(hist1, title1, 'l')
            legend.AddEntry(hist2, title2, 'l')
            legend.SetTextSize(0.040)
            legend.SetBorderSize(0)
            legend.SetFillStyle(0)
            legend.Draw()
            gStyle.SetOptStat(0)
            CMS_lumi.CMS_lumi(canvas, 13, 0)
            canvas.SaveAs("%s/%s_vs_pt_%s%s.png" %
                          (OUT_DIR, histname, etarange, label))
            canvas.Close()
            ROOT.gDirectory.Delete(hist1.GetName())
            ROOT.gDirectory.Delete(hist2.GetName())

    file1.Close()
    file2.Close()
Esempio n. 9
0
def compareVarsForLHESamples(filesetname, filenames):
    """Compare shapes of different variables for the same sample file."""
    print ">>>\n>>> compareVarsForSamples()"

    treename = "LHEF"
    dirname = makeDirectory(OUT_DIR)

    files = []
    hists = {}

    # GET histograms
    for ifile, (filename, filetitle) in enumerate(filenames, 1):
        print ">>> %s: %10s, %10s" % (ifile, filename, filetitle)
        file = TFile("%s/%s" % (LHE_DIR, filename))
        tree = file.Get(treename)
        print ">>>   %d events" % (tree.GetEntries())
        if hists.get(filetitle, False):
            warning("\"%s\" already exists!" % (filetitle))
        filehists = makeHistsFromLHETree(tree)
        #print filehists

        for histkey, hist in filehists.items():
            if histkey not in hists: hists[histkey] = []
            #print ">>>   %-10s - %s"%(histkey,filetitle)
            hists[histkey].append((filetitle, hist))
        files.append(file)

    # DRAW
    for histkey, filehists in hists.items():

        ymax = 0
        hist1 = None
        width = 0.30
        legendTextSize = 0.035
        height = 0.05 + len(filehists) * 0.038
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.84
        x1 = x2 - width  # Right
        y1 = 0.88
        y2 = y1 - height  # Top
        if "eta" in histkey:
            x1 = 0.34
            x2 = x1 + width  # Center
            if "tau" in histkey or "bquark" in histkey:
                y1 = 0.14
                y2 = y1 + height  # Bottom
        elif "pt_bquark" in histkey:
            if "600" in filesetname or "800" in filesetname:
                x1 = 0.16
                x2 = x1 + width  # Left
        elif "pt_tau" in histkey:
            if "600" in filesetname or "800" in filesetname:
                x1 = 0.26
                x2 = x1 + width  # CenterLeft
                y1 = 0.15
                y2 = y1 + height  # Bottom
        #elif "dR_bX" in histkey:
        #x1 = 0.16; x2 = x1 + width # Left
        #elif "tau" in histkey:
        #  y1 = 0.88; y2 = y1 - height
        elif "m_bX" in histkey:
            if "400" in filesetname or "600" in filesetname or "800" in filesetname:
                x1 = 0.16
                x2 = x1 + width  # Left

        canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
        canvas.SetBottomMargin(0.12)
        canvas.SetRightMargin(0.05)
        canvas.SetLeftMargin(0.12)
        canvas.SetTopMargin(0.08)
        legend = TLegend(x1, y1, x2, y2)

        for i, (filetitle, hist) in enumerate(filehists):
            histname = "%s_%s" % (histkey, i)
            N1 = hist.GetEntries()

            # REBIN
            if "m_bX" in histkey:
                if "170" in filesetname:
                    hist.GetXaxis().SetRangeUser(120, 240)
                elif "400" in filesetname:
                    hist.Rebin(7)
                    hist.GetXaxis().SetRangeUser(120, 600)
                elif "600" in filesetname:
                    hist.Rebin(14)
                    hist.GetXaxis().SetRangeUser(0, 1000)
                elif "800" in filesetname:
                    hist.Rebin(20)
                    hist.GetXaxis().SetRangeUser(0, 1400)
            elif "pt_tau" in histkey:
                if "400" in filesetname:
                    hist.Rebin(3)
                elif "600" in filesetname:
                    hist.Rebin(3)
                elif "800" in filesetname:
                    hist.Rebin(3)
            elif "pt_bquark" in histkey:
                if "170" not in filesetname:
                    hist.Rebin(2)

            hist.Scale(1 / N1)
            #hist.SetBinError(error/N1)
            hmax = hist.GetMaximum()
            if hmax > ymax:
                ymax = hmax
            hist.SetLineWidth(3)
            hist.SetLineStyle(1 + (i - 1) % 2)
            hist.SetLineColor(colors[i - 1])
            hist.SetMarkerSize(0)
            if i == 0:
                hist1 = hist
                hist.Draw("hist")
            else:
                hist.Draw("histsame")
            legend.AddEntry(hist, makeLaTeX(filetitle), 'l')

        hist1.GetXaxis().SetTitle(makeLaTeX(hist1.GetTitle()))
        hist1.GetYaxis().SetTitle("A.U.")
        hist1.GetXaxis().SetTitleSize(0.06)
        hist1.GetYaxis().SetTitleSize(0.06)
        hist1.GetXaxis().SetTitleOffset(0.90)
        hist1.GetYaxis().SetTitleOffset(1.05)
        hist1.GetXaxis().SetLabelSize(0.045)
        hist1.GetYaxis().SetLabelSize(0.045)
        hist1.SetMaximum(ymax * 1.10)
        legend.SetTextFont(42)
        legend.SetTextSize(legendTextSize)
        legend.SetBorderSize(0)
        legend.SetFillStyle(0)
        legend.Draw()
        CMS_lumi.CMS_lumi(gPad, 13, 0)
        gStyle.SetOptStat(0)
        canvas.SaveAs("%s/%s-%s%s.png" %
                      (dirname, histkey, filesetname, plotslabel))
        #canvas.SaveAs("%s/%s-%s%s.pdf" % (dirname,histkey,filesetname,plotslabel))
        canvas.Close()

    for file in files:
        file.Close()