Ejemplo n.º 1
0
def rooFit208():

    print ">>> setup component pdfs..."
    t = RooRealVar("t", "t", -10, 30)
    ml = RooRealVar("ml", "mean landau", 5., -20, 20)
    sl = RooRealVar("sl", "sigma landau", 1, 0.1, 10)
    landau = RooLandau("lx", "lx", t, ml, sl)
    mg = RooRealVar("mg", "mg", 0)
    sg = RooRealVar("sg", "sg", 2, 0.1, 10)
    gauss = RooGaussian("gauss", "gauss", t, mg, sg)

    print ">>> construct convolution pdf..."
    # Set #bins to be used for FFT sampling to 10000
    t.setBins(10000, "cache")

    # Construct landau (x) gauss
    convolution = RooFFTConvPdf("lxg", "landau (X) gauss", t, landau, gauss)

    print ">>> sample, fit and plot convoluted pdf..."
    data = convolution.generate(RooArgSet(t), 10000)  # RooDataSet
    convolution.fitTo(data)

    print "\n>>> plot everything..."
    frame1 = t.frame(Title("landau #otimes gauss convolution"))  # RooPlot
    data.plotOn(frame1, Binning(50), Name("data"))
    convolution.plotOn(frame1, Name("lxg"))
    gauss.plotOn(frame1, LineStyle(kDashed), LineColor(kRed), Name("gauss"))
    landau.plotOn(frame1, LineStyle(kDashed), LineColor(kGreen),
                  Name("landau"))

    print "\n>>> draw pfds and fits on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.6, 0.8, 0.8, 0.6)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.5)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("lxg", "convolution", 'L')
    legend.AddEntry("landau", "landau", 'L')
    legend.AddEntry("gauss", "gauss", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit208.png")
Ejemplo n.º 2
0
def rooFit503():

    print ">>> open and workspace file, list its contents and get workspace object..."
    file = TFile("rooFit502_workspace.root")
    file.ls()
    workspace = file.Get("workspace")  # RooWorkspace

    print "\n>>> retrieve pdf, data from workspace..."
    x = workspace.var("x")  # RooRealVar
    model = workspace.pdf("model")  # RooAbsPdf
    data = workspace.data("modelData")

    print ">>> print model tree:..."
    model.Print("t")

    print "\n>>> fit model to data..."
    model.fitTo(data)
    frame1 = x.frame(Title("Model and data read from workspace"))  # RooPlot

    print ">>> plot everything..."
    data.plotOn(frame1, Name("data"), Binning(40))
    model.plotOn(frame1, Name("model"))
    model.plotOn(frame1, Components("bkg"), LineStyle(kDashed), Name("bkg"))
    model.plotOn(frame1, Components("bkg,sig2"), LineStyle(kDotted),
                 Name("bkgsig2"))

    print "\n>>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.2, 0.8, 0.4, 0.6)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.5)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "model", 'L')
    legend.AddEntry("bkg", "background only", 'L')
    legend.AddEntry("bkgsig2", "background + signal 2", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit503.png")
Ejemplo n.º 3
0
def rooFit203():

    print ">>> setup model..."
    x = RooRealVar("x", "x", -10, 10)
    mean = RooRealVar("mean", "mean of gaussian", 0, -10, 10)
    gauss = RooGaussian("gauss", "gaussian PDF", x, mean, RooConst(1))

    # Construct px = 1 (flat in x)
    px = RooPolynomial("px", "px", x)

    # Construct model = f*gx + (1-f)px
    f = RooRealVar("f", "f", 0., 1.)
    model = RooAddPdf("model", "model", RooArgList(gauss, px), RooArgList(f))
    data = model.generate(RooArgSet(x), 10000)  # RooDataSet

    print ">>> fit to full data range..."
    result_full = model.fitTo(data, Save(kTRUE))  # RooFitResult

    print "\n>>> fit \"signal\" range..."
    # Define "signal" range in x as [-3,3]
    x.setRange("signal", -3, 3)
    result_sig = model.fitTo(data, Save(kTRUE),
                             Range("signal"))  # RooFitResult

    print "\n>>> plot and print results..."
    # Make plot frame in x and add data and fitted model
    frame1 = x.frame(Title("Fitting a sub range"))  # RooPlot
    data.plotOn(frame1, Name("data"))
    model.plotOn(frame1, Range("Full"), LineColor(kBlue),
                 Name("model"))  # Add shape in full ranged dashed
    model.plotOn(frame1, LineStyle(kDashed), LineColor(kRed),
                 Name("model2"))  # By default only fitted range is shown

    print "\n>>> result of fit on all data:"
    result_full.Print()

    print "\n>>> result of fit in in signal region (note increased error on signal fraction):"
    result_sig.Print()

    print ">>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.2, 0.85, 0.4, 0.65)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "fit (full range)", 'L')
    legend.AddEntry("model2", "fit (signal range)", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit203.png")
Ejemplo n.º 4
0
def rooFit510():

    print ">>> create and fill workspace..."
    workspace = RooWorkspace("workspace")  # RooWorkspace
    fillWorkspace(workspace)

    print ">>>\n>>> retrieve model from workspace..."
    # Exploit convention encoded in named set "parameters" and "observables"
    # to use workspace contents w/o need for introspected
    model = workspace.pdf("model")  # RooAbsPdf

    print ">>> generate and fit data in given observables"
    data = model.generate(workspace.set("observables"), 1000)  # RooDataSet
    model.fitTo(data)

    print ">>> plot model and data of first observables..."
    frame1 = workspace.set("observables").first().frame()  # RooPlot
    data.plotOn(frame1, Name("data"), Binning(50))
    model.plotOn(frame1, Name("model"))

    print ">>> overlay plots with reference parameters as stored in snapshots..."
    workspace.loadSnapshot("reference_fit")
    model.plotOn(frame1, LineColor(kRed), Name("model_ref"))
    workspace.loadSnapshot("reference_fit_bkgonly")
    model.plotOn(frame1, LineColor(kRed), LineStyle(kDashed), Name("bkg_ref"))

    print "\n>>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.2, 0.8, 0.4, 0.6)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.5)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "model", 'L')
    legend.AddEntry("model_ref", "model fit", 'L')
    legend.AddEntry("bkg_ref", "background only fit", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit510.png")

    # Print workspace contents
    workspace.Print()

    # Workspace will remain in memory after macro finishes
    gDirectory.Add(workspace)
Ejemplo n.º 5
0
def rooFit107():
    
    print ">>> setup model..."
    x      = RooRealVar("x","x",-3,3)
    mean   = RooRealVar("mean","mean of gaussian",1,-10,10)
    sigma  = RooRealVar("sigma","width of gaussian",1,0.1,10)
    gauss  = RooGaussian("gauss","gauss",x,mean,sigma)
    data   = gauss.generate(RooArgSet(x),1000) # RooDataSet
    gauss.fitTo(data)
    
    print ">>> plot pdf and data..."
    frame1 = x.frame(Name("frame1"),Title("Red Curve / SumW2 Histo errors"),Bins(20)) # RooPlot
    frame2 = x.frame(Name("frame2"),Title("Dashed Curve / No XError bars"),Bins(20)) # RooPlot
    frame3 = x.frame(Name("frame3"),Title("Filled Curve / Blue Histo"),Bins(20)) # RooPlot
    frame4 = x.frame(Name("frame4"),Title("Partial Range / Filled Bar chart"),Bins(20)) # RooPlot
    
    print ">>> data plotting styles..."
    data.plotOn(frame1,DataError(RooAbsData.SumW2))
    data.plotOn(frame2,XErrorSize(0))                           # Remove horizontal error bars
    data.plotOn(frame3,MarkerColor(kBlue),LineColor(kBlue))     # Blue markers and error bors
    data.plotOn(frame4,DrawOption("B"),DataError(RooAbsData.None),
                       XErrorSize(0),FillColor(kGray))          # Filled bar chart
    
    print ">>> data plotting styles..."
    gauss.plotOn(frame1,LineColor(kRed))    
    gauss.plotOn(frame2,LineStyle(kDashed))                              # Change line style to dashed
    gauss.plotOn(frame3,DrawOption("F"),FillColor(kOrange),MoveToBack()) # Filled shapes in green color
    gauss.plotOn(frame4,Range(-8,3),LineColor(kMagenta))
    
    print ">>> draw pfds and fits on canvas..."
    canvas = TCanvas("canvas","canvas",100,100,1000,1200)
    canvas.Divide(2,2)
    for i, frame in enumerate([frame1,frame2,frame3,frame4],1):
        canvas.cd(i)
        gPad.SetLeftMargin(0.15); gPad.SetRightMargin(0.05)
        frame.GetYaxis().SetTitleOffset(1.6)
        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("rooFit107.png")
Ejemplo n.º 6
0
def rooFit204():
    
    print ">>> setup model signal components: gaussians..."
    x      = RooRealVar("x","x",0,10)
    mean   = RooRealVar("mean","mean of gaussian",5)
    sigma1 = RooRealVar("sigma1","width of gaussians",0.5)
    sigma2 = RooRealVar("sigma2","width of gaussians",1)
    sig1   = RooGaussian("sig1","Signal component 1",x,mean,sigma1)
    sig2   = RooGaussian("sig2","Signal component 2",x,mean,sigma2)
    sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.)
    sig      = RooAddPdf("sig","Signal",RooArgList(sig1,sig2),RooArgList(sig1frac))
    
    print ">>> setup model background components: Chebychev polynomial..."
    a0  = RooRealVar("a0","a0",0.5,0.,1.)
    a1  = RooRealVar("a1","a1",-0.2,0.,1.)
    bkg = RooChebychev("bkg","Background",x,RooArgList(a0,a1))
    
    print ">>> construct extended components with specified range..."
    # Define signal range in which events counts are to be defined
    x.setRange("signalRange",5,6)
    
    # Associated nsig/nbkg as expected number of events with sig/bkg _in_the_range_ "signalRange"
    nsig = RooRealVar("nsig","number of signal events in signalRange",    500,0.,10000) 
    nbkg = RooRealVar("nbkg","number of background events in signalRange",500,0,10000) 
    esig = RooExtendPdf("esig","extended signal pdf",    sig,nsig,"signalRange") 
    ebkg = RooExtendPdf("ebkg","extended background pdf",bkg,nbkg,"signalRange") 
    
    print ">>> sum extended components..."
    # Construct sum of two extended p.d.f. (no coefficients required)
    model = RooAddPdf("model","(g1+g2)+a",RooArgList(ebkg,esig))
    
    print ">>> sample data, fit model..."
    data = model.generate(RooArgSet(x),1000) # RooDataSet 
    result = model.fitTo(data,Extended(kTRUE),Save()) # RooFitResult
    
    print "\n>>> fit result:"
    result.Print()
    
    
    
    print "\n>>> plot everything..."
    frame1 = x.frame(Title("Fitting a sub range")) # RooPlot
    data.plotOn(frame1,Binning(50),Name("data"))
    model.plotOn(frame1,LineColor(kBlue),Name("model"))
    argset1 = RooArgSet(bkg)
    model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kBlue),Name("bkg"),Normalization(1.0,RooAbsReal.RelativeExpected))
    #model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kRed),Name("bkg2"))
    
    print ">>> draw on canvas..."
    canvas = TCanvas("canvas","canvas",100,100,800,600)
    legend = TLegend(0.2,0.85,0.4,0.7)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14); gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data",   "data",           'LEP')
    legend.AddEntry("model",  "fit",            'L')
    legend.AddEntry("bkg",    "background only",'L')
    #legend.AddEntry("bkg2",   "background only (no extended norm)",'L')
    legend.Draw()
    canvas.SaveAs("rooFit204.png")
def rooFit202():

    print ">>> setup model component: gaussian signals and Chebychev polynomial background..."
    x = RooRealVar("x", "x", 0, 10)
    mean = RooRealVar("mean", "mean of gaussian", 5)
    sigma1 = RooRealVar("sigma1", "width of gaussian", 0.5)
    sigma2 = RooRealVar("sigma2", "width of gaussian", 1.0)
    sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1)
    sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2)

    a0 = RooRealVar("a0", "a0", 0.5, 0., 1.)
    a1 = RooRealVar("a1", "a1", -0.2, 0., 1.)
    bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1))

    # Sum the signal components into a composite signal p.d.f.
    sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8,
                          0., 1.)
    sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2),
                    RooArgList(sig1frac))

    print ">>>\n>>> METHOD 1"
    print ">>> construct extended composite model..."
    # Sum the composite signal and background into an extended pdf nsig*sig+nbkg*bkg
    nsig = RooRealVar("nsig", "number of signal events", 500, 0., 10000)
    nbkg = RooRealVar("nbkg", "number of background events", 500, 0, 10000)
    model = RooAddPdf("model", "(g1+g2)+a", RooArgList(bkg, sig),
                      RooArgList(nbkg, nsig))

    print ">>> sample, fit and plot extended model...\n"
    # Generate a data sample of expected number events in x from model
    #   nsig + nbkg = model.expectedEvents()
    # NOTE: since the model predicts a specific number events, one can
    #       omit the requested number of events to be generated
    # Introduce Poisson fluctuation with Extended(kTRUE)
    data = model.generate(RooArgSet(x), Extended(kTRUE))  # RooDataSet

    # Fit model to data, extended ML term automatically included
    # NOTE: Composite extended pdfs can only be successfully fit if the extended likelihood
    #       term -log(Poisson(Nobs,Nexp)) is included in the minimization because they have
    #       one extra degree of freedom in their parameterization that is constrained by
    #       this extended term. If a pdf is capable of calculating an extended term (i.e.
    #       any extended RooAddPdf), the extended term is AUTOMATICALLY included in the
    #       likelihood calculation. Override this behaviour with Extended():
    #           Extended(kTRUE)  ADD extended likelihood term
    #           Extended(kFALSE) DO NOT ADD extended likelihood
    #model.fitTo(data,Extended(kTRUE))
    model.fitTo(data)

    print "\n>>> plot data, model and model components..."
    # Plot data and PDF overlaid, use expected number of events for pdf projection
    # normalization, rather than observed number of events, data.numEntries()
    frame1 = x.frame(Title("extended ML fit example"))  # RooPlot
    data.plotOn(frame1, Binning(30), Name("data"))
    model.plotOn(frame1, Normalization(1.0, RooAbsReal.RelativeExpected),
                 Name("model"))

    # Overlay the background components of model
    # NOTE: By default, the pdf is normalized to event count of the last dataset added
    #       to the plot frame. Use "RelativeExpected" to normalize to the expected
    #       event count of the pdf instead
    argset1 = RooArgSet(bkg)
    argset2 = RooArgSet(sig1)
    argset3 = RooArgSet(sig2)
    argset4 = RooArgSet(bkg, sig2)
    model.plotOn(frame1, Components(argset1), LineStyle(kDashed),
                 LineColor(kBlue),
                 Normalization(1.0, RooAbsReal.RelativeExpected), Name("bkg"))
    #model.plotOn(frame1,Components(argset1),LineStyle(kDashed),LineColor(kBlue),  Name("bkg2"))
    model.plotOn(frame1, Components(argset2), LineStyle(kDotted),
                 LineColor(kMagenta),
                 Normalization(1.0, RooAbsReal.RelativeExpected), Name("sig1"))
    model.plotOn(frame1, Components(argset3), LineStyle(kDotted),
                 LineColor(kPink),
                 Normalization(1.0, RooAbsReal.RelativeExpected), Name("sig2"))
    model.plotOn(frame1, Components(argset4), LineStyle(kDashed),
                 LineColor(kAzure - 4),
                 Normalization(1.0, RooAbsReal.RelativeExpected),
                 Name("bkgsig2"))

    print "\n>>> structure of composite pdf:"
    model.Print("t")  # "tree" mode

    print "\n>>> parameters:"
    params = model.getVariables()  # RooArgSet
    params.Print("v")
    params.Print()

    print "\n>>> params.find(\"...\").getVal():"
    print ">>>   sigma1   = %.2f" % params.find("sigma1").getVal()
    print ">>>   sigma2   = %.2f" % params.find("sigma2").getVal()
    print ">>>   nsig     = %6.2f,  sig1frac = %5.2f" % (
        params.find("nsig").getVal(), params.find("sig1frac").getVal())
    print ">>>   nbkg     = %6.2f" % params.find("nbkg").getVal()

    print ">>>\n>>> components:"
    comps = model.getComponents()  # RooArgSet
    sig = comps.find("sig")  # RooAbsArg
    sigVars = sig.getVariables()  # RooArgSet
    sigVars.Print()

    print ">>>\n>>> METHOD 2"
    print ">>> construct extended components first..."
    # Associated nsig/nbkg as expected number of events with sig/bkg
    nsig = RooRealVar("nsig", "number of signal events", 500, 0., 10000)
    nbkg = RooRealVar("nbkg", "number of background events", 500, 0, 10000)
    esig = RooExtendPdf("esig", "extended signal pdf", sig, nsig)
    ebkg = RooExtendPdf("ebkg", "extended background pdf", bkg, nbkg)

    print ">>> sum extended components without coefficients..."
    # Construct sum of two extended p.d.f. (no coefficients required)
    model2 = RooAddPdf("model2", "(g1+g2)+a", RooArgList(ebkg, esig))

    # METHOD 2 is functionally completely equivalent to METHOD 1.
    # Its advantage is that the yield parameter is associated to the shape pdf
    # directly, while in METHOD 1 the association is made after constructing
    # a RooAddPdf. Also, class RooExtendPdf offers extra functionality to
    # interpret event counts in a different range.

    print ">>> plot model..."
    model2.plotOn(frame1, LineStyle(kDashed), LineColor(kRed),
                  Normalization(1.0, RooAbsReal.RelativeExpected),
                  Name("model2"))

    print ">>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.2, 0.85, 0.4, 0.65)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "composite model", 'L')
    legend.AddEntry("model2", "composite model (method 2)", 'L')
    legend.AddEntry("bkg", "background only", 'L')
    #legend.AddEntry("bkg2",   "background only (no extended norm)", 'L')
    legend.AddEntry("sig1", "signal 1", 'L')
    legend.AddEntry("sig2", "signal 2", 'L')
    legend.AddEntry("bkgsig2", "background + signal 2", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit202.png")
Ejemplo n.º 8
0
mean.setConstant(False)
gamma.setConstant(False)
sigma_1.setConstant(False)
sigma_2.setConstant(False)
rPhifit = tot.fitTo(splotData,Range(phimin,phimax),RooFit.NumCPU(args.ncpu),RooFit.Verbose(False))
nfits = nfits + 1

c = TCanvas("canvas","canvas",1200,900)
phiFrame = masskk.frame(Range(phimin,phimax),Normalization((nSig.getValV() + nBkg.getValV())), Title("#phi Mass"))
splotData.plotOn(phiFrame)
ratio = 1.0/float(nfits)

tot.plotOn(phiFrame,Normalization(ratio))
bFrac = (nBkg.getValV())/(nSig.getValV() + nBkg.getValV())
bkg.plotOn(phiFrame,LineColor(kRed),Normalization(bFrac),LineStyle(kDashed))
signal.plotOn(phiFrame,LineColor(kGreen),Normalization(1.0-bFrac))

a0.setConstant(True)
a1.setConstant(True)
a2.setConstant(True)
a3.setConstant(True)
a4.setConstant(True)
nBkg.setConstant(True)

tot.paramOn(phiFrame,RooFit.Layout(0.57,0.99,0.65))

phiFrame.Draw()

sidesigma = np.sqrt((rFrac.getValV())*sigma_1.getValV()**2 + (1.0 - (rFrac.getValV()))*sigma_2.getValV()**2)
Ejemplo n.º 9
0
#Plotting fits
canvs = []
fitPads = []
pullPads = []
pulls = []
for i in range(n_regions) :
    region = regions[i]
    canvs.append(TCanvas(region+"_canv", region+" D0 Mass Region Fit"))    

    frame = deltam.frame()
    datahist.plotOn(frame, Cut("regionIndex==regionIndex::"+region))
    regionIndexSet = RooArgSet(regionIndex)
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist))
    pulls.append(frame.pullHist())
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist), Components("bg_pdf"), LineColor(kGreen+2), LineStyle(2))
    total_pdf.plotOn(frame, Slice(regionIndex, region), ProjWData(regionIndexSet, datahist), Components("signal_pdf_"+region), LineColor(kRed+2), LineStyle(3))
    
    #Creating pad to plot fit to data
    fitPads.append(TPad("fitPad_{}".format(i), "fitPad_{}".format(i), 0., 0.3, 1., 1.)) 
    fitPads[i].SetMargin(0.08, 0.05, 0.05, 0.1)
    fitPads[i].Draw()
    fitPads[i].cd()
    frame.Draw()

    #Creating pad to plot pull ( (actual - fit) / uncertainty )
    canvs[i].cd() 
    pullPads.append(TPad("pullPad_{}".format(i), "pullPad_{}".format(i), 0., 0., 1., 0.3))
    pullPads[i].SetMargin(0.08, 0.05, 0.1, 0.05)
    pullPads[i].Draw()
Ejemplo n.º 10
0
masslist = RooArgList(mass)
dh = RooDataHist("dh", "dh", masslist, hist)
numEvts = dh.sum(False)
print numEvts

# In[10]:

tot.fitTo(dh)

# In[11]:

massFrame = mass.frame()
massFrame.SetTitle("Phi signal")
dh.plotOn(massFrame)
tot.plotOn(massFrame)
gauss.plotOn(massFrame, LineColor(kGreen), LineStyle(kDashed),
             Normalization((sFrac.getValV() * numEvts) / (numEvts)))
cheb.plotOn(massFrame, LineColor(kMagenta), LineStyle(kDotted),
            Normalization(((1.0 - sFrac.getValV()) * numEvts) / (numEvts)))
tot.paramOn(massFrame, Layout(0.60, 0.99, 0.75))
massFrame.Draw()

# In[12]:

plotmax = hist.GetMaximum() * 1.05
sidesigma = sigma.getValV()
leftlowside = -7. * sidesigma + mean.getValV()
leftupside = -5. * sidesigma + mean.getValV()
rightlowside = +5. * sidesigma + mean.getValV()
rightupside = +7. * sidesigma + mean.getValV()
Ejemplo n.º 11
0
def rooFit205():

    print ">>> setup model signal components: gaussians..."
    x = RooRealVar("x", "x", 0, 10)
    mean = RooRealVar("mean", "mean of gaussians", 5)
    sigma1 = RooRealVar("sigma1", "width of gaussians", 0.5)
    sigma2 = RooRealVar("sigma2", "width of gaussians", 1)
    sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1)
    sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2)
    sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8,
                          0., 1.)
    sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2),
                    RooArgList(sig1frac))

    print ">>> setup model background components: Chebychev polynomial plus exponential..."
    a0 = RooRealVar("a0", "a0", 0.5, 0., 1.)
    a1 = RooRealVar("a1", "a1", -0.2, 0., 1.)
    bkg1 = RooChebychev("bkg1", "Background 1", x, RooArgList(a0, a1))
    alpha = RooRealVar("alpha", "alpha", -1)
    bkg2 = RooExponential("bkg2", "Background 2", x, alpha)
    bkg1frac = RooRealVar("bkg1frac", "fraction of component 1 in background",
                          0.2, 0., 1.)
    bkg = RooAddPdf("bkg", "Signal", RooArgList(bkg1, bkg2),
                    RooArgList(bkg1frac))

    print ">>> sum signal and background component..."
    bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.)
    model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig),
                      RooArgList(bkgfrac))

    print ">>> setup basic plot with data and full pdf..."
    data = model.generate(RooArgSet(x), 1000)  # RooDataSet
    frame1 = x.frame(
        Title("Component plotting of pdf=(sig1+sig2)+(bkg1+bkg2)"))  # RooPlot
    data.plotOn(frame1, Name("data"))
    model.plotOn(frame1, Name("model"))

    print ">>> clone frame for reuse..."
    frame2 = frame1.Clone("frame2")  # RooPlot
    frame2.SetTitle("Get components with regular expressions")

    print ">>> make omponent by object reference..."
    # Plot multiple background components specified by object reference
    # Note that specified components may occur at any level in object tree
    # (e.g bkg is component of 'model' and 'sig2' is component 'sig')
    argset1 = RooArgSet(bkg)
    argset2 = RooArgSet(bkg2)
    argset3 = RooArgSet(bkg, sig2)
    model.plotOn(frame1, Components(argset1), LineColor(kRed), Name("bkgs1"))
    model.plotOn(frame1, Components(argset2), LineStyle(kDashed),
                 LineColor(kRed), Name("bkg2"))
    model.plotOn(frame1, Components(argset3), LineStyle(kDotted),
                 Name("bkgssig21"))

    print "\n>>> make component by name / regular expressions..."
    model.plotOn(frame2, Components("bkg"), LineColor(kAzure - 4),
                 Name("bkgs2"))  # by name
    model.plotOn(frame2, Components("bkg1,sig2"), LineColor(kAzure - 4),
                 LineStyle(kDotted), Name("bkg1sig22"))  # by name
    model.plotOn(frame2, Components("sig*"), LineColor(kAzure - 4),
                 LineStyle(kDashed), Name("sigs2"))  # with regexp (wildcard *)
    model.plotOn(frame2, Components("bkg1,sig*"), LineColor(kYellow),
                 LineStyle(kDashed),
                 Name("bkg1sigs2"))  # with regexp (,) #Invisible()

    print "\n>>> draw pfds and fits on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1400, 600)
    legend1 = TLegend(0.22, 0.85, 0.4, 0.65)
    legend2 = TLegend(0.22, 0.85, 0.4, 0.65)
    for legend in [legend1, legend2]:
        legend.SetTextSize(0.032)
        legend.SetBorderSize(0)
        legend.SetFillStyle(0)
    canvas.Divide(2)
    canvas.cd(1)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.6)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend1.AddEntry("data", "data", 'LEP')
    legend1.AddEntry("model", "model", 'L')
    legend1.AddEntry("bkgs1", "bkg", 'L')
    legend1.AddEntry("bkg2", "bkg2", 'L')
    legend1.AddEntry("bkgssig21", "bkg,sig2", 'L')
    legend1.Draw()
    canvas.cd(2)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame2.GetYaxis().SetLabelOffset(0.008)
    frame2.GetYaxis().SetTitleOffset(1.6)
    frame2.GetYaxis().SetTitleSize(0.045)
    frame2.GetXaxis().SetTitleSize(0.045)
    frame2.Draw()
    legend2.AddEntry("data", "data", 'LEP')
    legend2.AddEntry("model", "model", 'L')
    legend2.AddEntry("bkgs2", "\"bkg\"", 'L')
    legend2.AddEntry("bkg1sig22", "\"bkg1,sig2\"", 'L')
    legend2.AddEntry("sigs2", "\"sig*\"", 'L')
    legend2.AddEntry("bkg1sigs2", "\"bkg1,sig*\"", 'L')
    legend2.Draw()
    canvas.SaveAs("rooFit205.png")
def rooFit501():

    print ">>> setup model for physics sample..."
    x = RooRealVar("x", "x", -8, 8)
    mean = RooRealVar("mean", "mean", 0, -8, 8)
    sigma = RooRealVar("sigma", "sigma", 0.3, 0.1, 10)
    gauss = RooGaussian("gx", "gx", x, mean, sigma)
    a0 = RooRealVar("a0", "a0", -0.1, -1, 1)
    a1 = RooRealVar("a1", "a1", 0.004, -1, 1)
    px = RooChebychev("px", "px", x, RooArgList(a0, a1))
    f = RooRealVar("f", "f", 0.2, 0., 1.)
    model = RooAddPdf("model", "model", RooArgList(gauss, px), RooArgList(f))

    print ">>> setup model for control sample..."
    # NOTE: sigma is shared with the signal sample model
    mean_ctrl = RooRealVar("mean_ctrl", "mean_ctrl", -3, -8, 8)
    gauss_ctrl = RooGaussian("gauss_ctrl", "gauss_ctrl", x, mean_ctrl, sigma)
    a0_ctrl = RooRealVar("a0_ctrl", "a0_ctrl", -0.1, -1, 1)
    a1_ctrl = RooRealVar("a1_ctrl", "a1_ctrl", 0.5, -0.1, 1)
    px_ctrl = RooChebychev("px_ctrl", "px_ctrl", x,
                           RooArgList(a0_ctrl, a1_ctrl))
    f_ctrl = RooRealVar("f_ctrl", "f_ctrl", 0.5, 0., 1.)
    model_ctrl = RooAddPdf("model_ctrl", "model_ctrl",
                           RooArgList(gauss_ctrl, px_ctrl), RooArgList(f_ctrl))

    print ">>> generate events for both samples..."
    data = model.generate(RooArgSet(x), 100)  # RooDataSet
    data_ctrl = model_ctrl.generate(RooArgSet(x), 2000)  # RooDataSet

    print ">>> create index category and join samples..."
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    print ">>> construct combined dataset in (x,sample)..."
    combData = RooDataSet("combData", "combined data", RooArgSet(x),
                          Index(sample), Import("physics", data),
                          Import("control", data_ctrl))

    print ">>> construct a simultaneous pdf in (x,sample)..."
    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctrl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctrl, "control")

    print ">>> perform a simultaneous fit..."
    # Perform simultaneous fit of model to data and model_ctrl to data_ctrl
    simPdf.fitTo(combData)

    print "\n>>> plot model slices on data slices..."
    frame1 = x.frame(Bins(30), Title("Physics sample"))  # RooPlot
    combData.plotOn(frame1, Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, Slice(sample, "physics"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame1, Slice(sample, "physics"), Components("px"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> plot control sample slices..."
    frame2 = x.frame(Bins(30), Title("Control sample"))  # RooPlot
    combData.plotOn(frame2, Cut("sample==sample::control"))
    simPdf.plotOn(frame2, Slice(sample, "control"),
                  ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(frame2, Slice(sample, "control"), Components("px_ctrl"),
                  ProjWData(RooArgSet(sample), combData), LineStyle(kDashed))

    print "\n>>> draw on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1400, 600)
    canvas.Divide(2)
    canvas.cd(1)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.6)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    canvas.cd(2)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame2.GetYaxis().SetLabelOffset(0.008)
    frame2.GetYaxis().SetTitleOffset(1.6)
    frame2.GetYaxis().SetTitleSize(0.045)
    frame2.GetXaxis().SetTitleSize(0.045)
    frame2.Draw()
    canvas.SaveAs("rooFit501.png")
Ejemplo n.º 13
0
def rooFit201():
    
    print ">>> setup model component: gaussian signals and Chebychev polynomial background..."
    x      = RooRealVar("x","x",0,11)
    mean   = RooRealVar("mean","mean of gaussians",5)
    sigma1 = RooRealVar("sigma1","width of gaussians",0.5)
    sigma2 = RooRealVar("sigma2","width of gaussians",1)
    sig1   = RooGaussian("sig1","Signal component 1",x,mean,sigma1)
    sig2   = RooGaussian("sig2","Signal component 2",x,mean,sigma2)
    
    a0  = RooRealVar("a0","a0",0.5,0.,1.)
    a1  = RooRealVar("a1","a1",-0.2,0.,1.)
    bkg = RooChebychev("bkg","Background",x,RooArgList(a0,a1))
    
    
    
    print ">>>\n>>> METHOD 1 - Two RooAddPdfs"
    print ">>> add signal components..."
    # Sum the signal components into a composite signal p.d.f.
    sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.)
    sig      = RooAddPdf("sig","Signal",RooArgList(sig1,sig2),RooArgList(sig1frac))
    
    print ">>> add signal and background..."
    # Sum the composite signal and background
    bkgfrac = RooRealVar("bkgfrac","fraction of background",0.5,0.,1.)
    model   = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig),RooArgList(bkgfrac))
    
    print ">>> sample, fit and plot model..."
    data = model.generate(RooArgSet(x),1000) # RooDataSet
    model.fitTo(data)
    frame1 = x.frame(Title("Example of composite pdf=(sig1+sig2)+bkg")) # RooPlot
    data.plotOn(frame1,Binning(50),Name("data"))
    model.plotOn(frame1,Name("model"))
    
    # Overlay the background component of model with a dashed line
    argset1 = RooArgSet(bkg)
    model.plotOn(frame1,Components(argset1),LineWidth(2),Name("bkg")) #,LineStyle(kDashed)
    
    # Overlay the background+sig2 components of model with a dotted line
    argset2 = RooArgSet(bkg,sig2)
    model.plotOn(frame1,Components(argset2),LineWidth(2),LineStyle(kDashed),LineColor(kAzure-4),Name("bkgsig2")) #,LineStyle(kDotted)
    
    print "\n>>> structure of composite pdf:"
    model.Print("t") # "tree" mode
    
    print "\n>>> parameters:"
    params = model.getVariables() # RooArgSet
    params.Print("v")
    params.Print()
    
    print "\n>>> params.find(\"...\").getVal():"
    print ">>>   sigma1  = %.2f"   % params.find("sigma1").getVal()
    print ">>>   sigma2  = %.2f"   % params.find("sigma2").getVal()
    print ">>>   bkgfrac = %5.2f"  % params.find("bkgfrac").getVal()
    print ">>>   sig1frac = %5.2f" % params.find("sig1frac").getVal()
    
    print ">>>\n>>> components:"
    comps   = model.getComponents() # RooArgSet
    sig     = comps.find("sig")     # RooAbsArg
    sigVars = sig.getVariables()    # RooArgSet
    sigVars.Print()
    
    
    
    print ">>>\n>>> METHOD 2 - One RooAddPdf with recursive fractions"
    # Construct sum of models on one go using recursive fraction interpretations
    #   model2 = bkg + (sig1 + sig2)
    model2 = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig1,sig2),RooArgList(bkgfrac,sig1frac),kTRUE)
    
    # NB: Each coefficient is interpreted as the fraction of the
    # left-hand component of the i-th recursive sum, i.e.
    #   sum4 = A + ( B + ( C + D ) )
    # with fraction fA, fB and fC expands to
    #   sum4 = fA*A + (1-fA)*(fB*B + (1-fB)*(fC*C + (1-fC)*D))
    
    print ">>> plot recursive addition model..."
    argset3 = RooArgSet(bkg,sig2)
    model2.plotOn(frame1,LineColor(kRed),LineStyle(kDashDotted),LineWidth(3),Name("model2"))
    model2.plotOn(frame1,Components(argset3),LineColor(kMagenta),LineStyle(kDashDotted),LineWidth(3),Name("bkgsig22"))
    model2.Print("t")
    
    
    
    print ">>> draw pdfs and fits on canvas..."
    canvas = TCanvas("canvas","canvas",100,100,800,600)
    legend = TLegend(0.57,0.87,0.95,0.65)
    legend.SetTextSize(0.030)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.14); gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data",    "data",                            'LEP')
    legend.AddEntry("model",   "composite model",                 'L')
    legend.AddEntry("model2",  "composite model (method 2)",      'L')
    legend.AddEntry("bkg",     "background only",                 'L')
    legend.AddEntry("bkgsig2", "background + signal 2",           'L')
    legend.AddEntry("bkgsig22","background + signal 2 (method 2)",'L')
    legend.Draw()
    canvas.SaveAs("rooFit201.png")
Ejemplo n.º 14
0
def rooFit206():

    print ">>> setup model signal components: gaussians..."
    x = RooRealVar("x", "x", 0, 10)
    mean = RooRealVar("mean", "mean of gaussians", 5)
    sigma1 = RooRealVar("sigma1", "width of gaussians", 0.5)
    sigma2 = RooRealVar("sigma2", "width of gaussians", 1)
    sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1)
    sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2)
    sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8,
                          0., 1.)
    sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2),
                    RooArgList(sig1frac))

    print ">>> setup model background components: Chebychev polynomial plus exponential..."
    a0 = RooRealVar("a0", "a0", 0.5, 0., 1.)
    a1 = RooRealVar("a1", "a1", -0.2, 0., 1.)
    bkg1 = RooChebychev("bkg1", "Background 1", x, RooArgList(a0, a1))
    alpha = RooRealVar("alpha", "alpha", -1)
    bkg2 = RooExponential("bkg2", "Background 2", x, alpha)
    bkg1frac = RooRealVar("bkg1frac", "fraction of component 1 in background",
                          0.2, 0., 1.)
    bkg = RooAddPdf("bkg", "Signal", RooArgList(bkg1, bkg2),
                    RooArgList(bkg1frac))

    print ">>> sum signal and background component..."
    bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.)
    model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig),
                      RooArgList(bkgfrac))

    print ">>> composite tree in ASCII:"
    model.Print("t")

    print "\n>>> write to txt file"
    model.printCompactTree("", "rooFit206_asciitree.txt")

    print ">>> draw composite tree graphically..."
    # Print GraphViz DOT file with representation of tree
    model.graphVizTree("rooFit206_model.dot")

    # Make graphic output file with one of the GraphViz tools
    # (freely available from www.graphviz.org)
    #
    # 'Top-to-bottom graph'
    # unix> dot -Tgif -o rooFit206_model_dot.gif rooFit206_model.dot
    #
    # 'Spring-model graph'
    # unix> fdp -Tgif -o rooFit206_model_fdp.gif rooFit206_model.dot

    print ">>> plot everything..."
    data = model.generate(RooArgSet(x), 1000)  # RooDataSet
    frame1 = x.frame(
        Title("Component plotting of pdf=(sig1+sig2)+(bkg1+bkg2)"))  # RooPlot
    data.plotOn(frame1, Name("data"), Binning(40))
    model.plotOn(frame1, Name("model"))
    argset1 = RooArgSet(bkg)
    argset2 = RooArgSet(bkg2)
    argset3 = RooArgSet(bkg, sig2)
    model.plotOn(frame1, Components(argset1), LineColor(kRed), Name("bkg"))
    model.plotOn(frame1, Components(argset2), LineStyle(kDashed),
                 LineColor(kRed), Name("bkg2"))
    model.plotOn(frame1, Components(argset3), LineStyle(kDotted),
                 Name("bkgsig2"))

    print "\n>>> draw pfds and fits on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    legend = TLegend(0.22, 0.85, 0.4, 0.65)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    gPad.SetLeftMargin(0.15)
    gPad.SetRightMargin(0.02)
    frame1.GetYaxis().SetLabelOffset(0.008)
    frame1.GetYaxis().SetTitleOffset(1.6)
    frame1.GetYaxis().SetTitleSize(0.045)
    frame1.GetXaxis().SetTitleSize(0.045)
    frame1.Draw()
    legend.AddEntry("data", "data", 'LEP')
    legend.AddEntry("model", "model", 'L')
    legend.AddEntry("bkg", "bkg", 'L')
    legend.AddEntry("bkg2", "bkg2", 'L')
    legend.AddEntry("bkgsig2", "bkg,sig2", 'L')
    legend.Draw()
    canvas.SaveAs("rooFit206.png")