Beispiel #1
0
def testIthr():
    lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat')

    gr1 = TGraphErrors()
    gr2 = TGraphErrors()

    fUnit = 1000. / 0.7
    yUnit = 'e^{-}'

    for line in lines:
        if len(line) == 0: continue
        if line[0] in ['#', '\n']: continue
        fs = line.rstrip().split()

        ix = int(fs[0])
        gr1.SetPoint(ix, float(fs[1]), float(fs[2]) * fUnit)
        gr1.SetPointError(ix, 0, float(fs[3]) * fUnit)
        gr2.SetPoint(ix, float(fs[1]), float(fs[4]) * fUnit)
        gr2.SetPointError(ix, 0, float(fs[5]) * fUnit)

    useAtlasStyle()
    gStyle.SetMarkerStyle(20)

    gr1.SetMarkerStyle(20)
    gr1.Draw('AP')
    h1 = gr1.GetHistogram()
    h1.GetYaxis().SetTitle("Threshold [" + yUnit + "]")
    h1.GetXaxis().SetTitle("I_{Thre} code")
    # h1.GetYaxis().SetRangeUser(0,0.2)

    gPad.SetTicks(1, 0)
    gPad.SetRightMargin(0.16)

    y1b = 0
    y2b = 15
    x1 = h1.GetXaxis().GetXmax()
    y1 = h1.GetYaxis().GetXmin()
    y2 = h1.GetYaxis().GetXmax()
    raxis = TGaxis(x1, y1, x1, y2, y1b, y2b, 506, "+L")
    raxis.SetLineColor(2)
    raxis.SetLabelColor(2)
    raxis.SetTitleColor(2)
    raxis.SetTitle("ENC [" + yUnit + "]")
    raxis.Draw()

    nP = gr2.GetN()
    Ys = gr2.GetY()
    EYs = gr2.GetEY()
    Y = array(
        'd', [y1 + (y2 - y1) / (y2b - y1b) * (Ys[i] - y1b) for i in range(nP)])
    EY = array('d', [(y2 - y1) / (y2b - y1b) * EYs[i] for i in range(nP)])
    gr2x = TGraphErrors(nP, gr2.GetX(), Y, gr2.GetEX(), EY)
    gr2x.SetMarkerStyle(24)
    gr2x.SetLineColor(2)
    gr2x.SetMarkerColor(2)

    gr2x.Draw('Psame')

    waitRootCmdX()
Beispiel #2
0
    l1.AddEntry(hist, filterNames_mAug[i], "f")

# draw individual filter stack + overall rate hist
hs1.Draw("HIST")
totalRateHist.Draw("pSAME")

## configure axes
# set axis titles
hs1.GetXaxis().SetTitle("lumi block")
hs1.GetYaxis().SetTitle("n events")
hs1.GetYaxis().SetTitleOffset(.75)
# set axis ranges
hs1.GetXaxis().SetRangeUser(first_lb - 20, last_lb + 20)
hs1.GetYaxis().SetRangeUser(0, 100)
# set tick marks on all axes
gPad.SetTicks(1, 1)

# draw legend
l1.Draw()

# add text to plot
latex1 = ROOT.TLatex(0.52, 0.875, "#font[72]{ATLAS }#font[42]{Internal}")
latex1.SetNDC()
latex1.SetTextSize(0.05)
latex1.SetTextAlign(13)
latex1.Draw()
latex2 = ROOT.TLatex(0.55, 0.82, "Run " + runNumber)
latex2.SetNDC()
latex2.SetTextSize(0.05)
latex2.SetTextAlign(13)
latex2.SetTextFont(42)
Beispiel #3
0
def plot(tgr, n):  #(List, layer, tgrDict):
    H = 1600
    W = 800
    #print "----- Creating Third TCanvas -----"
    c = TCanvas("c", "Canvas", W, H)
    ymax = 0.0

    c.SetLeftMargin(0.15)
    c.SetRightMargin(0.06)
    c.SetTopMargin(0.09)
    c.SetBottomMargin(0.14)
    #gPad.SetGrid()
    gPad.SetTicks()
    #gPad.SetLogy()

    mg = TMultiGraph()

    tgr.SetMarkerColor(kGreen + 3)
    tgr.SetMarkerStyle(21)
    tgr.SetMarkerSize(1.5)
    mg.Add(tgr, 'AP')
    mg.Draw("a")

    l = TLegend(0.42, 0.15, 0.82, 0.35)
    l.SetFillColor(0)
    l.SetBorderSize(0)
    l.SetTextSize(0.03)
    l.SetNColumns(1)
    l.AddEntry(tgr, "CMS (13TeV)", "p")

    mg.SetTitle('')
    #mg.SetMaximum(ymax*1.1)
    mg.GetXaxis().SetTitle('Instantaneous Luminosity 10^{34} cm^{-2} s^{-1}')
    mg.GetXaxis().SetLabelFont(42)
    mg.GetXaxis().SetLabelOffset(0.007)
    mg.GetXaxis().SetLabelSize(0.043)
    mg.GetXaxis().SetTitleSize(0.03)
    mg.GetXaxis().SetTitleOffset(1.56)
    mg.GetXaxis().SetTitleFont(42)
    mg.GetYaxis().SetTitle('rate (Hz/cm^{2})')
    mg.GetYaxis().SetLabelFont(42)
    mg.GetYaxis().SetLabelOffset(0.008)
    mg.GetYaxis().SetLabelSize(0.02)
    mg.GetYaxis().SetTitleSize(0.03)
    mg.GetYaxis().SetTitleOffset(1.37)
    mg.GetYaxis().SetTitleFont(42)

    pv = TPaveText(.08, 0.94, .45, 0.94, "NDC")
    pv.AddText('CMS Preliminary Rack {}'.format(n))
    pv.SetFillStyle(0)
    pv.SetBorderSize(0)
    pv.SetTextSize(0.04)
    pv.Draw()

    fun1 = TF1("fun1", "pol1", 6000, 16000)
    fit1 = tgr.Fit("fun1", "R")  # "FQ")
    offset1 = fun1.GetParameter(0)
    slope1 = fun1.GetParameter(1)

    l.AddEntry(tgr, 'The p0 value is {0:.6f}'.format(offset1))
    l.AddEntry(tgr, 'The p1 value is {0:.6f}'.format(slope1))

    l.Draw("a")

    c.SaveAs("rack{}.png".format(n))
    c.SaveAs("rack{}.pdf".format(n))
    c.SaveAs("rack{}.C".format(n))
    return
Beispiel #4
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()
Beispiel #5
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()
Beispiel #6
0
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

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

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

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

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

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

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

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
Beispiel #7
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()
Beispiel #8
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()
Beispiel #9
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()
Beispiel #10
0
def checkDataPoissonErrors():
    '''Check on behaviour of Poisson errors in histograms.'''

    N = 100
    hist0 = TH1D("data0", "default", N, 0, N)
    hist1 = TH1D("data1", "TH1.kPoisson", N, 0, N)
    hist2 = TH1D("data2", "#chi^{2} quantile", N, 0, N)

    for i in xrange(0, N + 2):
        y = max(0, i - 1)
        hist0.SetBinContent(i, y)
        hist1.SetBinContent(i, y)
        hist2.SetBinContent(i, y)

    # GET data Possoin errors
    graph1 = getDataPoissonErrors(hist1,
                                  drawZeroBins=True,
                                  centerBin=False,
                                  kPoisson=True)
    graph2 = getDataPoissonErrors(hist2,
                                  drawZeroBins=True,
                                  centerBin=False,
                                  kPoisson=False)

    # FILL table
    table = []
    table.append(
        "%22s  %14s  %14s  %14s" %
        (" ", "default".center(14), "kPoisson".center(14), "chi^2".center(14)))
    table.append("%4s %7s  %7s   %6s %6s   %6s %6s   %6s %6s" %
                 ("bin", "content", "sqrt(N)", "errLow", "errUp", "errLow",
                  "errUp", "errLow", "errUp"))
    for i in xrange(1, N + 1):
        y = hist0.GetBinContent(i)
        table.append(
            "%4d %5d    %7.2f   %6.2f %6.2f   %6.2f %6.2f   %6.2f %6.2f" %
            (i, y, sqrt(y), hist0.GetBinErrorLow(i), hist0.GetBinErrorUp(i),
             graph1.GetErrorYlow(i - 1), graph1.GetErrorYhigh(i - 1),
             graph2.GetErrorYlow(i - 1), graph2.GetErrorYhigh(i - 1)))

    # PRINT table
    for line in table:
        print ">>> " + line
    print ">>> "

    # GRAPHS
    function = TF1("function1", "sqrt(x)", 0, N)
    function.SetTitle("#sqrt{N}")
    graphElow1, graphEup1 = makeErrorGraph(graph1)
    graphElow2, graphEup2 = makeErrorGraph(graph2)
    graphElow1.SetTitle("TH1.kPoisson low")
    graphEup1.SetTitle("TH1.kPoisson high")
    graphElow2.SetTitle("N-F^{-1}_{#chi^{2}}(1-#alpha,2N)/2")
    graphEup2.SetTitle("F^{-1}_{#chi^{2}}(#alpha,2(N-1))/2-N")
    graphs = [function, graphElow1, graphEup1, graphElow2, graphEup2]

    # DRAW settings
    W, H = 800, 800
    T, B = 0.04 * H, 0.14 * H
    L, R = 0.12 * W, 0.04 * W
    xmin, xmax = -N * 0.01, N * 1.01
    ymax = function.GetMaximum() * 1.16
    width = 0.25
    legendTextSize = 0.045
    height = 0.062 * (1 + len(graphs))
    x2 = 0.86
    x1 = x2 - width
    y1 = 0.20
    y2 = y1 + height

    # CANVAS
    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()

    # FRAME
    frame = gPad.DrawFrame(xmin, 0, xmax, ymax)
    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(505)
    frame.GetXaxis().SetTitle("number of events")
    frame.GetYaxis().SetTitle("error on number of events")
    legend = TLegend(x1, y1, x2, y2)

    # DRAW
    colors = [kRed, kBlue, kViolet, kYellow, kGreen]
    for i, graph in enumerate(graphs):
        style = kSolid
        width = 2
        if i < 3: width = 3
        if i > 2: style = kDashed
        graph.SetLineColor(colors[i % len(colors)])
        graph.SetLineStyle(style)
        graph.SetLineWidth(width)
        graph.Draw('L SAME')
        legend.AddEntry(graph, graph.GetTitle(), 'L')
    #CMS_lumi.CMS_lumi(gPad,13,0)
    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('SAME AXIS')

    # LEGEND
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(legendTextSize)
    legend.SetTextFont(62)
    legend.SetHeader("method")
    legend.SetTextFont(42)
    legend.Draw()

    # CHI2 TEXT
    text1 = "#splitline{#alpha = (1-0.6827)/2}{upper #chi^{2} CDF F_{#chi^{2}}}"
    text = TLatex()
    text.SetNDC()
    text.SetTextFont(42)
    text.SetTextSize(legendTextSize)
    text.SetTextAlign(13)  # centered: 22
    xoffset = (legend.GetX2() - legend.GetX1()) * legend.GetMargin() * 1.04
    text.DrawLatexNDC(legend.GetX1() + xoffset, legend.GetY1() - 0.012, text1)

    # 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
    frame_ratio = gPad.DrawFrame(xmin, 0.50, xmax, 1.50)
    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("number of events N")
    frame_ratio.GetYaxis().SetNdivisions(5)

    # DRAW ratio
    ratios = []
    graphf = makeGraphFromTF1(function, N)
    for i, graph in enumerate(graphs):
        if isinstance(graph, TF1): graph = makeGraphFromTF1(graph, N)
        ratio = makeRatioTGraphs(graph, graphf)
        ratio.SetLineColor(graph.GetLineColor())
        ratio.SetLineStyle(graph.GetLineStyle())
        ratio.SetLineWidth(graph.GetLineWidth())
        ratio.Draw('L SAME')
        ratios.append(ratio)
    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame_ratio.Draw('sameaxis')

    # SAVE
    canvas.SaveAs("PoissonError.png")
    canvas.Close()