def fit(model, hists, fitmethod, eps=1.0e-7): """Fit beam shapes to Beam Imaging data. model: Beam shape model (derived from BeamShapeCore). hists: List of four TH2F with BI data. fitmethod: Function(pdf, data) that fits pdf to data. eps: Value of convergence criteria. """ RooAbsReal.defaultIntegratorConfig().setEpsAbs(eps) RooAbsReal.defaultIntegratorConfig().setEpsRel(eps) modfuncs = model.model_functions() datahist = [ RooDataHist('scan{0}Beam{1}RestDataHist'.format(c, i), 'scan{0}Beam{1}RestDataHist'.format(c, i), RooArgList(model.xvar(), model.yvar()), hists[j]) for j, (i, c) in enumerate(ic) ] sample = RooCategory('sample', 'sample') for (i, c) in ic: sample.defineType('{0}_ScanData_Beam{1}Rest'.format(c, i)) combdata = RooDataHist('combdata', 'combined data', RooArgList(model.xvar(), model.yvar()), RooFit.Index(sample), RooFit.Import('X_ScanData_Beam1Rest', datahist[0]), RooFit.Import('Y_ScanData_Beam1Rest', datahist[1]), RooFit.Import('X_ScanData_Beam2Rest', datahist[2]), RooFit.Import('Y_ScanData_Beam2Rest', datahist[3])) simpdf = RooSimultaneous('simpdf', 'simultaneous pdf', sample) for j, (i, c) in enumerate(ic): simpdf.addPdf(modfuncs[j], '{0}_ScanData_Beam{1}Rest'.format(c, i)) result = fitmethod(simpdf, combdata) return result, modfuncs, datahist
def buildPdf(ws, p): mass = RooRealVar("mass", "mass", p.minMass, p.maxMass) getattr(ws,'import')(mass) # Construct signal pdf mean = RooRealVar("mean", "mean", 90, 85, 95) width = RooRealVar("width", "width", 2.4952, 1, 3) width.setConstant(ROOT.kTRUE) sigma = RooRealVar("sigma", "sigma", 1.2, 0.2, 10) signalAll = RooVoigtian("signalAll", "signalAll", mass, mean, width, sigma) turnOnAll = RooRealVar("turnOnAll","turnOnAll", 80., 40., 150.) widthAll_bkg = RooRealVar("widthAll","widthAll", 2., 0., 50.) decayAll_bkg = RooRealVar("decayAll","decayAll", 80., 20., 150.) meanB = RooRealVar("meanB", "meanB", 90, 60, 130) sigmaB = RooRealVar("sigmaB", "sigmaB", 10, 1, 20) bkg_a1 = RooRealVar("bkg_a1", "bkg_a1", 0., -2., 2.) bkg_a2 = RooRealVar("bkg_a2", "bkg_a2", 0., -2., 2.) backgroundAll = RooGaussian("backgroundAll", "backgroundAll", mass, meanB, sigmaB) # Construct composite pdf sigAll = RooRealVar("sigAll", "sigAll", 2000, 0, 100000) bkgAll = RooRealVar("bkgAll", "bkgAll", 100, 0, 10000) modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll, backgroundAll), RooArgList(sigAll, bkgAll)) if p.NoBkgd: modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll), RooArgList(sigAll)) # Define pdf for all probes # Construct signal pdf. # NOTE that sigma is shared with the signal sample model signalPass = RooVoigtian("signalPass","signalPass",mass,mean,width,sigma) # Construct the background pdf backgroundPass = RooGaussian("backgroundPass", "backgroundPass", mass, meanB, sigmaB) # Construct the composite model efficiency = RooRealVar("efficiency","efficiency",0.9,0.3,1.) sigPass = RooFormulaVar("sigPass", "@0*@1", RooArgList(sigAll, efficiency)) bkgPass = RooRealVar("bkgPass", "bkgPass", 100, 0, 10000) modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass, backgroundPass), RooArgList(sigPass, bkgPass)) if p.NoBkgd: modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass), RooArgList(sigPass)) frac = RooRealVar("frac", "frac", 0.8, 0., 1.) # Define combined pdf for simultaneous fit # Define category to distinguish physics and control samples events sample = RooCategory("sample","sample") sample.defineType("all") sample.defineType("pass") simPdf = RooSimultaneous("simPdf","simultaneous pdf",sample) # Associate model with the physics state and model_ctl with the control state simPdf.addPdf(modelAll,"all") simPdf.addPdf(modelPass,"pass") # ws.import(simPdf) getattr(ws,'import')(simPdf)
def main (): N_bkg1 = 9000 N_signal = 1000 N_bkg1_obs = 10000 N_signal_obs = 2000 N_data = N_bkg1_obs + N_signal_obs mu1, mu2, sigma1, sigma2 = 100, 140, 15, 5 x1 = mu1 + sigma1 * np.random.randn( N_bkg1 ) x2 = mu2 + sigma2 * np.random.randn( N_signal ) x1_obs = mu1 + sigma1 * np.random.randn( N_bkg1_obs ) x2_obs = mu2 + sigma2 * np.random.randn( N_signal_obs ) h1 = Hist( 100, 40, 200, title = 'Background' ) h2 = h1.Clone( title = 'Signal' ) h3 = h1.Clone( title = 'Data' ) h3.markersize = 1.2 # fill the histograms with our distributions map( h1.Fill, x1 ) map( h2.Fill, x2 ) map( h3.Fill, x1_obs ) map( h3.Fill, x2_obs ) histograms_1 = {'signal': h2, 'bkg1': h1, 'data': h3} histograms_2 = {'signal': h2, 'bkg1': h1, 'data': h3} # roofit_histograms contains RooDataHist # model = RooAddPdf model1, roofit_histograms_1,fit_variable_1 = get_roofit_model( histograms_1, fit_boundaries = ( 40, 200 ), name = 'm1' ) model2, roofit_histograms_2, fit_variable_2 = get_roofit_model( histograms_2, fit_boundaries = ( 40, 200 ), name = 'm2' ) sample = RooCategory( 'sample', 'sample' ) sample.defineType( 'm1', 1 ) sample.defineType( 'm2', 2 ) combined_data = deepcopy( roofit_histograms_1['data'] ) combined_data.add( roofit_histograms_2['data'] ) # RooDataHist(const char* name, const char* title, const RooArgList& vars, RooCategory& indexCat, map<std::string,TH1*> histMap, Double_t initWgt = 1.0) sim_pdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample ) sim_pdf.addPdf( model1, 'm1' ) sim_pdf.addPdf( model2, 'm2' ) variables = RooArgList() variables.add(fit_variable_1) variables.add(fit_variable_2) # combined_data = RooDataHist('combined_data', 'combined_data', # variables, RooFit.Index(sample), # RooFit.Import('m1', roofit_histograms_1['data']), # RooFit.Import('m2', roofit_histograms_2['data'])) fitResult = sim_pdf.fitTo( combined_data, # RooFit.Minimizer( "Minuit2", "Migrad" ), # RooFit.NumCPU( 1 ), # RooFit.Extended(), RooFit.Save(), )
def CreateSimPdf(w, typ): sim_pdf = RooSimultaneous("%s_sim_pdf" % typ, "", w.cat("cat")) # loop on cats found_one = False for c in range(w.cat("cat").numTypes()): w.cat("cat").setIndex(c) samp = w.cat("cat").getLabel() subpdfname = '%s_pdf_%s' % (typ, samp) if w.pdf(subpdfname): sim_pdf.addPdf(w.pdf(subpdfname), samp) found_one = True if found_one: getattr(w, 'import')(sim_pdf)
def build_model_ext(params, starting_pixels=None, starting_nights=None): num_pixels, num_nights, nstat = params # only need one x x = RooRealVar('x', 'x', 0, 20) starting_pixels = [0.005 for i in range(num_pixels)] starting_nights = [0.3 for i in range(num_nights)] # one dkct value for each pixel dkcts = [RooRealVar('dkct_{}'.format(i), 'dkct_{}'.format(i), starting_pixels[i], 0.000001, 10) for i in range(num_pixels)] # nsbg nsbgs = [RooRealVar('nsbg_{}'.format(i), 'nsbg_{}'.format(i), starting_nights[i], 0.000001, 10) for i in range(num_nights)] # model every spectrum as sum of dkcts and nsbg # for said night and pixel # need to create sum variables sumvars = [[RooFormulaVar('n{}px{}'.format(n, px), 'n{}px{}'.format(n, px), '@0+@1', RooArgList(dkcts[px], nsbgs[n])) for px, _ in enumerate(dkcts)] for n, _ in enumerate(nsbgs)] norm_models = [[RooPoisson('n_model_n{}_px{}'.format(n, px), 'n_model_n{}px{}'.format(n, px), x, sumvars[n][px]) for px, _ in enumerate(dkcts)] for n, _ in enumerate(nsbgs)] norms = [RooRealVar('nm', 'nm', nstat[i]) for i in range(num_nights)] models = [[RooExtendPdf('model_n{}_px{}'.format(n, px), 'model_n{}px{}'.format(n, px), norm_models[n][px], norms[n]) for px, _ in enumerate(dkcts)] for n, _ in enumerate(nsbgs)] # print('models shape:', np.array(models).shape) # indices and simul model index = RooCategory('index', 'index') for night in range(num_nights): for px in range(num_pixels): index.defineType('n{}px{}'.format(night, px)) # simul_model simul_model = RooSimultaneous('smodel', 'smodel', index) for night in range(num_nights): for px in range(num_pixels): simul_model.addPdf(models[night][px], 'n{}px{}'.format(night, px)) return ModelContainer(x, dkcts, nsbgs, index, simul_model, models, sumvars, norm_models, norms, starting_pixels, starting_nights)
def dump_simple_simul(): # idea: take two data sets, both low counts, but same lambda # and fit said lambda simultanously with both sets r_x = RooRealVar('x', 'x', 0, bins) r_lam = RooRealVar('lam', 'lam', 0.5, 0.0, 1.5) r_lam1 = RooRealVar('lam1', 'lam1', 0.5, 0.0, 1.5) r_lam2 = RooRealVar('lam2', 'lam2', 0.5, 0.0, 1.5) model1 = RooPoisson('pois1', 'pois1', r_x, r_lam1) model2 = RooPoisson('pois2', 'pois2', r_x, r_lam2) r_index = RooCategory('index', 'index') r_index.defineType('1') r_index.defineType('2') simul_model = RooSimultaneous('model', 'model', r_index) simul_model.addPdf(model1, '1') simul_model.addPdf(model2, '2') data1 = RooDataSet('', '', RooArgSet(r_x)) for val in unbinned_from_binned(xdata, ydata): r_x.setVal(val) data1.add(RooArgSet(r_x)) r_index.setLabel('1') data1.addColumn(r_index) data2 = RooDataSet('', '', RooArgSet(r_x)) for val in unbinned_from_binned(xdata, ydata2): r_x.setVal(val) data2.add(RooArgSet(r_x)) r_index.setLabel('2') data2.addColumn(r_index) data1.append(data2) _result = simul_model.fitTo(data1) print(r_lam.getVal(), '+-', r_lam.getError(), lam, np.abs(r_lam.getVal() - lam) / lam) print(r_lam1.getVal(), '+-', r_lam1.getError(), lam, np.abs(r_lam1.getVal() - lam) / lam) print(r_lam2.getVal(), '+-', r_lam2.getError(), lam, np.abs(r_lam2.getVal() - lam) / lam)
def fit(self): sim_pdf = RooSimultaneous("simPdf", "simultaneous pdf", self.sample) self.individual_results = {} for name, model in self.models.iteritems(): fit_input = self.fit_data[name] model.fitTo(fit_input.real_data_roofit_histogram()) self.individual_results[name] = fit_input.get_results() sim_pdf.addPdf(model, name) argument_list = RooLinkedList() argument_list.Add(RooFit.Minimizer("Minuit2", "Migrad")) argument_list.Add(RooFit.NumCPU(1)) argument_list.Add(RooFit.Extended()) argument_list.Add(RooFit.Save()) sim_pdf.fitTo( self.comb_data, # argument_list ) # sim_pdf.fitTo( self.combined_data, # RooFit.Minimizer( "Minuit2", "Migrad" ) ) # sim_pdf.fitTo( data = self.combined_data, # arg1 = RooFit.Minimizer( "Minuit2", "Migrad" ), # arg2 = RooFit.NumCPU( 1 ), # arg3 = RooFit.Extended(), # arg4 = RooFit.Save() ) # sim_pdf.fitTo( self.combined_data, # argument_list ) # get fit results results = {} for variable, fit_input in self.fit_data.iteritems(): results[variable] = fit_input.get_results() self.results = results return results
def fit(self): sim_pdf = RooSimultaneous("simPdf", "simultaneous pdf", self.sample) self.individual_results = {} for name, model in self.models.iteritems(): fit_input = self.fit_data[name] model.fitTo(fit_input.real_data_roofit_histogram()) self.individual_results[name] = fit_input.get_results() sim_pdf.addPdf(model, name) argument_list = RooLinkedList() argument_list.Add(RooFit.Minimizer("Minuit2", "Migrad")) argument_list.Add(RooFit.NumCPU(1)) argument_list.Add(RooFit.Extended()) argument_list.Add(RooFit.Save()) sim_pdf.fitTo(self.comb_data, # argument_list ) # sim_pdf.fitTo( self.combined_data, # RooFit.Minimizer( "Minuit2", "Migrad" ) ) # sim_pdf.fitTo( data = self.combined_data, # arg1 = RooFit.Minimizer( "Minuit2", "Migrad" ), # arg2 = RooFit.NumCPU( 1 ), # arg3 = RooFit.Extended(), # arg4 = RooFit.Save() ) # sim_pdf.fitTo( self.combined_data, # argument_list ) # get fit results results = {} for variable, fit_input in self.fit_data.iteritems(): results[variable] = fit_input.get_results() self.results = results return results
print '=' * 5, ' 2-step fit: DsK ', '=' * 5 dsk_fitresult = DsK_Model.fitTo(dsetlist[1], RooFit.Optimize(0), RooFit.Strategy(2), RooFit.Save(True), RooFit.NumCPU(1), RooFit.SumW2Error(True), RooFit.Offset(True), RooFit.Verbose(True)) dsk_fitresult.Print() # undo earlier set constant turnon.setConstant(False) exponent.setConstant(False) offset.setConstant(False) beta.setConstant(False) ## Build simultaneous 2-D PDF (t, δt) for DsPi and DsK PDF = RooSimultaneous('PDF', 'Simultaneous PDF', decaycat) PDF.addPdf(DsPi_Model, 'DsPi') PDF.addPdf(DsK_Model, 'DsK') pdflist += [PDF] # #errorPdf = RooHistPdf('errorPdf', 'Time error Hist PDF', # # RooArgSet(dt), datahist) # errorPdf = RooKeysPdf('errorPdf', 'errorPdf', dt, tmpdata) # PDF = RooProdPdf('PDF', 'Acceptance model with errors B_{s}', # RooArgSet(errorPdf), # RooFit.Conditional(RooArgSet(Model), RooArgSet(time))) # # enable caching for dt integral # PDF.setParameterizeIntegral(RooArgSet(dt)) ## Logging
shifts.append(RooRealVar("shift_"+region, "shift_"+region, 0., -1, 1)) shifts[i].setError(0.01) scales.append(RooRealVar("scale_"+region, "scale_"+region, 1., 0.001, 5)) scales[i].setError(0.01) for j in range(n_sig_pdf) : shiftedMeans[i].append(RooFormulaVar("shifted_mean_{}_".format(j)+region, "mean_{}+shift_".format(j)+region, RooArgList(means[j], shifts[i]))) scaledWidths[i].append(RooFormulaVar("scaled_width_{}_".format(j)+region, "width_{}*scale_".format(j)+region, RooArgList(widths[j], scales[i]))) sig[i].append(RooGaussian("sig_{}_".format(j)+region, "sig_{}_".format(j)+region, deltam, shiftedMeans[i][j], scaledWidths[i][j])) #Adding components to form total signal pdf region_sig_pdfs.append(RooAddPdf("signal_pdf_"+region, "signal_pdf_"+region, RooArgList(*sig[i]), RooArgList(*fracs))) bg_fracs.append(RooRealVar("bg_frac_"+region, "bg_frac_"+region, 0.107, 0, 1)) region_total_pdfs.append(RooAddPdf("total_pdf_"+region, "total_pdf_"+region, RooArgList(region_sig_pdfs[i], bg_pdf), RooArgList(bg_fracs[i]))) #Adding to simultaneous pdf total_pdf.addPdf(region_total_pdfs[i], region) #Simultaneously fit all mass regions - bg free and signal with shift/scale only total_pdf.fitTo(datahist) #Now, fix bg and fit signal only bgvar1.setConstant(True) bgvar2.setConstant(True) bgvar3.setConstant(True) deltam0.setConstant(True) for i in range(n_sig_pdf) : means[i].setConstant(False) widths[i].setConstant(False) if i < n_sig_pdf - 1 : fracs[i].setConstant(False)
musige=9999. #if fit=="sb": # musigv/=signalweight # musige/=signalweight #N(sig)="+str(int(nsigv))+"+-"+str(int(nsige))+", xframe=mass.frame(RooFit.Title("#mu(sig)="+str(int(musigv*1000.)/1000.)+"+-"+str(int(musige*1000.)/1000.)+", #chi^{2}/DOF = "+str(int((chi2.getVal()/(nbins-nfree))*10.)/10.))) if fit=="data": data.plotOn(xframe) else: data.plotOn(xframe,RooFit.DataError(RooAbsData.SumW2)) model.plotOn(xframe,RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) model.plotOn(xframe,RooFit.Components("bkg"+str(cut)),RooFit.LineStyle(kDashed),RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) model.plotOn(xframe,RooFit.Components("sig"),RooFit.LineStyle(kDotted),RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) canvas=TCanvas("c2","c2",0,0,600,600) xframe.Draw() canvas.SaveAs(prefix+"_"+plot[0]+str(cut)+"_fit"+fit+".pdf") sample=RooCategory("sample","sample") datasets=[] for cut in cuts[1:-1]: sample.defineType(str(cut)) datasets+=[RooFit.Import(str(cut),datalist[cut])] combData=RooDataHist("combData","combined data",RooArgList(mass),RooFit.Index(sample),*datasets) simPdf=RooSimultaneous("simPdf","simultaneous pdf",sample) for cut in cuts[1:-1]: simPdf.addPdf(modellist[cut],str(cut)) #simPdf.fitTo(combData) #simPdf.fitTo(combData) #simPdf.fitTo(combData)
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()
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)
model.plotOn( xframe, RooFit.Normalization(1.0, RooAbsReal.RelativeExpected)) model.plotOn( xframe, RooFit.Components("bkg" + str(cut)), RooFit.LineStyle(kDashed), RooFit.Normalization(1.0, RooAbsReal.RelativeExpected)) model.plotOn( xframe, RooFit.Components("sig"), RooFit.LineStyle(kDotted), RooFit.Normalization(1.0, RooAbsReal.RelativeExpected)) canvas = TCanvas("c2", "c2", 0, 0, 600, 600) xframe.Draw() canvas.SaveAs(prefix + "_" + plot[0] + str(cut) + "_fit" + fit + ".pdf") sample = RooCategory("sample", "sample") datasets = [] for cut in cuts[1:-1]: sample.defineType(str(cut)) datasets += [RooFit.Import(str(cut), datalist[cut])] combData = RooDataHist("combData", "combined data", RooArgList(mass), RooFit.Index(sample), *datasets) simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample) for cut in cuts[1:-1]: simPdf.addPdf(modellist[cut], str(cut)) #simPdf.fitTo(combData) #simPdf.fitTo(combData) #simPdf.fitTo(combData)
def buildPdf(ws, p): mass = RooRealVar("mass", "mass", p.minMass, p.maxMass) # ws.import(mass) getattr(ws,'import')(mass) # Construct signal pdf mean = RooRealVar("mean", "mean", 60, 0, 130) width = RooRealVar("width", "width", 10, 1, 40) # alpha = RooRealVar("alpha", "#alpha", -0.1, -10.0, -0.1) # npow = RooRealVar("npow", "n_{CB}", 2.3, 0.1, 10.) # width.setConstant(ROOT.kTRUE) sigma = RooRealVar("sigma", "sigma", 1.2, 0.2, 40) # minusMass = RooFormulaVar("minusMass", "@0*-1", RooArgList(mass)) # signalAll = RooCBShape("signalAll", "signalAll", mass, mean, width, alpha, npow); signalAll = RooVoigtian("signalAll", "signalAll", mass, mean, width, sigma) # Construct background pdf # a0_all = RooRealVar("a0_all","a0_all",-0.1,-1,1) # a1_all = RooRealVar("a1_all","a1_all",0.004,-1,1) # backgroundAll = RooChebychev("backgroundAll","backgroundAll",mass,RooArgList(a0_all,a1_all)) turnOnAll = RooRealVar("turnOnAll","turnOnAll", 80., 40., 150.) widthAll_bkg = RooRealVar("widthAll","widthAll", 2., 0., 50.) decayAll_bkg = RooRealVar("decayAll","decayAll", 80., 20., 150.) meanB = RooRealVar("meanB", "meanB", 90, 60, 130) sigmaB = RooRealVar("sigmaB", "sigmaB", 10, 1, 20) bkg_a1 = RooRealVar("bkg_a1", "bkg_a1", 0., -2., 2.) bkg_a2 = RooRealVar("bkg_a2", "bkg_a2", 0., -2., 2.) #backgroundAll = RooChebychev("backgroundAll", "backgroundAll", mass, RooArgList(bkg_a1, bkg_a2)) #backgroundAll = RooGenericPdf("backgroundAll","backgroundAll", "exp(-@0/@3)*(TMath::Erf((@0-@1)/@2)+1)", RooArgList(mass, turnOnAll, widthAll_bkg, decayAll_bkg)) backgroundAll = RooGenericPdf("backgroundAll","backgroundAll","exp(-@0/@1)",RooArgList(mass, decayAll_bkg)) #backgroundAll = RooGaussian("backgroundAll", "backgroundAll", mass, meanB, sigmaB) # Construct composite pdf sigAll = RooRealVar("sigAll", "sigAll", 2000, 0, 10000000) bkgAll = RooRealVar("bkgAll", "bkgAll", 100, 0, 1000000) modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll, backgroundAll), RooArgList(sigAll, bkgAll)) if p.NoBkgd: modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll), RooArgList(sigAll)) # Define pdf for all probes # Construct signal pdf. # NOTE that sigma is shared with the signal sample model signalPass = RooVoigtian("signalPass","signalPass",mass,mean,width,sigma) # signalPass = RooCBShape("signalPass", "signalPass", mass, mean, width, alpha, npow); # Construct the background pdf # a0_pass = RooRealVar("a0_pass","a0_pass",-0.1,-1,1) # a1_pass = RooRealVar("a1_pass","a1_pass",0.5,-0.1,1) # backgroundPass = RooChebychev("backgroundPass","backgroundPass",mass,RooArgList(a0_pass,a1_pass)) # turnOnPass = RooRealVar("turnOnPass","turnOnPass", 80., 50., 150.) # widthPass_bkg = RooRealVar("widthPass","widthPass", 2., 0., 50.) decayPass_bkg = RooRealVar("decayPass","decayPass", 80., 20., 150.) #backgroundPass = RooChebychev("backgroundPass", "backgroundPass", mass, RooArgList(bkg_a1, bkg_a2)) #backgroundPass = RooGenericPdf("backgroundPass","backgroundPass", "exp(-@0/@3)*(TMath::Erf((@0-@1)/@2)+1)", RooArgList(mass, turnOnPass, widthPass_bkg, decayPass_bkg)); #backgroundPass = RooGenericPdf("backgroundPass","backgroundPass", "exp(-@0/@3)*(TMath::Erf((@0-@1)/@2)+1)", RooArgList(mass, turnOnAll, widthAll_bkg, decayAll_bkg)); backgroundPass = RooGenericPdf("backgroundPass","backgroundPass","exp(-@0/@1)",RooArgList(mass, decayPass_bkg)) #backgroundPass = RooGaussian("backgroundPass", "backgroundPass", mass, meanB, sigmaB) # Construct the composite model efficiency = RooRealVar("efficiency","efficiency",0.9,0.1,1.) # Use it only analyzing the data prescaling value set to be 20 sigPass = RooFormulaVar("sigPass", "@0*@1*"+str(p.scaleFactor), RooArgList(sigAll, efficiency)) bkgPass = RooRealVar("bkgPass", "bkgPass", 100, 0, 1000000) # bkgPass = RooFormulaVar("bkgPass", "@0*@1", RooArgList(bkgAll, efficiency)) modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass, backgroundPass), RooArgList(sigPass, bkgPass)) if p.NoBkgd: modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass), RooArgList(sigPass)) frac = RooRealVar("frac", "frac", 0.8, 0., 1.) # Define combined pdf for simultaneous fit # Define category to distinguish physics and control samples events sample = RooCategory("sample","sample") sample.defineType("all") sample.defineType("pass") simPdf = RooSimultaneous("simPdf","simultaneous pdf",sample) # Associate model with the physics state and model_ctl with the control state simPdf.addPdf(modelAll,"all") simPdf.addPdf(modelPass,"pass") # ws.import(simPdf) getattr(ws,'import')(simPdf)
else: altscenario=scenario name=str(altscenario)+category name+="WvsZ" sample.defineType(name) datasets+=[RooFit.Import(name,datalist[name])] combData=RooDataHist("combData","combined data",RooArgList(mass),RooFit.Index(sample),*datasets) simPdf=RooSimultaneous("simPdf","simultaneous pdf",sample) for category in ["anti-btag","btag"]: if category=="btag": altscenario=btagscenario else: altscenario=scenario name=str(altscenario)+category name+="WvsZ" simPdf.addPdf(modellist[name],name) simPdf.fitTo(combData) simPdf.fitTo(combData) simPdf.fitTo(combData) #xframe=mass.frame(RooFit.Title("#Delta m="+str(int((meanWZ.getValV())*1000.)/1000.)+"#pm"+str(int(meanWZ.getError()*1000.)/1000.)+" GeV, #mu_{#sigma}="+str(int(musigv*1000.)/1000.)+"#pm"+str(int(musige*1000.)/1000.)+", #chi^{2}/N="+str(int((chi2.getVal()/(nbins-nfree))*10.)/10.))) xframe=mass.frame(RooFit.Title(" #Delta m="+str(int((meanWZ.getValV())*1000.)/1000.)+"#pm"+str(int(meanWZ.getError()*1000.)/1000.)+" GeV, #chi^{2}/N="+str(int((chi2.getVal()/(nbins-nfree))*10.)/10.))) for category in ["anti-btag","btag"]: if category=="btag": altscenario=btagscenario color=kRed else: altscenario=scenario color=kBlue name=str(altscenario)+category name+="WvsZ"
def setupWorkspace(ws, options): cfg = options.config #for convenience fit_sections = cfg.sections() fit_sections.remove( 'Global') #don't need to iterate over the global configuration if not isinstance(ws, RooWorkspace): print "You didn't pass a RooWorkspace!" exit(1) cpling_type = cfg.get('Global', 'couplingType') par1 = cfg.get('Global', 'par1Name') par1bound = [ -cfg.getfloat('Global', 'par1Max'), cfg.getfloat('Global', 'par1Max') ] par2 = cfg.get('Global', 'par2Name') par2bound = [ -cfg.getfloat('Global', 'par2Max'), cfg.getfloat('Global', 'par2Max') ] #create the parameters in the workspace ws.factory('%s_%s[0,%f,%f]' % (par1, cpling_type, par1bound[0], par1bound[1])) ws.factory('%s_%s[0,%f,%f]' % (par2, cpling_type, par2bound[0], par2bound[1])) # since the lumi error is correlated among all channels we only need one penalty term for it lumi_err = exp(options.config.getfloat( 'Global', 'lumi_err')) # exp because we use log normal ws.factory('luminosityError[%f]' % lumi_err) ws.factory('RooLognormal::lumiErr(err_gl[1,0.0001,50],1,luminosityError)') channel_cat = RooCategory('channels', 'channels') #first pass: process the backgrounds, signal and data into # simultaneous counting pdfs over the bins for section in fit_sections: #create the basic observable, this is used behind the scenes #in the background and signal models channel_cat.defineType(section) channel_cat.setLabel(section) print 'Building pdf for configuration section:', section for it, bkg in getBackgroundsInCfg(section, cfg).iteritems(): ws.factory('backgroundError_%s_%s[%f]' % (section, it, exp(bkg[1]))) ws.factory('selectionError_%s[%f]' % (section, exp(cfg.getfloat(section, 'selection_err')))) processFittingData(ws, cfg, section) processSignalModel(ws, cfg, section) processBackgroundModel(ws, cfg, section) createPdfForChannel(ws, cfg, section) ws.data('countingdata_%s' % section).addColumn(channel_cat) getattr(ws, 'import')(channel_cat) top = RooSimultaneous('TopLevelPdf', 'TopLevelPdf', ws.cat('channels')) alldatavars = RooArgSet(ws.cat('channels')) conditionals = RooArgSet() #second pass: process counting pdfs into simultaneous pdf over channels for section in fit_sections: top.addPdf(ws.pdf('countingpdf_%s' % section), section) alldatavars.add(ws.var('%s_%s' % (cfg.get(section, 'obsVar'), section))) conditionals.add( ws.var('%s_%s' % (cfg.get(section, 'obsVar'), section))) alldatavars.add(ws.var('n_observed_%s' % section)) getattr(ws, 'import')(top) ws.defineSet('condObs', conditionals) allcountingdata = RooDataSet('allcountingdata', 'allcountingdata', alldatavars) getattr(ws, 'import')(allcountingdata) allcountingdata = ws.data('allcountingdata') #third pass: make the final combined dataset for section in fit_sections: current = ws.data('countingdata_%s' % section) print 'countingdata_%s has %d entries' % (section, current.numEntries()) for i in range(current.numEntries()): alldatavars = current.get(i) allcountingdata.add(alldatavars)
bin = "1" mean1 = RooRealVar("mean{}".format(bin), "mean{}".format(bin), 3090, 2900, 3300) sigma1 = RooRealVar("sigma{}".format(bin), "sigma{}".format(bin), 10, 0, 30) gaus1 = RooGaussian("gx{}".format(bin), "gx{}".format(bin), m, mean1, sigma1) # define background pdf slope1 = RooRealVar("slope{}".format(bin), "slope{}".format(bin), -0.005, -0.01, -0.0001) exp1 = RooExponential("exp{}".format(bin), "exp{}".format(bin), m, slope1) # define yields nsig1 = RooRealVar("nsig{}".format(bin), "n. sig bin{}".format(bin), 1000, 0., 1000000) nbkg1 = RooRealVar("nbkg{}".format(bin), "n. bkg bin{}".format(bin), 1000, 0, 2000000) # sum pdfs model1 = RooAddPdf("model{}".format(bin), "model{}".format(bin), RooArgList(exp1, gaus1), RooArgList(nbkg1, nsig1)) simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample) simPdf.addPdf(model0, "matched") simPdf.addPdf(model1, "unmatched") start = time.time() result = simPdf.fitTo(combData, RooFit.Save(True), RooFit.NumCPU(12)) time_roofit = time.time() - start if do_probfit: print(f"time probfit: {time_probfit}") print(f"time RooFit: {time_roofit}") print(f"time zfit {'eager' if zfit_eager else 'graph'} compile: {time_zfit_compile}, time zfit min={time_zfit_min}")
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", 40, 200) nsig = RooRealVar("nsig", "#signal events", 200, 0.0, 10000) nbkg = RooRealVar("nbkg", "#background events", 800, 0.0, 200000) # Construct signal pdf mean = RooRealVar("mean", "mean", mu4, 40, 200) sigma = RooRealVar("sigma", "sigma", sigma4, 0.1, 20) gx = RooGaussian("gx", "gx", x, mean, sigma) # Construct background pdf mean_bkg = RooRealVar("mean_bkg", "mean_bkg", mu3, 40, 200) sigma_bkg = RooRealVar("sigma_bkg", "sigma_bkg", sigma3, 0.1, 20) px = RooGaussian("px", "px", x, mean_bkg, sigma_bkg) # Construct composite pdf model = RooAddPdf("model", "model", RooArgList(gx, px), RooArgList(nsig, nbkg)) # 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 y = RooRealVar("y", "y", 40, 200) mean_ctl = RooRealVar("mean_ctl", "mean_ctl", mu2, 40, 200) sigma_ctl = RooRealVar("sigma", "sigma", sigma2, 0.1, 10) gx_ctl = RooGaussian("gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl) # Construct the background pdf mean_bkg_ctl = RooRealVar("mean_bkg_ctl", "mean_bkg_ctl", mu1, 40, 200) sigma_bkg_ctl = RooRealVar("sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20) px_ctl = RooGaussian("px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl) # Construct the composite model # f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. ) model_ctl = RooAddPdf("model_ctl", "model_ctl", RooArgList(gx_ctl, px_ctl), RooArgList(nsig, nbkg)) # G e t e v e n t s f o r b o t h s a m p l e s # --------------------------------------------------------------- real_data, real_data_ctl = get_data() real_data_hist = RooDataHist("real_data_hist", "real_data_hist", RooArgList(x), real_data) real_data_ctl_hist = RooDataHist("real_data_ctl_hist", "real_data_ctl_hist", RooArgList(y), real_data_ctl) input_hists = MapStrRootPtr() input_hists.insert(StrHist("physics", real_data)) input_hists.insert(StrHist("control", real_data_ctl)) # 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 = RooDataHist("combData", "combined data", RooArgList(x), sample, input_hists) # 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 # --------------------------------------------------- model.fitTo(real_data_hist) summary = "fit in signal region\n" summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n" summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n" model_ctl.fitTo(real_data_ctl_hist) summary += "fit in control region\n" summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n" summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n" # Perform simultaneous fit of model to data and model_ctl to data_ctl simPdf.fitTo(combData) summary += "Combined fit\n" summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n" summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n" # 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 = y.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), ) simPdf.plotOn( frame2, RooFit.Slice(sample, "control"), RooFit.Components("gx_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() print summary raw_input()
def mbc_single_3s(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, RooDLineShape, RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta, TPaveText) set_root_style(stat=1, grid=0) # // sp1 = sigma of signal # // sp2 = ratio of sigmas betwwen sigma2 sigma 1 # // sp3 = ratio of sigmas betwwen sigma3 sigma 2 # // fa, fb, - fractions # // xi_side - slope of argus # // p_side - power of argus # mc = 1 Monte Carlo Model: EvtGenModels/Class/EvtVPHOtoVISR.cc # mc = 3 Data Model: with BES 2007 paper (BES2006 lineshape hepex/0612056) mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV') ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV') dflav = RooCategory('dflav', 'D 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) 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) signal1_3 = RooAddPdf("signal1_3", "signal1_3", alf1_123, af12) alf2_123 = RooArgList(fcn2_1, fcn2_2, fcn2_3) signal2_3 = RooAddPdf("signal2_3", "signal2_3", alf2_123, af12) p = RooRealVar("p", "p", setp, 0.1, 1.5) xi = RooRealVar("xi", "xi", setxi, -100.0, -0.1) Bkgd1 = RooArgusBG("argus1", "argus1", mbc, ebeam, xi, p) Bkgd2 = RooArgusBG("argus2", "argus2", mbc, ebeam, xi, p) shapes1 = RooArgList(signal1_3) shapes1.add(signal1_3) shapes1.add(Bkgd1) shapes2 = RooArgList(signal2_3) shapes2.add(signal2_3) shapes2.add(Bkgd2) N1 = RooRealVar("N1", "N1", setN1, 0.0, 200000000.0) N2 = RooRealVar("N2", "N2", setN2, 0.0, 200000000.0) Nbkgd1 = RooRealVar("Nbkgd1", "Nbkgd1", setNbkgd1, 0.0, 200000000.0) Nbkgd2 = RooRealVar("Nbkgd2", "Nbkgd2", setNbkgd2, 0.0, 200000000.0) yields1 = RooArgList(N1) yields1.add(N1) yields1.add(Nbkgd1) yields2 = RooArgList(N2) yields2.add(N2) yields2.add(Nbkgd2) totalPdf1 = RooAddPdf("totalPdf1", "totalPdf1", shapes1, yields1) totalPdf2 = RooAddPdf("totalPdf2", "totalPdf2", shapes2, yields2) totalPdf = RooSimultaneous("totalPdf", "totalPdf", dflav) totalPdf.addPdf(totalPdf1, "dflav") totalPdf.addPdf(totalPdf2, "dbarflav") # Check fitTo options at: # http://root.cern.ch/root/html512/RooAbsPdf.html#RooAbsPdf:fitTo # # Available fit options: # "m" = MIGRAD only, i.e. no MINOS # "s" = estimate step size with HESSE before starting MIGRAD # "h" = run HESSE after MIGRAD # "e" = Perform extended MLL fit # "0" = Run MIGRAD with strategy MINUIT 0 # (no correlation matrix calculation at end) # Does not apply to HESSE or MINOS, if run afterwards. # "q" = Switch off verbose mode # "l" = Save log file with parameter values at each MINUIT step # "v" = Show changed parameters at each MINUIT step # "t" = Time fit # "r" = Save fit output in RooFitResult object # Available optimizer options # "c" = Cache and precalculate components of PDF that exclusively # depend on constant parameters # "2" = Do NLL calculation in multi-processor mode on 2 processors # "3" = Do NLL calculation in multi-processor mode on 3 processors # "4" = Do NLL calculation in multi-processor mode on 4 processors 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: N1.setVal(0) N2.setVal(0) else: # Start Fitting fitres = totalPdf.fitTo(dataset, MINUIT) fitres.Print('v') # Save plots canvas = TCanvas('canvas', 'mbc', 1200, 400) canvas.Divide(3, 1) canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1') canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2') canvas_1.SetLogy(1) canvas_2.SetLogy(1) LineColorRed = RooFit.LineColor(kRed) LineColorBlue = RooFit.LineColor(kBlue) LineWidth = RooFit.LineWidth(1) #0.6) # Plot the D canvas.cd(1) mbcFrame = mbc.frame() mbcFrame = mbc.frame(60) dflav.setLabel('dflav') ebas = RooArgSet(ebeam, dflav) ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset) dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dflav")) mbcFrame.getAttMarker().SetMarkerSize(0.6) mbcFrame.Draw() Slice = RooFit.Slice(dflav) ProjWData = RooFit.ProjWData(ebas, ebeamdata) totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData) chisq1 = mbcFrame.chiSquare() * mbcFrame.GetNbinsX() mbcFrame.Draw() as_bkg1 = RooArgSet(Bkgd1) cp_bkg1 = RooFit.Components(as_bkg1) totalPdf.plotOn(mbcFrame, cp_bkg1, Slice, LineColorBlue, LineWidth, ProjWData) mbcFrame.SetTitle(title1) mbcFrame.SetMinimum(ymin) mbcFrame.Draw() # Plot the D bar canvas.cd(2) mbcFrame = mbc.frame() mbcFrame = mbc.frame(60) dflav.setLabel('dbarflav') ebas = RooArgSet(ebeam, dflav) ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset) dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dbarflav")) mbcFrame.getAttMarker().SetMarkerSize(0.6) mbcFrame.Draw() Slice = RooFit.Slice(dflav) ProjWData = RooFit.ProjWData(ebas, ebeamdata) totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData) chisq2 = mbcFrame.chiSquare() * mbcFrame.GetNbinsX() mbcFrame.Draw() as_bkg2 = RooArgSet(Bkgd2) cp_bkg2 = RooFit.Components(as_bkg2) totalPdf.plotOn(mbcFrame, cp_bkg2, Slice, LineColorBlue, LineWidth, ProjWData) mbcFrame.SetTitle(title2) mbcFrame.SetMinimum(ymin) mbcFrame.Draw() # Plot Statistics Box canvas.cd(3) mbcFrame = mbc.frame() paramWin1 = totalPdf.paramOn(mbcFrame, dataset, "", 2, "NELU", 0.1, 0.9, 0.9) mbcFrame.GetXaxis().SetLabelSize(0) mbcFrame.GetXaxis().SetTickLength(0) mbcFrame.GetXaxis().SetLabelSize(0) mbcFrame.GetXaxis().SetTitle("") mbcFrame.GetXaxis().CenterTitle() mbcFrame.GetYaxis().SetLabelSize(0) mbcFrame.GetYaxis().SetTitleSize(0.03) mbcFrame.GetYaxis().SetTickLength(0) paramWin1.getAttText().SetTextSize(0.06) mbcFrame.Draw() mbcFrame.SetTitle("Fit Parameters") ATextBox = TPaveText(.1, .1, .8, .2, "BRNDC") tempString = "#chi^{2}_{1} = %.1f, #chi^{2}_{2} = %.1f" % (chisq1, chisq2) ATextBox.AddText(tempString) ATextBox.SetFillColor(0) ATextBox.SetBorderSize(1) mbcFrame.addObject(ATextBox) mbcFrame.Draw() canvas.Print(epsfile) rootfile = epsfile.replace('.eps', '.root') canvas.Print(rootfile) # Save fitting parameters pars = [N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi] save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
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 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 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 mbc_single_3s(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, RooDLineShape, RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta, TPaveText) set_root_style(stat=1, grid=0) # // sp1 = sigma of signal # // sp2 = ratio of sigmas betwwen sigma2 sigma 1 # // sp3 = ratio of sigmas betwwen sigma3 sigma 2 # // fa, fb, - fractions # // xi_side - slope of argus # // p_side - power of argus # mc = 1 Monte Carlo Model: EvtGenModels/Class/EvtVPHOtoVISR.cc # mc = 3 Data Model: with BES 2007 paper (BES2006 lineshape hepex/0612056) mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV') ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV') dflav = RooCategory('dflav','D 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) 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) signal1_3 = RooAddPdf("signal1_3","signal1_3", alf1_123, af12) alf2_123 = RooArgList(fcn2_1,fcn2_2,fcn2_3) signal2_3 = RooAddPdf("signal2_3","signal2_3", alf2_123, af12) p = RooRealVar("p","p", setp, 0.1, 1.5) xi= RooRealVar("xi","xi",setxi,-100.0,-0.1) Bkgd1 = RooArgusBG("argus1","argus1",mbc,ebeam,xi,p) Bkgd2 = RooArgusBG("argus2","argus2",mbc,ebeam,xi,p) shapes1 = RooArgList(signal1_3) shapes1.add(signal1_3) shapes1.add(Bkgd1) shapes2 = RooArgList(signal2_3) shapes2.add(signal2_3) shapes2.add(Bkgd2) N1 = RooRealVar("N1","N1",setN1,0.0,200000000.0) N2 = RooRealVar("N2","N2",setN2,0.0,200000000.0) Nbkgd1 = RooRealVar("Nbkgd1","Nbkgd1",setNbkgd1, 0.0, 200000000.0) Nbkgd2 = RooRealVar("Nbkgd2","Nbkgd2",setNbkgd2, 0.0, 200000000.0) yields1 = RooArgList(N1) yields1.add(N1) yields1.add(Nbkgd1) yields2 = RooArgList(N2) yields2.add(N2) yields2.add(Nbkgd2) totalPdf1 = RooAddPdf("totalPdf1","totalPdf1", shapes1,yields1) totalPdf2 = RooAddPdf("totalPdf2","totalPdf2", shapes2,yields2) totalPdf = RooSimultaneous("totalPdf","totalPdf",dflav) totalPdf.addPdf(totalPdf1,"dflav") totalPdf.addPdf(totalPdf2,"dbarflav") # Check fitTo options at: # http://root.cern.ch/root/html512/RooAbsPdf.html#RooAbsPdf:fitTo # # Available fit options: # "m" = MIGRAD only, i.e. no MINOS # "s" = estimate step size with HESSE before starting MIGRAD # "h" = run HESSE after MIGRAD # "e" = Perform extended MLL fit # "0" = Run MIGRAD with strategy MINUIT 0 # (no correlation matrix calculation at end) # Does not apply to HESSE or MINOS, if run afterwards. # "q" = Switch off verbose mode # "l" = Save log file with parameter values at each MINUIT step # "v" = Show changed parameters at each MINUIT step # "t" = Time fit # "r" = Save fit output in RooFitResult object # Available optimizer options # "c" = Cache and precalculate components of PDF that exclusively # depend on constant parameters # "2" = Do NLL calculation in multi-processor mode on 2 processors # "3" = Do NLL calculation in multi-processor mode on 3 processors # "4" = Do NLL calculation in multi-processor mode on 4 processors 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: N1.setVal(0) N2.setVal(0) else: # Start Fitting fitres = totalPdf.fitTo(dataset, MINUIT) fitres.Print('v') # Save plots canvas = TCanvas('canvas','mbc', 1200, 400); canvas.Divide(3,1) canvas_1 = canvas.GetListOfPrimitives().FindObject('canvas_1') canvas_2 = canvas.GetListOfPrimitives().FindObject('canvas_2') canvas_1.SetLogy(1) canvas_2.SetLogy(1) LineColorRed = RooFit.LineColor(kRed) LineColorBlue = RooFit.LineColor(kBlue) LineWidth = RooFit.LineWidth(1) #0.6) # Plot the D canvas.cd(1) mbcFrame=mbc.frame() mbcFrame=mbc.frame(60) dflav.setLabel('dflav') ebas = RooArgSet(ebeam, dflav) ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset) dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dflav")) mbcFrame.getAttMarker().SetMarkerSize(0.6) mbcFrame.Draw() Slice = RooFit.Slice(dflav) ProjWData = RooFit.ProjWData(ebas, ebeamdata) totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData) chisq1 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX() mbcFrame.Draw() as_bkg1 = RooArgSet(Bkgd1) cp_bkg1 = RooFit.Components(as_bkg1) totalPdf.plotOn(mbcFrame, cp_bkg1, Slice, LineColorBlue, LineWidth, ProjWData) mbcFrame.SetTitle(title1) mbcFrame.SetMinimum(ymin) mbcFrame.Draw() # Plot the D bar canvas.cd(2) mbcFrame=mbc.frame() mbcFrame=mbc.frame(60) dflav.setLabel('dbarflav') ebas = RooArgSet(ebeam, dflav) ebeamdata = RooDataHist("ebeamdata", "ebeamdata", ebas, dataset) dataset.plotOn(mbcFrame, RooFit.Cut("dflav==dflav::dbarflav")) mbcFrame.getAttMarker().SetMarkerSize(0.6) mbcFrame.Draw() Slice = RooFit.Slice(dflav) ProjWData = RooFit.ProjWData(ebas, ebeamdata) totalPdf.plotOn(mbcFrame, LineColorRed, LineWidth, Slice, ProjWData) chisq2 = mbcFrame.chiSquare()*mbcFrame.GetNbinsX() mbcFrame.Draw() as_bkg2 = RooArgSet(Bkgd2) cp_bkg2 = RooFit.Components(as_bkg2) totalPdf.plotOn(mbcFrame, cp_bkg2, Slice, LineColorBlue, LineWidth, ProjWData) mbcFrame.SetTitle(title2) mbcFrame.SetMinimum(ymin) mbcFrame.Draw() # Plot Statistics Box canvas.cd(3) mbcFrame = mbc.frame() paramWin1 = totalPdf.paramOn(mbcFrame,dataset, "",2,"NELU",0.1,0.9,0.9) mbcFrame.GetXaxis().SetLabelSize(0) mbcFrame.GetXaxis().SetTickLength(0) mbcFrame.GetXaxis().SetLabelSize(0) mbcFrame.GetXaxis().SetTitle("") mbcFrame.GetXaxis().CenterTitle() mbcFrame.GetYaxis().SetLabelSize(0) mbcFrame.GetYaxis().SetTitleSize(0.03) mbcFrame.GetYaxis().SetTickLength(0) paramWin1.getAttText().SetTextSize(0.06) mbcFrame.Draw() mbcFrame.SetTitle("Fit Parameters") ATextBox = TPaveText(.1, .1, .8, .2,"BRNDC") tempString = "#chi^{2}_{1} = %.1f, #chi^{2}_{2} = %.1f" % (chisq1,chisq2) ATextBox.AddText(tempString) ATextBox.SetFillColor(0) ATextBox.SetBorderSize(1) mbcFrame.addObject(ATextBox) mbcFrame.Draw() canvas.Print(epsfile) rootfile = epsfile.replace('.eps', '.root') canvas.Print(rootfile) # Save fitting parameters pars = [N1, N2, Nbkgd1, Nbkgd2, md, p, sigmap1, xi] save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
RooFit.NumCPU(1), RooFit.SumW2Error(True), RooFit.Offset(True), RooFit.Verbose(True)) dsk_fitresult.Print() # undo earlier set constant turnon.setConstant(False) exponent.setConstant(False) offset.setConstant(False) beta.setConstant(False) ## Build simultaneous 2-D PDF (t, δt) for DsPi and DsK PDF = RooSimultaneous('PDF', 'Simultaneous PDF', decaycat) PDF.addPdf(DsPi_Model, 'DsPi') PDF.addPdf(DsK_Model, 'DsK') pdflist += [PDF] # #errorPdf = RooHistPdf('errorPdf', 'Time error Hist PDF', # # RooArgSet(dt), datahist) # errorPdf = RooKeysPdf('errorPdf', 'errorPdf', dt, tmpdata) # PDF = RooProdPdf('PDF', 'Acceptance model with errors B_{s}', # RooArgSet(errorPdf), # RooFit.Conditional(RooArgSet(Model), RooArgSet(time))) # # enable caching for dt integral # PDF.setParameterizeIntegral(RooArgSet(dt))
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)
myCat.defineType("failed", 0) # Convert binned data into RooDataHist # --------------------------------------------------------------- map_data = std_map("std::string, TH1*")() map_data.insert(("failed", data1)) map_data.insert(("passed", data2)) combined = RooDataHist("combined", "combined", RooArgList(x), myCat, map_data) # 1. Construct a simultaneous pdf using category sample as index # --------------------------------------------------------------- simPdf = RooSimultaneous("simPdf", "simultaneous pdf", myCat) # Associate model with the physics state and model_ctl with the control # state simPdf.addPdf(model, "failed") simPdf.addPdf(model_ctl, "passed") # FIT # --------------------------------------------------------------- # 2. Fit model to data simPdf.fitTo(combined) # 3. Create frame frame1 = x.frame(RooFit.Bins(30), RooFit.Title("Passed sample")) frame2 = x.frame(RooFit.Bins(30), RooFit.Title("Failed sample")) # 4. Put data on frame combined.plotOn(frame1, RooFit.Cut("myCat==myCat::passed")) combined.plotOn(frame2, RooFit.Cut("myCat==myCat::failed"))
sample.defineType('b1') sample.defineType('b2') sample.defineType('b3') combData= RooDataSet('combData','combined data',RooArgSet( x), RooFit.Index(sample), RooFit.Import('b1',dataset1S), RooFit.Import('b2',dataset2S), RooFit.Import('b3',dataset3S), ) #model1S,model2S = definemodel(x) simPdf = RooSimultaneous("simPdf","simultaneous pdf",sample) ; simPdf.addPdf(model1S,'b1') simPdf.addPdf(model2S,'b2') simPdf.addPdf(model3S,'b3') fitregion = x.setRange('fitregion',10.35,10.8) fitregion_1S = x.setRange('fitregion_1S',10.35,10.8) fitregion_2S = x.setRange('fitregion_2S',10.35,10.8) fitregion_3S = x.setRange('fitregion_3S',10.35,10.8) #simPdf.fitTo(combData,RooFit.Save(), RooFit.Range('fitregion'),RooFit.SplitRange()) simPdf.fitTo(combData,RooFit.Save()) #plotting frame1 = x.frame()
def rf501_simultaneouspdf(): signal_1, bkg_1, signal_2, bkg_2 = get_templates() # 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", 0, 200 ) x.setBins(n_bins) nsig = RooRealVar( "nsig", "#signal events", N_signal_obs, 0., 2*N_data ) nbkg = RooRealVar( "nbkg", "#background events", N_bkg1_obs, 0., 2*N_data ) # Construct signal pdf # mean = RooRealVar( "mean", "mean", mu4, 40, 200 ) # sigma = RooRealVar( "sigma", "sigma", sigma4, 0.1, 20 ) # gx = RooGaussian( "gx", "gx", x, mean, sigma ) roofit_signal_1 = RooDataHist( 'signal_1', 'signal_1', RooArgList(x), signal_1 ) signal_1_pdf = RooHistPdf ( 'signal_1_pdf' , 'signal_1_pdf', RooArgSet(x), roofit_signal_1) # Construct background pdf # mean_bkg = RooRealVar( "mean_bkg", "mean_bkg", mu3, 40, 200 ) # sigma_bkg = RooRealVar( "sigma_bkg", "sigma_bkg", sigma3, 0.1, 20 ) # px = RooGaussian( "px", "px", x, mean_bkg, sigma_bkg ) roofit_bkg_1 = RooDataHist( 'bkg_1', 'bkg_1', RooArgList(x), bkg_1 ) bkg_1_pdf = RooHistPdf ( 'bkg_1_pdf' , 'bkg_1_pdf', RooArgSet(x), roofit_bkg_1) # Construct composite pdf model = RooAddPdf( "model", "model", RooArgList( signal_1_pdf, bkg_1_pdf ), RooArgList( nsig, nbkg ) ) # 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 y = RooRealVar( "y", "y", 0, 200 ) y.setBins(n_bins) mean_ctl = RooRealVar( "mean_ctl", "mean_ctl", mu2, 0, 200 ) sigma_ctl = RooRealVar( "sigma", "sigma", sigma2, 0.1, 10 ) gx_ctl = RooGaussian( "gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl ) # Construct the background pdf mean_bkg_ctl = RooRealVar( "mean_bkg_ctl", "mean_bkg_ctl", mu1, 0, 200 ) sigma_bkg_ctl = RooRealVar( "sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20 ) px_ctl = RooGaussian( "px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl ) # Construct the composite model # f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. ) model_ctl = RooAddPdf( "model_ctl", "model_ctl", RooArgList( gx_ctl, px_ctl ), RooArgList( nsig, nbkg ) ) # G e t e v e n t s f o r b o t h s a m p l e s # --------------------------------------------------------------- real_data, real_data_ctl = get_data() real_data_hist = RooDataHist( 'real_data_hist', 'real_data_hist', RooArgList( x ), real_data ) real_data_ctl_hist = RooDataHist( 'real_data_ctl_hist', 'real_data_ctl_hist', RooArgList( y ), real_data_ctl ) input_hists = MapStrRootPtr() input_hists.insert( StrHist( "physics", real_data ) ) input_hists.insert( StrHist( "control", real_data_ctl ) ) # 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 = RooDataHist( "combData", "combined data", RooArgList( x), sample , input_hists ) # 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" ) #60093.048127 173.205689173 44.7112503776 # P e r f o r m a s i m u l t a n e o u s f i t # --------------------------------------------------- model.fitTo( real_data_hist, RooFit.Minimizer( "Minuit2", "Migrad" ), RooFit.NumCPU( 1 ), # RooFit.Extended(), # RooFit.Save(), ) summary = 'fit in signal region\n' summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' # # model_ctl.fitTo( real_data_ctl_hist ) # summary += 'fit in control region\n' # summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' # summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' # # # Perform simultaneous fit of model to data and model_ctl to data_ctl # simPdf.fitTo( combData ) # summary += 'Combined fit\n' # summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' # summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' # 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( "signal_1_pdf" ), RooFit.ProjWData( RooArgSet( sample ), combData ), RooFit.LineStyle( kDashed ), ) simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ), RooFit.Components( "bkg_1_pdf" ), RooFit.ProjWData( RooArgSet( sample ), combData ), RooFit.LineStyle( kDashed ), RooFit.LineColor( kRed ) ) # The same plot for the control sample slice frame2 = y.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() print summary print real_data.Integral() raw_input()
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", 40, 200) nsig = RooRealVar("nsig", "#signal events", 200, 0., 10000) nbkg = RooRealVar("nbkg", "#background events", 800, 0., 200000) # Construct signal pdf mean = RooRealVar("mean", "mean", mu4, 40, 200) sigma = RooRealVar("sigma", "sigma", sigma4, 0.1, 20) gx = RooGaussian("gx", "gx", x, mean, sigma) # Construct background pdf mean_bkg = RooRealVar("mean_bkg", "mean_bkg", mu3, 40, 200) sigma_bkg = RooRealVar("sigma_bkg", "sigma_bkg", sigma3, 0.1, 20) px = RooGaussian("px", "px", x, mean_bkg, sigma_bkg) # Construct composite pdf model = RooAddPdf("model", "model", RooArgList(gx, px), RooArgList(nsig, nbkg)) # 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 y = RooRealVar("y", "y", 40, 200) mean_ctl = RooRealVar("mean_ctl", "mean_ctl", mu2, 40, 200) sigma_ctl = RooRealVar("sigma", "sigma", sigma2, 0.1, 10) gx_ctl = RooGaussian("gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl) # Construct the background pdf mean_bkg_ctl = RooRealVar("mean_bkg_ctl", "mean_bkg_ctl", mu1, 40, 200) sigma_bkg_ctl = RooRealVar("sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20) px_ctl = RooGaussian("px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl) # Construct the composite model # f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. ) model_ctl = RooAddPdf("model_ctl", "model_ctl", RooArgList(gx_ctl, px_ctl), RooArgList(nsig, nbkg)) # G e t e v e n t s f o r b o t h s a m p l e s # --------------------------------------------------------------- real_data, real_data_ctl = get_data() real_data_hist = RooDataHist('real_data_hist', 'real_data_hist', RooArgList(x), real_data) real_data_ctl_hist = RooDataHist('real_data_ctl_hist', 'real_data_ctl_hist', RooArgList(y), real_data_ctl) input_hists = MapStrRootPtr() input_hists.insert(StrHist("physics", real_data)) input_hists.insert(StrHist("control", real_data_ctl)) # 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 = RooDataHist("combData", "combined data", RooArgList(x), sample, input_hists) # 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 # --------------------------------------------------- model.fitTo(real_data_hist) summary = 'fit in signal region\n' summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str( nsig.getError()) + '\n' summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str( nbkg.getError()) + '\n' model_ctl.fitTo(real_data_ctl_hist) summary += 'fit in control region\n' summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str( nsig.getError()) + '\n' summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str( nbkg.getError()) + '\n' # Perform simultaneous fit of model to data and model_ctl to data_ctl simPdf.fitTo(combData) summary += 'Combined fit\n' summary += 'nsig: ' + str(nsig.getValV()) + ' +- ' + str( nsig.getError()) + '\n' summary += 'nbkg: ' + str(nbkg.getValV()) + ' +- ' + str( nbkg.getError()) + '\n' # 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 = y.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)) simPdf.plotOn(frame2, RooFit.Slice(sample, "control"), RooFit.Components("gx_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() print summary raw_input()
yieldspass) #Fail componentsfail = RooArgList(sigShapePdf) #,bkgShapePdf ); yieldsfail = RooArgList(nSigfail) #, nBkgfail ); sumfail = RooAddPdf("sumfail", "fixed extended sum pdf", componentsfail, yieldsfail) #Creates category myFitCat = RooCategory("myFitCat", "Category: pass or fail") myFitCat.defineType("fail", 1) myFitCat.defineType("pass", 0) #Create PDF for simultaneous fit totalPdf = RooSimultaneous("totalPdf", "totalPdf", myFitCat) totalPdf.addPdf(sumpass, "pass") totalPdf.addPdf(sumfail, "fail") #Generate data and combine #For combining binned data look rf_combine_binned_data.py data_pass = gauss1.generate(RooArgSet(Mkk), 6000) data_fail = gauss1.generate(RooArgSet(Mkk), 4000) combData = RooDataSet("combData", "combined data", RooArgSet(Mkk), RooFit.Index(myFitCat), RooFit.Import("pass", data_pass), RooFit.Import("fail", data_fail)) #FIT totalPdf.fitTo(combData) #PLOT sampleSet = RooArgSet(myFitCat)
def setupWorkspace(ws,options): cfg = options.config #for convenience fit_sections = cfg.sections() fit_sections.remove('Global') #don't need to iterate over the global configuration if not isinstance(ws,RooWorkspace): print "You didn't pass a RooWorkspace!" exit(1) cpling_type = cfg.get('Global','couplingType') par1 = cfg.get('Global','par1Name') par1bound = [-cfg.getfloat('Global','par1Max'), cfg.getfloat('Global','par1Max')] par2 = cfg.get('Global','par2Name') par2bound = [-cfg.getfloat('Global','par2Max'), cfg.getfloat('Global','par2Max')] #create the parameters in the workspace ws.factory('%s_%s[0,%f,%f]'%(par1,cpling_type,par1bound[0],par1bound[1])) ws.factory('%s_%s[0,%f,%f]'%(par2,cpling_type,par2bound[0],par2bound[1])) # since the lumi error is correlated among all channels we only need one penalty term for it lumi_err = exp(options.config.getfloat('Global','lumi_err')) # exp because we use log normal ws.factory('luminosityError[%f]'%lumi_err) ws.factory('RooLognormal::lumiErr(err_gl[1,0.0001,50],1,luminosityError)') channel_cat = RooCategory('channels','channels') #first pass: process the backgrounds, signal and data into # simultaneous counting pdfs over the bins for section in fit_sections: #create the basic observable, this is used behind the scenes #in the background and signal models channel_cat.defineType(section) channel_cat.setLabel(section) print 'Building pdf for configuration section:',section for it,bkg in getBackgroundsInCfg(section,cfg).iteritems(): ws.factory('backgroundError_%s_%s[%f]'%(section,it,exp(bkg[1]))) ws.factory('selectionError_%s[%f]'%(section,exp(cfg.getfloat(section,'selection_err')))) processFittingData(ws,cfg,section) processSignalModel(ws,cfg,section) processBackgroundModel(ws,cfg,section) createPdfForChannel(ws,cfg,section) ws.data('countingdata_%s'%section).addColumn(channel_cat) getattr(ws,'import')(channel_cat) top = RooSimultaneous('TopLevelPdf', 'TopLevelPdf', ws.cat('channels')) alldatavars = RooArgSet(ws.cat('channels')) conditionals = RooArgSet() #second pass: process counting pdfs into simultaneous pdf over channels for section in fit_sections: top.addPdf(ws.pdf('countingpdf_%s'%section),section) alldatavars.add(ws.var('%s_%s'%(cfg.get(section,'obsVar'),section))) conditionals.add(ws.var('%s_%s'%(cfg.get(section,'obsVar'),section))) alldatavars.add(ws.var('n_observed_%s'%section)) getattr(ws,'import')(top) ws.defineSet('condObs',conditionals) allcountingdata = RooDataSet('allcountingdata', 'allcountingdata', alldatavars) getattr(ws,'import')(allcountingdata) allcountingdata = ws.data('allcountingdata') #third pass: make the final combined dataset for section in fit_sections: current = ws.data('countingdata_%s'%section) print 'countingdata_%s has %d entries'%(section,current.numEntries()) for i in range(current.numEntries()): alldatavars = current.get(i) allcountingdata.add(alldatavars)
def buildPdf(ws, p): mass = RooRealVar("mass", "mass", p.minMass, p.maxMass) getattr(ws, 'import')(mass) # Construct signal pdf mean = RooRealVar("mean", "mean", 90, 85, 95) width = RooRealVar("width", "width", 2.4952, 1, 3) width.setConstant(ROOT.kTRUE) sigma = RooRealVar("sigma", "sigma", 1.2, 0.2, 10) signalAll = RooVoigtian("signalAll", "signalAll", mass, mean, width, sigma) turnOnAll = RooRealVar("turnOnAll", "turnOnAll", 80., 40., 150.) widthAll_bkg = RooRealVar("widthAll", "widthAll", 2., 0., 50.) decayAll_bkg = RooRealVar("decayAll", "decayAll", 80., 20., 150.) meanB = RooRealVar("meanB", "meanB", 90, 60, 130) sigmaB = RooRealVar("sigmaB", "sigmaB", 10, 1, 20) bkg_a1 = RooRealVar("bkg_a1", "bkg_a1", 0., -2., 2.) bkg_a2 = RooRealVar("bkg_a2", "bkg_a2", 0., -2., 2.) backgroundAll = RooGaussian("backgroundAll", "backgroundAll", mass, meanB, sigmaB) # Construct composite pdf sigAll = RooRealVar("sigAll", "sigAll", 2000, 0, 100000) bkgAll = RooRealVar("bkgAll", "bkgAll", 100, 0, 10000) modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll, backgroundAll), RooArgList(sigAll, bkgAll)) if p.NoBkgd: modelAll = RooAddPdf("modelAll", "modelAll", RooArgList(signalAll), RooArgList(sigAll)) # Define pdf for all probes # Construct signal pdf. # NOTE that sigma is shared with the signal sample model signalPass = RooVoigtian("signalPass", "signalPass", mass, mean, width, sigma) # Construct the background pdf backgroundPass = RooGaussian("backgroundPass", "backgroundPass", mass, meanB, sigmaB) # Construct the composite model efficiency = RooRealVar("efficiency", "efficiency", 0.9, 0.3, 1.) sigPass = RooFormulaVar("sigPass", "@0*@1", RooArgList(sigAll, efficiency)) bkgPass = RooRealVar("bkgPass", "bkgPass", 100, 0, 10000) modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass, backgroundPass), RooArgList(sigPass, bkgPass)) if p.NoBkgd: modelPass = RooAddPdf("modelPass", "modelPass", RooArgList(signalPass), RooArgList(sigPass)) frac = RooRealVar("frac", "frac", 0.8, 0., 1.) # Define combined pdf for simultaneous fit # Define category to distinguish physics and control samples events sample = RooCategory("sample", "sample") sample.defineType("all") sample.defineType("pass") simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample) # Associate model with the physics state and model_ctl with the control state simPdf.addPdf(modelAll, "all") simPdf.addPdf(modelPass, "pass") # ws.import(simPdf) getattr(ws, 'import')(simPdf)