Example #1
0
def rooFit103():

    print ">>> construct generic pdf from interpreted expression..."
    # To construct a proper p.d.f, the formula expression is explicitly normalized internally
    # by dividing  it by a numeric integral of the expresssion over x in the range [-20,20]
    x = RooRealVar("x", "x", -20, 20)
    alpha = RooRealVar("alpha", "alpha", 5, 0.1, 10)
    genpdf = RooGenericPdf("genpdf", "genpdf",
                           "(1+0.1*abs(x)+sin(sqrt(abs(x*alpha+0.1))))",
                           RooArgList(x, alpha))

    print ">>> generate and fit toy data...\n"
    data = genpdf.generate(RooArgSet(x), 10000)  # RooDataSet
    genpdf.fitTo(data)
    frame1 = x.frame(Title("Interpreted expression pdf"))  # RooPlot
    data.plotOn(frame1, Binning(40))
    genpdf.plotOn(frame1)

    print "\n>>> construct standard pdf with formula replacing parameter..."
    mean2 = RooRealVar("mean2", "mean^2", 10, 0, 200)
    sigma = RooRealVar("sigma", "sigma", 3, 0.1, 10)
    mean = RooFormulaVar("mean", "mean", "sqrt(mean2)", RooArgList(mean2))
    gaus2 = RooGaussian("gaus2", "gaus2", x, mean, sigma)

    print ">>> generate and fit toy data...\n"
    gaus1 = RooGaussian("gaus1", "gaus1", x, RooConst(10), RooConst(3))
    data2 = gaus1.generate(RooArgSet(x), 1000)  # RooDataSet
    result = gaus2.fitTo(data2, Save())  # RooFitResult
    result.Print()
    frame2 = x.frame(Title("Tailored Gaussian pdf"))  # RooPlot
    data2.plotOn(frame2, Binning(40))
    gaus2.plotOn(frame2)

    print "\n>>> draw pfds and fits 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("rooFit103.png")
Example #2
0
def rooFit105():

    print ">>> bind TMath::Erf C function..."
    x = RooRealVar("x", "x", -3, 3)
    #print ">>> type(%s) = %s" % ("TMath.Erf",type(TMath.Erf))

    fa1 = TF1("fa2", "TMath::Erf(x)", 0, 10)
    erf = bindFunction(fa1, x)  # RooAbsReal
    #erf = bindFunction("erf",TMath.Erf,RooArgList(x)) # RooAbsReal
    erf.Print()
    frame1 = x.frame(Title("TMath::Erf bound as RooFit function"))  # RooPlot
    erf.plotOn(frame1)

    print ">>> bind ROOT::Math::beta_pdf C pdf..."
    x2 = RooRealVar("x2", "x2", 0, 0.999)
    a = RooRealVar("a", "a", 5, 0, 10)
    b = RooRealVar("b", "b", 2, 0, 10)
    print ">>> type(%s) = %s" % ("Math.beta_pdf", type(Math.beta_pdf))
    #beta = bindPdf("beta",Math.beta_pdf,RooArgList(x2,a,b)) # RooAbsPdf
    beta = bindPdf("beta", Math.beta_pdf, x2, a, b)  # RooAbsPdf
    beta.Print()

    print ">>> generate and fit data...\n"
    data = beta.generate(x2, 10000)  # RooDataSet
    beta.fitTo(data)
    frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf"))  # RooPlot
    data.plotOn(frame2)
    beta.plotOn(frame2)

    print ">>> bind ROOT::TF1 as RooFit function..."
    fa3 = TF1("fa3", "sin(x)/x", 0, 10)
    x3 = RooRealVar("x3", "x3", 0.01, 20)
    rfa1 = bindFunction(fa3, RooArgList(x3))  # RooAbsReal
    rfa1.Print()
    frame3 = x3.frame(Title("TF1 bound as RooFit function"))  # RooPlot
    rfa1.plotOn(frame3)

    print ">>> draw functions and toy data on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1800, 600)
    canvas.Divide(3)
    for i, frame in enumerate([frame1, frame2, frame3], 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("rooFit105.png")
def rooFit106():

    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), 10000)  # RooDataSet
    gauss.fitTo(data)

    print ">>> plot pdf and data..."
    frame = x.frame(Name("frame"), Title("RooPlot with decorations"),
                    Bins(40))  # RooPlot
    data.plotOn(frame)
    gauss.plotOn(frame)

    print ">>> RooGaussian::paramOn - add box with pdf parameters..."
    # https://root.cern.ch/doc/master/classRooAbsPdf.html#aa43b2556a1b419bad2b020ba9b808c1b
    # Layout(Double_t xmin, Double_t xmax, Double_t ymax)
    # left edge of box starts at 20% of x-axis
    gauss.paramOn(frame, Layout(0.55))

    print ">>> RooDataSet::statOn - add box with data statistics..."
    # https://root.cern.ch/doc/master/classRooAbsData.html#a538d58020b296a1623323a84d2bb8acb
    # x size of box is from 55% to 99% of x-axis range, top of box is at 80% of y-axis range)
    data.statOn(frame, Layout(0.20, 0.55, 0.8))

    print ">>> add text and arrow..."
    text = TText(2, 100, "Signal")
    text.SetTextSize(0.04)
    text.SetTextColor(kRed)
    frame.addObject(text)

    arrow = TArrow(2, 100, -1, 50, 0.01, "|>")
    arrow.SetLineColor(kRed)
    arrow.SetFillColor(kRed)
    arrow.SetLineWidth(3)
    frame.addObject(arrow)

    print ">>> persist frame with all decorations in ROOT file..."
    file = TFile("rooFit106.root", "RECREATE")
    frame.Write()
    file.Close()

    # To read back and plot frame with all decorations in clean root session do
    #   [0] TFile f("rooFit106.root")
    #   [1] xframe->Draw()

    print ">>> draw functions and toy data on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    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("rooFit106.png")
Example #4
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")
Example #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")
Example #6
0
def makePlot(mds, ds, pdf):
    """ Mass fit plot """
    frame = mds.frame()
    ds.plotOn(frame, DataError(RooAbsData.SumW2), MarkerSize(1))
    pdf.plotOn(frame, LineWidth(2))

    # pull histogram
    pullHist = frame.pullHist()
    pullFrame = mds.frame(Title(''))
    pullFrame.addPlotable(pullHist, 'P')
    pullFrame.GetYaxis().SetRangeUser(-5, 5)

    canvas = TCanvas('m(Ds)', 'm(Ds)', 600, 700)
    canvas.cd()

    pad1 = TPad('pad1', 'pad1', .01, .20, .99, .99)
    pad2 = TPad('pad2', 'pad2', .01, .01, .99, .20)
    pad1.Draw()
    pad2.Draw()

    pad1.cd()
    pad1.SetLeftMargin(0.15)
    pad1.SetFillColor(0)

    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleOffset(0.85)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(1.6)
    frame.Draw()

    pad2.cd()
    pad2.SetLeftMargin(0.15)
    pad2.SetFillColor(0)
    
    pullFrame.SetMarkerSize(0.05)
    pullFrame.Draw()

    mdsRange = fitRange()['mDs']
    lineUp = TLine(mdsRange[0], 3, mdsRange[1], 3)
    lineUp.SetLineColor(kBlue)
    lineUp.SetLineStyle(2)
    lineUp.Draw()

    lineCe = TLine(mdsRange[0], 0, mdsRange[1], 0)
    lineCe.SetLineColor(kBlue)
    lineCe.SetLineStyle(1)
    lineCe.SetLineWidth(2)
    lineCe.Draw()

    lineD0 = TLine(mdsRange[0], -3, mdsRange[0], -3)
    lineD0.SetLineColor(kBlue)
    lineD0.SetLineStyle(2)
    lineD0.Draw()

    canvas.Update()
Example #7
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")
Example #8
0
def rooFit101():

    print ">>> build gaussian pdf..."
    x = RooRealVar("x", "x", -10, 10)
    mean = RooRealVar("mean", "mean of gaussian", 1, -10, 10)
    sigma = RooRealVar("sigma", "width of gaussian", 1, 0.1, 10)
    gauss = RooGaussian("gauss", "gaussian PDF", x, mean, sigma)

    print ">>> plot pdf..."
    frame1 = x.frame(Title("Gaussian pdf"))  # RooPlot
    #xframe.SetTitle("Gaussian pdf")
    gauss.plotOn(frame1)

    print ">>> change parameter value and plot..."
    sigma.setVal(3)
    gauss.plotOn(frame1, LineColor(kRed))

    print ">>> generate events..."
    data = gauss.generate(RooArgSet(x), 10000)  # RooDataSet
    frame2 = x.frame()
    data.plotOn(frame2, Binning(40))
    gauss.plotOn(frame2)

    print ">>> fit gaussian...\n"
    gauss.fitTo(data)
    mean.Print()
    sigma.Print()

    print "\n>>> draw pdfs and fits 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("rooFit101.png")
Example #9
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")
def rooFit111():

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

    print ">>> create and plot derivatives wrt x..."
    dgdx = gauss.derivative(x, 1)  # RooAbsReal
    d2gdx2 = gauss.derivative(x, 2)  # RooAbsReal
    d3gdx3 = gauss.derivative(x, 3)  # RooAbsReal

    print ">>> plot gaussian and its first two derivatives..."
    frame1 = x.frame(Title("d^{n}(Gauss)/dx^{n}"))  # RooPlot
    norm1 = 10
    gauss.plotOn(frame1, LineColor(kBlue), Name(gauss.GetName()),
                 Normalization(norm1))
    dgdx.plotOn(frame1, LineColor(kMagenta), Name("dgdx"))
    d2gdx2.plotOn(frame1, LineColor(kRed), Name("d2gdx2"))
    d3gdx3.plotOn(frame1, LineColor(kOrange), Name("d3gdx3"))

    print ">>> create and plot derivatives wrt sigma..."
    dgds = gauss.derivative(sigma, 1)  # RooAbsReal
    d2gds2 = gauss.derivative(sigma, 2)  # RooAbsReal
    d3gds3 = gauss.derivative(sigma, 3)  # RooAbsReal

    print ">>> plot gaussian and its first two derivatives..."
    frame2 = sigma.frame(Title("d^{n}(Gauss)/d(sigma)^{n}"),
                         Range(0., 2.))  # RooPlot
    (norm2, norm21, norm22) = (8000, 15, 5)
    gauss.plotOn(frame2, LineColor(kBlue), Name(gauss.GetName()),
                 Normalization(norm2))
    dgds.plotOn(frame2, LineColor(kMagenta), Name("dgds"),
                Normalization(norm21))
    d2gds2.plotOn(frame2, LineColor(kRed), Name("d2gds2"),
                  Normalization(norm22))
    d3gds3.plotOn(frame2, LineColor(kOrange), Name("d3gds3"))

    print ">>> draw pdfs 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.60, 0.85, 0.8, 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(gauss.GetName(), "gaussian G (#times%s)" % norm1, 'L')
    legend1.AddEntry("dgdx", "d(G)/dx", 'L')
    legend1.AddEntry("d2gdx2", "d^{2}(G)/dx^{2}", 'L')
    legend1.AddEntry("d3gdx3", "d^{3}(G)/dx^{3}", '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(gauss.GetName(), "gaussian G (#times%s)" % norm2, 'L')
    legend2.AddEntry("dgds", "d(G)/ds (#times%s)" % norm21, 'L')
    legend2.AddEntry("d2gds2", "d^{2}(G)/ds^{2} (#times%s)" % norm22, 'L')
    legend2.AddEntry("d3gds3", "d^{3}(G)/ds^{3}", 'L')
    legend2.Draw()
    canvas.SaveAs("rooFit111.png")
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")
Example #12
0
nfits = nfits + 1

#gamma.setConstant(False)
#sigma.setConstant(False)
#rPhifit = tot.fitTo(splotData,Range(phimin,phimax),RooFit.NumCPU(args.ncpu),RooFit.Verbose(False))
#nfits = nfits + 1

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)
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()
Example #14
0
print "Tree entries %d"%(splotData.numEntries())

print "PHSP fit"

BkgTotalMPdf = RooGenericPdf("BkgPdf","BkgPdf","sqrt( pow(dimuonditrk_m_rf_c,4) + pow(3.0967,4) + pow(1.01946,4) - 2*pow(dimuonditrk_m_rf_c,2)*pow(3.0967,2) - 2*pow(3.0967,2)*pow(1.01946,2) - 2*pow(dimuonditrk_m_rf_c,2)*pow(1.01946,2) ) * sqrt( pow(5.279,4) + pow(dimuonditrk_m_rf_c,4) + pow(0.493677,4) - 2*pow(5.279,2)*pow(dimuonditrk_m_rf_c,2) - 2*pow(5.279,2)*pow(0.493677,2) - 2*pow(dimuonditrk_m_rf_c,2)*pow(0.493677,2) ) / (dimuonditrk_m_rf_c)", RooArgList(dimuonditrk_m_rf_c));

dimuonditrk_m_rf_c.setBins(80)
dimuonditrk_m_rf_c.setRange("baserange",4.0,5.0)
s = BkgTotalMPdf.createIntegral(RooArgSet(dimuonditrk_m_rf_c),"baserange").getVal()

#bkgFit = BkgTotalMPdf.fitTo(splotBkgData,Range(4.0,5.0),RooFit.NumCPU(args.ncpu),RooFit.Verbose(False))

cb = TCanvas("canvas_b","canvas_b",1200,800) 
print s
mumukkFrame = dimuonditrk_m_rf_c.frame(Title("Phase Space Fit"),Range(4.0,5.0),Normalization(1.0))
splotData.plotOn(mumukkFrame)

BkgTotalMPdf.plotOn(mumukkFrame,Normalization(1.65))

mumukkFrame.Draw()

if args.phsps:
    cb.SaveAs(args.path[:-5] + '_bu_phsp_plot.root')
    cb.SaveAs(args.path[:-5] + '_bu_phsp_plot.png')

    sys.exit()

print "SPLOT FIT"

a0 = RooRealVar("a0","a0",0.001,-10.,10.)
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")
Example #16
0
mean.setConstant(True)
gamma.setConstant(False)
rPhifit = tot.fitTo(splotData, Range(phimin, phimax), RooFit.NumCPU(args.ncpu),
                    RooFit.Verbose(False))
nfits = nfits + 1

mean.setConstant(False)
gamma.setConstant(False)
rPhifit = tot.fitTo(splotData, Range(phimin, phimax), RooFit.NumCPU(args.ncpu),
                    RooFit.Verbose(False))
nfits = nfits + 1

c = TCanvas("canvas", "canvas", 1200, 800)
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))
tot.paramOn(phiFrame, RooFit.Layout(0.57, 0.99, 0.65))

phiFrame.Draw()

sidesigma = np.sqrt(gamma.getValV()**2 + sigma.getValV()**2)

plotmax = 1.5 * float(nentries / binning)
lowside = -3. * sidesigma + mean.getValV()
Example #17
0
#mean.setConstant(True)
#gamma.setConstant(False)
#rPhifit = tot.fitTo(splotData,Range(psimin,psimax),RooFit.NumCPU(20),RooFit.Verbose(False))
#nfits = nfits + 1

mean.setConstant(False)
sigma.setConstant(False)
rPhifit = tot.fitTo(splotData, Range(psimin, psimax), RooFit.NumCPU(20),
                    RooFit.Verbose(False))
nfits = nfits + 1

c = TCanvas("canvas", "canvas", 1200, 800)
phiFrame = psiPrimeMass.frame(Range(psimin, psimax),
                              Normalization((nSig.getValV() + nBkg.getValV())),
                              Title("#mu#mu#pi#pi candidates - #psi(2S) fit "))
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)
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")
Example #19
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")
Example #20
0
def rooFit108():
    
    print ">>> setup model - a B decay with mixing..."
    dt  = RooRealVar("dt","dt",-20,20)
    dm  = RooRealVar("dm","dm",0.472)
    tau = RooRealVar("tau","tau",1.547)
    w   = RooRealVar("w","mistag rate",0.1)
    dw  = RooRealVar("dw","delta mistag rate",0.)
    
    # Build categories - possible values states
    # https://root.cern/doc/v610/classRooCategory.html
    mixState = RooCategory("mixState","B0/B0bar mixing state")
    mixState.defineType("mixed",-1)
    mixState.defineType("unmixed",1)
    tagFlav  = RooCategory("tagFlav","Flavour of the tagged B0")
    tagFlav.defineType("B0",1)
    tagFlav.defineType("B0bar",-1)
    
    # Build a gaussian resolution model
    dterr   = RooRealVar("dterr","dterr",0.1,1.0)
    bias1   = RooRealVar("bias1","bias1",0)
    sigma1  = RooRealVar("sigma1","sigma1",0.1)
    gm1     = RooGaussModel("gm1","gauss model 1",dt,bias1,sigma1)
    
    # Construct Bdecay (x) gauss
    # https://root.cern/doc/v610/classRooBMixDecay.html
    bmix    = RooBMixDecay("bmix","decay",dt,mixState,tagFlav,tau,dm,w,dw,gm1,RooBMixDecay.DoubleSided)
    
    print ">>> sample data from data..."
    data    =  bmix.generate(RooArgSet(dt,mixState,tagFlav),2000) # RooDataSet
    
    print ">>> show dt distribution with custom binning..."
    # Make plot of dt distribution of data in range (-15,15) with fine binning for dt>0
    # and coarse binning for dt<0
    tbins = RooBinning(-15,15)  # Create binning object with range (-15,15)
    tbins.addUniform(60,-15,0)  # Add 60 bins with uniform spacing in range (-15,0)
    tbins.addUniform(15,0,15)   # Add 15 bins with uniform spacing in range (0,15)
    dtframe = dt.frame(Range(-15,15),Title("dt distribution with custom binning")) # RooPlot
    data.plotOn(dtframe,Binning(tbins))
    bmix.plotOn(dtframe)
    
    # NB: Note that bin density for each bin is adjusted to that of default frame
    # binning as shown in Y axis label (100 bins --> Events/0.4*Xaxis-dim) so that
    # all bins represent a consistent density distribution
    
    
    
    print ">>> plot mixstate asymmetry with custom binning..."
    # Make plot of dt distribution of data asymmetry in 'mixState' with variable binning 
    abins = RooBinning(-10,10)  # Create binning object with range (-10,10)
    abins.addBoundary(0)        # Add boundaries at 0
    abins.addBoundaryPair(1)    # Add boundaries at (-1,1)
    abins.addBoundaryPair(2)    # Add boundaries at (-2,2)
    abins.addBoundaryPair(3)    # Add boundaries at (-3,3)
    abins.addBoundaryPair(4)    # Add boundaries at (-4,4)
    abins.addBoundaryPair(6)    # Add boundaries at (-6,6)
    aframe = dt.frame(Range(-10,10),Title("MixState asymmetry distribution with custom binning")) # RooPlot
    
    # Plot mixState asymmetry of data with specified customg binning
    data.plotOn(aframe,Asymmetry(mixState),Binning(abins))
    
    # Plot corresponding property of pdf
    bmix.plotOn(aframe,Asymmetry(mixState))
    
    # Adjust vertical range of plot to sensible values for an asymmetry
    aframe.SetMinimum(-1.1)
    aframe.SetMaximum( 1.1)
    
    # NB: For asymmetry distributions no density corrects are needed (and are thus not applied)
    
    
    
    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)
    dtframe.GetYaxis().SetLabelOffset(0.008)
    dtframe.GetYaxis().SetTitleOffset(1.6)
    dtframe.GetYaxis().SetTitleSize(0.045)
    dtframe.GetXaxis().SetTitleSize(0.045)
    dtframe.Draw()
    canvas.cd(2)
    gPad.SetLeftMargin(0.15); gPad.SetRightMargin(0.02)
    aframe.GetYaxis().SetLabelOffset(0.008)
    aframe.GetYaxis().SetTitleOffset(1.6)
    aframe.GetYaxis().SetTitleSize(0.045)
    aframe.GetXaxis().SetTitleSize(0.045)
    aframe.Draw()
    canvas.SaveAs("rooFit108.png")
def rooFit102():

    print ">>> import TH1 into RooDataHist..."
    hist = makeTH1()
    x = RooRealVar("x", "x", -10, 10)
    data_hist = RooDataHist("data_hist", "data_hist", RooArgList(x),
                            Import(hist))

    print ">>> plot and fit RooDataHist...\n"
    mean = RooRealVar("mean", "mean of gaussian", 1, -10, 10)
    sigma = RooRealVar("sigma", "width of gaussian", 1, 0.1, 10)
    gauss = RooGaussian("gauss", "gaussian PDF", x, mean, sigma)
    gauss.fitTo(data_hist)
    frame1 = x.frame(Title("Imported TH1 with Poisson error bars"))  # RooPlot
    data_hist.plotOn(frame1)
    gauss.plotOn(frame1)

    print "\n>>> plot and fit RooDataHist with internal errors..."
    # If histogram has custom error (i.e. its contents is does not originate from a
    # Poisson process but e.g. is a sum of weighted events) you can create data with
    # symmetric 'sum-of-weights' error instead (i.e. same error bars as shown by ROOT)
    frame2 = x.frame(Title("Imported TH1 with internal errors"))
    data_hist.plotOn(frame2, DataError(RooAbsData.SumW2))
    gauss.plotOn(frame2)

    # Please note that error bars shown (Poisson or SumW2) are for visualization only,
    # the are NOT used in a maximum likelihood (ML) fit
    #
    # A (binned) ML fit will ALWAYS assume the Poisson error interpretation of data
    # (the mathematical definition  of likelihood does not take any external definition
    # of errors). Data with non-unit weights can only be correctly fitted with a chi^2
    # fit (see rf602_chi2fit.C)

    print ">>> import TTree into RooDataHist..."
    # Construct unbinned dataset importing tree branches x and y matching between
    # branches and RooRealVars is done by name of the branch/RRV
    #
    # Note that ONLY entries for which x,y have values within their allowed ranges as
    # defined in RooRealVar x and y are imported. Since the y values in the import tree
    # are in the range [-15,15] and RRV y defines a range [-10,10] this means that the
    # RooDataSet below will have less entries than the TTree 'tree'
    tree = makeTTree()
    px = RooRealVar("px", "px", -10, 10)
    py = RooRealVar("py", "py", -10, 10)
    data_set = RooDataSet("data_set", "data_set", RooArgSet(px, py),
                          Import(tree))
    data_set.Print()
    frame3 = py.frame(Title("Unbinned data shown in default frame binning"))
    frame4 = py.frame(Title("Unbinned data shown with custom binning"))
    data_set.plotOn(frame3)  # default frame binning of 100 bins
    data_set.plotOn(frame4, Binning(20))  # custom binning choice

    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("rooFit102.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")
Example #23
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 rooFit104():

    print ">>> RooClassFactory::makePdf - write class (\"MyPdfV1\") skeleton code..."
    # Write skeleton p.d.f class with variable x,a,b
    # To use this class,
    #   - Edit the file MyPdfV1.cxx and implement the evaluate() method in terms of x,a and b
    #   - Compile and link class with '.x MyPdfV1.cxx+'
    RooClassFactory.makePdf("MyPdfV1", "x,A,B")

    print ">>> write class (\"MyPdfV2\") with added initial value expression..."
    # Write skeleton pdf class with variable x,a,b and given formula expression
    # To use this class,
    #   - Compile and link class with '.x MyPdfV2.cxx+'
    RooClassFactory.makePdf("MyPdfV2", "x,A,B", "", "A*fabs(x)+pow(x-B,2)")

    print ">>> write class (\"MyPdfV3\") with added analytical integral expression..."
    # Write skeleton p.d.f class with variable x,a,b, given formula expression _and_
    # given expression for analytical integral over x
    # To use this class,
    #   - Compile and link class with '.x MyPdfV3.cxx+'
    RooClassFactory.makePdf(
        "MyPdfV3", "x,A,B", "", "A*fabs(x)+pow(x-B,2)", kTRUE, kFALSE,
        "x:(A/2)*(pow(x.max(rangeName),2)+pow(x.min(rangeName),2))+(1./3)*(pow(x.max(rangeName)-B,3)-pow(x.min(rangeName)-B,3))"
    )

    print ">>> compile and load \"MyPdfV3\" class..."
    gROOT.ProcessLineSync(".x MyPdfV3.cxx+")
    #MyPdfV3 = gROOT.LoadClass("MyPdfV3.cxx+") # TClass
    #print ">>> type(%s) = %s" % ("MyPdfV3",type(MyPdfV3))
    from ROOT import MyPdfV3

    print ">>> generate and fit data with \"MyPdfV3\" class...\n"
    a = RooRealVar("a", "a", 1)
    b = RooRealVar("b", "b", 2, -10, 10)
    x = RooRealVar("x", "x", -10, 10)
    pdf = MyPdfV3("pdf", "pdf", x, a, b)
    frame1 = x.frame(Title("Compiled class MyPdfV3"))  # RooPlot
    data = pdf.generate(RooArgSet(x), 1000)  # RooDataSet
    pdf.fitTo(data)
    data.plotOn(frame1, Binning(40))
    pdf.plotOn(frame1)

    print "\n>>> RooClassFactory::makePdfInstance - generate a pdf instance directly..."
    # The RooClassFactory::makePdfInstance() function performs code writing, compiling, linking
    # and object instantiation in one go and can serve as a straight replacement of RooGenericPdf
    y = RooRealVar("y", "y", -20, 20)
    alpha = RooRealVar("alpha", "alpha", 5, 0.1, 10)
    genpdf = RooClassFactory.makePdfInstance(
        "GenPdf", "(1+0.1*fabs(y)+sin(sqrt(fabs(y*alpha+0.1))))",
        RooArgList(y, alpha))  # RooAbsPdf

    print ">>> generate and fit data with pdf instance...\n"
    data2 = genpdf.generate(RooArgSet(y), 10000)  # RooDataSet
    genpdf.fitTo(data2)
    frame2 = y.frame(Title("Compiled version of pdf of rf103"))  # RooPlot
    data2.plotOn(frame2, Binning(50))
    genpdf.plotOn(frame2)

    print "\n>>> draw pdfs and fits 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("rooFit104.png")
if args.prompt:
    theData = theData.reduce("xL < 1.5")

if args.ptcuts is not None:
    theData = theData.reduce("trigp_pT > " + str(args.ptcuts))
    theData = theData.reduce("trign_pT > " + str(args.ptcuts))
    cuts += "P_t_" + str(args.ptcuts) + "_"
#### #### Plotting variables
#### TrakTrak Data

if args.noplot:

    print("TrakTrak data plotting . . .")

    print("All : " + str(theData.numEntries()))
    ttFrame = tt_mass.frame(Title("KK mass"))
    theData.plotOn(ttFrame)
    ttFrame.Draw()
    c.SaveAs(region + "/tt_mass" + cuts + ".png")

    #### MuMu Data
    print("MuMu data plotting . . .")

    print("All : " + str(theData.numEntries()))
    mumuFrame = mm_mass.frame(Title("KK mass"))
    theData.plotOn(mumuFrame)
    mumuFrame.Draw()
    c.SaveAs(region + "/mm_mass.png")

    #### X Data
    print("TrakTrakMuMu data plotting . . .")
Example #26
0
def rooFit110():
    
    print ">>> setup  model..."
    x     = RooRealVar("x","x",-10,10)
    mean  = RooConst(-2)
    sigma = RooConst(3)
    gauss = RooGaussian("gauss","gauss",x,mean,sigma)
    frame1 = x.frame(Title("Gaussian pdf")) # RooPlot
    gauss.plotOn(frame1)
    
    print ">>> retrieve raw & normalized values of RooFit pdfs...\n>>>"
    # Return 'raw' unnormalized value of gauss
    print ">>>   raw value:          gauss.getVal( )  = %.3f" % gauss.getVal() + " depends on x range"
    print ">>>   normalization:      gauss.getVal(x)  = %.3f" % gauss.getVal(RooArgSet(x))
    print ">>>   normalization:     gauss.getNorm(x)  = %.3f" % gauss.getNorm(RooArgSet(x))
    print ">>>                  1/(sigma*sqrt(2*pi))  = %.3f" % (1/(sigma.getValV()*sqrt(2*pi)))
    # Create object representing integral over gauss
    # which is used to calculate  gauss_Norm[x] == gauss / gauss_Int[x]
    igauss = gauss.createIntegral(RooArgSet(x)) # RooAbsReal
    print ">>>   integral:          igauss.getVal( )  = %.3f" % igauss.getVal()
    print ">>>                      igauss.getVal(x)  = %.3f" % igauss.getVal(RooArgSet(x))
    print ">>>                    1/igauss.getVal(x)  = %.3f" % (1/igauss.getVal(RooArgSet(x)))
    print ">>>       gauss.getVal()/igauss.getVal(x)  = %.3f" % (gauss.getVal()/igauss.getVal(RooArgSet(x)))
    # maximum
    print ">>>   maximum:         gauss.getMaxVal(x)  = %.3f" % gauss.getMaxVal(RooArgSet(x))
    print ">>>                       gauss.getMax(0)  = %.3f" % gauss.maxVal(0)
    print ">>>                       gauss.getMax(1)  = %.3f" % gauss.maxVal(1)
    print ">>>           gauss.asTF(x).GetMaximumX()  = %.3f" % gauss.asTF(RooArgList(x)).GetMaximumX()
    print ">>>            gauss.asTF(x).GetMaximum()  = %.3f" % gauss.asTF(RooArgList(x)).GetMaximum()
    xmaxVal = gauss.asTF(RooArgList(x)).GetMaximumX()
    xmax = RooRealVar("x_max","x_max",xmaxVal)
    x.setVal(xmaxVal)
    print ">>>                    gauss.getVal(    )  = %.3f" % gauss.getVal()
    print ">>>                    gauss.getVal(xmax)  = %.3f" % gauss.getVal(RooArgSet(x))
    print ">>>                    gauss.getVal(xmax)  = %.3f" % gauss.getVal(RooArgSet(xmax))
    
    print ">>> plot"
    frame2 = x.frame(Title("integral of Gaussian pdf")) # RooPlot
    line1 = RooLinearVar("line1","line1",x,RooConst(0),RooConst(gauss.getVal()))
    line2 = RooLinearVar("line2","line2",x,RooConst(0),RooConst(gauss.getVal(RooArgSet(x))))
    igauss.plotOn(frame2,LineColor(kBlue), Name(igauss.GetName()))
    line1.plotOn( frame2,LineColor(kRed),  Name(line1.GetName()))
    line2.plotOn( frame2,LineColor(kGreen),Name(line2.GetName()))
    
    print ">>>\n>>> integrate normalized pdf over subrange..."
    # Define a range named "signal" in x from -5,5
    x.setRange("signal",-5,5)
    
    # Create an integral of gauss_Norm[x] over x in range "signal"
    # This is the fraction of of p.d.f. gauss_Norm[x] which is in
    # the range named "signal"
    igauss_sig = gauss.createIntegral(RooArgSet(x),NormSet(RooArgSet(x)),Range("signal")) # RooAbsReal
    print ">>>   gauss_Int[x|signal]_Norm[x] = %.2f" % igauss_sig.getVal()
    
    print ">>> construct cumulative distribution function from pdf..."
    # Create the cumulative distribution function of
    # gauss, i.e. calculate Int[-10,x] gauss(x') dx'
    gauss_cdf = gauss.createCdf(RooArgSet(x)) # RooAbsReal
    frame3 = x.frame(Title("cdf of Gaussian pdf")) # RooPlot
    gauss_cdf.plotOn(frame3)
    
    print ">>> draw functions on canvas..."
    canvas = TCanvas("canvas","canvas",100,100,2000,400)
    legend = TLegend(0.6,0.6,0.8,0.42)
    legend.SetTextSize(0.032)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    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.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()
        if i is 2:
            legend.AddEntry(line1.GetName(), " gauss.getVal( )",'L')
            legend.AddEntry(line2.GetName(), " gauss.getVal(x)",'L')
            legend.AddEntry(igauss.GetName(),"igauss.getVal( )",'L')
            legend.Draw()
    canvas.SaveAs("rooFit110.png")