Ejemplo n.º 1
0
 def setcanvas(self, **kwargs):
     """Make canvas and pads for ratio plots."""
     square = kwargs.get('square', False)
     double = kwargs.get('ratio', False)  # include lower panel
     width = kwargs.get('width', 900 if square else 800 if double else 800)
     height = kwargs.get('height',
                         900 if square else 750 if double else 600)
     lmargin = kwargs.get('lmargin', 1.)
     rmargin = kwargs.get('rmargin', 1.)
     tmargin = kwargs.get('tmargin', 1.)
     bmargin = kwargs.get('bmargin', 1.)
     pads = kwargs.get('pads', [])  # pass list as reference
     #if not CMSStyle.lumi_13TeV:
     #  tmargin *= 0.7
     if square:
         lmargin *= 1.15
         tmargin *= 0.90
         #rmargin *= 3.6
         #CMSStyle.relPosX = 0.15
     canvas = TCanvas('canvas', 'canvas', 100, 100, width, height)
     canvas.SetFillColor(0)
     #canvas.SetFillStyle(0)
     canvas.SetBorderMode(0)
     canvas.SetFrameBorderMode(0)
     if double:
         canvas.SetMargin(0.0, 0.0, 0.0, 0.0)  # LRBT
         canvas.Divide(2)
         canvas.cd(1)
         gPad.SetPad('pad1', 'pad1', 0.0, 0.33, 1.0, 1.0)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.029,
                        0.075 * tmargin)
         gPad.SetFillColor(0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         #gPad.SetFillStyle(0)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(2)
         gPad.SetPad('pad2', 'pad2', 0.0, 0.0, 1.0, 0.33)
         gPad.SetMargin(0.145 * lmargin, 0.04 * rmargin, 0.355 * bmargin,
                        0.04)
         gPad.SetFillColor(0)  #gPad.SetFillColorAlpha(0,0.0)
         gPad.SetFillStyle(4000)  # transparant (for pdf)
         gPad.SetBorderMode(0)
         gPad.Draw()
         canvas.cd(1)
     else:
         canvas.SetMargin(0.145 * lmargin, 0.05 * rmargin, 0.145 * bmargin,
                          0.06 * tmargin)
     return canvas
Ejemplo n.º 2
0
 def setPadStyle():
     gPad.SetLeftMargin(0.05)
     gPad.SetRightMargin(0.08)
     gPad.SetTopMargin(0.10)
     gPad.SetBottomMargin(0.10)
     gPad.SetLogz(plots[plot].zLog)
     gPad.SetFillColor(kWhite)
     gPad.SetBorderMode(0)
Ejemplo n.º 3
0
def setpad(left, right, top, bottom):
    gPad.SetFillColor(10)
    gPad.SetBorderMode(0)
    gPad.SetBorderSize(0)
    gPad.SetFrameFillColor(10)
    gPad.SetFrameBorderMode(0)
    gPad.SetFrameBorderSize(0)
    gPad.SetLeftMargin(left)
    gPad.SetRightMargin(right)
    gPad.SetTopMargin(top)
    gPad.SetBottomMargin(bottom)
    gPad.SetGridx(0)
    gPad.SetGridy(0)
    gStyle.SetOptStat(0)
def rooFit109():

    print ">>> setup model..."
    x = RooRealVar("x", "x", -10, 10)
    sigma = RooRealVar("sigma", "sigma", 3, 0.1, 10)
    mean = RooRealVar("mean", "mean", 0, -10, 10)
    gauss = RooGaussian("gauss", "gauss", x, RooConst(0),
                        sigma)  # RooConst(0) gives segfaults
    data = gauss.generate(RooArgSet(x), 100000)  # RooDataSet
    #sigma = 3.15 # overwrites RooRealVar with a float
    sigma.setVal(3.15)

    print ">>> plot data and slightly distorted model..."
    frame1 = x.frame(Title("Data with distorted Gaussian pdf"),
                     Bins(40))  # RooPlot
    data.plotOn(frame1, DataError(RooAbsData.SumW2))
    gauss.plotOn(frame1)

    print ">>> calculate chi^2..."
    # Show the chi^2 of the curve w.r.t. the histogram
    # If multiple curves or datasets live in the frame you can specify
    # the name of the relevant curve and/or dataset in chiSquare()
    print ">>>   chi^2 = %.2f" % frame1.chiSquare()

    print ">>> construct histograms with the residuals and pull of the data wrt the curve"
    hresid = frame1.residHist()  # RooHist
    hpull = frame1.pullHist()  # RooHist
    frame2 = x.frame(Title("Residual Distribution"))  # RooPlot
    frame2.addPlotable(hresid, "P")
    frame3 = x.frame(Title("Pull Distribution"))  # RooPlot
    frame3.addPlotable(hpull, "P")

    print ">>> draw functions and toy data on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 2000, 400)
    canvas.Divide(3)
    for i, frame in enumerate([frame1, frame2, frame3], 1):
        canvas.cd(i)
        gPad.SetLeftMargin(0.14)
        gPad.SetRightMargin(0.04)
        frame.GetYaxis().SetTitleOffset(1.5)
        frame.GetYaxis().SetLabelOffset(0.010)
        frame.GetYaxis().SetTitleSize(0.045)
        frame.GetYaxis().SetLabelSize(0.042)
        frame.GetXaxis().SetTitleSize(0.045)
        frame.GetXaxis().SetLabelSize(0.042)
        frame.Draw()
    canvas.SaveAs("rooFit109.png")
    canvas.Close()

    # ratio/pull/residual plot
    print ">>> draw with pull plot..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1000, 1000)
    canvas.Divide(2)
    canvas.cd(1)
    gPad.SetPad("pad1", "pad1", 0, 0.33, 1, 1, 0, -1, 0)
    gPad.SetTopMargin(0.10)
    gPad.SetBottomMargin(0.03)
    gPad.SetLeftMargin(0.14)
    gPad.SetRightMargin(0.04)
    gPad.SetBorderMode(0)
    gStyle.SetTitleFontSize(0.062)
    frame1.GetYaxis().SetTitle("Events / %.3g GeV" % frame1.getFitRangeBinW())
    frame1.GetYaxis().SetTitleSize(0.059)
    frame1.GetYaxis().SetTitleOffset(1.21)
    #frame1.GetYaxis().SetLabelOffset(0.010)
    frame1.GetXaxis().SetLabelSize(0)
    frame1.GetYaxis().SetLabelSize(0.045)
    frame1.Draw()
    canvas.cd(2)
    gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.33, 0, -1, 0)
    gPad.SetTopMargin(0.01)
    gPad.SetBottomMargin(0.30)
    gPad.SetLeftMargin(0.14)
    gPad.SetRightMargin(0.04)
    gPad.SetBorderMode(0)
    gPad.SetGridy(kTRUE)
    line1 = TLine(frame3.GetXaxis().GetXmin(), 0,
                  frame3.GetXaxis().GetXmax(), 0)
    line2 = TLine(frame3.GetXaxis().GetXmin(), 0,
                  frame3.GetXaxis().GetXmax(), 0)
    line1.SetLineColor(0)  # white to clear dotted grid lines
    line2.SetLineColor(12)  # dark grey
    line2.SetLineStyle(2)
    frame3.SetTitle("")
    frame3.GetYaxis().SetTitle("pull")
    frame3.GetXaxis().SetTitle("#Deltam^{2}_{ll} [GeV]")
    frame3.GetXaxis().SetTitleSize(0.13)
    frame3.GetYaxis().SetTitleSize(0.12)
    frame3.GetXaxis().SetTitleOffset(1.0)
    frame3.GetYaxis().SetTitleOffset(0.58)
    frame3.GetXaxis().SetLabelSize(0.10)
    frame3.GetYaxis().SetLabelSize(0.10)
    frame3.GetXaxis().SetLabelOffset(0.02)
    frame3.GetYaxis().SetLabelOffset(0.01)
    frame3.GetYaxis().SetRangeUser(-5, 5)
    frame3.GetYaxis().CenterTitle(True)
    frame3.GetYaxis().SetNdivisions(505)
    frame3.Draw("")
    line1.Draw("SAME")
    line2.Draw("SAME")
    frame3.Draw("SAME")
    canvas.SaveAs("rooFit109_ratiolike.png")
    canvas.Close()
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
def smear(mu, sigma0, smearfactor, N=100000, lcut=None, ucut=None, nbins=80):
    print ">>> smearing for N(%s,%s) with a factor of %s" % (mu, sigma0,
                                                             smearfactor)

    # HISTS
    xmin, xmax = mu - sigma0 * 5, mu + sigma0 * 4
    sigma1 = sigma0 * (1 + smearfactor)
    histname0 = "unsmeared"
    histname1 = "smeared"
    histtitle0 = "unsmeared, #sigma_{0} = %s" % (sigma0)
    histtitle1 = "smeared, #sigma_{new} = %s" % (sigma1)
    hist0 = TH1F(histname0, histtitle0, nbins, xmin, xmax)
    hist1 = TH1F(histname1, histtitle1, nbins, xmin, xmax)

    # FIT FUNCTIONS
    xminf = xmin if lcut == None else lcut
    xmaxf = xmax if ucut == None else ucut
    gaus0 = TF1("gaus0", "gaus", xminf, xmaxf)
    gaus1 = TF1("gaus1", "gaus", xminf, xmaxf)
    gaus0.SetTitle("%s fit" % histname0)
    gaus1.SetTitle("%s fit" % histname1)
    gaus0.SetParameters(N, mu, sigma0)
    gaus1.SetParameters(N, mu, sigma1)
    #gaus0.SetParLimits(2,sigma0*0.9,sigma0*1.1)
    #gaus1.SetParLimits(2,sigma1*0.9,sigma1*1.1)
    hists = [(hist0, gaus0), (hist1, gaus1)]

    # SMEAR & FILL
    #sigma1 = smearfactor
    #sigma1 = (smearfactor**2)/2.
    #sigma1 = sqrt(2.*(smearfactor))
    #sigma1 = sqrt(-2.*log(smearfactor))
    #sigma1 = 1./(2*smearfactor**2)
    sigma2 = sqrt(sigma1**2 - sigma0**2)
    print ">>>   sigma0 = %.3f, sigma1 = %.3f, sigma2 = %.3f" % (
        sigma0, sigma1, sigma2)
    print ">>>   generating %s events..." % (N)
    for i in xrange(N):
        xval0 = gRandom.Gaus(mu, sigma0)
        if lcut != None and xval0 < lcut: continue
        if ucut != None and xval0 > ucut: continue
        #rand  = gRandom.Gaus(1,smearfactor)
        #xval1 = xval0 * rand
        #rand  = gRandom.Gaus(0,1+smearfactor)
        #xval1 = xval0 + rand
        rand = gRandom.Gaus(0, 1)
        xval1 = xval0 + sigma2 * rand
        hist0.Fill(xval0)
        if lcut != None and xval1 < lcut: continue
        if ucut != None and xval1 > ucut: continue
        hist1.Fill(xval1)

    # PLOT SETTINGS
    xtitle = "x variable"
    ytitle = "events"
    title = "Gauss(%s,%s)" % (mu, "#sigma")
    canvasname = "smear_%.1f-%.1f_by_%.2f" % (mu, sigma0, smearfactor)
    if lcut != None: canvasname += "_gt%.1f" % (lcut)
    if ucut != None: canvasname += "_lt%.1f" % (ucut)
    canvasname = canvasname.replace('.', 'p')
    ymin, ymax = 0, 1.14 * max(hist0.GetMaximum(), hist1.GetMaximum())
    rmin, rmax = 0.60, 1.40
    lmargin, rmargin = 0.14, 0.04

    # CANVAS
    print ">>> plotting..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 800)
    canvas.Divide(2)

    # MAIN plot
    canvas.cd(1)
    gPad.SetPad("pad1", "pad1", 0, 0.33, 1, 1, 0, -1, 0)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetFrameFillStyle(0)
    gPad.SetFrameBorderMode(0)
    gPad.SetTopMargin(0.06)
    gPad.SetBottomMargin(0.02)
    gPad.SetLeftMargin(lmargin)
    gPad.SetRightMargin(rmargin)
    gPad.SetGrid()
    gPad.cd()

    textsize = 0.050
    x1, width = 0.18, 0.25
    y1, height = 0.89, textsize * 1.08 * 5
    legend = TLegend(x1, y1, x1 + width, y1 - height)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetTextFont(62)
    legend.SetHeader(title)
    legend.SetTextFont(42)

    # FRAME
    frame = gPad.DrawFrame(xmin, ymin, xmax, ymax)
    frame.GetYaxis().SetTitleSize(0.070)
    frame.GetXaxis().SetTitleSize(0.070)
    frame.GetXaxis().SetLabelSize(0.000)
    frame.GetYaxis().SetLabelSize(0.060)
    frame.GetXaxis().SetTitleOffset(1.00)
    frame.GetYaxis().SetTitleOffset(1.06)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetXaxis().SetTitle(xtitle)
    frame.GetYaxis().SetTitle(ytitle)

    # DRAW & FIT
    print ">>>   fitting..."
    fits = []
    for i, (hist, gaus) in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.SetLineStyle(1)
        gaus.SetLineColor(color + 1)
        gaus.SetLineWidth(2)
        gaus.SetLineStyle(2)
        hist.Fit(gaus.GetName(), '0', '', xminf, xmaxf)
        hist.Draw('SAME')
        gaus.Draw('SAME')
        gtitle = "#sigma_{fit} = %.3f" % (gaus.GetParameter(2)
                                          )  #gaus.GetTitle()
        legend.AddEntry(hist, hist.GetTitle(), 'l')
        legend.AddEntry(gaus, gtitle, 'l')
    print ">>>   real unsmeared sigma:    %5.3f" % (sigma0)
    print ">>>   fitted unsmeared sigma:  %5.3f" % (gaus0.GetParameter(2))
    print ">>>   real smear factor:       %5.3f" % (smearfactor)
    print ">>>   fitted smeared sigma:    %5.3f" % (gaus1.GetParameter(2))

    legend.Draw()
    frame.Draw('SAMEAXIS')
    gPad.Modified()

    # RATIO plot
    canvas.cd(2)
    gPad.SetPad("pad2", "pad2", 0, 0, 1, 0.32, 0, -1, 0)
    gPad.SetTopMargin(0.04)
    gPad.SetBottomMargin(0.29)
    gPad.SetLeftMargin(lmargin)
    gPad.SetRightMargin(rmargin)

    # RATIO FRAME
    rframe = gPad.DrawFrame(xmin, rmin, xmax, rmax)
    rframe.GetYaxis().CenterTitle()
    rframe.GetXaxis().SetTitleSize(0.144)
    rframe.GetYaxis().SetTitleSize(0.140)
    rframe.GetXaxis().SetLabelSize(0.130)
    rframe.GetYaxis().SetLabelSize(0.120)
    rframe.GetXaxis().SetLabelOffset(0.012)
    rframe.GetXaxis().SetTitleOffset(0.85)
    rframe.GetYaxis().SetTitleOffset(0.53)
    rframe.GetXaxis().SetNdivisions(508)
    rframe.GetYaxis().CenterTitle(True)
    rframe.GetYaxis().SetTitle("ratio")
    rframe.GetXaxis().SetTitle(xtitle)
    rframe.GetYaxis().SetNdivisions(5)

    # RATIO
    ratios = []
    for i, (hist, gaus) in enumerate(hists):
        #if i==0: continue
        #ratio = hist.Clone(hist.GetName()+"_ratio")
        #ratio.Divide(hist0)
        ratio = divideHists(hist, hist0, name=hist.GetName() + "_ratio")
        ratio.Draw('HISTSAME')
        ratios.append(ratio)
        #ratiof = createTH1FromTF1(gaus,nbins,xmin,xmax)
        #ratiof.Divide(hist0)
        ratiof = divideTF1ByTH1(gaus, hist0, name=gaus.GetName() + "_ratio")
        ratiof.Draw('HISTSAME')
        ratios.append(ratiof)
        print ratiof
    #line = TLine(xmin,1.,xmax,1.)
    #line.SetLineColor(hist0.GetLineColor())
    #line.SetLineWidth(hist0.GetLineWidth())
    #line.SetLineStyle(1)
    #line.Draw('SAME')

    gPad.SetGrid()
    gPad.Modified()
    rframe.Draw('sameaxis')

    canvas.SaveAs(canvasname + ".png")
    canvas.SaveAs(canvasname + ".pdf")
    canvas.Close()
    print ">>> "