def addConstraint(workspace,rrv_x, x_mean, x_sigma, ConstraintsList): rrv_x_mean = RooRealVar(rrv_x.GetName()+"_mean",rrv_x.GetName()+"_mean",x_mean ) rrv_x_sigma = RooRealVar(rrv_x.GetName()+"_sigma",rrv_x.GetName()+"_sigma",x_sigma ) constrainpdf_x = RooGaussian("constrainpdf_"+rrv_x.GetName(),"constrainpdf_"+rrv_x.GetName(),rrv_x, rrv_x_mean, rrv_x_sigma) ConstraintsList.append(constrainpdf_x.GetName()) getattr(workspace,"import")(constrainpdf_x) return constrainpdf_x
def test_1d(): m1 = RooRealVar("m1", "m1", 125.0, 110, 140) s1 = RooRealVar("s1", "s1", 2.5, 0, 10) m2 = RooRealVar("m2", "m2", 124.0, 110, 140) s2 = RooRealVar("s2", "s2", 2.0, 0, 10) m3 = RooRealVar("m3", "m3", 126.0, 110, 140) s3 = RooRealVar("s3", "s3", 3.0, 0, 10) m4l = RooRealVar("m4l", "m4l", 110, 140) g1 = RooGaussian("g1", "g1", m4l, m1, s1) g2 = RooGaussian("g2", "g2", m4l, m2, s2) g3 = RooGaussian("g3", "g3", m4l, m3, s3) nuis_var = RooRealVar('nuis_var', "nuis_var", 0., -5., 5.) morph = createMorph(m4l, nuis_var, g1, g3, g2) canvas = ROOT.TCanvas("canvas", "canvas", 450, 450) frame = m4l.frame() morph.plotOn(frame, ROOT.RooFit.LineColor(2)) nuis_var.setVal(1.0) morph.plotOn(frame, ROOT.RooFit.LineColor(4)) nuis_var.setVal(0.5) morph.plotOn(frame, ROOT.RooFit.LineColor(8), ROOT.RooFit.LineStyle(2)) nuis_var.setVal(-0.5) morph.plotOn(frame, ROOT.RooFit.LineColor(8), ROOT.RooFit.LineStyle(2)) nuis_var.setVal(-1.0) morph.plotOn(frame, ROOT.RooFit.LineColor(4)) frame.Draw() canvas.SaveAs("gaussian_morph_1d.pdf")
def main1(): m = RooRealVar('evt.m', 'evt.m', 1.92, 2.02) mode = RooCategory('evt.mode', 'evt.mode') mode.defineType('phipi', 0) aset = RooArgSet('aset') aset.add(m) aset.add(mode) tuplist = tupleList('genmc', 7) dst, _, f = getTree('/'.join([tuplePath(), tuplist[-1]])) # dst.Print() # dst.Show(0) # for evt in dst: # print('Hello!') # print(evt.evt.m) # break ds = RooDataSet('ds', 'ds', dst, aset) print(ds.numEntries()) mean = RooRealVar('mean', 'mean', 1.96, 1.92, 2.0) width = RooRealVar('width', 'width', 0.006, 0.001, 0.010) pdf = RooGaussian('pdf', 'pdf', m, mean, width) pdf.fitTo(ds, Verbose(), Timer(True)) makePlot(m, ds, pdf) raw_input("Press Enter to continue...")
def generate_testfiles(): h = TH1D("gaussian_hist", "Gaussian histgram", 100, -3, 3) h.FillRandom("gaus", 1000) file = TFile( os.path.dirname(__file__) + ('/../testfiles/root_testfiles.root'), 'RECREATE') file.cd() h.Write() x = RooRealVar("D0_M", "m(K_{S}^{0}K^{+}K^{-})", 1860, 1800, 1930, "\\mathrm{MeV}/c^{2}") x.setBins(130) m1 = RooRealVar("m1", "mean 1", 1864, 1860, 1870) s1 = RooRealVar("s1", "sigma 1", 2, 0, 5) g1 = RooGaussian("g1", "Gaussian 1", x, m1, s1) m2 = RooRealVar("m2", "mean 2", 1864, 1860, 1870) s2 = RooRealVar("s2", "sigma 2", 4, 0, 5) g2 = RooGaussian("g2", "Gaussian 2", x, m2, s2) f1 = RooRealVar("f", "f", 0.5, 0, 1) m = RooAddPdf("model", "model", RooArgList(g1, g2), f1) data = m.generate(x, 1e6) x.Write("x") m.Write("model") data.Write("data") file.Close() return
def RooFitSig(mbbarray, bdtarray, weightarray, TC_mass, binstart, binend): fitstart = 40 fitend = 150 mbbarray = range(200) bdtarray = range(200) weightarray = range(200) mass = RooRealVar("X", "m(bb)[GeV]", fitstart, fitend) BDT = RooRealVar("BDT", "BDT", -1, 100) weight = RooRealVar("weight", "weight", -100, 200) branchnames = ["X", "BDT", "weight"] dtype = np.dtype([(branchnames[idx], np.float64) for idx in range(len(branchnames))]) treearray = np.array([(mbbarray[idx], bdtarray[idx], weightarray[idx]) for idx in range(len(mbbarray))], dtype) tree = rnp.array2tree(treearray) m0 = RooRealVar("m0", "m0", TC_mass * 1., TC_mass * 1. - 60., TC_mass * 1. + 60.) m02 = RooRealVar("m02", "m02", TC_mass * 1., TC_mass * 1. - 60., TC_mass * 1. + 60.) alpha = RooRealVar("alpha", "alpha", 1.295, 1.0, 1.6) sigma2 = RooRealVar("sigma2", "sigma2", 35, 8., 100) n = RooRealVar("n", "n", 5, 1, 35) mean = RooRealVar("mean", "mean of gaussian", 750, 0, 6000) sigma = RooRealVar("sigma", "width of gaussian", 90, 38, 300) gauss = RooGaussian("gauss", "gaussian PDF", mass, m0, sigma) gauss2 = RooGaussian("gauss2", "gaussian PDF", mass, m02, sigma2) CBshape = RooCBShape("CBshape", "Crystal Ball PDF", mass, m0, sigma2, alpha, n) ##PDF normalization num1 = RooRealVar("num1", "number of events", 400, 0, 5000) ##relative weight of 2 PDFs f = RooRealVar("f", "f", 0.95, 0.6, 1) sigPdf = RooAddPdf("sigPdf", "Signal PDF", RooArgList(CBshape, gauss), RooArgList(f)) extPdf = RooExtendPdf("extPdf", "extPdf", sigPdf, num1) data = RooDataSet("data", "data", tree, RooArgSet(mass, BDT, weight), "BDT>0", "weight") xframe = mass.frame() mass.setBins(20) data.plotOn(xframe) extPdf.plotOn( xframe) #,Normalization(1.0,RooAbsReal.RelativeExpected),LineColor(1)) hist = extPdf.createHistogram("X", fitend - fitstart) hist.SetAxisRange(binstart, binend) return deepcopy(hist)
def Gausintialization(self): round_energy = round(float(self.energy),-1) if round_energy ==240 : round_energy = 250 self.x = RooRealVar("signal_%s_%dGeV"%(self.crystal,round_energy),"signal_%s_%dGeV"%(self.crystal,round_energy),max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale)) self.roohist = RooDataHist("roohist_fit_%s_%s"%(self.crystal,self.energy),"roohist_fit_%s_%s"%(self.crystal,self.energy),RooArgList(self.x),self.hist) self.m = RooRealVar("mean_%s_%s"%(self.crystal,self.energy),"mean_%s_%s"%(self.crystal,self.energy),self.peak_position,max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale)) self.s = RooRealVar("sigma_%s_%s"%(self.crystal,self.energy),"sigma_%s_%s"%(self.crystal,self.energy),self.s_initial,0.001,1.) self.sig = RooGaussian("signal_%s_%s"%(self.crystal,self.energy),"signal_%s_%s"%(self.crystal,self.energy),self.x,self.m,self.s)
def fitNSig(ibdt, fulldata, isample): mean = RooRealVar("mass", "mean", B0Mass_, 3, 7, "GeV") sigma = RooRealVar("#sigma_{1}", "sigma", 0.028, 0, 10, "GeV") signalGauss = RooGaussian("signalGauss", "signal gauss", theBMass, mean, sigma) sigma2 = RooRealVar("#sigma_{2}", "sigma2", 0.048, 0, 0.09, "GeV") signalGauss2 = RooGaussian("signalGauss2", "signal gauss2", theBMass, mean, sigma2) f1 = RooRealVar("f1", "f1", 0.8, 0., 1.) gaus = RooAddPdf("gaus", "gaus1+gaus2", RooArgList(signalGauss, signalGauss2), RooArgList(f1)) pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10) # pol_c3 = RooRealVar ("p3" , "coeff x^2 term", 0.5, -10, 10); # slope = RooRealVar ("slope" , "slope" , 0.5, -10, 10); # bkg_exp = RooExponential("bkg_exp" , "exponential" , slope, theBMass ); bkg_pol = RooChebychev("bkg_pol", "2nd order pol", theBMass, RooArgList(pol_c1)) nsig = RooRealVar("Yield", "signal frac", 40000, 0, 1000000) nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 550000) cut = cut_base + '&& bdt_prob > %s' % (ibdt) data = fulldata.reduce(RooArgSet(theBMass, mumuMass, mumuMassE), cut) fitFunction = RooAddPdf("fitfunction", "fit function", RooArgList(gaus, bkg_pol), RooArgList(nsig, nbkg)) r = fitFunction.fitTo(data, RooFit.Extended(True), RooFit.Save(), RooFit.Range(4.9, 5.6), RooFit.PrintLevel(-1)) frame = theBMass.frame() data.plotOn(frame, RooFit.Binning(70), RooFit.MarkerSize(.7)) fitFunction.plotOn(frame, ) fitFunction.plotOn(frame, RooFit.Components("bkg_pol"), RooFit.LineStyle(ROOT.kDashed)) fitFunction.plotOn(frame, RooFit.Components("signalGauss"), RooFit.LineStyle(ROOT.kDashed), RooFit.LineColor(ROOT.kGreen + 1)) fitFunction.plotOn(frame, RooFit.Components("signalGauss2"), RooFit.LineStyle(ROOT.kDashed), RooFit.LineColor(ROOT.kOrange + 1)) parList = RooArgSet(nsig, sigma, sigma2, mean) ###### fitFunction.plotOn(frame, RooFit.Components("signalGauss2"), RooFit.LineStyle(ROOT.kDashed), RooFit.LineColor(ROOT.kGreen+2)); fitFunction.paramOn(frame, RooFit.Parameters(parList), RooFit.Layout(0.62, 0.86, 0.88)) canv = ROOT.TCanvas() frame.Draw() # canv.SaveAs('sig_fit_bdt%f_sample%i.pdf'%(ibdt,isample)) dict_s_v1[ibdt] = [nsig.getVal(), nsig.getError()] dict_sigma[ibdt] = math.sqrt(f1.getVal() * (sigma.getVal()**2) + (1 - f1.getVal()) * (sigma2.getVal()**2))
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")
def doubleG(mean_, sigma1_, sigma2_, f1_, tagged_mass, w, fn): mean = RooRealVar ("mean^{%s}"%fn , "massDG" , mean_ , 5, 6, "GeV") sigma1 = RooRealVar ("#sigma_{1}^{%s}"%fn , "sigmaDG1" , sigma1_ , 0, 1, "GeV") signalGauss1 = RooGaussian("dg_firstGauss_%s"%fn , "firstGauss" , tagged_mass, mean, sigma1) sigma2 = RooRealVar ("#sigma_{2}^{%s}"%fn , "sigmaDG2" , sigma2_ , 0, 0.12, "GeV") signalGauss2 = RooGaussian("dg_secondGauss_%s"%fn , "secondGauss" , tagged_mass, mean, sigma2) f1 = RooRealVar ("f^{%s}"%fn , "f1" , f1_ , 0., 1. ) doublegaus = RooAddPdf ("doublegaus_%s"%fn , "gaus1+gaus2" , RooArgList(signalGauss1,signalGauss2), RooArgList(f1)) _import(w,doublegaus)
def toy_run(nevents): lower = -1 upper = 1 # create observables obs = RooRealVar("obs", "obs1", lower, upper) # create parameters mean1 = RooRealVar("mean1", "mean of gaussian", 0, -1, 1) sigma1 = RooRealVar("sigma1", "sigma of gaussian", 0.1, -1, 1) gauss1 = RooGaussian("gauss1", "gaussian PDF", obs, mean1, sigma1) mean2 = RooRealVar("mean2", "mean of gaussian", 0.5, -1, 1) sigma2 = RooRealVar("sigma2", "sigma of gaussian", 0.2, -1, 1) gauss2 = RooGaussian("gauss2", "gaussian PDF", obs, mean2, sigma2) frac = RooRealVar("frac", "Fraction of a gauss", 0.5, 0, 1) arg_list = RooArgList( gauss1, gauss2, gauss2, gauss2, gauss2, # gauss2, gauss2, gauss2, gauss1) arg_list.addOwned(gauss2) pdf = RooAddPdf( "sum_pdf", "sum of pdfs", arg_list, RooArgList( frac, frac, frac, # frac, # frac, frac, frac, frac, frac, frac)) # obs, pdf = build_pdf() timer = zfit_benchmark.timer.Timer(f"Toys {nevents}") with timer: data = pdf.generate(RooArgSet(obs), nevents) pdf.fitTo(data) # mgr.generateAndFit(n_toys, nevents) return float(timer.elapsed)
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")
def tripleG(doublegaus, mean, sigma3_, f2_, tagged_mass, w): sigma3 = RooRealVar ("#sigma_{TG3}" , "sigmaTG3" , sigma3_ , 0, 0.2, "GeV") signalGauss3 = RooGaussian("thirdGauss" , "thirdGauss" , tagged_mass, mean, sigma3) f2 = RooRealVar ("f2" , "f2" , f2_ , 0., 1. ) triplegaus = RooAddPdf ("triplegaus" , "doublegaus+gaus3", RooArgList(doublegaus,signalGauss3), RooArgList(f2)) _import(w,triplegaus)
class GaussianConstraint(object): def __init__(self, name, expr, deps, mean, sigma): self.name = name self.expr = expr self.deps = deps self.mean = mean self.sigma = sigma # pdf of yield vs coupling modificators dependentlist = RooArgList() for dep in deps: dependentlist.add(dep) self.pdf_yield = RooGenericPdf(name, name, expr, dependentlist) # observable (measurement) obsname = name + 'Obs' self.var_obs = RooRealVar(obsname, obsname, mean) # width of Gaussian pdf sname = name + 'Sigma' self.var_sigma = RooRealVar(sname, sname, sigma) # Gaussian pdf gname = name + "Constraint" self.pdf_constraint = RooGaussian(gname, gname, self.var_obs, self.pdf_yield, self.var_sigma) self.pulls = ROOT.TH1F('pulls_' + name, name, 1000, -10, 10) def fill_pull(self): pull = (self.pdf_yield.getVal() - 1) / self.var_sigma.getVal() self.pulls.Fill(pull) def info(self): print self.name self.pdf_yield.Print() self.var_obs.Print() self.var_sigma.Print() self.pdf_constraint.Print()
def main(): # Mjj0 of TT MC Bkg f1 = TFile("Merged_TT_TuneCUETP8M1_13TeV-powheg-pythia8-runallAnalysis.root") h_Mjj = f1.Get("histfacFatJet_ZLight/h_Mjj0") h_Mjj.GetXaxis().SetRangeUser(0,300) var_mean = h_Mjj.GetMean() # Build Gaussian PDF x = RooRealVar( 'x', 'x', 0, 300 ) mean = RooRealVar( 'mean', 'mean of gaussian', var_mean ) sigma = RooRealVar( 'sigma', 'width of gaussian', 5) gauss = RooGaussian( 'gauss', 'gaussian PDF', x, mean, sigma) data = RooDataHist("data","Mjj dataset",RooArgList(x), h_Mjj); # Plot PDF xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) gauss.plotOn( xframe ) gauss.plotOn(xframe,RooFit.LineColor(2)) # Generate a toy MC set # data = gauss.generate( RooArgSet(x), 10000 ) # Plot PDF and toy data overlaid xframe2 = x.frame(RooFit.Title("Gaussian p.d.f. with Mjj")) # data.plotOn( xframe2, RooLinkedList() ) # data.plotOn( xframe2 ) data.plotOn( xframe2 ) gauss.plotOn( xframe2) # Fit PDF to toy mean.setConstant( kFALSE ) sigma.setConstant( kFALSE ) gauss.fitTo(data) c1 = TCanvas("c1","Example",800,400) c1.Divide(3) c1.cd(1) gPad.SetLeftMargin(0.15) xframe.GetYaxis().SetTitleOffset(1.6) xframe.Draw() c1.cd(2) gPad.SetLeftMargin(0.15) xframe2.GetYaxis().SetTitleOffset(1.6) xframe2.Draw() c1.SaveAs('testMjj0.png') # # Print final value of parameters fout = TFile("output.root","recreate") c1.Write() fout.Close()
def DoRooFit(histo, title): can = makeCMSCanvas(str(random.random()),"Fit result ",900,700) #Varible if "ele" in title: x1 = RooRealVar("x1","m_{e^{+}e^{-}}",80,100) if "mu" in title: x1 = RooRealVar("x1","m_{#mu^{+}#mu^{-}}",80,100) #Define CB function m = RooRealVar("mean_{CB}","mean of gaussian",60,120) s = RooRealVar("#sigma_{CB}","width of gaussian",0,3) a = RooRealVar("#alpha_{CB}","mean of gaussian",0,100) n = RooRealVar("n_{CB}","width of gaussian",0,5) CB = RooCBShape("CB","CB PDF",x1, m, s, a, n) m.setConstant(kFALSE) s.setConstant(kFALSE) a.setConstant(kFALSE) n.setConstant(kFALSE) #Define Gaussian function mean1 = RooRealVar("mean_{G}","mean of gaussian",-60,60) sigma1 = RooRealVar("#sigma_{G}","width of gaussian",0,10) gauss1 = RooGaussian("gauss1","gaussian PDF",x1,mean1,sigma1) mean1.setConstant(kFALSE) sigma1.setConstant(kFALSE) #Starting values of the parameters mean1.setVal(1.0) sigma1.setVal(1.0) m.setVal(90.0) s.setVal(1.0) a.setVal(10.0) n.setVal(2.0) # Construct CB (x) gauss x1.setBins(10000, "cache") CBxG = RooFFTConvPdf("CBxG", "CB (X) gauss", x1, CB, gauss1) can.cd() d = RooDataHist("d","d",RooArgList(x1),RooFit.Import(histo)) CBxG.fitTo(d, RooLinkedList()) # Plot PDF and toy data overlaid xframe2 = x1.frame(RooFit.Name("xframe"),RooFit.Title("")) # RooPlot d.plotOn(xframe2, RooLinkedList() ) CBxG.paramOn(xframe2, RooFit.Layout(0.65,0.99,0.9)) xframe2.getAttText().SetTextSize(0.03) CBxG.plotOn(xframe2) xframe2.Draw() can.SaveAs("DataVsMC/FitResults/"+title+"_Roofit.pdf") can.SaveAs("DataVsMC/FitResults/"+title+"_Roofit.png") return;
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")
def _constrainVar(var): constr = _getFittedVar(var.GetName(), w) gauss_constr = RooGaussian("c_%s" % var.GetName(), "c_%s" % var.GetName(), var, ROOT.RooFit.RooConst(constr.n), ROOT.RooFit.RooConst(constr.s)) print 'constraining var', var.GetName( ), ': ', constr.n, ' with uncertainty ', constr.s return gauss_constr
def fitPed(hist, ws, name='x'): maxBin = hist.GetMaximumBin() x = ws.var(name) #rds = ds.reduce('{1}<{0:0.2f}'.format(hist.GetBinLowEdge(maxBin+2),name)) #rds.Print() x.setRange('ped_fit', x.getMin(), hist.GetBinLowEdge(maxBin+3)) pedMean = RooRealVar('pedMean', 'mean_{ped}', hist.GetBinCenter(maxBin), x.getMin(), x.getMax()) pedMean.Print() pedWidth = RooRealVar('pedWidth', 'sigma_{ped}', 1., 0., 10.) pedWidth.Print() ped = RooGaussian('ped', 'ped', x, pedMean, pedWidth) pedMean.setConstant(False) ped.fitTo(ws.data('ds'), RooFit.Minos(False), RooFit.Range('ped_fit'), RooFit.PrintLevel(0)) getattr(ws, 'import')(ped)
def fitPed(hist, ws, name='x'): maxBin = hist.GetMaximumBin() x = ws.var(name) #rds = ds.reduce('{1}<{0:0.2f}'.format(hist.GetBinLowEdge(maxBin+2),name)) #rds.Print() x.setRange('ped_fit', x.getMin(), hist.GetBinLowEdge(maxBin + 3)) pedMean = RooRealVar('pedMean', 'mean_{ped}', hist.GetBinCenter(maxBin), x.getMin(), x.getMax()) pedMean.Print() pedWidth = RooRealVar('pedWidth', 'sigma_{ped}', 1., 0., 10.) pedWidth.Print() ped = RooGaussian('ped', 'ped', x, pedMean, pedWidth) pedMean.setConstant(False) ped.fitTo(ws.data('ds'), RooFit.Minos(False), RooFit.Range('ped_fit'), RooFit.PrintLevel(0)) getattr(ws, 'import')(ped)
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")
def setUp(self): from e5.lhcb.util import setup_roofit, silence_roofit setup_roofit() silence_roofit() from ROOT import RooArgSet, RooGaussian, RooRealVar self.x = RooRealVar('x', 'x', -10, 10) self.mean = RooRealVar('mean', 'mean', 1, -10, 10) self.sigma = RooRealVar('sigma', 'sigma', 1, 0, 10) self.model = RooGaussian('model', 'model', self.x, self.mean, self.sigma) self.data = self.model.generate(RooArgSet(self.x), 1000)
def __init__(self, adc, name): #input ADC values self.adc = adc #1n Gaussian mean_nam = "mean_1n_" + name self.mean_1n = RooRealVar(mean_nam, mean_nam, 40., 120.) sigma_nam = "sigma_1n_" + name self.sigma_1n = RooRealVar(sigma_nam, sigma_nam, 0., 100.) gauss_nam = "gauss_1n_" + name self.gauss_1n = RooGaussian(gauss_nam, gauss_nam, self.adc, self.mean_1n, self.sigma_1n)
def CBintialization(self): round_energy = round(float(self.energy),-1) if round_energy ==240 : round_energy = 250 self.x = RooRealVar("signal_%s_%dGeV"%(self.crystal,round_energy),"signal_%s_%dGeV"%(self.crystal,round_energy),max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale)) self.roohist = RooDataHist("roohist_fit_%s_%s"%(self.crystal,self.energy),"roohist_fit_%s_%s"%(self.crystal,self.energy),RooArgList(self.x),self.hist) self.m = RooRealVar("mean_%s_%s"%(self.crystal,self.energy),"mean_%s_%s"%(self.crystal,self.energy),self.peak_position,max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale)) self.s = RooRealVar("sigma_%s_%s"%(self.crystal,self.energy),"sigma_%s_%s"%(self.crystal,self.energy),self.s_initial,0.001,1.) #500. self.a = RooRealVar("alpha_%s_%s"%(self.crystal,self.energy),"alpha_%s_%s"%(self.crystal,self.energy),self.a_initial,-10.,10) self.n = RooRealVar("exp_%s_%s"%(self.crystal,self.energy),"exp_%s_%s"%(self.crystal,self.energy),self.n_initial,0.,30) self.sig = RooCBShape("signal_%s_%s"%(self.crystal,self.energy),"signal_%s_%s"%(self.crystal,self.energy),self.x,self.m,self.s,self.a,self.n)
def test_plot(): c = TCanvas('c', 'canvas', 300, 300) 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) xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) #gauss.plotOn(xframe) sigma.setVal(3) as_x = RooArgSet(x) data = gauss.generate(as_x,10000) data.plotOn(xframe, RooFit.MarkerSize(0.6), RooFit.MarkerStyle(20)) xframe.Draw() pdffile = 'test.pdf' c.SaveAs(pdffile)
def _constrainVar(var, nsigma, pars_init_vals): constr = _getFittedVar(var.GetName(), w) gauss_constr = RooGaussian("c_%s" % var.GetName(), "c_%s" % var.GetName(), var, ROOT.RooFit.RooConst(constr.n), ROOT.RooFit.RooConst(nsigma * constr.s)) ## save initial value (for toys) # pdb.set_trace() pars_init_vals[var.GetName()] = constr.n # print 'constraining var', var.GetName(), ': ', constr.n , ' with uncertainty ' , nsigma*constr.s return gauss_constr
def test_plot(): c = TCanvas('c', 'canvas', 300, 300) 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) xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) #gauss.plotOn(xframe) sigma.setVal(3) as_x = RooArgSet(x) data = gauss.generate(as_x, 10000) data.plotOn(xframe, RooFit.MarkerSize(0.6), RooFit.MarkerStyle(20)) xframe.Draw() pdffile = 'test.pdf' c.SaveAs(pdffile)
def get_fit_normalisation_constraints( self, model, roofit_variables ): result = [] for sample, constraint in self.constraints.iteritems(): if self.normalisation[sample] != 0: roo_constraint = RooGaussian( sample + "_constraint", sample + "_constraint", roofit_variables[sample], RooFit.RooConst( self.normalisation[sample] ), RooFit.RooConst( constraint * self.normalisation[sample] ), ) result.append( roo_constraint ) return result
def rooFit502(): print ">>> setup model components..." x = RooRealVar("x", "x", 0, 10) mean = RooRealVar("mean", "mean of gaussians", 5, 0, 10) 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 ">>> sum model components..." sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.) sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2), RooArgList(sig1frac)) bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.) model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig), RooArgList(bkgfrac)) print ">>> generate data..." data = model.generate(RooArgSet(x), 1000) # RooDataSet print ">>> create workspace, import data and model..." workspace = RooWorkspace("workspace", "workspace") # empty RooWorkspace getattr(workspace, 'import')(model) # import model and all its components getattr(workspace, 'import')(data) # import data #workspace.import(model) # causes synthax error in python #workspace.import(data) # causes synthax error in python print "\n>>> print workspace contents:" workspace.Print() print "\n>>> save workspace in file..." workspace.writeToFile("rooFit502_workspace.root") print ">>> save workspace in memory (gDirectory)..." gDirectory.Add(workspace)
def test_correlated_values(): try: import uncertainties except ImportError: raise SkipTest("uncertainties package is not installed") from rootpy.stats.correlated_values import correlated_values # construct pdf and toy data following example at # http://root.cern.ch/drupal/content/roofit # --- Observable --- mes = RooRealVar("mes", "m_{ES} (GeV)", 5.20, 5.30) # --- Parameters --- sigmean = RooRealVar("sigmean", "B^{#pm} mass", 5.28, 5.20, 5.30) sigwidth = RooRealVar("sigwidth", "B^{#pm} width", 0.0027, 0.001, 1.) # --- Build Gaussian PDF --- signal = RooGaussian("signal", "signal PDF", mes, sigmean, sigwidth) # --- Build Argus background PDF --- argpar = RooRealVar("argpar", "argus shape parameter", -20.0, -100., -1.) background = RooArgusBG("background", "Argus PDF", mes, RooFit.RooConst(5.291), argpar) # --- Construct signal+background PDF --- nsig = RooRealVar("nsig", "#signal events", 200, 0., 10000) nbkg = RooRealVar("nbkg", "#background events", 800, 0., 10000) model = RooAddPdf("model", "g+a", RooArgList(signal,background), RooArgList(nsig,nbkg)) # --- Generate a toyMC sample from composite PDF --- data = model.generate(RooArgSet(mes), 2000) # --- Perform extended ML fit of composite PDF to toy data --- fitresult = model.fitTo(data, RooFit.Save(), RooFit.PrintLevel(-1)) nsig, nbkg = correlated_values(["nsig", "nbkg"], fitresult) # Arbitrary math expression according to what the `uncertainties` # package supports, automatically computes correct error propagation sum_value = nsig + nbkg value, error = sum_value.nominal_value, sum_value.std_dev workspace = Workspace(name='workspace') # import the data assert_false(workspace(data)) with TemporaryFile(): workspace.Write()
def saveLandauHistoAmplitude(histo, outfile, canvas, XaxisTitle="", YaxisTitle="", plotTitle="", stats=0): ex = "Null Fit" amplitude = RooRealVar("amplitude", "Cluster Amplitude", 0, 5000) landau_data = RooDataHist("landau_data", "landau_data", RooArgList(amplitude), histo) ml = RooRealVar("ml", "mean landau", 1500., 1000, 2000) sl = RooRealVar("sl", "sigma landau", 250, 100, 1000) landau = RooLandau("lx", "lx", amplitude, ml, sl) mg = RooRealVar("mg", "mg", 0) sg = RooRealVar("sg", "sg", 100, 20, 500) gauss = RooGaussian("gauss", "gauss", amplitude, mg, sg) lxg = RooNumConvPdf("lxg", "lxg", amplitude, landau, gauss) result = lxg.fitTo(landau_data) frame = amplitude.frame() landau_data.plotOn(frame) lxg.plotOn(frame) frame.Draw("") frame.SetTitle(plotTitle) frame.GetXaxis().SetTitle(XaxisTitle) frame.GetYaxis().SetTitle(YaxisTitle) frame.SetStats(stats) frame.Write(plotTitle) canvas.Print(outfile + ".pdf") peak = [] try: mean = RooRealVar(result.floatParsFinal().find("landau_mean")) err = RooRealVar(mean.errorVar()) peak.append(mean.GetVal()) peak.append(err.GetVal()) except Exception as ex: print(ex) peak.append(0) peak.append(0) return peak
def rooFit602(): print ">>> setup model..." 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) 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,RooArgSet(a0,a1)) sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.) sig = RooAddPdf("sig","Signal",RooArgList(sig1,sig2),sig1frac) bkgfrac = RooRealVar("bkgfrac","fraction of background",0.5,0.,1.) model = RooAddPdf("model","g1+g2+a",RooArgList(bkg,sig),bkgfrac) print ">>> create binned dataset..." data = model.generate(RooArgSet(x),10000) # RooDataSet hist = data.binnedClone() # RooDataHist # Construct a chi^2 of the data and the model. # When a p.d.f. is used in a chi^2 fit, the probability density scaled # by the number of events in the dataset to obtain the fit function # If model is an extended p.d.f, the expected number events is used # instead of the observed number of events. model.chi2FitTo(hist) # NB: It is also possible to fit a RooAbsReal function to a RooDataHist # using chi2FitTo(). # Note that entries with zero bins are _not_ allowed # for a proper chi^2 calculation and will give error # messages data_small = date.reduce(EventRange(1,100)) # RooDataSet hist_small = data_small.binnedClone() # RooDataHist chi2_lowstat("chi2_lowstat","chi2",model,hist_small) print ">>> chi2_lowstat.getVal() = %s" % chi2_lowstat.getVal()
def build_pdf(): lower = -1 upper = 1 # create observables obs = RooRealVar("obs", "obs1", lower, upper) # create parameters mean1 = RooRealVar("mean1", "mean of gaussian", 0, -1, 1) sigma1 = RooRealVar("sigma1", "sigma of gaussian", 0.1, -1, 1) gauss1 = RooGaussian("gauss1", "gaussian PDF", obs, mean1, sigma1) mean2 = RooRealVar("mean2", "mean of gaussian", 0.5, -1, 1) sigma2 = RooRealVar("sigma2", "sigma of gaussian", 0.2, -1, 1) gauss2 = RooGaussian("gauss2", "gaussian PDF", obs, mean2, sigma2) mean3 = RooRealVar("mean3", "mean of gaussian", 0.5, -1, 1) sigma3 = RooRealVar("sigma3", "sigma of gaussian", 0.3, -1, 1) gauss3 = RooGaussian("gauss3", "gaussian PDF", obs, mean3, sigma3) mean4 = RooRealVar("mean4", "mean of gaussian", 0.5, -1, 1) sigma4 = RooRealVar("sigma4", "sigma of gaussian", 0.4, -1, 1) gauss4 = RooGaussian("gauss4", "gaussian PDF", obs, mean4, sigma4) mean5 = RooRealVar("mean5", "mean of gaussian", 0.5, -1, 1) sigma5 = RooRealVar("sigma5", "sigma of gaussian", 0.5, -1, 1) gauss5 = RooGaussian("gauss5", "gaussian PDF", obs, mean5, sigma5) frac1 = RooRealVar("frac", "Fraction of a gauss", 0.5, 0, 1) frac2 = RooRealVar("frac", "Fraction of a gauss", 0.5, 0, 1) frac3 = RooRealVar("frac", "Fraction of a gauss", 0.5, 0, 1) frac4 = RooRealVar("frac", "Fraction of a gauss", 0.5, 0, 1) model = RooAddPdf( "sum_pdf", "sum of pdfs", RooArgList(RooArgList(gauss1, gauss2), RooArgList(gauss3, gauss4, gauss5)), RooArgList(frac1, frac2, frac3, frac4)) return obs, model
def test_plottable(): # construct pdf and toy data following example at # http://root.cern.ch/drupal/content/roofit # Observable mes = RooRealVar("mes", "m_{ES} (GeV)", 5.20, 5.30) # Parameters sigmean = RooRealVar("sigmean", "B^{#pm} mass", 5.28, 5.20, 5.30) sigwidth = RooRealVar("sigwidth", "B^{#pm} width", 0.0027, 0.001, 1.) # Build Gaussian PDF signal = RooGaussian("signal", "signal PDF", mes, sigmean, sigwidth) # Build Argus background PDF argpar = RooRealVar("argpar", "argus shape parameter", -20.0, -100., -1.) background = RooArgusBG("background", "Argus PDF", mes, RooFit.RooConst(5.291), argpar) # Construct signal+background PDF nsig = RooRealVar("nsig", "#signal events", 200, 0., 10000) nbkg = RooRealVar("nbkg", "#background events", 800, 0., 10000) model = RooAddPdf("model", "g+a", RooArgList(signal, background), RooArgList(nsig, nbkg)) # Generate a toyMC sample from composite PDF data = model.generate(RooArgSet(mes), 2000) # Perform extended ML fit of composite PDF to toy data fitresult = model.fitTo(data, RooFit.Save(), RooFit.PrintLevel(-1)) # Plot toy data and composite PDF overlaid mesframe = asrootpy(mes.frame()) data.plotOn(mesframe) model.plotOn(mesframe) for obj in mesframe.objects: assert_true(obj) for curve in mesframe.curves: assert_true(curve) for hist in mesframe.data_hists: assert_true(hist) assert_true(mesframe.plotvar) with TemporaryFile(): mesframe.Write()
class Test_lhcb: def setUp(self): from e5.lhcb.util import setup_roofit, silence_roofit setup_roofit() silence_roofit() from ROOT import RooArgSet, RooGaussian, RooRealVar self.x = RooRealVar('x', 'x', -10, 10) self.mean = RooRealVar('mean', 'mean', 1, -10, 10) self.sigma = RooRealVar('sigma', 'sigma', 1, 0, 10) self.model = RooGaussian('model', 'model', self.x, self.mean, self.sigma) self.data = self.model.generate(RooArgSet(self.x), 1000) def test_max_ap(self): from e5.lhcb.fit import max_ap max_ap(self.model, self.data) def test_assemble_model(self): from e5.lhcb.model import assemble_model w = assemble_model(os.path.dirname(__file__) + '/../testdata/test.model') assert w def test_save_dataset(self): from e5.lhcb.util import save_dataset #from lhcb.fit import load_dataset save_dataset(self.data, 'mytest.root') assert os.path.exists('mytest.root') os.remove('mytest.root') def test_get_cmdline_parser(self): from e5.lhcb.config import get_cmdline_parser parser = get_cmdline_parser() args = parser.parse_args('show --graph model test.model'.split()) def test_get_named_section(self): from e5.lhcb.config import get_config, get_named_section config = get_config(os.path.dirname(__file__) + '/../testdata/test.cfg') assert bool(get_named_section(config, 'named', 'first')) def test_add_weights(self): from e5.lhcb.fit import add_weights sigData, bkgData = add_weights(self.model, self.data, ['sigN', 'bkgN']) assert sigData assert bkgData
def rooFit207(): print ">>> setup model signal components: gaussians..." x = RooRealVar("x","x",0,10) mean = RooRealVar("mean","mean of gaussians",5) sigma = RooRealVar("sigma","width of gaussians",0.5) sig = RooGaussian("sig","Signal",x,mean,sigma) 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)) # Create dummy dataset that has more observables than the above pdf y = RooRealVar("y","y",-10,10) data = RooDataSet("data","data",RooArgSet(x,y)) # Basic information requests:" print ">>> get list of observables of pdf in context of a dataset..." # Observables are define each context as the variables # shared between a model and a dataset. In this case # that is the variable 'x' model_obs = model.getObservables(data) # RooArgSet model_obs.Print('v') print "\n>>> get list of parameters..." # Get list of parameters, given list of observables model_params = model.getParameters(RooArgSet(x)) # RooArgSet print ">>> model_params.getStringValue(\"a0\") = %s" % (model_params.getStringValue("a0")) print ">>> model_params.getRealValue(\"a0\") = %s" % (model_params.getRealValue("a0")) print ">>> model_params.find(\"a0\").GetName() = %s" % (model_params.find("a0").GetName()) print ">>> model_params.find(\"a0\").getVal() = %s" % (model_params.find("a0").getVal()) # print ">>> for param in model_params:" # for param in model_params.(): # print ">>> %s"%(model_params.first()) # print ">>> %s"%(model_params.first()) # model_params.selectByName("a*").Print('v') model_params.Print('v') print "\n>>> get list of parameters of a dataset..." # Gives identical results to operation above model_params2 = model.getParameters(data) # RooArgSet model_params2.Print() print "\n>>> get list of components..." # Get list of component objects, including top-level node model_comps = model.getComponents() # RooArgSet model_comps.Print('v') print "\n>>> modifications to structure of composites..." sigma2 = RooRealVar("sigma2","width of gaussians",1) sig2 = RooGaussian("sig2","Signal component 1",x,mean,sigma2) sig1frac = RooRealVar("sig1frac","fraction of component 1 in signal",0.8,0.,1.) sigsum = RooAddPdf("sigsum","sig+sig2",RooArgList(sig,sig2),RooArgList(sig1frac)) print ">>> construct a customizer utility to customize model..." cust = RooCustomizer(model,"cust") print ">>> instruct the customizer to replace node 'sig' with node 'sigsum'..." cust.replaceArg(sig,sigsum) # Build a clone of the input pdf according to the above customization # instructions. Each node that requires modified is clone so that the # original pdf remained untouched. The name of each cloned node is that # of the original node suffixed by the name of the customizer object # # The returned head node own all nodes that were cloned as part of # the build process so when cust_clone is deleted so will all other # nodes that were created in the process. cust_clone = cust.build(kTRUE) # RooAbsPdf # Print structure of clone of model with sig->sigsum replacement. cust_clone.Print("t") # delete clone del cust_clone
a1 = RooRealVar("a1","a1",0.001,-0.5,0.5) a2 = RooRealVar("a2","a2",-0.00001,-2.,2.) a3 = RooRealVar("a3","a3",-0.000001,-0.1,0.1) a4 = RooRealVar("a4","a4",0.0,-0.1,0.1) a5 = RooRealVar("a5","a5",0.0,-0.025,0.05) a6 = RooRealVar("a6","a6",0.0,-0.001,0.001) aset = RooArgList(a0,a1,a2,a3,a4,a5) sFrac = RooRealVar("sFrac","sFrac",0.5,0.,1.0) # In[8]: cheb = RooChebychev("cheb","Background",mass,aset) gauss = RooGaussian("gauss","gaussian PDF ",mass,mean,sigma) tot = RooAddPdf("tot","g+cheb",gauss,cheb,sFrac) # In[9]: masslist = RooArgList(mass) dh = RooDataHist("dh","dh",masslist,hist) numEvts = dh.sum(False) print numEvts # In[10]:
def rf101_basics(): # S e t u p m o d e l # --------------------- # Declare variables x,mean,sigma with associated name, title, initial value and allowed range 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) # Build gaussian p.d.f in terms of x,mean and sigma gauss = RooGaussian("gauss","gaussian PDF",x,mean,sigma) # Construct plot frame in 'x' xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) # P l o t m o d e l a n d c h a n g e p a r a m e t e r v a l u e s # --------------------------------------------------------------------------- # Plot gauss in frame (i.e. in x) gauss.plotOn(xframe) # Change the value of sigma to 3 sigma.setVal(3) # Plot gauss in frame (i.e. in x) and draw frame on canvas gauss.plotOn(xframe,RooFit.LineColor(kRed)) # G e n e r a t e e v e n t s # ----------------------------- # Generate a dataset of 1000 events in x from gauss data = gauss.generate(RooArgSet(x),10000.) # Make a second plot frame in x and draw both the # data and the p.d.f in the frame xframe2 = x.frame(RooFit.Title("Gaussian p.d.f. with data")) data.plotOn(xframe2) gauss.plotOn(xframe2) # F i t m o d e l t o d a t a # ----------------------------- # Fit pdf to data gauss.fitTo(data) # Print values of mean and sigma (that now reflect fitted values and errors) mean.Print() sigma.Print() # Draw all frames on a canvas c = TCanvas("rf101_basics","rf101_basics",800,400) c.Divide(2) c.cd(1) gPad.SetLeftMargin(0.15) xframe.GetYaxis().SetTitleOffset(1.6) xframe.Draw() c.cd(2) gPad.SetLeftMargin(0.15) xframe2.GetYaxis().SetTitleOffset(1.6) xframe2.Draw() raw_input()
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) # RooRealVar x("x","x",-10,10) ; # RooRealVar mean("mean","mean of gaussian",1,-10,10) ; # RooRealVar sigma("sigma","width of gaussian",1,0.1,10) ; #//cout<<"test"<< endl; #// mean.Print() ; #// sigma.Print() ; # // Build gaussian p.d.f in terms of x,mean and sigma # RooGaussian gauss("gauss","gaussian PDF",x,mean,sigma) ; gauss = RooGaussian("gauss","gaussian PDF",x,mean,sigma) # // Construct plot frame in 'x' # RooPlot* xframe = x.frame(Title("Gaussian p.d.f.")) ; xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) # // P l o t m o d e l a n d c h a n g e p a r a m e t e r v a l u e s # // --------------------------------------------------------------------------- # // Plot gauss in frame (i.e. in x) gauss.plotOn(xframe) ; # // Change the value of sigma to 3 sigma.setVal(3) ;
# Parameters 1 mean = RooRealVar( 'mean', 'mean', 1000.0 ) sigma = RooRealVar( 'sigma', 'width of gaussian', 15.0 ) alpha = RooRealVar( 'alpha', 'alpha', -2.5) beta = RooRealVar( 'beta', 'beta', 0.5) n1 = RooRealVar( 'n1', 'n1', 1.0) n2 = RooRealVar( 'n2', 'n2', 1.0) # Parameters 2 mean2 = RooRealVar( 'mean2', 'mean of gaussian', 1000.0 ) sigma2 = RooRealVar( 'sigma2', 'width of gaussian', 15.0 ) p1 = RooDoubleCBShape( 'double_crystal_ball', 'PDF', \ x, mean, sigma, alpha, beta, n1, n2) p2 = RooGaussian( 'gauss1', 'gaussian PDF', \ x, mean2, sigma2 ) pdf = p1 #pdf = RooPdfAdd("pdf", 'convolution', x, p2, p1) # Plot PDF canvas = TCanvas("c1","",1200,480); canvas.Divide(3,1); canvas.cd(1) xframe = x.frame() p1.plotOn( xframe ) xframe.Draw() gPad.SetLogy()
print "" """ # ------------------------------------------- # 7. use ext PDF to fit SB only and plot xframe7 = x.frame(RooFit.Title("7. use ext PDF to fit SB only and plot")) # gauss 10 mean10 = RooRealVar("mean10","mean of gaussian",3,-10,10) sigma10 = RooRealVar("sigma10","width of gaussian",2,0.1,10) gauss10 = RooGaussian("gauss10","gaussian PDF",x,mean10,sigma10) # generate to MC data3 = gauss10.generate(RooArgSet(x),1000) # split to half dataset data3_half = RooDataSet("data3_half", "data3 half", RooArgSet(x), RooFit.Import( data3 ), RooFit.Cut("x<3") ) # set range x.setRange("whole_range",-10 ,10 ) x.setRange("right_gaussian_range",3 ,10 ) x.setRange("left_gaussian_range",-10 ,3 ) # another PDF gauss 11 mean11 = RooRealVar("mean11","mean of gaussian",2,-10,10)
parser.add_option("-b", "--bash", action="store_true", default=False, dest="bash") (options, args) = parser.parse_args() if options.bash: gROOT.SetBatch(True) # ------------------------------------------- # 1. gau1 generate toy MC, use gau2 to fit x = RooRealVar("x","x",-10,10) xframe1 = x.frame(RooFit.Title("1. use gauss1 generate toy MC, use gauss2 to fit")) # gauss1 mean1 = RooRealVar("mean1","mean of gaussian",2,-10,10) sigma1 = RooRealVar("sigma1","width of gaussian",2,0.1,10) gauss1 = RooGaussian("gauss1","gaussian PDF",x,mean1,sigma1) # generate toy MC data1 = gauss1.generate(RooArgSet(x),500) data1.plotOn(xframe1) gauss1.plotOn(xframe1) #gauss1.plotOn(xframe1, RooFit.Normalization(500, RooAbsReal.NumEvent) , RooFit.LineColor(RooFit.kGreen)) # gauss2 mean2 = RooRealVar("mean2","mean of gaussian",0,-10,10) sigma2 = RooRealVar("sigma2","width of gaussian",1,0.1,10) gauss2 = RooGaussian("gauss2","gaussian PDF",x,mean2,sigma2)
m[2][2] = 5.4 print m[2][2] # ------------------------------------------------- # use Gaussian to generate toy MC x = RooRealVar("x","x",-10,10) xframe = x.frame(RooFit.Title("Gaussian p.d.f.")) mean1 = RooRealVar("mean1","mean of gaussian",2,-10,10) sigma1 = RooRealVar("sigma1","width of gaussian",1,0.1,10) mean1.setConstant(True) sigma1.setConstant(True) gauss1 = RooGaussian("gauss1","gaussian PDF",x,mean1,sigma1) data = gauss1.generate(RooArgSet(x),1000) data.plotOn(xframe) gauss1.plotOn(xframe,RooFit.LineColor(4)) # ------------------------------------------------- # use another Gaussian to fit toy MC mean2 = RooRealVar("mean2","mean of gaussian",2,-10,10) sigma2 = RooRealVar("sigma2","width of gaussian",1,0.1,10) gauss2 = RooGaussian("gauss2","gaussian PDF",x,mean2,sigma2) fit_result = gauss2.fitTo(data, RooFit.SumW2Error(True), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.Save(1), RooFit.PrintLevel(1))