def generateBkg(tagged_mass, ibin, n_bkg): slope = RooRealVar("slope", "slope", -4.2) bkg_exp = RooExponential("bkg_exp", "exponential", slope, tagged_mass) pol_c1 = RooRealVar("p1", "coeff x^0 term", -1.2) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.3) bkg_pol = RooChebychev("bkg_pol", "2nd order pol", tagged_mass, RooArgList(pol_c1, pol_c2)) n_togen = np.random.poisson(n_bin[ibin] * n_bkg, 1) toybkg = bkg_pol.generate(RooArgSet(tagged_mass), n_togen[0]) return toybkg
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 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 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 fitMC(fulldata, correctTag, ibin): print 'now fitting: ', ibin, ' for ', correctTag * 'correctTag ', ( 1 - correctTag) * 'wrongTag' cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % ( q2binning[ibin], q2binning[ibin + 1]) data = fulldata.reduce(RooArgSet(thevarsMC), cut) pol_c1 = RooRealVar("p1", "coeff x^0 term", -0.5, -10, 10) bkg_pol = RooChebychev("bkg_pol", "bkg_pol", tagged_mass, RooArgList(pol_c1)) signalFunction = bkg_pol ### just a placeholder nsig = RooRealVar("Yield", "nsig", 10000, 0, 1000000) nbkg = RooRealVar("nbkg", "nbkg", 10, 0, 100000) doextended = False fitrange = "mcrange" nbins = 70 if correctTag: doubleG(B0Mass_, initial_sigma1, initial_sigma2, 0.8, tagged_mass, w, "RT%s" % ibin) ## (mean_ , sigma1_, sigma2_, f1_) signalFunction = w.pdf("doublegaus_RT%s" % ibin) fitFunction = RooAddPdf("fitfunction", "fit function", RooArgList(signalFunction, bkg_pol), RooArgList(nsig, nbkg)) doextended = True fitrange = "full" nbins = 60 else: mean = RooRealVar("mean^{WT%s}" % ibin, "massWT", B0Mass_, 5, 6, "GeV") sigmaCB = RooRealVar("#sigma_{CB}^{WT%s}" % ibin, "sigmaCB", 0.03, 0, 1) alpha1 = RooRealVar("#alpha_{1}^{WT%s}" % ibin, "#alpha_{1}", 0.5, 0, 10) alpha2 = RooRealVar("#alpha_{2}^{WT%s}" % ibin, "#alpha_{2}", 0.5, 0, 10) n1 = RooRealVar("n_{1}^{WT%s}" % ibin, "n_1", 2, 0, 90) n2 = RooRealVar("n_{2}^{WT%s}" % ibin, "n_2", 1, 0, 90) doublecb = ROOT.RooDoubleCBFast("doublecb_%s" % ibin, "doublecb", tagged_mass, mean, sigmaCB, alpha1, n1, alpha2, n2) # getattr(w, 'import')(doublecb) signalFunction = doublecb fitFunction = doublecb getattr(w, "import")(signalFunction) r = fitFunction.fitTo(data, RooFit.Extended(doextended), RooFit.Save(), RooFit.Range(fitrange)) print 'fit status: ', r.status(), r.covQual() if not _goodFit(r): r = fitFunction.fitTo(data, RooFit.Extended(doextended), RooFit.Save(), RooFit.Range(fitrange)) print 'fit status (redo): ', r.status(), r.covQual() if not _goodFit(r) and correctTag: r = fitFunction.fitTo(data, RooFit.Extended(doextended), RooFit.Save(), RooFit.Range(fitrange)) print 'fit status (redo2): ', r.status(), r.covQual() params = signalFunction.getParameters(RooArgSet(tagged_mass)) w.saveSnapshot( "reference_fit_%s_%s" % ('RT' * correctTag + 'WT' * (1 - correctTag), ibin), params, ROOT.kTRUE) frame = tagged_mass.frame(RooFit.Range(fitrange)) data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7)) drawPdfComponents(fitFunction, frame, ROOT.kGreen if correctTag else ROOT.kViolet, RooFit.NormRange(fitrange), RooFit.Range(fitrange), isData=False) fitFunction.plotOn(frame, RooFit.NormRange(fitrange), RooFit.Range(fitrange)) fitFunction.paramOn(frame, RooFit.Layout(0.62, 0.86, 0.88)) frame.Draw() niceFrame(frame, '') frame.addObject(_writeFitStatus(r)) ## evaluate sort of chi2 and save number of RT/WT events observables = RooArgSet(tagged_mass) flparams = fitFunction.getParameters(observables) nparam = int(flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize()) if correctTag: frame.addObject( _writeChi2( frame.chiSquare( "fitfunction_Norm[tagged_mass]_Range[full]_NormRange[full]", "h_fullmc", nparam))) dict_s_rt[ibin] = _getFittedVar(nsig) nRT = RooRealVar("nRT_%s" % ibin, "yield of RT signal", 0, 1.E6) nRT.setVal(dict_s_rt[ibin].n) nRT.setError(dict_s_rt[ibin].s) getattr(w, "import")(nRT) else: frame.addObject( _writeChi2( frame.chiSquare( "doublecb_%s_Norm[tagged_mass]_Comp[doublecb_%s]_Range[mcrange]_NormRange[mcrange]" % (ibin, ibin), "h_fullmc", nparam))) dict_s_wt[ibin] = ufloat(data.sumEntries(), math.sqrt(data.sumEntries())) nWT = RooRealVar("nWT_%s" % ibin, "yield of WT signal", 0, 1.E6) nWT.setVal(dict_s_wt[ibin].n) nWT.setError(dict_s_wt[ibin].s) getattr(w, "import")(nWT) # chi2 = frame.chiSquare("doublecb_%s_Norm[tagged_mass]_Comp[doublecb_%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin), "h_fullmc", nparam) # if chi2 == -1: # chi2 = frame.chiSquare("gauscb_%s_Norm[tagged_mass]_Comp[gauscb_%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin), "h_fullmc", nparam) # frame. addObject(_writeChi2( chi2 ) ) frame.Draw() frame.SetTitle('correctly' * correctTag + 'wrongly' * (1 - correctTag) + ' tagged events') # c1.SetLogy() c1.SaveAs('fit_results_mass/save_fit_mc_%s_%s_%sT_newCB.pdf' % (ibin, args.year, "R" * correctTag + "W" * (1 - correctTag))) out_f.cd() r.Write('results_%s_%s' % (correctTag * 'RT' + (1 - correctTag) * 'WT', ibin))
sigma = RooRealVar("#sigma", "sigma", 0.028, 0, 10, "GeV") signalGauss = RooGaussian("signalGauss", "signal gauss", theBMass, mean, sigma) sigma2 = RooRealVar("#sigma2", "sigma2", 0.048, 0, 0.07, "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, pol_c2)) nsig = RooRealVar("Yield", "signal frac", 4000, 0, 10000) nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 55000) fitFunction = RooAddPdf("fitfunction", "fit function", RooArgList(signalGauss, bkg_pol), RooArgList(nsig, nbkg)) r = fitFunction.fitTo(data, RooFit.Extended(True), RooFit.Save(), RooFit.Range(4.9, 5.6)) # r = fitFunction.fitTo(data, RooFit.Extended(True), RooFit.Save())#, RooFit.Range(B0Mass_-0.28, B0Mass_+0.28)) frame = theBMass.frame() data.plotOn(frame, RooFit.Binning(75), RooFit.MarkerSize(.5)) fitFunction.plotOn(frame, )
from ROOT import RooRealVar, RooGaussian, RooChebychev, RooAddPdf, RooArgList, RooArgSet, RooFit x = RooRealVar("x", "x", -1, 1) # Use RooGaussian in the generation mean = RooRealVar("mean", "mean of gaussian", 0, -1, 1) sigma = RooRealVar("sigma", "sigma of gaussian", 0.1, -1, 1) sig = RooGaussian("gauss", "gaussian PDF", x, mean, sigma) # Background a0 = RooRealVar("a0", "a0", 0.5, 0., 1.) a1 = RooRealVar("a1", "a1", -0.2, 0., 1.) bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1)) bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.) model = RooAddPdf("model", "g+a", RooArgList(bkg, sig), RooArgList(bkgfrac)) data = model.generate(RooArgSet(x), 10000) model.fitTo(data)
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")
def fit_gau2_che(var, dataset, title='', print_pars=False, test=False, mean_=None, sigma_=None, sigma1_=None, sigmaFraction_=None): # define background c0 = RooRealVar('c0', 'constant', 0.1, -1, 1) c1 = RooRealVar('c1', 'linear', 0.6, -1, 1) c2 = RooRealVar('c2', 'quadratic', 0.1, -1, 1) c3 = RooRealVar('c3', 'c3', 0.1, -1, 1) bkg = RooChebychev('bkg', 'background pdf', var, RooArgList(c0, c1, c2, c3)) # define signal val = 5.28 dmean = 0.05 valL = val - dmean valR = val + dmean if mean_ is None: mean = RooRealVar("mean", "mean", val, valL, valR) else: mean = RooRealVar("mean", "mean", mean_) val = 0.05 dmean = 0.02 valL = val - dmean valR = val + dmean if sigma_ is None: sigma = RooRealVar('sigma', 'sigma', val, valL, valR) else: sigma = RooRealVar('sigma', 'sigma', sigma_) if sigma1_ is None: sigma1 = RooRealVar('sigma1', 'sigma1', val, valL, valR) else: sigma1 = RooRealVar('sigma1', 'sigma1', sigma1_) peakGaus = RooGaussian("peakGaus", "peakGaus", var, mean, sigma) peakGaus1 = RooGaussian("peakGaus1", "peakGaus1", var, mean, sigma1) if sigmaFraction_ is None: sigmaFraction = RooRealVar("sigmaFraction", "Sigma Fraction", 0.5, 0., 1.) else: sigmaFraction = RooRealVar("sigmaFraction", "Sigma Fraction", sigmaFraction_) glist = RooArgList(peakGaus, peakGaus1) peakG = RooAddPdf("peakG", "peakG", glist, RooArgList(sigmaFraction)) listPeak = RooArgList("listPeak") listPeak.add(peakG) listPeak.add(bkg) fbkg = 0.45 nEntries = dataset.numEntries() val = (1 - fbkg) * nEntries listArea = RooArgList("listArea") areaPeak = RooRealVar("areaPeak", "areaPeak", val, 0., nEntries) listArea.add(areaPeak) nBkg = fbkg * nEntries areaBkg = RooRealVar("areaBkg", "areaBkg", nBkg, 0., nEntries) listArea.add(areaBkg) model = RooAddPdf("model", "fit model", listPeak, listArea) if not test: fitres = model.fitTo(dataset, RooFit.Extended(kTRUE), RooFit.Minos(kTRUE), RooFit.Save(kTRUE)) nbins = 35 frame = var.frame(nbins) frame.GetXaxis().SetTitle("B^{0} mass (GeV/c^{2})") frame.GetXaxis().CenterTitle() frame.GetYaxis().CenterTitle() frame.SetTitle(title) mk_size = RooFit.MarkerSize(0.3) mk_style = RooFit.MarkerStyle(kFullCircle) dataset.plotOn(frame, mk_size, mk_style) model.plotOn(frame) as_bkg = RooArgSet(bkg) cp_bkg = RooFit.Components(as_bkg) line_style = RooFit.LineStyle(kDashed) model.plotOn(frame, cp_bkg, line_style) if print_pars: fmt = RooFit.Format('NEU') lyt = RooFit.Layout(0.65, 0.95, 0.92) param = model.paramOn(frame, fmt, lyt) param.getAttText().SetTextSize(0.02) param.getAttText().SetTextFont(60) frame.Draw() pars = [ areaBkg, areaPeak, c0, c1, c2, c3, mean, sigma, sigma1, sigmaFraction ] return pars
def rooFit205(): print ">>> setup model signal components: gaussians..." x = RooRealVar("x", "x", 0, 10) mean = RooRealVar("mean", "mean of gaussians", 5) sigma1 = RooRealVar("sigma1", "width of gaussians", 0.5) sigma2 = RooRealVar("sigma2", "width of gaussians", 1) sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1) sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2) sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.) sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2), RooArgList(sig1frac)) print ">>> setup model background components: Chebychev polynomial plus exponential..." a0 = RooRealVar("a0", "a0", 0.5, 0., 1.) a1 = RooRealVar("a1", "a1", -0.2, 0., 1.) bkg1 = RooChebychev("bkg1", "Background 1", x, RooArgList(a0, a1)) alpha = RooRealVar("alpha", "alpha", -1) bkg2 = RooExponential("bkg2", "Background 2", x, alpha) bkg1frac = RooRealVar("bkg1frac", "fraction of component 1 in background", 0.2, 0., 1.) bkg = RooAddPdf("bkg", "Signal", RooArgList(bkg1, bkg2), RooArgList(bkg1frac)) print ">>> sum signal and background component..." bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.) model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig), RooArgList(bkgfrac)) print ">>> setup basic plot with data and full pdf..." data = model.generate(RooArgSet(x), 1000) # RooDataSet frame1 = x.frame( Title("Component plotting of pdf=(sig1+sig2)+(bkg1+bkg2)")) # RooPlot data.plotOn(frame1, Name("data")) model.plotOn(frame1, Name("model")) print ">>> clone frame for reuse..." frame2 = frame1.Clone("frame2") # RooPlot frame2.SetTitle("Get components with regular expressions") print ">>> make omponent by object reference..." # Plot multiple background components specified by object reference # Note that specified components may occur at any level in object tree # (e.g bkg is component of 'model' and 'sig2' is component 'sig') argset1 = RooArgSet(bkg) argset2 = RooArgSet(bkg2) argset3 = RooArgSet(bkg, sig2) model.plotOn(frame1, Components(argset1), LineColor(kRed), Name("bkgs1")) model.plotOn(frame1, Components(argset2), LineStyle(kDashed), LineColor(kRed), Name("bkg2")) model.plotOn(frame1, Components(argset3), LineStyle(kDotted), Name("bkgssig21")) print "\n>>> make component by name / regular expressions..." model.plotOn(frame2, Components("bkg"), LineColor(kAzure - 4), Name("bkgs2")) # by name model.plotOn(frame2, Components("bkg1,sig2"), LineColor(kAzure - 4), LineStyle(kDotted), Name("bkg1sig22")) # by name model.plotOn(frame2, Components("sig*"), LineColor(kAzure - 4), LineStyle(kDashed), Name("sigs2")) # with regexp (wildcard *) model.plotOn(frame2, Components("bkg1,sig*"), LineColor(kYellow), LineStyle(kDashed), Name("bkg1sigs2")) # with regexp (,) #Invisible() print "\n>>> draw pfds and fits on canvas..." canvas = TCanvas("canvas", "canvas", 100, 100, 1400, 600) legend1 = TLegend(0.22, 0.85, 0.4, 0.65) legend2 = TLegend(0.22, 0.85, 0.4, 0.65) for legend in [legend1, legend2]: legend.SetTextSize(0.032) legend.SetBorderSize(0) legend.SetFillStyle(0) canvas.Divide(2) canvas.cd(1) gPad.SetLeftMargin(0.15) gPad.SetRightMargin(0.02) frame1.GetYaxis().SetLabelOffset(0.008) frame1.GetYaxis().SetTitleOffset(1.6) frame1.GetYaxis().SetTitleSize(0.045) frame1.GetXaxis().SetTitleSize(0.045) frame1.Draw() legend1.AddEntry("data", "data", 'LEP') legend1.AddEntry("model", "model", 'L') legend1.AddEntry("bkgs1", "bkg", 'L') legend1.AddEntry("bkg2", "bkg2", 'L') legend1.AddEntry("bkgssig21", "bkg,sig2", 'L') legend1.Draw() canvas.cd(2) gPad.SetLeftMargin(0.15) gPad.SetRightMargin(0.02) frame2.GetYaxis().SetLabelOffset(0.008) frame2.GetYaxis().SetTitleOffset(1.6) frame2.GetYaxis().SetTitleSize(0.045) frame2.GetXaxis().SetTitleSize(0.045) frame2.Draw() legend2.AddEntry("data", "data", 'LEP') legend2.AddEntry("model", "model", 'L') legend2.AddEntry("bkgs2", "\"bkg\"", 'L') legend2.AddEntry("bkg1sig22", "\"bkg1,sig2\"", 'L') legend2.AddEntry("sigs2", "\"sig*\"", 'L') legend2.AddEntry("bkg1sigs2", "\"bkg1,sig*\"", 'L') legend2.Draw() canvas.SaveAs("rooFit205.png")
def mbc_gau_che(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa, fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2, title1, title2, epsfile, txtfile, ymin=0.5, cuts=None, err_type='SYMM', test=False): from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet, RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous, RooArgusBG, RooFormulaVar, RooChebychev, RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta, TPaveText) set_root_style(stat=1, grid=0) mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV') ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV') dflav = RooCategory('dflav', 'D0 flavor') dflav.defineType('dflav', 1) dflav.defineType('dbarflav', -1) if cuts != None: if 'kkmass' in cuts: kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV') ras = RooArgSet(mbc, ebeam, kkmass, dflav) dataset = RooDataSet.read(evtfile, ras) elif 'kpimass' in cuts: kpimass = RooRealVar('kpimass', 'Kpi invariant mass', 0.6, 1.4, 'GeV') ras = RooArgSet(mbc, ebeam, kpimass, dflav) dataset = RooDataSet.read(evtfile, ras) else: raise NameError(cuts) sys.stdout.write('Using cuts: %s...' % cuts) dataset = dataset.reduce(cuts) sys.stdout.write(' selected %s events.\n' % dataset.numEntries()) else: ras = RooArgSet(mbc, ebeam, dflav) dataset = RooDataSet.read(evtfile, ras) #sigma = RooRealVar('sigma', 'D width', 0.0001, 0.005, 'GeV') sigma = RooRealVar('sigma', 'D width', 0.00468, 'GeV') mbc_dp = RooRealVar('mbc_dp', 'D+ Mass', 1.86962, 'GeV') sigpdf = RooGaussian('gauss_dp', 'D+ gaussian', mbc, mbc_dp, sigma) #arg_cutoff = RooRealVar('arg_cutoff', 'Argus cutoff', 1.88, 1.89, 'GeV') #arg_slope = RooRealVar('arg_slope', 'Argus slope', -10, -100, -1) #bkgpdf = RooArgusBG('argus', 'Argus BG', mbc, arg_cutoff, arg_slope) con0 = RooRealVar('c0', 'constant', -1, 1) con1 = RooRealVar('c1', 'linear', -10, 10) con2 = RooRealVar('c2', 'quadratic', 1) bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2)) yld = RooRealVar('yld', 'D yield', 100, 0, 2000) bkg = RooRealVar('bkg', 'Background', 100, 0, 1000) sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf), RooArgList(yld, bkg)) yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000) bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000) sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigpdf, bkgpdf), RooArgList(yldbar, bkgbar)) totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav) totalpdf.addPdf(sumpdf, 'dflav') totalpdf.addPdf(sumpdfbar, 'dbarflav') MINUIT = 'ermh4' if err_type == 'ASYM': MINUIT = 'erh4' if test: sys.stdout.write('Will save epsfile as: %s \n' % epsfile) sys.stdout.write('Will save txtfile as: %s \n' % txtfile) return if dataset.numEntries() == 0: yld.setVal(0) yldbar.setVal(0) else: # Start Fitting fitres = totalpdf.fitTo(dataset, MINUIT) fitres.Print('v') # Save plots canvas = TCanvas('canvas', 'mbc', 400, 400) xframe = mbc.frame(50) ProjWData = RooFit.ProjWData(dataset) RooAbsData.plotOn(dataset, xframe) totalpdf.plotOn(xframe, ProjWData) totalpdf.paramOn(xframe) xframe.Draw() canvas.Print(epsfile) # Save fitting parameters pars = [bkg, bkgbar, con1, yld, yldbar] save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
def fitMC(fulldata, correctTag, ibin): print 'now fitting: ', ibin, ' for ', correctTag * 'correctTag ', ( 1 - correctTag) * 'wrongTag' cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % ( q2binning[ibin], q2binning[ibin + 1]) data = fulldata.reduce(RooArgSet(thevarsMC), cut) pol_c1 = RooRealVar("p1", "coeff x^0 term", -0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^0 term", 0.5, -10, 10) bkg_pol = RooChebychev("bkg_pol", "bkg_pol", tagged_mass, RooArgList(pol_c1)) signalFunction = bkg_pol ### just a placeholder nsig = RooRealVar("Yield", "nsig", 500000, 0, 1E7) nbkg = RooRealVar("nbkg", "nbkg", 1000, 0, 1E6) doextended = False fitrange = "mcrange" tag = 'RT' if correctTag else 'WT' if correctTag: ### double CB, 1 sigma mean = RooRealVar("mean_{RT}^{%s}" % ibin, "massRT", B0Mass_, 5, 6, "GeV") if ibin < 5: sigmaCB = RooRealVar("#sigma_{RT1}^{%s}" % ibin, "sigmaCB", 0.03, 0, 1) alpha1 = RooRealVar("#alpha_{RT1}^{%s}" % ibin, "#alpha_{1}", 0.5, 0, 10) alpha2 = RooRealVar("#alpha_{RT2}^{%s}" % ibin, "#alpha_{2}", 2.5, 0, 10) n1 = RooRealVar("n_{RT1}^{%s}" % ibin, "n_1", 1, 0, 20) n2 = RooRealVar("n_{RT2}^{%s}" % ibin, "n_2", 1, 0, 30) doublecb = ROOT.RooDoubleCBFast("doublecb_RT%s" % ibin, "doublecb", tagged_mass, mean, sigmaCB, alpha1, n1, alpha2, n2) signalFunction = doublecb else: ### double CB, 2 sigmas # mean = RooRealVar ("mean^{RT}"%ibin, "massRT" , B0Mass_ , 5, 6, "GeV") crystalBall(mean, initial_sigma1, 1.5, 1, tagged_mass, w, 'RT1', ibin, [0, 10]) crystalBall(mean, initial_sigma2, -2, 1, tagged_mass, w, 'RT2', ibin, [-10, 0]) doubleCB(w.pdf("cbshape_RT1_%s" % (ibin)), w.pdf("cbshape_RT2_%s" % ibin), 0.8, tagged_mass, w, "RT%s" % ibin) signalFunction = w.pdf("doublecb_RT%s" % ibin) fitFunction = signalFunction else: mean = RooRealVar("mean_{WT}^{%s}" % ibin, "massWT", B0Mass_, 5, 6, "GeV") sigmaCB = RooRealVar("#sigma_{WT1}^{%s}" % ibin, "sigmaCB", 0.03, 0, 1) alpha1 = RooRealVar("#alpha_{WT1}^{%s}" % ibin, "#alpha_{1}", 0.5, 0, 10) alpha2 = RooRealVar("#alpha_{WT2}^{%s}" % ibin, "#alpha_{2}", 2.5, 0, 10) n1 = RooRealVar("n_{WT1}^{%s}" % ibin, "n_1", 1, 0, 60) n2 = RooRealVar("n_{WT2}^{%s}" % ibin, "n_2", 1, 0, 60) doublecb = ROOT.RooDoubleCBFast("doublecb_%s" % ibin, "doublecb", tagged_mass, mean, sigmaCB, alpha1, n1, alpha2, n2) signalFunction = doublecb fitFunction = doublecb getattr(w, "import")(signalFunction) r = fitFunction.fitTo(data, RooFit.Extended(doextended), RooFit.Save(), RooFit.Range(fitrange)) print 'fit status: ', r.status(), r.covQual() ## draw everything params = signalFunction.getParameters(RooArgSet(tagged_mass)) w.saveSnapshot("reference_fit_%s_%s" % (tag, ibin), params, ROOT.kTRUE) frame = tagged_mass.frame( RooFit.Range(fitrange) ) #, RooFit.Title('correctly'*correctTag + 'wrongly'*(1-correctTag) + ' tagged events')) data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7)) drawPdfComponents(fitFunction, frame, ROOT.kGreen if correctTag else ROOT.kViolet, RooFit.NormRange(fitrange), RooFit.Range(fitrange), isData=False) fitFunction.plotOn(frame, RooFit.NormRange(fitrange), RooFit.Range(fitrange)) fitFunction.paramOn(frame, RooFit.Layout(0.62, 0.86, 0.88)) frame.Draw() niceFrame( frame, 'correctly' * correctTag + 'wrongly' * (1 - correctTag) + ' tagged events') frame.addObject(_writeFitStatus(r)) ## evaluate sort of chi2 and save number of RT/WT events observables = RooArgSet(tagged_mass) flparams = fitFunction.getParameters(observables) nparam = int(flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize()) pdfstring = '' if correctTag: # pdfstring = "doublegaus_RT%s_Norm[tagged_mass]_Comp[doublegaus_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) pdfstring = "doublecb_RT%s_Norm[tagged_mass]_Comp[doublecb_RT%s]_Range[mcrange]_NormRange[mcrange]" % ( ibin, ibin) # pdfstring = "gauscb_RT%s_Norm[tagged_mass]_Comp[gauscb_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) # pdfstring = "expGaussExp_RT%s_Norm[tagged_mass]_Comp[expGaussExp_RT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) if doextended: dict_s_rt[ibin] = _getFittedVar(nsig) else: dict_s_rt[ibin] = ufloat(data.sumEntries(), math.sqrt(data.sumEntries())) nRT = RooRealVar("nRT_%s" % ibin, "yield of RT signal", 0, 1.E6) nRT.setVal(dict_s_rt[ibin].n) nRT.setError(dict_s_rt[ibin].s) print 'setting nRT to ', dict_s_rt[ibin].n getattr(w, "import")(nRT) else: pdfstring = "doublecb_%s_Norm[tagged_mass]_Comp[doublecb_%s]_Range[mcrange]_NormRange[mcrange]" % ( ibin, ibin) # pdfstring = "doublegaus_WT%s_Norm[tagged_mass]_Comp[doublegaus_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) # pdfstring = "gauscb_WT%s_Norm[tagged_mass]_Comp[gauscb_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) # pdfstring = "expGaussExp_WT%s_Norm[tagged_mass]_Comp[expGaussExp_WT%s]_Range[mcrange]_NormRange[mcrange]"%(ibin,ibin) dict_s_wt[ibin] = ufloat(data.sumEntries(), math.sqrt(data.sumEntries())) nWT = RooRealVar("nWT_%s" % ibin, "yield of WT signal", 0, 1.E6) nWT.setVal(dict_s_wt[ibin].n) nWT.setError(dict_s_wt[ibin].s) print 'setting nWT to ', dict_s_wt[ibin].n getattr(w, "import")(nWT) ## eval and save goodness of fit indicators chi2s['%s%s' % (tag, ibin)] = frame.chiSquare(pdfstring, "h_fullmc", nparam) frame.addObject(_writeChi2(chi2s['%s%s' % (tag, ibin)])) fitStats['%s%s' % (tag, ibin)] = r.status() covStats['%s%s' % (tag, ibin)] = r.covQual() c1 = ROOT.TCanvas() upperPad = ROOT.TPad('upperPad', 'upperPad', 0., 0.35, 1., 1.) lowerPad = ROOT.TPad('lowerPad', 'lowerPad', 0., 0.0, 1., 0.345) upperPad.SetBottomMargin(0.012) lowerPad.SetTopMargin(0) lowerPad.SetBottomMargin(0.2) upperPad.Draw() lowerPad.Draw() upperPad.cd() frame.Draw() ## add plot of pulls lowerPad.cd() hpull = frame.pullHist("h_fullmc", pdfstring) frame2 = tagged_mass.frame(RooFit.Range(fitrange), RooFit.Title('')) frame2.addPlotable(hpull, "P") niceFrameLowerPad(frame2, 'pull') frame2.Draw() line = ROOT.TLine(5.0, 1, 5.6, 1) line.SetLineColor(ROOT.kGreen + 3) line.Draw() ## save to pdf and root files for ilog in [True, False]: upperPad.SetLogy(ilog) c1.SaveAs( 'fit_results_mass_checkOnMC/save_fit_mc_%s_%s_%s_newSigmaFRT_%s.pdf' % (ibin, args.year, tag, '_logScale' * ilog)) out_f.cd() r.Write('results_%s_%s' % (tag, ibin)) return dict_s_rt[ibin].n if correctTag else dict_s_wt[ibin].n
a0 = RooRealVar("a0","a0",0.001,-1.,1.) 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 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")
def fillWorkspace(workspace): 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 ">>> import model into workspace..." getattr(workspace, 'import')(model) # import model and all its components #workspace.import(model) # causes synthax error in python print "\n>>> encode definition of parameters and observables in workspace..." # Define named sets "parameters" and "observables", which list which variables should # be considered parameters and observables by the users convention # # Variables appearing in sets _must_ live in the workspace already, or the autoImport # flag of defineSet must be set to import them on the fly. Named sets contain only # references to the original variables, therefore the value of observables in named # sets already reflect their 'current' value params = model.getParameters(RooArgSet(x)) # RooArgSet workspace.defineSet("parameters", RooArgSet(params)) workspace.defineSet("observables", RooArgSet(x)) # Encode reference value for parameters in workspace: # Define a parameter 'snapshot' in the pdf # Unlike a named set, a parameter snapshot stores an independent set of values for # a given set of variables in the workspace. The values can be stored and reloaded # into the workspace variable objects using the loadSnapshot() and saveSnapshot() # methods. A snapshot saves the value of each variable, any errors that are stored # with it as well as the 'Constant' flag that is used in fits to determine if a # parameter is kept fixed or not. print ">>> generate and fit data..." # Do a dummy fit to a (supposedly) reference dataset here and store the results # of that fit into a snapshot refData = model.generate(RooArgSet(x), 10000) # RooDataSet model.fitTo(refData, PrintLevel(-1)) print "\n>>> save fit results into a snapshot in the workspace..." # The kTRUE flag imports the values of the objects in (*params) into the workspace # If not set, the present values of the workspace parameters objects are stored workspace.saveSnapshot("reference_fit", params, kTRUE) print ">>> make another fit with the signal component forced to zero..." bkgfrac.setVal(1) bkgfrac.setConstant(kTRUE) bkgfrac.removeError() model.fitTo(refData, PrintLevel(-1)) print "\n>>> save new fit parameters in different snapshot..." workspace.saveSnapshot("reference_fit_bkgonly", params, kTRUE)
def PeakFit_likelihood(Likelihood_cut: pd.DataFrame, mass_energy: pd.DataFrame, cutval, plots=True, constant_mean=True, constant_width=True, classifier_name='Likelihood', CB=True, Gauss=False, bkg_comb=True, bkg_exp=False, bkg_cheb=False): print('Starting fit...') matplotlib.use('Agg') # Check if we have mass in MeV or GeV if np.mean(mass_energy) > 1000: normalization_mass = 1000 else: normalization_mass = 1 sns.set_style("whitegrid") # White background on plot prediction = Likelihood_cut # rename to prediction # Set range mZmin = 60.0 mZmax = 130.0 # Number of bins NbinsZmass = 100 #Initiate the mass variable m_ee = ROOT.RooRealVar("m_ee", "Invariant mass (GeV/c^{2})", mZmin, mZmax) m_ee.setRange("MC_mZfit_range", mZmin, mZmax) # ============================================================================= # fit signal # ============================================================================= # Make a mask in the signal range. Prediction is 0 or 1, so above 0.5 is signal mask_mass = (mass_energy / normalization_mass > mZmin) & ( mass_energy / normalization_mass < mZmax) & (prediction > 0.5) Z_mass_signal = np.array(mass_energy[mask_mass] / normalization_mass) #Make np.array # Initiate 1D histogram h_mZ_all = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass, mZmin, mZmax) for isample in range(Z_mass_signal.shape[0]): score = Z_mass_signal[isample] h_mZ_all.Fill(score) # Constructs histogram with m_ee as argument from the 1d histogram h_mZ_all mc_Zee_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee", RooArgList(m_ee), h_mZ_all) # Define variables for the fits. # BW: Breit-Wigner. CB: Crystal-Ball meanBW = ROOT.RooRealVar("meanBW", "meanBW", 91.1876, 60.0, 120.0) #91.1876 meanBW.setConstant(True) # this is a theoretical constant sigmaBW = ROOT.RooRealVar("sigmaBW", "sigmaBW", 2.4952, 2.0, 20.0) #2.4952 sigmaBW.setConstant(True) # this is a theoretical constant # if constant_mean: func_BW = ROOT.RooBreitWigner("func_BW", "Breit-Wigner", m_ee, meanBW, sigmaBW) # Make the function from the constants # Crystal ball if CB: meanCB = RooRealVar("meanCB", "meanCB", -0.0716, -10.0, 10.0) # meanCB.setConstant(True) #if commented out, it can float between the minimum and maximum sigmaCB = RooRealVar("sigmaCB", "sigmaCB", 0.193, 0, 15) # sigmaCB.setConstant(True) alphaCB = RooRealVar("alphaCB", "alphaCB", 1.58, 0.0, 10.0) # alphaCB.setConstant(True) nCB = RooRealVar("nCB", "nCB", 0.886, -10, 50.0) # nCB.setConstant(True) func_sig_CB = RooCBShape("func_CB", "Crystal Ball", m_ee, meanCB, sigmaCB, alphaCB, nCB) # Define Crystal-Ball function # Gaussian elif Gauss: # Use Gaussian if True in function call meanGA = RooRealVar("meanGA", "meanGA", 10.0, -10.0, 10.0) sigmaGA = RooRealVar("sigmaGA", "sigmaGA", 3.0, 0.01, 10.0) if constant_width: sigmaGA.setConstant(True) nGA = RooRealVar("nGA", "nGA", 1.5, 0.0, 20.0) func_GA = RooGaussian("func_GA", "Gaussian", m_ee, meanGA, sigmaGA) #, nGA); if CB: # Convolute Breit-Wigner and Crystal-Ball print("Convoluting a Crystal-Ball and Breit-Wigner for signal") func_BWxCB_unextended = RooFFTConvPdf("func_BWxCB_unextended", "Breit-Wigner (X) Crystal Ball", m_ee, func_BW, func_sig_CB) elif Gauss: # Convolute Breit-Wigner and Gauss print("Convoluting a Gauss and Breit-Wigner for signal") func_BWxCB_unextended = RooFFTConvPdf("func_BWxCB_unextended", "Breit-Wigner (X) Gaussian", m_ee, func_BW, func_GA) else: # only Breit-Wigner fit on the signal print("Fitting only with Breit-Wigner for signal") func_BWxCB_unextended = func_BW m_ee.setRange("MC_mZfit_range", 85, 97) # Set the fit range for the signal nsig = RooRealVar("ntotal", "ntotal", 1000, 0, 10e6) # Define the variable for the number of signal func_BWxCB = ROOT.RooExtendPdf("signal_func_Zee", "signal_func_Zee", func_BWxCB_unextended, nsig) # Adding the nsig term to the pdf func_BWxCB.fitTo(mc_Zee_mZ, RooFit.Range("MC_mZfit_range")) # Fit the signal if plots: # Plots the signal using the function "root_plot" defined above mc_Zee_signal = root_plot(m_ee=m_ee, distribution=mc_Zee_mZ, fit=func_BWxCB, mZmin=mZmin, mZmax=mZmax, title=f'signal for cut {cutval}') #cut {cutval} # ============================================================================= # background # ============================================================================= nbkg = RooRealVar("nbkg", "nbkg", 1000, 0, 10e6) # Define the variable for the number of background #if True: m_ee.setRange("MC_mZfit_range", mZmin, mZmax) # Set range for fit as defined in the beginning c_bkg_mZ = ROOT.TCanvas("c_bkg_mZ", "", 0, 0, 1000, 500) # Make the canvas for plotting Z_mass_background = np.array(mass_energy[mask_mass] / normalization_mass) # Mask for background h_mZWenu_all = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass, mZmin, mZmax) # Initiate 1D histogram for isample in range(Z_mass_background.shape[0]): score = Z_mass_background[isample] h_mZWenu_all.Fill(score) # Create the lin + exponential fit lam = RooRealVar("lambda", "Exponent", -0.04, -5.0, 0.0) func_expo = ROOT.RooExponential("func_expo", "Exponential PDF", m_ee, lam) #coef_pol1 = RooRealVar("coef_pol1", "Slope of background", 0.0, -10.0, 10.0); #func_pol1 = ROOT.RooPolynomial("func_pol1", "Linear PDF", m_ee, RooArgList(coef_pol1)); # Create Chebychev polymonial a0 = RooRealVar("a0", "a0", -0.4, -5.0, 5.0) a1 = RooRealVar("a1", "a1", -0.03, -5.0, 5.0) a2 = RooRealVar("a2", "a2", 0.02, -5.0, 5.0) a3 = RooRealVar("a3", "a3", 0.02, -5.0, 5.0) # Polynomials with different order func_Cpol1 = RooChebychev("func_Cpol1", "Chebychev polynomial of 1st order", m_ee, RooArgList(a0, a1)) func_Cpol2 = RooChebychev("func_Cpol2", "Chebychev polynomial of 2nd order", m_ee, RooArgList(a0, a1, a2)) func_Cpol3 = RooChebychev("func_Cpol3", "Chebychev polynomial of 3rd order", m_ee, RooArgList(a0, a1, a2, a3)) f_exp_mZ = RooRealVar("N_lin_mZ", "CLinear fraction", 0.50, 0, 1) m_ee.setRange("low", 60, 70) m_ee.setRange("high", 110, 130) # Adding exponential and Chebychev if comb: if bkg_comb: func_ExpLin_mZ_unextended = ROOT.RooAddPdf( "func_ExpLin_mZ_unextended", "Exponential and Linear PDF", RooArgList(func_Cpol3, func_expo), RooArgList(f_exp_mZ)) elif bkg_exp: func_ExpLin_mZ_unextended = func_expo elif bkg_cheb: func_ExpLin_mZ_unextended = func_Cpol3 else: print("No background fit called. Exiting") return None func_ExpLin_mZ = ROOT.RooExtendPdf("func_ExpLin_mZ", "func_ExpLin_mZ", func_ExpLin_mZ_unextended, nbkg) # Adding the nbkg term to the pdf # Constructs histogram with m_ee as argument from the 1d histogram h_mZ_all mc_Wenu_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee", RooArgList(m_ee), h_mZWenu_all) func_ExpLin_mZ.fitTo(mc_Wenu_mZ, RooFit.Range("MC_mZfit_range")) #ROOT.RooFit.Range("low,high")); # Fits background #Plotting background residue = root_plot(m_ee=m_ee, distribution=mc_Wenu_mZ, fit=func_ExpLin_mZ, mZmin=mZmin, mZmax=mZmax, title=f'Background for cut {cutval}') # # ============================================================================= # Combining signal and background # ============================================================================= m_ee.setRange("MC_mZfit_range", mZmin, mZmax) Z_mass = np.array(mass_energy[mask_mass] / normalization_mass) h_mZWenu = ROOT.TH1D("h_mZ_all", "Histogram of Z mass", NbinsZmass, mZmin, mZmax) for isample in range(Z_mass.shape[0]): score = Z_mass[isample] h_mZWenu.Fill(score) # Constructs histogram with m_ee as argument from the 1d hist ogram h_mZ_all mc_ZeeWenu_mZ = ROOT.RooDataHist("mc_Zee_mZ", "Dataset with Zee m_ee", RooArgList(m_ee), h_mZWenu) ## Fits the data and returns the fraction of background f_bkg_mZ = RooRealVar("f_bkg_mZ", "Signal fraction", nbkg.getVal() / nsig.getVal(), 0.0, 1) ## Combining the signal and background fits func_SigBkg_mZ_unextended = ROOT.RooAddPdf( "func_SigBkg_mZ", "Signal and Background PDF", RooArgList(func_ExpLin_mZ_unextended, func_BWxCB_unextended), RooArgList(f_bkg_mZ)) # func_SigBkg_mZ_unextended = func_BWxCB_unextended;#ROOT.RooAddPdf("func_SigBkg_mZ", "Signal and Background PDF", RooArgList(func_BWxCB_unextended, func_BWxCB_unextended), RooArgList(f_bkg_mZ)); ntotal = RooRealVar("ntotal", "ntotal", 10000, 0, 10e6) func_SigBkg_mZ = ROOT.RooExtendPdf("func_ExpLin_mZ", "func_ExpLin_mZ", func_SigBkg_mZ_unextended, ntotal) func_SigBkg_mZ.fitTo(mc_ZeeWenu_mZ) # Fits the full data set if plots: mc_ZeeWenu_mZ_resid = root_plot(m_ee=m_ee, distribution=mc_ZeeWenu_mZ, fit=func_SigBkg_mZ, mZmin=mZmin, mZmax=mZmax, title=f'Bkg+Sig for cut {cutval}') # Baseline ntotal = 41231 (Data) # fraction 0.9333 # Baseline ntotal = 74747 (MC) # fraction 0.4427 # Malte script len(Z_mass) bkg = len(Z_mass) * f_bkg_mZ.getVal() sig = len(Z_mass) * (1 - f_bkg_mZ.getVal()) print(f_bkg_mZ.getVal()) #DATA #BL_sig = 41231*(1-0.9333) # BL = baseline, the number is the fraction of bkg in baseline #BL_bkg = 41231*0.9333 # BL = baseline # DATA OS # BL_sig = 22276 * (1-0.853) # BL = baseline, the number is the fraction of bkg in baseline # BL_bkg = 22276 * 0.853 # BL = baseline # DATA SS # BL_sig = 18925 * (1-0.993552)#74747 * (1-0.4427)#41054 # BL_bkg = 18925 - BL_sig #MC OS # exp BL_sig = 46547 * (1 - 0.0350) #74747 * (1-0.4427)#41054 BL_bkg = 46547 * 0.0350 #comb #BL_sig = 74747*(1-0.4427) # BL = baseline, the number is the fraction of bkg in baseline #BL_bkg = 74747*0.4427 # BL = baseline bkg_ratio = bkg / BL_bkg sig_ratio = sig / BL_sig max_residue = max(abs(mc_ZeeWenu_mZ_resid.getYAxisMax()), abs(mc_ZeeWenu_mZ_resid.getYAxisMin())) print(max_residue) print(bkg_ratio) print(sig_ratio) if (bkg_ratio < 1.009) & (sig_ratio < 1.009) & (abs( mc_ZeeWenu_mZ_resid.getYAxisMin()) < 4) & (abs( mc_ZeeWenu_mZ_resid.getYAxisMax()) < 4): # input('....') return BL_sig, BL_bkg, sig_ratio, bkg_ratio #max_residue, ntotal.getVal(), nsig.getVal(), nbkg.getVal()return sigmaCB if CB else sigmaGA #sig_ratio, sigma_sig, bkg_ratio, sigma_bkg else: return 0, 0, 0, 0
def fitData(fulldata, ibin): cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % ( q2binning[ibin], q2binning[ibin + 1]) data = fulldata.reduce(RooArgSet(tagged_mass, mumuMass, mumuMassE), cut) fraction = dict_s_rt[ibin] / (dict_s_rt[ibin] + dict_s_wt[ibin]) print 'mistag fraction on MC for bin ', ibin, ' : ', fraction.n, '+/-', fraction.s ### creating RT component w.loadSnapshot("reference_fit_RT_%s" % ibin) sigmart1 = w.var("#sigma_{1}^{RT%s}" % ibin) sigmart2 = w.var("#sigma_{2}^{RT%s}" % ibin) massrt = w.var("mean^{RT%s}" % ibin) f1rt = w.var("f^{RT%s}" % ibin) theRTgauss = w.pdf("doublegaus_RT%s" % ibin) c_sigma_rt1 = _constrainVar(sigmart1) c_sigma_rt2 = _constrainVar(sigmart2) c_mean_rt = _constrainVar(massrt) c_f1rt = _constrainVar(f1rt) ### creating WT component w.loadSnapshot("reference_fit_WT_%s" % ibin) meanwt = w.var("mean^{WT%s}" % ibin) sigmawt = w.var("#sigma_{CB}^{WT%s}" % ibin) alphawt1 = w.var("#alpha_{1}^{WT%s}" % ibin) alphawt2 = w.var("#alpha_{2}^{WT%s}" % ibin) nwt1 = w.var("n_{1}^{WT%s}" % ibin) nwt2 = w.var("n_{2}^{WT%s}" % ibin) theWTgauss = w.pdf("doublecb_%s" % ibin) c_mean_wt = _constrainVar(meanwt) c_sigma_wt = _constrainVar(sigmawt) c_alpha_wt1 = _constrainVar(alphawt1) c_alpha_wt2 = _constrainVar(alphawt2) c_n_wt1 = _constrainVar(nwt1) c_n_wt2 = _constrainVar(nwt2) ### creating constraints for the RT component c_RTgauss = RooProdPdf( "c_RTgauss", "c_RTgauss", RooArgList(theRTgauss, c_sigma_rt1, c_sigma_rt2, c_mean_rt, c_f1rt)) c_vars = RooArgSet(c_sigma_rt1, c_sigma_rt2, c_f1rt, c_mean_rt) c_vars.add(c_sigma_wt) c_vars.add(c_mean_wt) c_vars.add(c_alpha_wt1) c_vars.add(c_alpha_wt2) c_vars.add(c_n_wt1) c_vars.add(c_n_wt2) ### creating constraints for the WT component c_WTgauss = RooProdPdf( "c_WTgauss", "c_WTgauss", RooArgList(theWTgauss, c_alpha_wt1, c_n_wt1, c_sigma_wt, c_mean_wt, c_alpha_wt2, c_n_wt2)) frt = RooRealVar("F_{RT}", "frt", fraction.n, 0, 1) signalFunction = RooAddPdf("sumgaus", "rt+wt", RooArgList(c_RTgauss, c_WTgauss), RooArgList(frt)) c_frt = RooGaussian("c_frt", "c_frt", frt, ROOT.RooFit.RooConst(fraction.n), ROOT.RooFit.RooConst(fraction.s)) c_signalFunction = RooProdPdf("c_signalFunction", "c_signalFunction", RooArgList(signalFunction, c_frt)) c_vars.add(frt) ### now create background parametrization slope = RooRealVar("slope", "slope", 0.5, -10, 10) bkg_exp = RooExponential("bkg_exp", "exponential", slope, tagged_mass) pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10) bkg_pol = RooChebychev("bkg_pol", "2nd order pol", tagged_mass, RooArgList(pol_c1, pol_c2)) nsig = RooRealVar("Yield", "signal frac", 4000, 0, 1000000) nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 550000) # fitFunction = RooAddPdf ("fitfunction" , "fit function" , RooArgList(c_signalFunction, bkg_pol), RooArgList(nsig, nbkg)) fitFunction = RooAddPdf("fitfunction", "fit function", RooArgList(c_signalFunction, bkg_exp), RooArgList(nsig, nbkg)) r = fitFunction.fitTo(data, RooFit.Extended(True), RooFit.Save(), RooFit.Range("full"), RooFit.Verbose(False), ROOT.RooFit.Constrain(c_vars)) frame = tagged_mass.frame(RooFit.Range("full")) data.plotOn(frame, RooFit.Binning(35), RooFit.MarkerSize(.7)) fitFunction.plotOn(frame) drawPdfComponents(fitFunction, frame, ROOT.kAzure, RooFit.NormRange("full"), RooFit.Range("full"), isData=True) parList = RooArgSet(nsig, massrt, sigmart1, sigmart2, f1rt, meanwt, sigmawt, alphawt1) parList.add(alphawt2) parList.add(nwt1) parList.add(nwt2) parList.add(frt) fitFunction.paramOn(frame, RooFit.Parameters(parList), RooFit.Layout(0.62, 0.86, 0.89)) frame.Draw() niceFrame(frame, '') frame.addObject(_writeFitStatus(r)) if not args.year == 'test': writeCMS(frame, args.year, [q2binning[ibin], q2binning[ibin + 1]]) frame.Draw() c1.SaveAs('fit_results_mass/save_fit_data_%s_%s_LMNR.pdf' % (ibin, args.year))
a1 = RooRealVar("a1","a1",0.001,-0.5,0.5) a2 = RooRealVar("a2","a2",-0.00001,-2.,2.) a3 = RooRealVar("a3","a3",0.0)# 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) sigma = RooRealVar("sigma","width of gaussian",0.0013) gamma = RooRealVar("gamma","gamma of bw",0.004253)#,0.001,0.01) mean = RooRealVar("mean","mean of gaussian",phimean,phimean-0.005,phimean+0.005); nSig = RooRealVar("nSig","nSig",1E6,0.,5.0E6) nBkg = RooRealVar("nBkg","nBkg",5E5,0.,5.0E6) cheb = RooChebychev("cheb","Background",masskk,aset) #gauss = RooGaussian("gauss","gaussian PDF ",mass,mean,sigma) signal = RooVoigtian("signal","signal",masskk,mean,gamma,sigma) tot = RooAddPdf("tot","g+cheb",RooArgList(signal,cheb),RooArgList(nSig,nBkg)) # In[ ]: masskk.setBins(100) mass.setBins(100) h = xdataPrompt.createHistogram(masskk,mass,20,20) h1 = h.ProjectionX() dh1 = RooDataHist("kmass","kmass",RooArgList(masskk),h1)
a4 = RooRealVar("a_{4}", "a4", 0.0, -0.2, 0.2) 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) sigma = RooRealVar("#sigma", "width of gaussian", 0.01, 0.001, 0.05) gamma = RooRealVar("#Gamma", "gamma of bw", 0.0042, 0.001, 0.01) mean = RooRealVar("#mu", "mean of gaussian", phimean, phimean - 0.1, phimean + 0.1) nSig = RooRealVar("n_{Sig}", "nSig", float(nentries) * 0.1, 0., float(nentries)) nBkg = RooRealVar("n_{Bkg}", "nBkg", float(nentries) * 0.9, 0., float(nentries)) cheb = RooChebychev("cheb", "Background", masskk, aset) gauss = RooGaussian("gauss", "gaussian PDF ", masskk, mean, sigma) #signal = RooVoigtian("signal","signal",psiPrimeMass,mean,gamma,sigma) signal = gauss B_1 = RooRealVar("B_{1}", "B_1 ", 0.3, -20, 100) B_2 = RooRealVar("B_{2}", "B_2", 0.3, -20, 100) B_3 = RooRealVar("B_{3}", "B_3", 0.3, -20, 100) B_4 = RooRealVar("B_{4}", "B_4", 0.3, -20, 100) bkg = RooChebychev("pdfB", "pdfB", masskk, RooArgList(aset)) tot = RooAddPdf("tot", "g+cheb", RooArgList(signal, bkg), RooArgList(nSig, nBkg)) nfits = 0
sigma = RooRealVar("sigma1", "width of gaussian1", 0.001, 0.0005, 0.05) a0 = RooRealVar("a0", "a0", 0.001, -1., 1.) 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]: tot.fitTo(dh)
def mbc_dline_che(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa, fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2, title1, title2, epsfile, txtfile, ymin=0.5, cuts=None, err_type='SYMM', test=False): from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet, RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous, RooArgusBG, RooFormulaVar, RooChebychev, RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta, TPaveText, RooDLineShape) set_root_style(stat=1, grid=0) mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV') ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV') dflav = RooCategory('dflav', 'D0 flavor') dflav.defineType('dflav', 1) dflav.defineType('dbarflav', -1) if cuts != None: if 'kkmass' in cuts: kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV') ras = RooArgSet(mbc, ebeam, kkmass, dflav) dataset = RooDataSet.read(evtfile, ras) else: raise NameError(cuts) sys.stdout.write('Using cuts: %s...' % cuts) dataset = dataset.reduce(cuts) sys.stdout.write(' selected %s events.\n' % dataset.numEntries()) else: ras = RooArgSet(mbc, ebeam, dflav) dataset = RooDataSet.read(evtfile, ras) res = RooRealVar("datares", "datares", mc) mres = RooRealVar("mres", "mres", setMres) gamma = RooRealVar('gamma', 'gamma', setGamma) r = RooRealVar('r', 'r', setR) sigmaE = RooRealVar("sigmaE", "sigmaE", 0.0021) sigmap1 = RooRealVar("sigmap1", "sigmap1", sp1, 0.002, 0.040) scalep2 = RooRealVar("scalep2", "scalep2", 2.00, 1.500, 5.500) scalep3 = RooRealVar("scalep3", "scalep3", 5.00, 3.00, 10.000) scalep2.setVal(sp2) scalep2.setConstant(1) scalep3.setVal(sp3) scalep3.setConstant(1) as12 = RooArgList(sigmap1, scalep2) sigmap2 = RooFormulaVar("sigmap2", "sigma2", "sigmap1*scalep2", as12) as123 = RooArgList(sigmap1, scalep2, scalep3) sigmap3 = RooFormulaVar("sigmap3", "sigma3", "sigmap1*scalep2*scalep3", as123) md = RooRealVar("md", "md", setmd, 1.863, 1.875) f2 = RooRealVar("f2", "f2", fa) f3 = RooRealVar("f3", "f3", fb) al23 = RooArgList(f2, f3) f1 = RooFormulaVar("f1", "f1", "1.0-f2-f3", al23) # Construct signal shape fcn1_1 = RooDLineShape("DLineshape1_1", "DLineShape1_1", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap1, md, res) fcn1_2 = RooDLineShape("DLineshape1_2", "DLineShape1_2", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap2, md, res) fcn1_3 = RooDLineShape("DLineshape1_3", "DLineShape1_3", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap3, md, res) fcn2_1 = RooDLineShape("DLineshape2_1", "DLineShape2_1", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap1, md, res) fcn2_2 = RooDLineShape("DLineshape2_2", "DLineShape2_2", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap2, md, res) fcn2_3 = RooDLineShape("DLineshape2_3", "DLineShape2_3", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap3, md, res) alf1_123 = RooArgList(fcn1_1, fcn1_2, fcn1_3) af12 = RooArgList(f1, f2) sigpdf = RooAddPdf("signal1_3", "signal1_3", alf1_123, af12) alf2_123 = RooArgList(fcn2_1, fcn2_2, fcn2_3) sigbarpdf = RooAddPdf("signal2_3", "signal2_3", alf2_123, af12) con0 = RooRealVar('c0', 'constant', -1, 1) con1 = RooRealVar('c1', 'linear', -10, 10) con2 = RooRealVar('c2', 'quadratic', 1) bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2)) bkgbarpdf = RooChebychev('bkgbarpdf', 'Background', mbc, RooArgList(con1, con2)) yld = RooRealVar('yld', 'D yield', 100, 0, 2000) bkg = RooRealVar('bkg', 'Background', 100, 0, 1000) sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf), RooArgList(yld, bkg)) yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000) bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000) sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigbarpdf, bkgbarpdf), RooArgList(yldbar, bkgbar)) totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav) totalpdf.addPdf(sumpdf, 'dflav') totalpdf.addPdf(sumpdfbar, 'dbarflav') MINUIT = 'ermh4' if err_type == 'ASYM': MINUIT = 'erh4' if test: sys.stdout.write('Will save epsfile as: %s \n' % epsfile) sys.stdout.write('Will save txtfile as: %s \n' % txtfile) return if dataset.numEntries() == 0: yld.setVal(0) yldbar.setVal(0) else: # Start Fitting fitres = totalpdf.fitTo(dataset, MINUIT) fitres.Print('v') # Save plots canvas = TCanvas('canvas', 'mbc', 400, 400) xframe = mbc.frame(50) ProjWData = RooFit.ProjWData(dataset) RooAbsData.plotOn(dataset, xframe) totalpdf.plotOn(xframe, ProjWData) totalpdf.paramOn(xframe) xframe.Draw() canvas.Print(epsfile) # Save fitting parameters pars = [bkg, bkgbar, con1, md, sigmap1, yld, yldbar] save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
def alpha(channel): nElec = channel.count("e") nMuon = channel.count("m") nLept = nElec + nMuon nBtag = channel.count("b") # Channel-dependent settings # Background function. Semi-working options are: EXP, EXP2, EXPN, EXPTAIL if nLept == 0: treeName = "SR" signName = "XZh" colorVjet = sample["DYJetsToNuNu"]["linecolor"] triName = "HLT_PFMET" leptCut = "0==0" topVeto = selection["TopVetocut"] massVar = "X_cmass" binFact = 1 fitFunc = "EXPN" if nBtag < 2 else "EXPN" fitAltFunc = "EXPTAIL" if nBtag < 2 else "EXPTAIL" fitFuncVjet = "ERFEXP" if nBtag < 2 else "EXP" fitAltFuncVjet = "POL" if nBtag < 2 else "POL" fitFuncVV = "EXPGAUS" if nBtag < 2 else "EXPGAUS" fitFuncTop = "GAUS2" elif nLept == 1: treeName = "WCR" signName = "XWh" colorVjet = sample["WJetsToLNu"]["linecolor"] triName = "HLT_Ele" if nElec > 0 else "HLT_Mu" leptCut = "isWtoEN" if nElec > 0 else "isWtoMN" topVeto = selection["TopVetocut"] massVar = "X_mass" binFact = 2 if nElec > 0: fitFunc = "EXPTAIL" if nBtag < 2 else "EXPN" fitAltFunc = "EXPN" if nBtag < 2 else "POW" else: fitFunc = "EXPN" if nBtag < 2 else "EXPN" fitAltFunc = "EXPTAIL" if nBtag < 2 else "POW" fitFuncVjet = "ERFEXP" if nBtag < 2 else "EXP" fitAltFuncVjet = "POL" if nBtag < 2 else "POL" fitFuncVV = "EXPGAUS" if nBtag < 2 else "EXPGAUS" fitFuncTop = "GAUS3" if nBtag < 2 else "GAUS2" else: treeName = "XZh" signName = "XZh" colorVjet = sample["DYJetsToLL"]["linecolor"] triName = "HLT_Ele" if nElec > 0 else "HLT_Mu" leptCut = "isZtoEE" if nElec > 0 else "isZtoMM" topVeto = "X_dPhi>2.5" massVar = "X_mass" binFact = 2 if nElec > 0: fitFunc = "EXPTAIL" if nBtag < 2 else "EXPTAIL" fitAltFunc = "POW" if nBtag < 2 else "POW" else: fitFunc = "EXPTAIL" if nBtag < 2 else "EXPTAIL" fitAltFunc = "POW" if nBtag < 2 else "POW" fitFuncVjet = "ERFEXP" if nBtag < 2 and nElec < 1 else "EXP" fitAltFuncVjet = "POL" if nBtag < 2 else "POL" fitFuncVV = "EXPGAUS2" if nBtag < 2 else "EXPGAUS2" fitFuncTop = "GAUS" btagCut = selection["2Btag"] if nBtag == 2 else selection["1Btag"] print "--- Channel", channel, "---" print " number of electrons:", nElec, " muons:", nMuon, " b-tags:", nBtag print " read tree:", treeName, "and trigger:", triName if ALTERNATIVE: print " using ALTERNATIVE fit functions" print "-" * 11 * 2 # Silent RooFit RooMsgService.instance().setGlobalKillBelow(RooFit.FATAL) # *******************************************************# # # # Variables and selections # # # # *******************************************************# # Define all the variables from the trees that will be used in the cuts and fits # this steps actually perform a "projection" of the entire tree on the variables in thei ranges, so be careful once setting the limits X_mass = RooRealVar(massVar, "m_{X}" if nLept > 0 else "m_{T}^{X}", XBINMIN, XBINMAX, "GeV") J_mass = RooRealVar("fatjet1_prunedMassCorr", "jet corrected pruned mass", HBINMIN, HBINMAX, "GeV") CSV1 = RooRealVar("fatjet1_CSVR1", "", -1.0e99, 1.0e4) CSV2 = RooRealVar("fatjet1_CSVR2", "", -1.0e99, 1.0e4) nB = RooRealVar("fatjet1_nBtag", "", 0.0, 4) CSVTop = RooRealVar("bjet1_CSVR", "", -1.0e99, 1.0e4) X_dPhi = RooRealVar("X_dPhi", "", 0.0, 3.15) isZtoEE = RooRealVar("isZtoEE", "", 0.0, 2) isZtoMM = RooRealVar("isZtoMM", "", 0.0, 2) isWtoEN = RooRealVar("isWtoEN", "", 0.0, 2) isWtoMN = RooRealVar("isWtoMN", "", 0.0, 2) weight = RooRealVar("eventWeightLumi", "", -1.0e9, 1.0) # Define the RooArgSet which will include all the variables defined before # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add' variables = RooArgSet(X_mass, J_mass, CSV1, CSV2, nB, CSVTop, X_dPhi) variables.add(RooArgSet(isZtoEE, isZtoMM, isWtoEN, isWtoMN, weight)) # set reasonable ranges for J_mass and X_mass # these are used in the fit in order to avoid ROOFIT to look in regions very far away from where we are fitting # (honestly, it is not clear to me why it is necessary, but without them the fit often explodes) J_mass.setRange("h_reasonable_range", LOWMIN, HIGMAX) X_mass.setRange("X_reasonable_range", XBINMIN, XBINMAX) # Set RooArgSets once for all, see https://root.cern.ch/phpBB3/viewtopic.php?t=11758 jetMassArg = RooArgSet(J_mass) # Define the ranges in fatJetMass - these will be used to define SB and SR J_mass.setRange("LSBrange", LOWMIN, LOWMAX) J_mass.setRange("HSBrange", HIGMIN, HIGMAX) J_mass.setRange("VRrange", LOWMAX, SIGMIN) J_mass.setRange("SRrange", SIGMIN, SIGMAX) # Set binning for plots J_mass.setBins(HBINS) X_mass.setBins(binFact * XBINS) # Define the selection for the various categories (base + SR / LSBcut / HSBcut ) baseCut = leptCut + " && " + btagCut + "&&" + topVeto massCut = massVar + ">%d" % XBINMIN baseCut += " && " + massCut # Cuts SRcut = baseCut + " && %s>%d && %s<%d" % (J_mass.GetName(), SIGMIN, J_mass.GetName(), SIGMAX) LSBcut = baseCut + " && %s>%d && %s<%d" % (J_mass.GetName(), LOWMIN, J_mass.GetName(), LOWMAX) HSBcut = baseCut + " && %s>%d && %s<%d" % (J_mass.GetName(), HIGMIN, J_mass.GetName(), HIGMAX) SBcut = baseCut + " && ((%s>%d && %s<%d) || (%s>%d && %s<%d))" % ( J_mass.GetName(), LOWMIN, J_mass.GetName(), LOWMAX, J_mass.GetName(), HIGMIN, J_mass.GetName(), HIGMAX, ) VRcut = baseCut + " && %s>%d && %s<%d" % (J_mass.GetName(), LOWMAX, J_mass.GetName(), SIGMIN) # Binning binsJmass = RooBinning(HBINS, HBINMIN, HBINMAX) # binsJmass.addUniform(HBINS, HBINMIN, HBINMAX) binsXmass = RooBinning(binFact * XBINS, XBINMIN, XBINMAX) # binsXmass.addUniform(binFact*XBINS, XBINMIN, XBINMAX) # *******************************************************# # # # Input files # # # # *******************************************************# # Import the files using TChains (separately for the bkg "classes" that we want to describe: here DY and VV+ST+TT) treeData = TChain(treeName) treeMC = TChain(treeName) treeVjet = TChain(treeName) treeVV = TChain(treeName) treeTop = TChain(treeName) treeSign = {} nevtSign = {} for i, m in enumerate(massPoints): treeSign[m] = TChain(treeName) # Read data pd = getPrimaryDataset(triName) if len(pd) == 0: raw_input("Warning: Primary Dataset not recognized, continue?") for i, s in enumerate(pd): treeData.Add(NTUPLEDIR + s + ".root") # Read V+jets backgrounds for i, s in enumerate(["WJetsToLNu_HT", "DYJetsToNuNu_HT", "DYJetsToLL_HT"]): for j, ss in enumerate(sample[s]["files"]): treeVjet.Add(NTUPLEDIR + ss + ".root") # Read VV backgrounds for i, s in enumerate(["VV"]): for j, ss in enumerate(sample[s]["files"]): treeVV.Add(NTUPLEDIR + ss + ".root") # Read Top backgrounds for i, s in enumerate(["ST", "TTbar"]): for j, ss in enumerate(sample[s]["files"]): treeTop.Add(NTUPLEDIR + ss + ".root") # Read signals for i, m in enumerate(massPoints): for j, ss in enumerate(sample["%s_M%d" % (signName, m)]["files"]): treeSign[m].Add(NTUPLEDIR + ss + ".root") sfile = TFile(NTUPLEDIR + ss + ".root", "READ") shist = sfile.Get("Counters/Counter") nevtSign[m] = shist.GetBinContent(1) sfile.Close() # Sum all background MC treeMC.Add(treeVjet) treeMC.Add(treeVV) treeMC.Add(treeTop) # create a dataset to host data in sideband (using this dataset we are automatically blind in the SR!) setDataSB = RooDataSet( "setDataSB", "setDataSB", variables, RooFit.Cut(SBcut), RooFit.WeightVar(weight), RooFit.Import(treeData) ) setDataLSB = RooDataSet( "setDataLSB", "setDataLSB", variables, RooFit.Import(setDataSB), RooFit.Cut(LSBcut), RooFit.WeightVar(weight) ) setDataHSB = RooDataSet( "setDataHSB", "setDataHSB", variables, RooFit.Import(setDataSB), RooFit.Cut(HSBcut), RooFit.WeightVar(weight) ) # Observed data (WARNING, BLIND!) setDataSR = RooDataSet( "setDataSR", "setDataSR", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeData) ) setDataVR = RooDataSet( "setDataVR", "setDataVR", variables, RooFit.Cut(VRcut), RooFit.WeightVar(weight), RooFit.Import(treeData) ) # Observed in the VV mass, just for plotting purposes setDataSRSB = RooDataSet( "setDataSRSB", "setDataSRSB", variables, RooFit.Cut("(" + SRcut + ") || (" + SBcut + ")"), RooFit.WeightVar(weight), RooFit.Import(treeData), ) # same for the bkg datasets from MC, where we just apply the base selections (not blind) setVjet = RooDataSet( "setVjet", "setVjet", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeVjet) ) setVjetSB = RooDataSet( "setVjetSB", "setVjetSB", variables, RooFit.Import(setVjet), RooFit.Cut(SBcut), RooFit.WeightVar(weight) ) setVjetSR = RooDataSet( "setVjetSR", "setVjetSR", variables, RooFit.Import(setVjet), RooFit.Cut(SRcut), RooFit.WeightVar(weight) ) setVV = RooDataSet( "setVV", "setVV", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeVV) ) setVVSB = RooDataSet( "setVVSB", "setVVSB", variables, RooFit.Import(setVV), RooFit.Cut(SBcut), RooFit.WeightVar(weight) ) setVVSR = RooDataSet( "setVVSR", "setVVSR", variables, RooFit.Import(setVV), RooFit.Cut(SRcut), RooFit.WeightVar(weight) ) setTop = RooDataSet( "setTop", "setTop", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeTop) ) setTopSB = RooDataSet( "setTopSB", "setTopSB", variables, RooFit.Import(setTop), RooFit.Cut(SBcut), RooFit.WeightVar(weight) ) setTopSR = RooDataSet( "setTopSR", "setTopSR", variables, RooFit.Import(setTop), RooFit.Cut(SRcut), RooFit.WeightVar(weight) ) print " Data events SB: %.2f" % setDataSB.sumEntries() print " V+jets entries: %.2f" % setVjet.sumEntries() print " VV, VH entries: %.2f" % setVV.sumEntries() print " Top,ST entries: %.2f" % setTop.sumEntries() nVV = RooRealVar("nVV", "VV normalization", setVV.sumEntries(SBcut), 0.0, 2 * setVV.sumEntries(SBcut)) nTop = RooRealVar("nTop", "Top normalization", setTop.sumEntries(SBcut), 0.0, 2 * setTop.sumEntries(SBcut)) nVjet = RooRealVar("nVjet", "Vjet normalization", setDataSB.sumEntries(), 0.0, 2 * setDataSB.sumEntries(SBcut)) nVjet2 = RooRealVar("nVjet2", "Vjet2 normalization", setDataSB.sumEntries(), 0.0, 2 * setDataSB.sumEntries(SBcut)) # Apply Top SF nTop.setVal(nTop.getVal() * topSF[nLept][nBtag]) nTop.setError(nTop.getVal() * topSFErr[nLept][nBtag]) # Define entries entryVjet = RooRealVar("entryVjets", "V+jets normalization", setVjet.sumEntries(), 0.0, 1.0e6) entryVV = RooRealVar("entryVV", "VV normalization", setVV.sumEntries(), 0.0, 1.0e6) entryTop = RooRealVar("entryTop", "Top normalization", setTop.sumEntries(), 0.0, 1.0e6) entrySB = RooRealVar("entrySB", "Data SB normalization", setDataSB.sumEntries(SBcut), 0.0, 1.0e6) entrySB.setError(math.sqrt(entrySB.getVal())) entryLSB = RooRealVar("entryLSB", "Data LSB normalization", setDataSB.sumEntries(LSBcut), 0.0, 1.0e6) entryLSB.setError(math.sqrt(entryLSB.getVal())) entryHSB = RooRealVar("entryHSB", "Data HSB normalization", setDataSB.sumEntries(HSBcut), 0.0, 1.0e6) entryHSB.setError(math.sqrt(entryHSB.getVal())) ################################################################################### # _ _ # # | \ | | | (_) | | (_) # # | \| | ___ _ __ _ __ ___ __ _| |_ ___ __ _| |_ _ ___ _ __ # # | . ` |/ _ \| '__| '_ ` _ \ / _` | | / __|/ _` | __| |/ _ \| '_ \ # # | |\ | (_) | | | | | | | | (_| | | \__ \ (_| | |_| | (_) | | | | # # |_| \_|\___/|_| |_| |_| |_|\__,_|_|_|___/\__,_|\__|_|\___/|_| |_| # # # ################################################################################### # fancy ASCII art thanks to, I guess, Jose # start by creating the fit models to get the normalization: # * MAIN and SECONDARY bkg are taken from MC by fitting the whole J_mass range # * The two PDFs are added together using the relative normalizations of the two bkg from MC # * DATA is then fit in the sidebands only using the combined bkg PDF # * The results of the fit are then estrapolated in the SR and the integral is evaluated. # * This defines the bkg normalization in the SR # *******************************************************# # # # V+jets normalization # # # # *******************************************************# # Variables for V+jets constVjet = RooRealVar("constVjet", "slope of the exp", -0.020, -1.0, 0.0) offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 30.0, -50.0, 400.0) widthVjet = RooRealVar("widthVjet", "width of the erf", 100.0, 1.0, 200.0) # 0, 400 a0Vjet = RooRealVar("a0Vjet", "width of the erf", -0.1, -5, 0) a1Vjet = RooRealVar("a1Vjet", "width of the erf", 0.6, 0, 5) a2Vjet = RooRealVar("a2Vjet", "width of the erf", -0.1, -1, 1) if channel == "XZhnnb": offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 500.0, 200.0, 1000.0) if channel == "XZhnnbb": offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 350.0, 200.0, 500.0) # if channel == "XWhenb" or channel == "XZheeb": # offsetVjet.setVal(120.) # offsetVjet.setConstant(True) if channel == "XWhenb": offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 120.0, 80.0, 155.0) if channel == "XWhenbb" or channel == "XZhmmb": offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 67.0, 50.0, 100.0) if channel == "XWhmnb": offsetVjet = RooRealVar("offsetVjet", "offset of the erf", 30.0, -50.0, 600.0) if channel == "XZheeb": offsetVjet.setMin(-400) offsetVjet.setVal(0.0) offsetVjet.setMax(1000) widthVjet.setVal(1.0) # Define V+jets model if fitFuncVjet == "ERFEXP": VjetMass = RooErfExpPdf("VjetMass", fitFuncVjet, J_mass, constVjet, offsetVjet, widthVjet) elif fitFuncVjet == "EXP": VjetMass = RooExponential("VjetMass", fitFuncVjet, J_mass, constVjet) elif fitFuncVjet == "GAUS": VjetMass = RooGaussian("VjetMass", fitFuncVjet, J_mass, offsetVjet, widthVjet) elif fitFuncVjet == "POL": VjetMass = RooChebychev("VjetMass", fitFuncVjet, J_mass, RooArgList(a0Vjet, a1Vjet, a2Vjet)) elif fitFuncVjet == "POW": VjetMass = RooGenericPdf("VjetMass", fitFuncVjet, "@0^@1", RooArgList(J_mass, a0Vjet)) else: print " ERROR! Pdf", fitFuncVjet, "is not implemented for Vjets" exit() if fitAltFuncVjet == "POL": VjetMass2 = RooChebychev("VjetMass2", "polynomial for V+jets mass", J_mass, RooArgList(a0Vjet, a1Vjet, a2Vjet)) else: print " ERROR! Pdf", fitAltFuncVjet, "is not implemented for Vjets" exit() # fit to main bkg in MC (whole range) frVjet = VjetMass.fitTo( setVjet, RooFit.SumW2Error(True), RooFit.Range("h_reasonable_range"), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) frVjet2 = VjetMass2.fitTo( setVjet, RooFit.SumW2Error(True), RooFit.Range("h_reasonable_range"), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) if VERBOSE: print "********** Fit result [JET MASS Vjets] *" + "*" * 40, "\n", frVjet.Print(), "\n", "*" * 80 # likelihoodScan(VjetMass, setVjet, [constVjet, offsetVjet, widthVjet]) # *******************************************************# # # # VV, VH normalization # # # # *******************************************************# # Variables for VV # Error function and exponential to model the bulk constVV = RooRealVar("constVV", "slope of the exp", -0.030, -0.1, 0.0) offsetVV = RooRealVar("offsetVV", "offset of the erf", 90.0, 1.0, 300.0) widthVV = RooRealVar("widthVV", "width of the erf", 50.0, 1.0, 100.0) erfrVV = RooErfExpPdf("baseVV", "error function for VV jet mass", J_mass, constVV, offsetVV, widthVV) expoVV = RooExponential("baseVV", "error function for VV jet mass", J_mass, constVV) # gaussian for the V mass peak meanVV = RooRealVar("meanVV", "mean of the gaussian", 90.0, 60.0, 100.0) sigmaVV = RooRealVar("sigmaVV", "sigma of the gaussian", 10.0, 6.0, 30.0) fracVV = RooRealVar("fracVV", "fraction of gaussian wrt erfexp", 3.2e-1, 0.0, 1.0) gausVV = RooGaussian("gausVV", "gaus for VV jet mass", J_mass, meanVV, sigmaVV) # gaussian for the H mass peak meanVH = RooRealVar("meanVH", "mean of the gaussian", 125.0, 100.0, 150.0) sigmaVH = RooRealVar("sigmaVH", "sigma of the gaussian", 10.0, 5.0, 50.0) fracVH = RooRealVar("fracVH", "fraction of gaussian wrt erfexp", 1.5e-2, 0.0, 1.0) gausVH = RooGaussian("gausVH", "gaus for VH jet mass", J_mass, meanVH, sigmaVH) # Define VV model if fitFuncVV == "ERFEXPGAUS": VVMass = RooAddPdf("VVMass", fitFuncVV, RooArgList(gausVV, erfrVV), RooArgList(fracVV)) elif fitFuncVV == "ERFEXPGAUS2": VVMass = RooAddPdf("VVMass", fitFuncVV, RooArgList(gausVH, gausVV, erfrVV), RooArgList(fracVH, fracVV)) elif fitFuncVV == "EXPGAUS": VVMass = RooAddPdf("VVMass", fitFuncVV, RooArgList(gausVV, expoVV), RooArgList(fracVV)) elif fitFuncVV == "EXPGAUS2": VVMass = RooAddPdf("VVMass", fitFuncVV, RooArgList(gausVH, gausVV, expoVV), RooArgList(fracVH, fracVV)) else: print " ERROR! Pdf", fitFuncVV, "is not implemented for VV" exit() # fit to secondary bkg in MC (whole range) frVV = VVMass.fitTo( setVV, RooFit.SumW2Error(True), RooFit.Range("h_reasonable_range"), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) if VERBOSE: print "********** Fit result [JET MASS VV] ****" + "*" * 40, "\n", frVV.Print(), "\n", "*" * 80 # *******************************************************# # # # Top, ST normalization # # # # *******************************************************# # Variables for Top # Error Function * Exponential to model the bulk constTop = RooRealVar("constTop", "slope of the exp", -0.030, -1.0, 0.0) offsetTop = RooRealVar("offsetTop", "offset of the erf", 175.0, 50.0, 250.0) widthTop = RooRealVar("widthTop", "width of the erf", 100.0, 1.0, 300.0) gausTop = RooGaussian("baseTop", "gaus for Top jet mass", J_mass, offsetTop, widthTop) erfrTop = RooErfExpPdf("baseTop", "error function for Top jet mass", J_mass, constTop, offsetTop, widthTop) # gaussian for the W mass peak meanW = RooRealVar("meanW", "mean of the gaussian", 80.0, 70.0, 90.0) sigmaW = RooRealVar("sigmaW", "sigma of the gaussian", 10.0, 2.0, 20.0) fracW = RooRealVar("fracW", "fraction of gaussian wrt erfexp", 0.1, 0.0, 1.0) gausW = RooGaussian("gausW", "gaus for W jet mass", J_mass, meanW, sigmaW) # gaussian for the Top mass peak meanT = RooRealVar("meanT", "mean of the gaussian", 175.0, 150.0, 200.0) sigmaT = RooRealVar("sigmaT", "sigma of the gaussian", 12.0, 5.0, 30.0) fracT = RooRealVar("fracT", "fraction of gaussian wrt erfexp", 0.1, 0.0, 1.0) gausT = RooGaussian("gausT", "gaus for T jet mass", J_mass, meanT, sigmaT) if channel == "XZheeb" or channel == "XZheebb" or channel == "XZhmmb" or channel == "XZhmmbb": offsetTop = RooRealVar("offsetTop", "offset of the erf", 200.0, -50.0, 450.0) widthTop = RooRealVar("widthTop", "width of the erf", 100.0, 1.0, 1000.0) # Define Top model if fitFuncTop == "ERFEXPGAUS2": TopMass = RooAddPdf("TopMass", fitFuncTop, RooArgList(gausW, gausT, erfrTop), RooArgList(fracW, fracT)) elif fitFuncTop == "ERFEXPGAUS": TopMass = RooAddPdf("TopMass", fitFuncTop, RooArgList(gausT, erfrTop), RooArgList(fracT)) elif fitFuncTop == "GAUS3": TopMass = RooAddPdf("TopMass", fitFuncTop, RooArgList(gausW, gausT, gausTop), RooArgList(fracW, fracT)) elif fitFuncTop == "GAUS2": TopMass = RooAddPdf("TopMass", fitFuncTop, RooArgList(gausT, gausTop), RooArgList(fracT)) elif fitFuncTop == "GAUS": TopMass = RooGaussian("TopMass", fitFuncTop, J_mass, offsetTop, widthTop) else: print " ERROR! Pdf", fitFuncTop, "is not implemented for Top" exit() # fit to secondary bkg in MC (whole range) frTop = TopMass.fitTo( setTop, RooFit.SumW2Error(True), RooFit.Range("h_reasonable_range"), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) if VERBOSE: print "********** Fit result [JET MASS TOP] ***" + "*" * 40, "\n", frTop.Print(), "\n", "*" * 80 # likelihoodScan(TopMass, setTop, [offsetTop, widthTop]) # *******************************************************# # # # All bkg normalization # # # # *******************************************************# # nVjet.setConstant(False) # nVjet2.setConstant(False) # # constVjet.setConstant(False) # offsetVjet.setConstant(False) # widthVjet.setConstant(False) # a0Vjet.setConstant(False) # a1Vjet.setConstant(False) # a2Vjet.setConstant(False) constVV.setConstant(True) offsetVV.setConstant(True) widthVV.setConstant(True) meanVV.setConstant(True) sigmaVV.setConstant(True) fracVV.setConstant(True) meanVH.setConstant(True) sigmaVH.setConstant(True) fracVH.setConstant(True) constTop.setConstant(True) offsetTop.setConstant(True) widthTop.setConstant(True) meanW.setConstant(True) sigmaW.setConstant(True) fracW.setConstant(True) meanT.setConstant(True) sigmaT.setConstant(True) fracT.setConstant(True) nVV.setConstant(True) nTop.setConstant(True) nVjet.setConstant(False) nVjet2.setConstant(False) # Final background model by adding the main+secondary pdfs (using 'coef': ratio of the secondary/main, from MC) TopMass_ext = RooExtendPdf("TopMass_ext", "extended p.d.f", TopMass, nTop) VVMass_ext = RooExtendPdf("VVMass_ext", "extended p.d.f", VVMass, nVV) VjetMass_ext = RooExtendPdf("VjetMass_ext", "extended p.d.f", VjetMass, nVjet) VjetMass2_ext = RooExtendPdf("VjetMass_ext", "extended p.d.f", VjetMass, nVjet2) BkgMass = RooAddPdf( "BkgMass", "BkgMass", RooArgList(TopMass_ext, VVMass_ext, VjetMass_ext), RooArgList(nTop, nVV, nVjet) ) BkgMass2 = RooAddPdf( "BkgMass2", "BkgMass2", RooArgList(TopMass_ext, VVMass_ext, VjetMass2_ext), RooArgList(nTop, nVV, nVjet2) ) BkgMass.fixAddCoefRange("h_reasonable_range") BkgMass2.fixAddCoefRange("h_reasonable_range") # Extended fit model to data in SB frMass = BkgMass.fitTo( setDataSB, RooFit.SumW2Error(True), RooFit.Extended(True), RooFit.Range("LSBrange,HSBrange"), RooFit.Strategy(2), RooFit.Minimizer("Minuit"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) # , RooFit.NumCPU(10) if VERBOSE: print "********** Fit result [JET MASS DATA] **" + "*" * 40, "\n", frMass.Print(), "\n", "*" * 80 frMass2 = BkgMass2.fitTo( setDataSB, RooFit.SumW2Error(True), RooFit.Extended(True), RooFit.Range("LSBrange,HSBrange"), RooFit.Strategy(2), RooFit.Minimizer("Minuit"), RooFit.Save(1), RooFit.PrintLevel(1 if VERBOSE else -1), ) if VERBOSE: print "********** Fit result [JET MASS DATA] **" + "*" * 40, "\n", frMass2.Print(), "\n", "*" * 80 # if SCAN: # likelihoodScan(VjetMass, setVjet, [constVjet, offsetVjet, widthVjet]) # Fix normalization and parameters of V+jets after the fit to data nVjet.setConstant(True) nVjet2.setConstant(True) constVjet.setConstant(True) offsetVjet.setConstant(True) widthVjet.setConstant(True) a0Vjet.setConstant(True) a1Vjet.setConstant(True) a2Vjet.setConstant(True) # integrals for global normalization # do not integrate the composte model: results have no sense # integral for normalization in the SB iSBVjet = VjetMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("LSBrange,HSBrange")) iSBVV = VVMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("LSBrange,HSBrange")) iSBTop = TopMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("LSBrange,HSBrange")) # integral for normalization in the SR iSRVjet = VjetMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("SRrange")) iSRVV = VVMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("SRrange")) iSRTop = TopMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("SRrange")) # integral for normalization in the VR iVRVjet = VjetMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("VRrange")) iVRVV = VVMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("VRrange")) iVRTop = TopMass.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("VRrange")) # formual vars SByield = RooFormulaVar( "SByield", "extrapolation to SR", "@0*@1 + @2*@3 + @4*@5", RooArgList(iSBVjet, nVjet, iSBVV, nVV, iSBTop, nTop) ) VRyield = RooFormulaVar( "VRyield", "extrapolation to VR", "@0*@1 + @2*@3 + @4*@5", RooArgList(iVRVjet, nVjet, iVRVV, nVV, iVRTop, nTop) ) SRyield = RooFormulaVar( "SRyield", "extrapolation to SR", "@0*@1 + @2*@3 + @4*@5", RooArgList(iSRVjet, nVjet, iSRVV, nVV, iSRTop, nTop) ) # fractions fSBVjet = RooRealVar( "fVjet", "Fraction of Vjet events in SB", iSBVjet.getVal() * nVjet.getVal() / SByield.getVal(), 0.0, 1.0 ) fSBVV = RooRealVar( "fSBVV", "Fraction of VV events in SB", iSBVV.getVal() * nVV.getVal() / SByield.getVal(), 0.0, 1.0 ) fSBTop = RooRealVar( "fSBTop", "Fraction of Top events in SB", iSBTop.getVal() * nTop.getVal() / SByield.getVal(), 0.0, 1.0 ) fSRVjet = RooRealVar( "fSRVjet", "Fraction of Vjet events in SR", iSRVjet.getVal() * nVjet.getVal() / SRyield.getVal(), 0.0, 1.0 ) fSRVV = RooRealVar( "fSRVV", "Fraction of VV events in SR", iSRVV.getVal() * nVV.getVal() / SRyield.getVal(), 0.0, 1.0 ) fSRTop = RooRealVar( "fSRTop", "Fraction of Top events in SR", iSRTop.getVal() * nTop.getVal() / SRyield.getVal(), 0.0, 1.0 ) # final normalization values bkgYield = SRyield.getVal() bkgYield2 = ( (VjetMass2.createIntegral(jetMassArg, RooFit.NormSet(jetMassArg), RooFit.Range("SRrange"))).getVal() * nVjet2.getVal() + iSRVV.getVal() * nVV.getVal() + iSRTop.getVal() * nTop.getVal() ) bkgYield_syst = math.sqrt(SRyield.getPropagatedError(frVV) ** 2 + SRyield.getPropagatedError(frTop) ** 2) bkgYield_stat = math.sqrt(SRyield.getPropagatedError(frMass) ** 2) bkgYield_alte = abs(bkgYield - bkgYield2) # /bkgYield bkgYield_eig_norm = RooRealVar("predSR_eig_norm", "expected yield in SR", bkgYield, 0.0, 1.0e6) print "Events in channel", channel, ": V+jets %.3f (%.1f%%), VV %.3f (%.1f%%), Top %.3f (%.1f%%)" % ( iSRVjet.getVal() * nVjet.getVal(), fSRVjet.getVal() * 100, iSRVV.getVal() * nVV.getVal(), fSRVV.getVal() * 100, iSRTop.getVal() * nTop.getVal(), fSRTop.getVal() * 100, ) print "Events in channel", channel, ": Integral = $%.3f$ & $\pm %.3f$ & $\pm %.3f$ & $\pm %.3f$, observed = %.0f" % ( bkgYield, bkgYield_stat, bkgYield_syst, bkgYield_alte, setDataSR.sumEntries() if not False else -1, )
5 a_{1} -1.14362e-01 7.12943e-04 4.41214e-05 -2.28745e-02 6 a_{2} 2.43201e-02 4.14706e-04 9.36506e-05 1.21604e-02 7 a_{3} -2.42999e-02 6.27522e-04 3.86717e-04 -4.86190e-02 8 n_{Bkg} 1.87466e+07 1.36843e+04 3.48814e-04 8.52813e-01 9 n_{Sig} 1.92959e+06 1.30579e+04 3.90748e-04 3.83492e+00 ''' sigma_1 = RooRealVar("#sigma_{1}","width of gaussian",1.6002e-03,0.001,0.004) sigma_2 = RooRealVar("#sigma_{2}","width of gaussian",1.6002e-03,0.001,0.004) rFrac = RooRealVar("f_{1}","f1",0.5,0.0,1.0) gamma = RooRealVar("#Gamma","gamma of bw",4.41369e-03,0.004,0.005) mean = RooRealVar("m","mean of gaussian",1.01959e+00,phimean-0.005,phimean+0.005); nSig = RooRealVar("n_{Sig}","nSig",float(nentries)*0.01,0.,float(nentries)*0.5) nBkg = RooRealVar("n_{Bkg}","nBkg",float(nentries)*0.9,0.,float(nentries)) cheb = RooChebychev("cheb","Background",masskk,aset) res = RooGaussian("gauss","gaussian PDF ",masskk,mean,sigma_1) peak = RooVoigtian("peak","peak",masskk,mean,gamma,sigma_2) signal = RooAddPdf("signal","signal",res,peak,rFrac) B_1 = RooRealVar ( "B_{1}" , "B_1 " , 0.3 , -20 , 100 ) B_2 = RooRealVar ( "B_{2}" , "B_2" , 0.3 , -20 , 100 ) B_3 = RooRealVar ( "B_{3}" , "B_3" , 0.3 , -20 , 100 ) B_4 = RooRealVar ( "B_{4}" , "B_4" , 0.3 , -20 , 100 ) bkg = RooChebychev("pdfB" , "pdfB" , masskk , RooArgList(aset)) tot = RooAddPdf("tot","g+cheb",RooArgList(signal,bkg),RooArgList(nSig,nBkg)) nfits = 0
def RooFitHist(inputhist, title='title', path='.'): # RooFit.gErrorIgnoreLevel = RooFit.kInfo # <6.02 # RooFit.SetSilentMode()# >6.02 # RooMsgService().instance().SetSilentMode(kTRUE) fitbinning = array('d') binwidth = 200 #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 ) NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) # print(fitbinning) hist = inputhist.Rebin(NBins, "fit parameter", fitbinning) meanstart = hist.GetBinCenter(hist.GetMaximumBin()) sigmastart = hist.GetRMS() print('meanstart:', meanstart, 'sigmastart:', sigmastart) # inputhist.Draw() # hist.Draw() # hold=raw_input('press enter to exit.') gStyle.SetOptFit(1100) gStyle.SetOptTitle(0) RooFit.SumW2Error(kTRUE) mjj = RooRealVar('mjj', 'M_{jj-AK8}', fitbinning[0], fitbinning[len(fitbinning) - 1], 'GeV') mjjral = RooArgList(mjj) dh = RooDataHist('dh', 'dh', mjjral, RooFit.Import(hist)) shapes = {} #Gaussian gaussmean = RooRealVar('#mu_{gauss}', 'mass mean value', meanstart, 0, 2 * meanstart) gausssigma = RooRealVar('#sigma_{gauss}', 'mass resolution', sigmastart, 0, 2 * sigmastart) gauss = RooGaussian('gauss', 'gauss', mjj, gaussmean, gausssigma) shapes.update({'Gauss': gauss}) #CrystalBall mean = RooRealVar('#mu', 'mean', meanstart, 0, 2 * meanstart) sigma = RooRealVar('#sigma', 'sigma', sigmastart, 0, 2 * sigmastart) alpha = RooRealVar('#alpha', 'Gaussian tail', -1000, 0) n = RooRealVar('n', 'Normalization', -1000, 1000) cbshape = RooCBShape('cbshape', 'crystalball PDF', mjj, mean, sigma, alpha, n) shapes.update({'CrystalBall': cbshape}) #Voigt voigtmean = RooRealVar('#mu', 'mass mean value', meanstart, 0, 2 * meanstart) voigtwidth = RooRealVar('#gamma', 'width of voigt', 0, 5000) voigtsigma = RooRealVar('#sigma', 'mass resolution', sigmastart, 0, 2 * sigmastart) voigt = RooVoigtian('voigt', 'voigt', mjj, voigtmean, voigtwidth, voigtsigma) shapes.update({'Voigt': voigt}) #BreitWigner bwmean = RooRealVar('#mu', 'mass mean value', meanstart, 0, 2 * meanstart) bwwidth = RooRealVar('#sigma', 'width of bw', sigmastart, 0, 2 * sigmastart) bw = RooBreitWigner('bw', 'bw', mjj, bwmean, bwwidth) shapes.update({'BreitWigner': bw}) #Landau landaumean = RooRealVar('#mu_{landau}', 'mean landau', meanstart, 0, 2 * meanstart) landausigma = RooRealVar('#sigma_{landau}', 'mass resolution', sigmastart, 0, 2 * sigmastart) landau = RooLandau('landau', 'landau', mjj, landaumean, landausigma) shapes.update({'Landau': landau}) #LandauGauss Convolution landaugauss = RooFFTConvPdf('landaugauss', 'landau x gauss', mjj, landau, gauss) shapes.update({'LandauGauss': landaugauss}) #Logistics # logisticsmean=RooRealVar('#mu_{logistics}','mean logistics',meanstart,0,2*meanstart) # logisticssigma= RooRealVar('#sigma_{logistics}','mass resolution',sigmastart,0,2*sigmastart) # logistics=RooLogistics('logistics','logistics',mjj,logisticsmean,logisticssigma) # shapes.update({'Logistics':logistics}) #ExpAndGauss # expgaussmean=RooRealVar('#mu_{expgauss}','mean expgauss',meanstart,0,2*meanstart) # expgausssigma= RooRealVar('#sigma_{expgauss}','mass resolution',sigmastart,0,2*sigmastart) # expgausstrans= RooRealVar('trans','trans',0,100) # expgauss=RooExpAndGauss('expgauss','expgauss',mjj,expgaussmean,expgausssigma,expgausstrans) # shapes.update({'ExpAndGauss':expgauss}) #BifurGauss BifurGaussmean = RooRealVar('#mu_{BifurGauss}', 'mean BifurGauss', meanstart, 0, 2 * meanstart) BifurGausslsigma = RooRealVar('#sigma_{left}', 'mass resolution', sigmastart, 0, 2 * sigmastart) BifurGaussrsigma = RooRealVar('#sigma_{right}', 'mass resolution', sigmastart, 0, 2 * sigmastart) BifurGauss = RooBifurGauss('BifurGauss', 'BifurGauss', mjj, BifurGaussmean, BifurGausslsigma, BifurGaussrsigma) shapes.update({'BifurGauss': BifurGauss}) #Chebychev Chebychev1 = RooRealVar('c0', 'Chebychev0', -1000, 1000) Chebychev2 = RooRealVar('c1', 'Chebychev1', -1000, 1000) Chebychev3 = RooRealVar('c2', 'Chebychev2', 2, -1000, 1000) Chebychev = RooChebychev('Chebychev', 'Chebychev', mjj, RooArgList(Chebychev1, Chebychev2, Chebychev3)) shapes.update({'Chebychev': Chebychev}) #Polynomial Polynomial1 = RooRealVar('Polynomial1', 'Polynomial1', 100, 0, 1000) Polynomial2 = RooRealVar('Polynomial2', 'Polynomial2', 100, 0, 1000) Polynomial = RooPolynomial('Polynomial', 'Polynomial', mjj, RooArgList(Polynomial1, Polynomial2)) shapes.update({'Polynomial': Polynomial}) # mjj.setRange("FitRange",1050.,14000.) # for fname in ['Gauss','Logistics','BifurGauss']: for fname in ['BifurGauss']: plottitle = '%s Fit of %s' % (fname, title) shape = shapes[fname] # shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.SumW2Error(True)) shape.fitTo(dh, RooFit.SumW2Error(True)) frame = mjj.frame(RooFit.Title(plottitle)) frame.GetYaxis().SetTitleOffset(2) dh.plotOn(frame, RooFit.MarkerStyle(4)) shape.plotOn(frame, RooFit.LineColor(2)) ndof = dh.numEntries() - 3 #chiSquare legend chi2 = frame.chiSquare() probChi2 = TMath.Prob(chi2 * ndof, ndof) chi2 = round(chi2, 2) probChi2 = round(probChi2, 2) leg = TLegend(0.5, 0.5, 0.9, 0.65) leg.SetBorderSize(0) leg.SetFillStyle(0) shape.paramOn(frame, RooFit.Layout(0.5, 0.9, 0.9)) leg.AddEntry(0, '#chi^{2} =' + str(chi2), '') leg.AddEntry(0, 'Prob #chi^{2} = ' + str(probChi2), '') leg.SetTextSize(0.04) frame.addObject(leg) canv = TCanvas(plottitle, plottitle, 700, 700) canv.SetLogy() canv.SetLeftMargin(0.20) canv.cd() frame.SetMinimum(10**(-3)) frame.Draw() canv.Print(path + '/%s__%s.eps' % (title, fname)) return chi2
def rf501_simultaneouspdf(): # C r e a t e m o d e l f o r p h y s i c s s a m p l e # ------------------------------------------------------------- # Create observables x = RooRealVar( "x", "x", -8, 8 ) # Construct signal pdf mean = RooRealVar( "mean", "mean", 0, -8, 8 ) sigma = RooRealVar( "sigma", "sigma", 0.3, 0.1, 10 ) gx = RooGaussian( "gx", "gx", x, mean, sigma ) # Construct background pdf a0 = RooRealVar( "a0", "a0", -0.1, -1, 1 ) a1 = RooRealVar( "a1", "a1", 0.004, -1, 1 ) px = RooChebychev( "px", "px", x, RooArgList( a0, a1 ) ) # Construct composite pdf f = RooRealVar( "f", "f", 0.2, 0., 1. ) model = RooAddPdf( "model", "model", RooArgList( gx, px ), RooArgList( f ) ) # C r e a t e m o d e l f o r c o n t r o l s a m p l e # -------------------------------------------------------------- # Construct signal pdf. # NOTE that sigma is shared with the signal sample model mean_ctl = RooRealVar( "mean_ctl", "mean_ctl", -3, -8, 8 ) gx_ctl = RooGaussian( "gx_ctl", "gx_ctl", x, mean_ctl, sigma ) # Construct the background pdf a0_ctl = RooRealVar( "a0_ctl", "a0_ctl", -0.1, -1, 1 ) a1_ctl = RooRealVar( "a1_ctl", "a1_ctl", 0.5, -0.1, 1 ) px_ctl = RooChebychev( "px_ctl", "px_ctl", x, RooArgList( a0_ctl, a1_ctl ) ) # Construct the composite model f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 1. ) model_ctl = RooAddPdf( "model_ctl", "model_ctl", RooArgList( gx_ctl, px_ctl ), RooArgList( f_ctl ) ) # G e n e r a t e e v e n t s f o r b o t h s a m p l e s # --------------------------------------------------------------- # Generate 1000 events in x and y from model data = model.generate( RooArgSet( x ), 100 ) data_ctl = model_ctl.generate( RooArgSet( x ), 2000 ) # C r e a t e i n d e x c a t e g o r y a n d j o i n s a m p l e s # --------------------------------------------------------------------------- # Define category to distinguish physics and control samples events sample = RooCategory( "sample", "sample" ) sample.defineType( "physics" ) sample.defineType( "control" ) # Construct combined dataset in (x,sample) combData = RooDataSet( "combData", "combined data", RooArgSet(x), RooFit.Index( sample ), RooFit.Import( "physics", data ), RooFit.Import( "control", data_ctl ) ) # C o n s t r u c t a s i m u l t a n e o u s p d f i n ( x , s a m p l e ) # ----------------------------------------------------------------------------------- # Construct a simultaneous pdf using category sample as index simPdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample ) # Associate model with the physics state and model_ctl with the control state simPdf.addPdf( model, "physics" ) simPdf.addPdf( model_ctl, "control" ) # P e r f o r m a s i m u l t a n e o u s f i t # --------------------------------------------------- # Perform simultaneous fit of model to data and model_ctl to data_ctl simPdf.fitTo( combData ) # P l o t m o d e l s l i c e s o n d a t a s l i c e s # ---------------------------------------------------------------- # Make a frame for the physics sample frame1 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Physics sample" ) ) # Plot all data tagged as physics sample combData.plotOn( frame1, RooFit.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, RooFit.Slice( sample, "physics" ), RooFit.ProjWData( RooArgSet(sample), combData ) ) simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ), RooFit.Components( "px" ), RooFit.ProjWData( RooArgSet(sample), combData ), RooFit.LineStyle( kDashed ) ) # The same plot for the control sample slice frame2 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Control sample" ) ) combData.plotOn( frame2, RooFit.Cut( "sample==sample::control" ) ) simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ), RooFit.ProjWData( RooArgSet(sample), combData ) ) simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ), RooFit.Components( "px_ctl" ), RooFit.ProjWData( RooArgSet(sample), combData ), RooFit.LineStyle( kDashed ) ) c = TCanvas( "rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400 ) c.Divide( 2 ) c.cd( 1 ) gPad.SetLeftMargin( 0.15 ) frame1.GetYaxis().SetTitleOffset( 1.4 ) frame1.Draw() c.cd( 2 ) gPad.SetLeftMargin( 0.15 ) frame2.GetYaxis().SetTitleOffset( 1.4 ) frame2.Draw() raw_input()
a4 = RooRealVar("p_4", "p_4", -0.000001, -10., 10.) a5 = RooRealVar("p_5", "p_5", -0.000001, -10., 10.) poliset = RooArgList(a0, a1, a2, a3, a4) # gaussFrac = RooRealVar("s","fraction of component 1 in kkSig",0.3,0.0,1.0) nSigKK = RooRealVar("nSig", "nSig", theData.numEntries() * 0.3, 0.0, theData.numEntries() * 1.5) nBkgKK = RooRealVar("nBkg", "nBkg", theData.numEntries() * 0.7, 0.0, theData.numEntries() * 1.5) kkSig = RooVoigtian("kkSig", "kkSig", tt_mass, kkMean, kkGamma, kkSigma) #kkSig = RooGaussian("kkSig","kkSig",tt_mass,kkMean,kkGamma)#,kkSigma) #kkBkg = RooBernstein("kkBkg" , "kkBkg", tt_mass, RooArgList(B_1, B_2,B_3,B_4))#,B_5) )#,B_6)) kkBkg = RooChebychev("kkBkg", "Background", tt_mass, poliset) kkTot = RooAddPdf("kkTot", "kkTot", RooArgList(kkSig, kkBkg), RooArgList(nSigKK, nBkgKK)) nfit = 0 #kkfit = kkTot.fitTo(traKFitData,Range(fitphimin+0.005,fitphimax-0.005),RooFit.PrintLevel(-1), RooFit.NumCPU(7),RooFit.Save()) #nfit +=1 if debugging: kkGamma.setConstant(kTRUE) kkMean.setConstant(kTRUE) kkSigma.setConstant(kTRUE) a0.setConstant(kTRUE) a1.setConstant(kTRUE) a2.setConstant(kTRUE)
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 fitData(fulldata, ibin, nRT_fromMC, nWT_fromMC): cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % ( q2binning[ibin], q2binning[ibin + 1]) fulldata_v2 = fulldata.reduce( RooArgSet(tagged_mass, mumuMass, mumuMassE, randVar), cut) ## reduce to data-like statistics nDataEntries = fulldata_v2.sumEntries() nDesired = n_bin[ibin] / nDataEntries cut = 'rand < %f' % nDesired data = fulldata_v2.reduce(RooArgSet(tagged_mass, mumuMass, mumuMassE), cut) fraction = dict_s_rt[ibin] / (dict_s_rt[ibin] + dict_s_wt[ibin]) print 'mistag fraction on MC for bin ', ibin, ' : ', fraction.n, '+/-', fraction.s ### creating RT component w.loadSnapshot("reference_fit_RT_%s" % ibin) mean_rt = w.var("mean_{RT}^{%s}" % ibin) sigma_rt1 = w.var("#sigma_{RT1}^{%s}" % ibin) sigma_rt2 = RooRealVar() alpha_rt1 = RooRealVar() alpha_rt2 = RooRealVar() n_rt1 = RooRealVar() n_rt2 = RooRealVar() f1rt = RooRealVar() ## double cb fast if ibin < 4: alpha_rt1 = w.var("#alpha_{RT1}^{%s}" % ibin) alpha_rt2 = w.var("#alpha_{RT2}^{%s}" % ibin) n_rt1 = w.var("n_{RT1}^{%s}" % ibin) n_rt2 = w.var("n_{RT2}^{%s}" % ibin) ## double cb old else: sigma_rt2 = w.var("#sigma_{RT2}^{%s}" % ibin) alpha_rt1 = w.var("#alpha_{RT1}^{%s}" % ibin) alpha_rt2 = w.var("#alpha_{RT2}^{%s}" % ibin) n_rt1 = w.var("n_{RT1}^{%s}" % ibin) n_rt2 = w.var("n_{RT2}^{%s}" % ibin) f1rt = w.var("f^{RT%s}" % ibin) theRTgauss = w.pdf("doublecb_RT%s" % ibin) ### creating WT component w.loadSnapshot("reference_fit_WT_%s" % ibin) mean_wt = w.var("mean_{WT}^{%s}" % ibin) sigma_wt = w.var("#sigma_{WT1}^{%s}" % ibin) alpha_wt1 = w.var("#alpha_{WT1}^{%s}" % ibin) alpha_wt2 = w.var("#alpha_{WT2}^{%s}" % ibin) n_wt1 = w.var("n_{WT1}^{%s}" % ibin) n_wt2 = w.var("n_{WT2}^{%s}" % ibin) theWTgauss = w.pdf("doublecb_%s" % ibin) ### creating variable for the difference between the two peaks deltaPeaks = RooFormulaVar("deltaPeaks", "@0 - @1", RooArgList(mean_rt, mean_wt)) frt = RooRealVar("F_{RT}", "frt", fraction.n, 0, 1) signalFunction = RooAddPdf("sumgaus", "rt+wt", RooArgList(theRTgauss, theWTgauss), RooArgList(frt)) ### now create background parametrization slope = RooRealVar("slope", "slope", 0.5, -10, 10) bkg_exp = RooExponential("bkg_exp", "exponential", slope, tagged_mass) pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10) bkg_pol = RooChebychev("bkg_pol", "2nd order pol", tagged_mass, RooArgList(pol_c1)) nsig = RooRealVar("Yield", "signal frac", nRT_fromMC + nWT_fromMC, 0, 1000000) nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 550000) print nsig.getVal() ### creating constraints c_vars = RooArgSet() c_pdfs = RooArgSet() c_sigma_rt1 = _constrainVar(sigma_rt1, 1) c_alpha_rt1 = _constrainVar(alpha_rt1, 1) c_alpha_rt2 = _constrainVar(alpha_rt2, 1) c_n_rt1 = _constrainVar(n_rt1, 1) c_n_rt2 = _constrainVar(n_rt2, 1) c_sigma_wt = _constrainVar(sigma_wt, 1) c_alpha_wt1 = _constrainVar(alpha_wt1, 1) c_alpha_wt2 = _constrainVar(alpha_wt2, 1) c_n_wt1 = _constrainVar(n_wt1, 1) c_n_wt2 = _constrainVar(n_wt2, 1) if ibin < 4: c_pdfs = RooArgSet(c_sigma_rt1, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2) c_vars = RooArgSet(sigma_rt1, alpha_rt1, alpha_rt2, n_rt1, n_rt2) else: c_sigma_rt2 = _constrainVar(sigma_rt2, 1) c_f1rt = _constrainVar(f1rt, 1) c_pdfs = RooArgSet(c_sigma_rt1, c_sigma_rt2, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2, c_f1rt) c_vars = RooArgSet(sigma_rt1, sigma_rt2, alpha_rt1, alpha_rt2, n_rt1, n_rt2, f1rt) c_pdfs.add(c_sigma_wt) c_vars.add(sigma_wt) c_pdfs.add(c_alpha_wt1) c_vars.add(alpha_wt1) c_pdfs.add(c_alpha_wt2) c_vars.add(alpha_wt2) c_pdfs.add(c_n_wt1) c_vars.add(n_wt1) c_pdfs.add(c_n_wt2) c_vars.add(n_wt2) ### creating constraints for the difference between the two peaks c_deltaPeaks = RooGaussian( "c_deltaPeaks", "c_deltaPeaks", deltaPeaks, ROOT.RooFit.RooConst(deltaPeaks.getVal()), ROOT.RooFit.RooConst(0.0005) ## value to be checked ) c_pdfs.add(c_deltaPeaks) c_vars.add(deltaPeaks) c_frt = RooGaussian("c_frt%s" % ibin, "c_frt", frt, ROOT.RooFit.RooConst(fraction.n), ROOT.RooFit.RooConst(frt_sigma[ibin])) c_pdfs.add(c_frt) c_vars.add(frt) constr_list = RooArgList(c_pdfs) constr_list.add(signalFunction) c_signalFunction = RooProdPdf("c_signalFunction", "c_signalFunction", constr_list) fitFunction = c_signalFunction r = fitFunction.fitTo( data, # RooFit.Extended(True), RooFit.Range("full"), ROOT.RooFit.Constrain(c_vars), ROOT.RooFit.Minimizer("Minuit2", "migrad"), ROOT.RooFit.Hesse(True), ROOT.RooFit.Strategy(2), ROOT.RooFit.Minos(False), ) print 'fit with Hesse strategy 2 done, now Minos' r = fitFunction.fitTo( data, # RooFit.Extended(True), RooFit.Save(), RooFit.Range("full"), RooFit.Verbose(False), ROOT.RooFit.Constrain(c_vars), # ROOT.RooFit.Minimizer("Minuit2","migrad"), # ROOT.RooFit.Hesse(True), ROOT.RooFit.Strategy(2), ROOT.RooFit.Minos(True), ) r.Print() r.correlationMatrix().Print() fitStats['data%s' % (ibin)] = r.status() covStats['data%s' % (ibin)] = r.covQual() frame = tagged_mass.frame(RooFit.Range("full")) data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7)) fitFunction.plotOn(frame, RooFit.NormRange("full"), RooFit.Range("full")) ## evaluate sort of chi2 and save number of RT/WT events observables = RooArgSet(tagged_mass) flparams = fitFunction.getParameters(observables) nparam = int(flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize()) pdfstring = "c_signalFunction_Norm[tagged_mass]_Range[full]_NormRange[full]" chi2s['data%s' % ibin] = frame.chiSquare(pdfstring, "h_fulldata", nparam) frame.addObject(_writeChi2(chi2s['data%s' % ibin])) drawPdfComponents(fitFunction, frame, ROOT.kAzure, RooFit.NormRange("full"), RooFit.Range("full"), isData=True) parList = RooArgSet(nsig, mean_rt, mean_wt, sigma_rt1, sigma_rt2, alpha_rt1, alpha_rt2, mean_wt, sigma_wt) parList.add(alpha_wt1) parList.add(alpha_wt2) parList.add(n_wt1) parList.add(n_wt2) parList.add(frt) fitFunction.paramOn(frame, RooFit.Parameters(parList), RooFit.Layout(0.62, 0.86, 0.89)) frame.Draw() niceFrame(frame, '') frame.addObject(_writeFitStatus(r)) c1 = ROOT.TCanvas() upperPad = ROOT.TPad('upperPad', 'upperPad', 0., 0.35, 1., 1.) lowerPad = ROOT.TPad('lowerPad', 'lowerPad', 0., 0.0, 1., 0.345) upperPad.SetBottomMargin(0.012) lowerPad.SetTopMargin(0) lowerPad.SetBottomMargin(0.2) upperPad.Draw() lowerPad.Draw() upperPad.cd() frame.Draw() if not args.year == 'test': writeCMS(frame, args.year, [q2binning[ibin], q2binning[ibin + 1]], 1) frame.Draw() ## add plot of pulls lowerPad.cd() hpull = frame.pullHist("h_fulldata", pdfstring) frame2 = tagged_mass.frame(RooFit.Range("full"), RooFit.Title('')) frame2.addPlotable(hpull, "P") niceFrameLowerPad(frame2, 'pull') frame2.Draw() line = ROOT.TLine(5.0, 1, 5.6, 1) line.SetLineColor(ROOT.kGreen + 3) line.Draw() for ilog in [True, False]: upperPad.SetLogy(ilog) c1.SaveAs( 'fit_results_mass_checkOnMC/save_fit_data_%s_%s_LMNR_newSigmaFRT_%s.pdf' % (ibin, args.year, '_logScale' * ilog)) out_f.cd() r.Write('results_data_%s' % (ibin)) params = fitFunction.getParameters(RooArgSet(tagged_mass)) w.saveSnapshot("reference_fit_data_%s" % (ibin), params, ROOT.kTRUE) getattr(w, 'import')(fitFunction)
def fitMass(rangem=[0.4, 2.0], iflag=1, iopt_bkgshape=0, CBpar=[0., 0., 0.]): global myc, fitres m0 = sum(rangem) / 2 #w0=(rangem[1]-rangem[0])/10 w0 = 0.004 mass = RooRealVar("ee_ivm", "ee_ivm", rangem[0], rangem[1]) if iflag == 1: ###Construct signal pdf with gaus mean = RooRealVar("mean", "mean", m0) sigma = RooRealVar("sigma", "sigma", w0) signal = RooGaussian("signal", "signal", mass, mean, sigma) elif iflag == 2 or iflag == 3: ## Construct signal pdf with CB function ##print "outinfo",x,CBpar[0],CBpar[1],CBpar[2],CBpar[3] cbmean = RooRealVar("cbmean", "cbmean", m0) cbsigma = RooRealVar("cbsigma", "cbsigma", CBpar[0]) n1 = RooRealVar("n1", "", CBpar[1]) alpha = RooRealVar("alpha", "", CBpar[2]) cbsigma.setConstant(ROOT.kTRUE) n1.setConstant(ROOT.kTRUE) alpha.setConstant(ROOT.kTRUE) signal = RooCBShape("cball", "crystal ball1", mass, cbmean, cbsigma, alpha, n1) # elif iflag ==3: # pass else: print "ERROR, please specify signal shape for fitting!!" sys.exit() # Construct background pdf a0 = RooRealVar("a0", "a0", 0.1, -1, 1) a1 = RooRealVar("a1", "a1", 0.004, -1, 1) a2 = RooRealVar("a2", "a2", 0.001, -1, 1) if iopt_bkgshape == 0: background = RooChebychev("background", "background", mass, RooArgList(a0, a1)) else: background = RooChebychev("background", "background", mass, RooArgList(a0, a1, a2)) # Construct composite pdf if iflag == 1: up_nsig = 40 else: up_nsig = 60 nsig = RooRealVar("nsig", "nsig", 5, 0.0, up_nsig) nbkg = RooRealVar("nbkg", "nbkg", 800, 0, 3000) #frac = RooRealVar("frac", "frac", 0.001, 0.0001, 0.1) model = RooAddPdf("model", "model", RooArgList(signal, background), RooArgList(nsig, nbkg)) #model = RooAddPdf("model", "model", RooArgList(signal, background), RooArgList(frac)) mcdata = RooDataSet( "ds", "ds", RooArgSet(mass), RooFit.Import(data), RooFit.Cut("ee_ivm<" + str(rangem[1]) + "&&ee_ivm>" + str(rangem[0]))) if optp == 1: ipr = 1 verbose = 0 elif optp == 2: ipr = 1 verbose = 1 else: ipr = -1 verbose = 0 fitres=model.fitTo(mcdata,RooFit.Save(),RooFit.Minos(1), RooFit.Strategy(2),\ RooFit.PrintLevel(ipr), RooFit.Verbose(verbose)) nll = RooNLLVar("nll", "nll", model, mcdata, RooFit.Range(rangem[0], rangem[1])) pll = nll.createProfile(RooArgSet(nsig)) Profile = RooProfileLL("Profile", "Profile", nll, RooArgSet(nsig)) llhoodP = RooFormulaVar("llhoodP", "exp(-0.5*Profile)", RooArgList(Profile)) xframe2 = nsig.frame(RooFit.Title("number of signal")) nllplot = nll.plotOn(xframe2, RooFit.ShiftToZero()) themin = RooConstVar("themin", "themin", nllplot.GetMinimum()) llhood = RooFormulaVar("llhood", "exp(-0.5*(nll-themin*0.95))", RooArgList(nll, themin)) if optp: xframe = mass.frame(RooFit.Title("mass of ee pair")) xframe3 = nsig.frame(RooFit.Title("number of signal")) xframe3.SetYTitle("Likelihood") mcdata.plotOn(xframe) model.plotOn(xframe) model.plotOn(xframe, RooFit.Components("background"), RooFit.LineStyle(ROOT.kDashed), RooFit.LineColor(ROOT.kRed)) model.plotOn(xframe, RooFit.Components("cball"), RooFit.LineStyle(ROOT.kDashed), RooFit.LineColor(ROOT.kGreen)) myc.cd(1) xframe.Draw() #pll.plotOn(xframe2,RooFit.LineColor(ROOT.kRed)) if optp: print "***** archmin ", themin.Print() #llhoodP.plotOn(xframe3, RooFit.LineColor(ROOT.kRed)) llhood.plotOn(xframe3) myc.cd(2) xframe2.SetMinimum(0) xframe2.Draw() myc.cd(3) xframe3.Draw() myc.Update() raw_input() nsig.setRange("IntRange1", 0, 1000.) Int1 = llhood.createIntegral(RooArgSet(nsig), ROOT.RooFit.Range('IntRange1')) Int1Val = Int1.getVal() i = 0 hit = False while not (hit): i = i + 1 nsig.setRange("IntRange2", 0, float(i)) Int2 = llhood.createIntegral(RooArgSet(nsig), ROOT.RooFit.Range('IntRange2')) if Int2.getVal() >= Int1Val * 0.9: if optp: print "&&& ", i hit = True return i
def fitData(fulldata, ibin, n_bkg, w): cut = cut_base + '&& (mumuMass*mumuMass > %s && mumuMass*mumuMass < %s)' % ( q2binning[ibin], q2binning[ibin + 1]) fulldata_v2 = fulldata.reduce( RooArgSet(tagged_mass, mumuMass, mumuMassE, randVar), cut) ## reduce to data-like statistics nDataEntries = fulldata_v2.sumEntries() nDesired = n_bin[ibin] / nDataEntries cut = 'rand < %f' % nDesired signaldata = fulldata_v2.reduce( RooArgSet(tagged_mass, mumuMass, mumuMassE), cut) n_realsignal = signaldata.sumEntries() nrt_mc = _getFittedVar("nRT_%s" % ibin, w) nwt_mc = _getFittedVar("nWT_%s" % ibin, w) fraction = nrt_mc / (nrt_mc + nwt_mc) ### creating RT component w.loadSnapshot("reference_fit_RT_%s" % ibin) meanrt = w.var("mean^{RT%s}" % ibin) sigmart = RooRealVar() sigmart1 = RooRealVar() sigmart2 = RooRealVar() alphart1 = RooRealVar() alphart2 = RooRealVar() nrt1 = RooRealVar() nrt2 = RooRealVar() ## double cb fast if ibin < 5: sigmart = w.var("#sigma_{CB}^{RT%s}" % ibin) alphart1 = w.var("#alpha_{1}^{RT%s}" % ibin) alphart2 = w.var("#alpha_{2}^{RT%s}" % ibin) nrt1 = w.var("n_{1}^{RT%s}" % ibin) nrt2 = w.var("n_{2}^{RT%s}" % ibin) ## double cb old else: sigmart1 = w.var("#sigma_{CBRT0}^{%s}" % ibin) sigmart2 = w.var("#sigma_{CBRT1}^{%s}" % ibin) alphart1 = w.var("#alpha_{RT0}^{%s}" % ibin) alphart2 = w.var("#alpha_{RT1}^{%s}" % ibin) nrt1 = w.var("n_{RT0}^{%s}" % ibin) nrt2 = w.var("n_{RT1}^{%s}" % ibin) pars_init_vals = {} theRTgauss = w.pdf("doublecb_RT%s" % ibin) if ibin < 5: c_sigma_rt = _constrainVar(sigmart, 1, pars_init_vals) else: c_sigma_rt1 = _constrainVar(sigmart1, 1, pars_init_vals) c_sigma_rt2 = _constrainVar(sigmart2, 1, pars_init_vals) c_alpha_rt1 = _constrainVar(alphart1, 1, pars_init_vals) c_alpha_rt2 = _constrainVar(alphart2, 1, pars_init_vals) c_n_rt1 = _constrainVar(nrt1, 1, pars_init_vals) c_n_rt2 = _constrainVar(nrt2, 1, pars_init_vals) ### creating WT component w.loadSnapshot("reference_fit_WT_%s" % ibin) meanwt = w.var("mean^{WT%s}" % ibin) sigmawt = w.var("#sigma_{CB}^{WT%s}" % ibin) alphawt1 = w.var("#alpha_{1}^{WT%s}" % ibin) alphawt2 = w.var("#alpha_{2}^{WT%s}" % ibin) nwt1 = w.var("n_{1}^{WT%s}" % ibin) nwt2 = w.var("n_{2}^{WT%s}" % ibin) theWTgauss = w.pdf("doublecb_%s" % ibin) c_sigma_wt = _constrainVar(sigmawt, 1, pars_init_vals) c_alpha_wt1 = _constrainVar(alphawt1, 1, pars_init_vals) c_alpha_wt2 = _constrainVar(alphawt2, 1, pars_init_vals) c_n_wt1 = _constrainVar(nwt1, 1, pars_init_vals) c_n_wt2 = _constrainVar(nwt2, 1, pars_init_vals) ### creating constraints for the RT component c_vars = RooArgSet() if ibin < 5: c_RTgauss = RooProdPdf( "c_RTgauss", "c_RTgauss", RooArgList(theRTgauss, c_alpha_rt1, c_n_rt1, c_sigma_rt, c_alpha_rt2, c_n_rt2)) c_vars = RooArgSet(c_sigma_rt, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2) else: c_RTgauss = RooProdPdf( "c_RTgauss", "c_RTgauss", RooArgList(theRTgauss, c_alpha_rt1, c_n_rt1, c_sigma_rt1, c_sigma_rt2, c_alpha_rt2, c_n_rt2)) c_vars = RooArgSet(c_sigma_rt1, c_sigma_rt2, c_alpha_rt1, c_alpha_rt2, c_n_rt1, c_n_rt2) ### creating constraints for the WT component c_WTgauss = RooProdPdf( "c_WTgauss", "c_WTgauss", RooArgList(theWTgauss, c_alpha_wt1, c_n_wt1, c_sigma_wt, c_alpha_wt2, c_n_wt2)) c_vars.add(c_sigma_wt) c_vars.add(c_alpha_wt1) c_vars.add(c_alpha_wt2) c_vars.add(c_n_wt1) c_vars.add(c_n_wt2) frt = RooRealVar("F_{RT}", "frt", fraction.n, 0, 1) signalFunction = RooAddPdf("sumgaus", "rt+wt", RooArgList(c_RTgauss, c_WTgauss), RooArgList(frt)) c_frt = RooGaussian("c_frt", "c_frt", frt, ROOT.RooFit.RooConst(fraction.n), ROOT.RooFit.RooConst(fraction.s)) ### creating constraints for the difference between the two peaks deltaPeaks = RooFormulaVar("deltaPeaks", "@0 - @1", RooArgList(meanrt, meanwt)) c_deltaPeaks = RooGaussian( "c_deltaPeaks", "c_deltaPeaks", deltaPeaks, ROOT.RooFit.RooConst(deltaPeaks.getVal()), ROOT.RooFit.RooConst(0.0005) ## value to be checked ) c_signalFunction = RooProdPdf( "c_signalFunction", "c_signalFunction", RooArgList(signalFunction, c_frt, c_deltaPeaks)) c_vars.add(frt) c_vars.add(deltaPeaks) ### now create background parametrization slope = RooRealVar("slope", "slope", 0.5, -10, 10) bkg_exp = RooExponential("bkg_exp", "exponential", slope, tagged_mass) pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10) bkg_pol = RooChebychev("bkg_pol", "2nd order pol", tagged_mass, RooArgList(pol_c1, pol_c2)) nsig = RooRealVar("Yield", "signal frac", nrt_mc.n + nwt_mc.n, 0, 1000000) nbkg = RooRealVar("nbkg", "bkg fraction", 1000, 0, 550000) print nsig.getVal() fitFunction = RooAddPdf("fitfunction", "fit function", RooArgList(c_signalFunction, bkg_pol), RooArgList(nsig, nbkg)) pars_to_tune = [ sigmawt, alphawt1, alphawt2, nwt1, nwt2, alphart1, alphart2, nrt1, nrt2 ] if ibin < 5: pars_to_tune.append(sigmart) else: pars_to_tune.append(sigmart1) pars_to_tune.append(sigmart2) ## add toy bkg for itoy in range(args.ntoys): data = deepcopy(signaldata) toy_bkg = generateBkg(tagged_mass, ibin, n_bkg) data.append(toy_bkg) print 'toy number', itoy for ipar in pars_to_tune: ipar.setVal(pars_init_vals[ipar.GetName()]) # r = fitFunction.fitTo(data, # RooFit.Extended(True), # RooFit.Range("full"), # ROOT.RooFit.Constrain(c_vars), # # ROOT.RooFit.Minimizer("Minuit2","migrad"), # ROOT.RooFit.Hesse(True), # ROOT.RooFit.Strategy(2), # ROOT.RooFit.Minos(False), # ) # # print 'fit with Hesse strategy 2 done, now Minos' r = fitFunction.fitTo( data, RooFit.Extended(True), RooFit.Save(), RooFit.Range("full"), RooFit.Verbose(False), ROOT.RooFit.Constrain(c_vars), # ROOT.RooFit.Minimizer("Minuit2","migrad"), # ROOT.RooFit.Hesse(True), ROOT.RooFit.Strategy(2), ROOT.RooFit.Minos(True), ) # # r.Print() # # r.correlationMatrix().Print() fitStats['data%s_itoy%s' % (ibin, itoy)] = r.status() covStats['data%s_itoy%s' % (ibin, itoy)] = r.covQual() frame = tagged_mass.frame(RooFit.Range("full")) data.plotOn(frame, RooFit.Binning(nbins), RooFit.MarkerSize(.7)) fitFunction.plotOn(frame, RooFit.NormRange("full"), RooFit.Range("full")) ## evaluate sort of chi2 and save number of RT/WT events observables = RooArgSet(tagged_mass) flparams = fitFunction.getParameters(observables) nparam = int( flparams.selectByAttrib("Constant", ROOT.kFALSE).getSize()) pdfstring = "fitfunction_Norm[tagged_mass]_Range[full]_NormRange[full]" chi2s['data%s_itoy%s' % (ibin, itoy)] = frame.chiSquare( pdfstring, "h_fulldata", nparam) frame.addObject(_writeChi2(chi2s['data%s_itoy%s' % (ibin, itoy)])) ## save plot only if 1 toy is run if args.ntoys == 1: drawPdfComponents(fitFunction, frame, ROOT.kAzure, RooFit.NormRange("full"), RooFit.Range("full"), isData=True) fitFunction.paramOn(frame, RooFit.Layout(0.62, 0.86, 0.89)) # parList = RooArgSet (nsig, nbkg, meanrt, meanwt, alphart1, alphart2, meanwt, sigmawt) # if ibin < 5 : # parList.add(sigmart) # else: # parList.add(sigmart1) # parList.add(sigmart2) # parList.add(alphawt1) # parList.add(alphawt2) # parList.add(nwt1) # parList.add(nwt2) # parList.add(frt) # fitFunction.paramOn(frame, RooFit.Parameters(parList), RooFit.Layout(0.62,0.86,0.89)) frame.Draw() niceFrame(frame, '') frame.addObject(_writeFitStatus(r)) c1 = ROOT.TCanvas() upperPad = ROOT.TPad('upperPad', 'upperPad', 0., 0.35, 1., 1.) lowerPad = ROOT.TPad('lowerPad', 'lowerPad', 0., 0.0, 1., 0.345) upperPad.SetBottomMargin(0.012) lowerPad.SetTopMargin(0) lowerPad.SetBottomMargin(0.2) upperPad.Draw() lowerPad.Draw() upperPad.cd() frame.Draw() if not args.year == 'test': writeCMS(frame, args.year, [q2binning[ibin], q2binning[ibin + 1]], 1) frame.Draw() ## add plot of pulls lowerPad.cd() hpull = frame.pullHist("h_fulldata", pdfstring) frame2 = tagged_mass.frame(RooFit.Range("full"), RooFit.Title('')) frame2.addPlotable(hpull, "P") niceFrameLowerPad(frame2, 'pull') frame2.Draw() line = ROOT.TLine(5.0, 1, 5.6, 1) line.SetLineColor(ROOT.kGreen + 3) line.Draw() for ilog in [True, False]: upperPad.SetLogy(ilog) c1.SaveAs( 'fit_results_mass_checkOnMC/toybkg/save_fit_data_%s_%s_nbkg%s_LMNR_Final%s_%s_update_pol2bkg.pdf' % (ibin, args.year, n_bkg, '_logScale' * ilog, itoy)) out_f.cd() # r.Write('results_data_%s_ntoy%s'%(ibin,itoy)) ## compare nkbg fitted w/ original value nbkgs['data%s_itoy%s' % (ibin, itoy)] = (toy_bkg.sumEntries() - nbkg.getVal()) / toy_bkg.sumEntries() nsigs['data%s_itoy%s' % (ibin, itoy)] = (n_realsignal - nsig.getVal()) / n_realsignal
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
def RooFitHist(inputhist,title='title',path='.'): # RooFit.gErrorIgnoreLevel = RooFit.kInfo # <6.02 # RooFit.SetSilentMode()# >6.02 # RooMsgService().instance().SetSilentMode(kTRUE) fitbinning=array('d') binwidth=200 #NBins=(14000/binwidth) - ( (1040/binwidth) + 1 ) Mjj NBins=(8000/binwidth) - ( (200/binwidth)+1 )#pT for i in range(NBins+1): fitbinning.append(210+i*binwidth)# Mjj 1050 # print(fitbinning) #import numpy as np #fitbinning=np.linspace(0,8000,81) hist=inputhist.Rebin(NBins,"fit parameter",fitbinning) #hist=inputhist.Rebin(80,"fit parameter", fitbinning) #meanstart=hist.GetBinCenter(2000) meanstart=hist.GetBinCenter(hist.GetMaximumBin())#maximum sigmastart=hist.GetRMS() #sigmastart=3000 print('meanstart:',meanstart,'sigmastart:',sigmastart) # inputhist.Draw() # hist.Draw() # hold=raw_input('press enter to exit.') gStyle.SetOptFit(1111) gStyle.SetOptTitle(0) RooFit.SumW2Error(kTRUE) RooFit.Extended(kTRUE) # RooDataHist::adjustBinning(dh): fit range of variable mjj expanded to nearest bin boundaries: [1050,13850] --> [1050,13850] mjj=RooRealVar('mjj','P_{T-AK8}',fitbinning[0],fitbinning[len(fitbinning)-1],'GeV') mjjral=RooArgList(mjj) dh=RooDataHist('dh','dh',mjjral,RooFit.Import(hist)) #shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.Extended(True),RooFit.SumW2Error(False)) shapes={} #Gaussian not really # 3rd, 4th and 5th arguments are: (starting value, minimum possible value, maximum possible value) -- not goot gaussmean = RooRealVar('#mu_{gauss}','mass mean value',meanstart,0,2*meanstart) gausssigma= RooRealVar('#sigma_{gauss}','mass resolution',sigmastart,0,2*meanstart) gauss=RooGaussian('gauss','gauss',mjj,gaussmean,gausssigma) shapes.update({'Gauss':gauss}) #poisson poissonmean = RooRealVar('#mu_{poisson}', 'pT mean value', meanstart,0,2*meanstart) poissonsigma = RooRealVar('#sigma_{poisson]', 'pT resolution', sigmastart, 0, 2*sigmastart) poisson = RooPoisson('poisson', 'poisson', mjj, poissonmean, False) shapes.update({'Poisson': poisson}) #Landau -- not good landaumean=RooRealVar('#mu_{landau}','mean landau',meanstart,0,2*meanstart) landausigma= RooRealVar('#sigma_{landau}','mass resolution',sigmastart,0,2*sigmastart)#bzw8 landau=RooLandau('landau','landau',mjj,landaumean,landausigma) shapes.update({'Landau':landau}) #CrystalBall -> this is close to be good but matrix error :( mean = RooRealVar('#mu','mean',meanstart,0,2*meanstart) sigma= RooRealVar('#sigma','sigma',sigmastart,0,2*sigmastart) alpha=RooRealVar('#alpha','Gaussian tail',-1000,0) n=RooRealVar('n','Normalization',-1000,1000) cbshape=RooCBShape('cbshape','crystalball PDF',mjj,mean,sigma,alpha,n) shapes.update({'CrystalBall':cbshape}) #Voigt ---pff voigtmean = RooRealVar('#mu','mass mean value',meanstart,0,2*meanstart) voigtwidth = RooRealVar('#gamma','width of voigt',0,100) voigtsigma= RooRealVar('#sigma','mass resolution',sigmastart,0,150) voigt=RooVoigtian('voigt','voigt',mjj,voigtmean,voigtwidth,voigtsigma) shapes.update({'Voigt':voigt}) #BreitWigner--worst bwmean = RooRealVar('#mu','mass mean value',meanstart,0,2*meanstart) bwwidth = RooRealVar('#sigma','width of bw',sigmastart,100, 150) bw=RooBreitWigner('bw','bw',mjj,bwmean,bwwidth) shapes.update({'BreitWigner':bw}) #Logistics #logisticsmean=RooRealVar('#mu_{logistics}','mean logistics',meanstart,0,2*meanstart) #logisticssigma= RooRealVar('#sigma_{logistics}','mass resolution',sigmastart,0,2*sigmastart) #logistics=RooLogistics('logistics','logistics',mjj,logisticsmean,logisticssigma) #shapes.update({'Logistics':logistics}) #ExpAndGauss expgaussmean=RooRealVar('#mu_{expgauss}','mean expgauss',meanstart,490,900) expgausssigma= RooRealVar('#sigma_{expgauss}','mass resolution',sigmastart,20,3*sigmastart) expgausstrans= RooRealVar('trans','trans',0,1000) ExpAndGauss=RooExpAndGauss('expgauss','expgauss',mjj,expgaussmean,expgausssigma,expgausstrans) shapes.update({'ExpAndGauss':ExpAndGauss}) #Exp #expmean=RooRealVar('') #BifurGauss -bad BifurGaussmean=RooRealVar('#mu_{BifurGauss}','mean BifurGauss',meanstart,0,2*meanstart) BifurGausslsigma= RooRealVar('#sigma_{left}','mass resolution',sigmastart,200,2*sigmastart)#2*sigmastart BifurGaussrsigma= RooRealVar('#sigma_{right}','mass resolution',sigmastart,200,2*sigmastart) BifurGauss=RooBifurGauss('BifurGauss','BifurGauss',mjj,BifurGaussmean,BifurGausslsigma,BifurGaussrsigma) shapes.update({'BifurGauss':BifurGauss}) #Chebychev -nope Chebychev1=RooRealVar('c0','Chebychev0',-1000,1000) Chebychev2= RooRealVar('c1','Chebychev1',-1000,1000) Chebychev3= RooRealVar('c2','Chebychev2',2,-1000,1000) Chebychev=RooChebychev('Chebychev','Chebychev',mjj,RooArgList(Chebychev1,Chebychev2,Chebychev3)) shapes.update({'Chebychev':Chebychev}) #Polynomial -nope Polynomial1=RooRealVar('Polynomial1','Polynomial1',100,0,1000) Polynomial2= RooRealVar('Polynomial2','Polynomial2',100,0,1000) Polynomial=RooPolynomial('Polynomial','Polynomial',mjj,RooArgList(Polynomial1,Polynomial2)) shapes.update({'Polynomial':Polynomial}) #pareto #___________________________________________________________We will see #Convolutions #-> use bin > 1000 for better accuracy -----cyclic trouble #-> Convolution depends on order!!! RooFFTConvPdf the first p.d.f. is the theory model and that the second p.d.f. is the resolution model # #LandauGauss Convolution - really bad landaugauss=RooFFTConvPdf('landaugauss','landau x gauss',mjj,landau, gauss) #landaugauss.setBufferFraction(126) shapes.update({'LandauGauss':landaugauss}) #GaussLandau Convolution -> Better but NOT posdef. ...but for 100 it is gausslandau=RooFFTConvPdf('gausslandau','gauss x landau ',mjj,gauss,landau) #gausslandau.setBufferFraction(126) shapes.update({'GaussLandau':gausslandau}) #CrystalBallLandau Convolution cbshape x landau looks better -> status failed crystlandau=RooFFTConvPdf('crystallandau','cbshape x landau', mjj, landau, cbshape) crystlandau.setBufferFraction(39) shapes.update({'CrystLandau': crystlandau}) #BifurGaussLandau Convolution -> Better in look, NO matrix error for Binwidth 200 BifurGaussLandau=RooFFTConvPdf('bifurgausslandau','landau x bifurgauss',mjj,landau, BifurGauss) BifurGaussLandau.setBufferFraction(39) #against over cycling shapes.update({'BifurGaussLandau':BifurGaussLandau}) #CrystalGauss Convolution looks better -> status failed crystgauss=RooFFTConvPdf('crystalgauss','cbshape x gauss', mjj, cbshape, gauss) #crystgauss.setBufferFraction(39) shapes.update({'CrystGauss': crystgauss}) #BreitWignerLandau Convolution (Breitwigner = Lorentz)-> status OK.... BreitWignerLandau=RooFFTConvPdf('breitwignerlandau','breitwigner x landau',mjj,landau,bw,3) #BreitWignerLandau.setBufferFraction(48) #setBufferFraction(fraction of the sampling array size) ->cyclic behaviour fix #crystgauss.setShift(0,0) #s1 and s2 are the amounts by which the sampling ranges for pdf's are shifted respectively #(0,-(xmin+xmax)/2) replicates the default behavior #(0,0) disables the shifting feature altogether shapes.update({'BreitWignerLandau':BreitWignerLandau}) for fname in ['ExpAndGauss']: plottitle='%s Fit of %s'%(fname,title) shape=shapes[fname] # shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.SumW2Error(True)) #shape.fitTo(dh,RooFit.Extended(True),RooFit.SumW2Error(True)) mjj.setRange("FitRange",500,4000)#tried shape.fitTo(dh,RooFit.Range("FitRange"),RooFit.Extended(False),RooFit.SumW2Error(True)) frame=mjj.frame(RooFit.Title(plottitle)) #frame.GetYaxis().SetTitleOffset(2) dh.plotOn(frame,RooFit.MarkerStyle(4)) shape.plotOn(frame,RooFit.LineColor(2)) ndof=dh.numEntries()-3 print ('ndof', ndof) #chiSquare legend chi2 = frame.chiSquare()#there are 2 chiSquare. the 2cond returns chi2/ndf /// \return \f$ \chi^2 / \mathrm{ndf} \f$ print ('chi2', chi2) probChi2 = TMath.Prob(chi2*ndof, ndof)# why chi2*ndof ?! makes no sense to me #Double_t Prob(Double_t chi2, Int_t ndf) #Computation of the probability for a certain Chi-squared (chi2) #and number of degrees of freedom (ndf). #P(a,x) represents the probability that the observed Chi-squared #for a correct model should be less than the value chi2. #The returned probability corresponds to 1-P(a,x), !!!! #which denotes the probability that an observed Chi-squared exceeds #the value chi2 by chance, even for a correct model. #--- NvE 14-nov-1998 UU-SAP Utrecht #probChi2=TMath.Prob(chi2, ndof) chi2 = round(chi2,2) #probChi2 = round(probChi2,2) leg = TLegend(0.5,0.5,0.5,0.65)#0.9 leg.SetBorderSize(0) leg.SetFillStyle(0) shape.paramOn(frame, RooFit.Layout(0.5,0.9,0.9)) leg.AddEntry(0,'#chi^{2} ='+str(chi2),'') leg.AddEntry(0,'Prob #chi^{2} = '+str(probChi2),'') leg.SetTextSize(0.04) frame.addObject(leg) canv=TCanvas(plottitle,plottitle,700,700) canv.SetLogy() canv.SetLeftMargin(0.20) canv.cd() frame.SetMaximum(10**(1)) frame.SetMinimum(10**(-11))#from -3 -> -6 frame.Draw() #canv.Print(path+'/%s__%sS2MoreLessY.pdf'%(title,fname)) raw_input('press enter to continue') return chi2