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 main1(): m = RooRealVar('evt.m', 'evt.m', 1.92, 2.02) mode = RooCategory('evt.mode', 'evt.mode') mode.defineType('phipi', 0) aset = RooArgSet('aset') aset.add(m) aset.add(mode) tuplist = tupleList('genmc', 7) dst, _, f = getTree('/'.join([tuplePath(), tuplist[-1]])) # dst.Print() # dst.Show(0) # for evt in dst: # print('Hello!') # print(evt.evt.m) # break ds = RooDataSet('ds', 'ds', dst, aset) print(ds.numEntries()) mean = RooRealVar('mean', 'mean', 1.96, 1.92, 2.0) width = RooRealVar('width', 'width', 0.006, 0.001, 0.010) pdf = RooGaussian('pdf', 'pdf', m, mean, width) pdf.fitTo(ds, Verbose(), Timer(True)) makePlot(m, ds, pdf) raw_input("Press Enter to continue...")
def 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(), )
class MLFit : def __init__(self, plot_dire, condition): self.plot_dire = plot_dire self.condition = condition self.mjj = RooRealVar("ZJJMass", "ZJJMass", 50., 7000.) #self.costhetastar = RooRealVar("costhetastar", "costhetastar", -1., 1.) self.weight = RooRealVar("weight", "weight", -100., 100.) self.isSignal = RooCategory("isSignal", "isSignal") self.isSignal.defineType("signal", 1); self.isSignal.defineType("background", 0); self.ras = RooArgSet(self.mjj, self.weight) self.ds = RooDataSet("ds"+condition, "ds"+condition, self.ras, "weight") #self.mu = RooRealVar("mu", "mu", 90., 80., 100.) #self.widthL = RooRealVar("widthL", "widthL", 15., 2., 30.) #self.widthR = RooRealVar("widthR", "widthR", 4., 2., 15.) #self.sigmass = RooBifurGauss("bifurgauss", "bifurgauss", self.mjj, self.mu, self.widthL, self.widthR) self.c0 = RooRealVar("c0", "c0", -100., 100.) self.bkgmass = RooExponential("expo", "expo", self.mjj, self.c0) #self.nsig = RooRealVar("nsig", "nsig", 100, 0, 200) #self.nbkg = RooRealVar("nbkg", "nbkg", 100, 0, 200) #self.components = RooArgList(self.sigmass, self.bkgmass) #self.coefficients = RooArgList(self.nsig, self.nbkg) self.modelmass = self.bkgmass #RooAddPdf("massmodel", "massmodel", self.components, self.coefficients) def addToDataset(self, event, isSignal): if not eval(self.condition): return self.mjj = event.ZJJMass print self.mjj #self.costhetastar = event.costhetastar self.weight = event.weight #self.isSignal = isSignal self.ds.fill() def fit(self): print "nentries", self.ds.numEntries() #for i in range(self.ds.numEntries()): # argset = self.ds.get(i) # argset.Dump() fitresult = self.modelmass.fitTo(self.ds, RooFit.Save(True), RooFit.Extended(), RooFit.PrintLevel(3), RooFit.Strategy(2)) #, RooFit.SumW2Error(True))
def __init__(self, plot_dire, condition): self.plot_dire = plot_dire self.condition = condition self.mjj = RooRealVar("ZJJMass", "ZJJMass", 50., 7000.) #self.costhetastar = RooRealVar("costhetastar", "costhetastar", -1., 1.) self.weight = RooRealVar("weight", "weight", -100., 100.) self.isSignal = RooCategory("isSignal", "isSignal") self.isSignal.defineType("signal", 1); self.isSignal.defineType("background", 0); self.ras = RooArgSet(self.mjj, self.weight) self.ds = RooDataSet("ds"+condition, "ds"+condition, self.ras, "weight") #self.mu = RooRealVar("mu", "mu", 90., 80., 100.) #self.widthL = RooRealVar("widthL", "widthL", 15., 2., 30.) #self.widthR = RooRealVar("widthR", "widthR", 4., 2., 15.) #self.sigmass = RooBifurGauss("bifurgauss", "bifurgauss", self.mjj, self.mu, self.widthL, self.widthR) self.c0 = RooRealVar("c0", "c0", -100., 100.) self.bkgmass = RooExponential("expo", "expo", self.mjj, self.c0) #self.nsig = RooRealVar("nsig", "nsig", 100, 0, 200) #self.nbkg = RooRealVar("nbkg", "nbkg", 100, 0, 200) #self.components = RooArgList(self.sigmass, self.bkgmass) #self.coefficients = RooArgList(self.nsig, self.nbkg) self.modelmass = self.bkgmass #RooAddPdf("massmodel", "massmodel", self.components, self.coefficients)
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 __init__( self, fit_data ): MapStrRootPtr = stl.map( stl.string, "TH1*" ) StrHist = stl.pair( stl.string, "TH1*" ) self.fit_data = fit_data self.models = {} self.sample = RooCategory( 'sample', 'sample' ) self.roofit_variables = [] input_hists = MapStrRootPtr() # first create observables # Since we are looking for normalisation in equivalent regions # the number of events in each sample has to be identical # Hence, pick one fit_data to create the set of observables fit_data_1 = fit_data.itervalues().next() samples = fit_data_1.samples self.observables = {} N_min = 0 N_max = fit_data_1.n_data() * 2 for sample in samples: self.observables[sample] = Observable( 'n_' + sample, 'number of ' + sample + " events", fit_data_1.normalisation[sample], N_min, N_max, "events" ) # next create the models for variable, fit_input in fit_data.iteritems(): self.models[variable] = fit_input.get_roofit_model( variable, self.observables ) self.sample.defineType( variable ) self.sample.setLabel ( variable ) data = deepcopy( fit_input.real_data_histogram() ) input_hists.insert( StrHist( variable, data ) ) self.roofit_variables.append( fit_input.fit_variable ) self.comb_data = RooDataHist( "combData", "combined data", RooArgList( self.roofit_variables[0] ), self.sample, input_hists, )
def __init__(self, pdf, component, fit_opts, correct_weights=True): self.__comp = component self.__pdf = pdf self.__fit_opts = fit_opts self.__result = None self.__correct_weights = correct_weights from ROOT import RooCategory self.__status = RooCategory("sweight_status", "sweight fit status") self.__status.defineType("success", 0) self.__status.defineType("one", 1) self.__status.defineType("two", 2) self.__status.defineType("three", 3) self.__status.defineType("other", 4) self.__parameters = None
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)
model2S = RooAddPdf('model2S','model2S',RooArgList(signal2S_1,signal2S_2,background2S),RooArgList(nsig2S1,nsig2S2,nbck2S)) n_evts_1_3s = RooRealVar('N_{3P_{1}}','N_{3P_{1}}',50,10,1000) n_evts_2_3s = RooFormulaVar('N_{3P_{2}}','@0*@1',RooArgList(n_evts_1_3s,ratio21_v3s)) n_bck3s = RooRealVar('nbkg3s','n_{bkg}',500,0,100000) model3S = RooAddPdf('model3S', 'model3S', RooArgList(chib13s,chib23s,background3s),RooArgList(n_evts_1_3s,n_evts_2_3s,n_bck3s)) # start simultaneous fit sample= RooCategory('sample','sample') 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) ;
class SWeightTransform(object): def __init__(self, pdf, component, fit_opts, correct_weights=True): self.__comp = component self.__pdf = pdf self.__fit_opts = fit_opts self.__result = None self.__correct_weights = correct_weights from ROOT import RooCategory self.__status = RooCategory("sweight_status", "sweight fit status") self.__status.defineType("success", 0) self.__status.defineType("one", 1) self.__status.defineType("two", 2) self.__status.defineType("three", 3) self.__status.defineType("other", 4) self.__parameters = None def __call__(self, data): pdf_pars = self.__pdf.getParameters(data.get()) if not self.__parameters: self.__parameters = pdf_pars self.__parameters = [p for p in pdf_pars] + [self.__status] else: for p in self.__parameters: pdf_par = pdf_pars.find(p.GetName()) if not pdf_par: continue pdf_par.setVal(p.getVal()) pdf_par.setError(p.getError()) success = False status = 4 for i in range(3): self.__result = self.__pdf.fitTo(data, **self.__fit_opts) status = self.__result.status() if status == 0: success = True break if status < 4: self.__status.setIndex(self.__result.status()) else: self.__status.setIndex(4) if success: from P2VV.Utilities.SWeights import SData self.__sData = SData(Pdf=self.__pdf, Data=data, Name="MassSPlot") data = self.__sData.data(self.__comp) if self.__correct_weights: from P2VV.Utilities.DataHandling import correctWeights data = correctWeights(data, splitCatNames=None, ImportIntoWS=False) return data else: return None def gen_params(self, observables=None): from ROOT import RooArgSet if self.__parameters: return self.__parameters else: if observables and not isinstance(observables, RooArgSet): obs = RooArgSet() for o in observables: obs.add(o._target_() if hasattr(o, "_target_") else o) observables = obs params = self.__pdf.getParameters(observables) self.__parameters = [p for p in params] + [self.__status] return self.__parameters def result_params(self): if not self.__result: return [] else: return [p for p in self.__result.floatParsFinal()] + [self.__status] def set_params(self, data_params): from ROOT import RooCategory for trans_param in self.result_params(): data_param = data_params.find(trans_param.GetName()) if isinstance(trans_param, RooCategory): data_param.setIndex(trans_param.getIndex()) else: data_param.setVal(trans_param.getVal()) # This sets a symmetric error, but since we don't run Minos, that's ok data_param.setError(trans_param.getError())
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)
runPeriods = [ 2011, 2012 ] from P2VV import RooFitDecorators from ROOT import TFile print 'reading data set "%s" from file "%s"' % ( dataSetName, filePathIn ) fileIn = TFile.Open(filePathIn) dsIn = fileIn.Get(dataSetName) obsSetIn = dsIn.get() dsIn.Print() runPeriodCat = obsSetIn.find('runPeriod') for period in runPeriods : assert runPeriodCat.isValidIndex(period) if len(runPeriods) < runPeriodCat.numTypes() : from ROOT import RooCategory runPeriodCatOut = RooCategory( runPeriodCat.GetName(), runPeriodCat.GetTitle() ) for catType in runPeriodCat : if catType.getVal() in runPeriods : runPeriodCatOut.defineType( catType.GetName(), catType.getVal() ) from ROOT import RooArgSet obsSetOut = RooArgSet(obsSetIn) obsSetOut.remove(runPeriodCat) obsSetOut.add(runPeriodCatOut) else : obsSetOut = obsSetIn cuts = '||'.join( 'runPeriod==%d' % period for period in runPeriods ) from ROOT import RooDataSet, RooFit print 'creating new data set for run periods %s' % runPeriods print 'applying cuts "%s"' % cuts
scale = 1 elif pidcut.find(' 10') > 0: wt = 'wt3' scale = 10 else: print 'Unknown PID selection. Weights not applied.' wtvar = RooRealVar(wt, 'weight', 0.0, 1.0) # dataset = fill_dataset(RooArgSet(time, wtvar), ftree, wt, wtvar, cutstr) dataset = get_dataset(RooArgSet(time, wtvar), ftree, cutstr, wt, scale) name_title = '{}_{}'.format(dataset.GetName(), mode) dataset.SetNameTitle(name_title, name_title) print '%s is weighted: %s' % (dataset.GetName(), dataset.isWeighted()) dsetlist += [dataset] decaycat = RooCategory('decaycat', 'Decay mode category') decaycat.defineType('DsPi') decaycat.defineType('DsK') varlist += [decaycat] for idx, mode in enumerate(['DsPi', 'DsK']): decaycat.setLabel(mode) dsetlist[idx].addColumn(decaycat) dataset = RooDataSet('dataset', 'Combined dataset (DsK + DsPi)', RooArgSet(time, decaycat), RooFit.Import(dsetlist[0])) dataset.append(dsetlist[1]) for dset in dsetlist: dset.Print()
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: data.plotOn(xframe,RooFit.DataError(RooAbsData.SumW2),RooFit.MarkerSize(1)) model.plotOn(xframe,RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) model.plotOn(xframe,RooFit.Components("bkg"+name),RooFit.LineStyle(kDashed),RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) model.plotOn(xframe,RooFit.Components("sigW"),RooFit.LineStyle(kDotted),RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) model.plotOn(xframe,RooFit.Components("sigZ"),RooFit.LineStyle(kDashDotted),RooFit.Normalization(1.0,RooAbsReal.RelativeExpected)) canvas=TCanvas("c2","c2",0,0,600,600) xframe.GetYaxis().SetTitle("Events") xframe.Draw() canvas.SaveAs(prefix+"_"+plot[0]+name+"_fit"+fit+".pdf") canvas.SaveAs(prefix+"_"+plot[0]+name+"_fit"+fit+".root") if Wonly: continue if fit=="data": sample=RooCategory("sample","sample") datasets=[] for category in ["anti-btag","btag"]: if category=="btag": altscenario=btagscenario 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
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)
# seed the Random number generator rndm = TRandom3(SEED + 1) RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295))) del rndm # start building the fit from B2DXFitters.WS import WS ws = RooWorkspace('ws') one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) # start by defining observables time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0)) qf = WS(ws, RooCategory('qf', 'final state charge')) qf.defineType('h+', +1) qf.defineType('h-', -1) qt = WS(ws, RooCategory('qt', 'tagging decision')) qt.defineType( 'B+', +1) qt.defineType('Untagged', 0) qt.defineType( 'B-', -1) # now other settings Gamma = WS(ws, RooRealVar( 'Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar( 'Dm', 'Dm', 17.719)) # ps^-1 mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0))
def rooFit108(): print ">>> setup model - a B decay with mixing..." dt = RooRealVar("dt","dt",-20,20) dm = RooRealVar("dm","dm",0.472) tau = RooRealVar("tau","tau",1.547) w = RooRealVar("w","mistag rate",0.1) dw = RooRealVar("dw","delta mistag rate",0.) # Build categories - possible values states # https://root.cern/doc/v610/classRooCategory.html mixState = RooCategory("mixState","B0/B0bar mixing state") mixState.defineType("mixed",-1) mixState.defineType("unmixed",1) tagFlav = RooCategory("tagFlav","Flavour of the tagged B0") tagFlav.defineType("B0",1) tagFlav.defineType("B0bar",-1) # Build a gaussian resolution model dterr = RooRealVar("dterr","dterr",0.1,1.0) bias1 = RooRealVar("bias1","bias1",0) sigma1 = RooRealVar("sigma1","sigma1",0.1) gm1 = RooGaussModel("gm1","gauss model 1",dt,bias1,sigma1) # Construct Bdecay (x) gauss # https://root.cern/doc/v610/classRooBMixDecay.html bmix = RooBMixDecay("bmix","decay",dt,mixState,tagFlav,tau,dm,w,dw,gm1,RooBMixDecay.DoubleSided) print ">>> sample data from data..." data = bmix.generate(RooArgSet(dt,mixState,tagFlav),2000) # RooDataSet print ">>> show dt distribution with custom binning..." # Make plot of dt distribution of data in range (-15,15) with fine binning for dt>0 # and coarse binning for dt<0 tbins = RooBinning(-15,15) # Create binning object with range (-15,15) tbins.addUniform(60,-15,0) # Add 60 bins with uniform spacing in range (-15,0) tbins.addUniform(15,0,15) # Add 15 bins with uniform spacing in range (0,15) dtframe = dt.frame(Range(-15,15),Title("dt distribution with custom binning")) # RooPlot data.plotOn(dtframe,Binning(tbins)) bmix.plotOn(dtframe) # NB: Note that bin density for each bin is adjusted to that of default frame # binning as shown in Y axis label (100 bins --> Events/0.4*Xaxis-dim) so that # all bins represent a consistent density distribution print ">>> plot mixstate asymmetry with custom binning..." # Make plot of dt distribution of data asymmetry in 'mixState' with variable binning abins = RooBinning(-10,10) # Create binning object with range (-10,10) abins.addBoundary(0) # Add boundaries at 0 abins.addBoundaryPair(1) # Add boundaries at (-1,1) abins.addBoundaryPair(2) # Add boundaries at (-2,2) abins.addBoundaryPair(3) # Add boundaries at (-3,3) abins.addBoundaryPair(4) # Add boundaries at (-4,4) abins.addBoundaryPair(6) # Add boundaries at (-6,6) aframe = dt.frame(Range(-10,10),Title("MixState asymmetry distribution with custom binning")) # RooPlot # Plot mixState asymmetry of data with specified customg binning data.plotOn(aframe,Asymmetry(mixState),Binning(abins)) # Plot corresponding property of pdf bmix.plotOn(aframe,Asymmetry(mixState)) # Adjust vertical range of plot to sensible values for an asymmetry aframe.SetMinimum(-1.1) aframe.SetMaximum( 1.1) # NB: For asymmetry distributions no density corrects are needed (and are thus not applied) print "\n>>> draw on canvas..." canvas = TCanvas("canvas","canvas",100,100,1400,600) canvas.Divide(2) canvas.cd(1) gPad.SetLeftMargin(0.15); gPad.SetRightMargin(0.02) dtframe.GetYaxis().SetLabelOffset(0.008) dtframe.GetYaxis().SetTitleOffset(1.6) dtframe.GetYaxis().SetTitleSize(0.045) dtframe.GetXaxis().SetTitleSize(0.045) dtframe.Draw() canvas.cd(2) gPad.SetLeftMargin(0.15); gPad.SetRightMargin(0.02) aframe.GetYaxis().SetLabelOffset(0.008) aframe.GetYaxis().SetTitleOffset(1.6) aframe.GetYaxis().SetTitleSize(0.045) aframe.GetXaxis().SetTitleSize(0.045) aframe.Draw() canvas.SaveAs("rooFit108.png")
RooAbsRealLValue.__assign__(var, entry) dataset.add(RooArgSet(var)) return dataset m = RooRealVar("Jpsi_M", "mass", fit_range[0], fit_range[1]) data_m = RooDataSet("data_m", "data_m", RooArgSet(m)) data_u = RooDataSet("data_u", "data_u", RooArgSet(m)) data_m = load_set(tot_m, m, data_m) data_u = load_set(tot_u, m, data_u) data_m.Print("v") data_u.Print("v") sample = RooCategory("sample", "sample") sample.defineType("matched") sample.defineType("unmatched") # define the combined set combData = RooDataSet( "combData", "combined data", RooArgSet(m), RooFit.Index(sample), RooFit.Import( "matched", data_m), RooFit.Import( "unmatched", data_u))
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 buildDataAndCategories(ws, options, args): #Get the input data inputData = TChain(options.treeName, 'The input data') for arg in args: print 'Adding data from: ', arg inputData.Add(arg) foldname = '' phirange = [0, 90] if not options.folded: foldname = '' phirange = [-180, 180] #variables necessary for j/psi mass,lifetime,polarization fit jPsiMass = RooRealVar('JpsiMass', 'M [GeV]', 2.7, 3.5) jPsiRap = RooRealVar('JpsiRap', '#nu', -2.3, 2.3) jPsiPt = RooRealVar("JpsiPt", "pT [GeV]", 0, 40) jPsicTau = RooRealVar('Jpsict', 'l_{J/#psi} [mm]', -1, 2.5) jPsicTauError = RooRealVar('JpsictErr', 'Error on l_{J/#psi} [mm]', 0, 2) jPsiVprob = RooRealVar('JpsiVprob', '', .01, 1) jPsiHXcosth = None jPsiHXphi = None jPsicTau.setBins(10000, "cache") if options.fitFrame is not None: jPsiHXcosth = RooRealVar('costh_' + options.fitFrame + foldname, 'cos(#theta)_{' + options.fitFrame + '}', -1, 1) jPsiHXphi = RooRealVar('phi_' + options.fitFrame + foldname, '#phi_{' + options.fitFrame + '}', phirange[0], phirange[1]) else: jPsiHXcosth = RooRealVar('costh_CS' + foldname, 'cos(#theta)_{CS}', -1, 1) jPsiHXphi = RooRealVar('phi_CS' + foldname, '#phi_{CS}', phirange[0], phirange[1]) #vars needed for on the fly calc of polarization variables jPsimuPosPx = RooRealVar('muPosPx', '+ Muon P_{x} [GeV]', 0) jPsimuPosPy = RooRealVar('muPosPy', '+ Muon P_{y} [GeV]', 0) jPsimuPosPz = RooRealVar('muPosPz', '+ Muon P_{z} [GeV]', 0) jPsimuNegPx = RooRealVar('muNegPx', '- Muon P_{x} [GeV]', 0) jPsimuNegPy = RooRealVar('muNegPy', '- Muon P_{y} [GeV]', 0) jPsimuNegPz = RooRealVar('muNegPz', '- Muon P_{z} [GeV]', 0) #create RooArgSet for eventual dataset creation dataVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError, jPsimuPosPx, jPsimuPosPy, jPsimuPosPz) #add trigger requirement if specified if options.triggerName: trigger = RooRealVar(options.triggerName, 'Passes Trigger', 0.5, 1.5) dataVars.add(trigger) dataVars.add(jPsiVprob) dataVars.add(jPsimuNegPx) dataVars.add(jPsimuNegPy) dataVars.add(jPsimuNegPz) dataVars.add(jPsiHXcosth) dataVars.add(jPsiHXphi) redVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError) redVars.add(jPsiHXcosth) redVars.add(jPsiHXphi) fitVars = redVars.Clone() ### HERE IS WHERE THE BIT FOR CALCULATING POLARIZATION VARS GOES ctauStates = RooCategory('ctauRegion', 'Cut Region in lifetime') ctauStates.defineType('prompt', 0) ctauStates.defineType('nonPrompt', 1) massStates = RooCategory('massRegion', 'Cut Region in mass') massStates.defineType('signal', 1) massStates.defineType('separation', 0) massStates.defineType('leftMassSideBand', -2) massStates.defineType('rightMassSideBand', -1) states = RooCategory('mlRegion', 'Cut Region in mass') states.defineType('nonPromptSignal', 2) states.defineType('promptSignal', 1) states.defineType('separation', 0) states.defineType('leftMassSideBand', -2) states.defineType('rightMassSideBand', -1) #define corresponding ranges in roorealvars #mass is a little tricky since the sidebands change definitions in each rap bin #define the names here and change as we do the fits #jPsiMass.setRange('NormalizationRangeFormlfit_promptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_nonPromptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_leftMassSideBand',2.7,3.1) #jPsiMass.setRange('NormalizationRangeFormlfit_rightMassSideBand',3.1,3.5) #want the prompt fit only done in prompt region #non-prompt only in non-prompt region #background over entire cTau range #jPsicTau.setRange('NormalizationRangeFormlfit_promptSignal',-1,.1) #jPsicTau.setRange('NormalizationRangeFormlfit_nonPromptSignal',.1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_leftMassSideBand',-1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_rightMassSideBand',-1,2.5) #redVars.add(ctauStates) #redVars.add(massStates) #redVars.add(states) fitVars.add(ctauStates) fitVars.add(massStates) fitVars.add(states) fullData = RooDataSet('fullData', 'The Full Data From the Input ROOT Trees', dataVars, ROOT.RooFit.Import(inputData)) for rap_bin in range(1, len(jpsi.pTRange)): yMin = jpsi.rapForPTRange[rap_bin - 1][0] yMax = jpsi.rapForPTRange[rap_bin - 1][-1] for pt_bin in range(len(jpsi.pTRange[rap_bin])): ptMin = jpsi.pTRange[rap_bin][pt_bin][0] ptMax = jpsi.pTRange[rap_bin][pt_bin][-1] sigMaxMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sigMinMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sbHighMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigBkgHigh * jpsi.sigmaMassJpsi[rap_bin] sbLowMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigBkgLow * jpsi.sigmaMassJpsi[rap_bin] ctauNonPrompt = .1 massFun = RooFormulaVar( 'massRegion', 'Function that returns the mass state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) ctauFun = RooFormulaVar( 'ctauRegion', 'Function that returns the ctau state.', '(' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ')', RooArgList(jPsiMass, jPsicTau)) mlFun = RooFormulaVar( 'mlRegion', 'Function that returns the mass and lifetime state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') + (' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ' && ' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) cutStringPt = '(' + jPsiPt.GetName() + ' > ' + str( ptMin) + ' && ' + jPsiPt.GetName() + ' < ' + str(ptMax) + ')' cutStringY = '( abs(' + jPsiRap.GetName() + ') > ' + str( yMin) + ' && abs(' + jPsiRap.GetName() + ') < ' + str( yMax) + ')' #cutStringM1 = '('+jPsiMass.GetName()+' < '+str(sigMinMass)+' && '+jPsiMass.GetName()+' > '+str(sbLowMass)+')' #cutStringM2 = '('+jPsiMass.GetName()+' < '+str(sbHighMass)+' && '+jPsiMass.GetName()+' > '+str(sigMaxMass)+')' #cutStringMT = '!('+cutStringM1+' || '+cutStringM2+')' cutString = cutStringPt + ' && ' + cutStringY #+' && '+cutStringMT print cutString #get the reduced dataset we'll do the fit on binData = fullData.reduce( ROOT.RooFit.SelectVars(redVars), ROOT.RooFit.Cut(cutString), ROOT.RooFit.Name('data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1)), ROOT.RooFit.Title('Data For Fitting')) binDataWithCategory = RooDataSet( 'data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1), 'Data For Fitting', fitVars) #categorize binData.addColumn(ctauStates) binData.addColumn(massStates) binData.addColumn(states) for ev in range(binData.numEntries()): args = binData.get(ev) jPsiMass.setVal(args.find(jPsiMass.GetName()).getVal()) jPsiRap.setVal(args.find(jPsiRap.GetName()).getVal()) jPsiPt.setVal(args.find(jPsiPt.GetName()).getVal()) jPsicTau.setVal(args.find(jPsicTau.GetName()).getVal()) jPsicTauError.setVal( args.find(jPsicTauError.GetName()).getVal()) jPsiHXcosth.setVal(args.find(jPsiHXcosth.GetName()).getVal()) jPsiHXphi.setVal(args.find(jPsiHXphi.GetName()).getVal()) massStates.setIndex(int(massFun.getVal())) ctauStates.setIndex(int(ctauFun.getVal())) states.setIndex(int(mlFun.getVal())) binDataWithCategory.add(fitVars) getattr(ws, 'import')(binDataWithCategory)
RooArgList(nSig, efficiency)) #Pass componentspass = RooArgList(sigShapePdf) #,bkgShapePdf); yieldspass = RooArgList(nSigpass) #, nBkgpass); sumpass = RooAddPdf("sumpass", "fixed extended sum pdf", componentspass, 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))
class SimultaneousFit: """ A fit that performs a simultaneous fit in more than one variable. It expects the input of fit_data which is a dictionary of the form {variable_name: FitData()}""" def __init__(self, fit_data): MapStrRootPtr = stl.map(stl.string, "TH1*") StrHist = stl.pair(stl.string, "TH1*") self.fit_data = fit_data self.models = {} self.sample = RooCategory("sample", "sample") self.roofit_variables = [] input_hists = MapStrRootPtr() # first create observables # Since we are looking for normalisation in equivalent regions # the number of events in each sample has to be identical # Hence, pick one fit_data to create the set of observables fit_data_1 = fit_data.itervalues().next() samples = fit_data_1.samples self.observables = {} N_min = 0 N_max = fit_data_1.n_data() * 2 for sample in samples: self.observables[sample] = Observable( "n_" + sample, "number of " + sample + " events", fit_data_1.normalisation[sample], N_min, N_max, "events", ) # next create the models for variable, fit_input in fit_data.iteritems(): self.models[variable] = fit_input.get_roofit_model(variable, self.observables) self.sample.defineType(variable) self.sample.setLabel(variable) data = deepcopy(fit_input.real_data_histogram()) input_hists.insert(StrHist(variable, data)) self.roofit_variables.append(fit_input.fit_variable) self.comb_data = RooDataHist( "combData", "combined data", RooArgList(self.roofit_variables[0]), self.sample, input_hists ) 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 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)
print "Getting deltam..." #deltam = m_D* - m_D0 deltam = lo_dataset.get(0)["deltam"] deltam.setMax(152) dm_min = deltam.getMin() dm_max = deltam.getMax() print "deltam accessed. \nBinning dataset..." ##### Dividing dataset based on D0 mass ##### #Define allowed regionsi regions = ["lo_mid", "mid", "hi_mid"] n_regions= len(regions) #Create index for RooFit to distinguish regions regionIndex = RooCategory("regionIndex", "regionIndex") for i in range(n_regions) : regionIndex.defineType(regions[i]) lo_mass_cut = 1845 hi_mass_cut = 1885 lo_mid_dataset = mid_dataset_raw.reduce("D0_mass < "+str(lo_mass_cut)) mid_dataset = mid_dataset_raw.reduce("D0_mass >= "+str(lo_mass_cut)+" && D0_mass <= "+str(hi_mass_cut)) hi_mid_dataset = mid_dataset_raw.reduce("D0_mass > "+str(hi_mass_cut)) #Create new dataset separated by region dataset = RooDataSet("dataset_"+mag, "dataset_"+mag, RooArgSet(deltam), Index(regionIndex), Import("lo_mid", lo_mid_dataset), Import("mid", mid_dataset), Import("hi_mid", hi_mid_dataset)) datahist = dataset.binnedClone() ############################################## print "Dataset binned successfully!\n"
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_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 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_dline_che(evtfile, mc, setMres, setGamma, setR, sp1, sp2, sp3, fa, fb, setmd, setp, setxi, setN1, setN2, setNbkgd1, setNbkgd2, title1, title2, epsfile, txtfile, ymin=0.5, cuts=None, err_type='SYMM', test=False): from ROOT import (gROOT, RooRealVar, RooCategory, RooArgSet, RooDataSet, RooFit, RooGaussian, RooArgList, RooAddPdf, RooSimultaneous, RooArgusBG, RooFormulaVar, RooChebychev, RooAbsData, RooDataHist, TCanvas, kRed, kBlue, kGreen, kMagenta, TPaveText, RooDLineShape) set_root_style(stat=1, grid=0) mbc = RooRealVar('mbc', 'Beam constrained mass', 1.83, 1.89, 'GeV') ebeam = RooRealVar('ebeam', 'Ebeam', 1.8815, 1.892, 'GeV') dflav = RooCategory('dflav', 'D0 flavor') dflav.defineType('dflav', 1) dflav.defineType('dbarflav', -1) if cuts != None: if 'kkmass' in cuts: kkmass = RooRealVar('kkmass', 'KK invariant mass', 0.97, 1.90, 'GeV') ras = RooArgSet(mbc, ebeam, kkmass, dflav) dataset = RooDataSet.read(evtfile, ras) else: raise NameError(cuts) sys.stdout.write('Using cuts: %s...' % cuts) dataset = dataset.reduce(cuts) sys.stdout.write(' selected %s events.\n' % dataset.numEntries()) else: ras = RooArgSet(mbc, ebeam, dflav) dataset = RooDataSet.read(evtfile, ras) res = RooRealVar("datares", "datares", mc) mres = RooRealVar("mres", "mres", setMres) gamma = RooRealVar('gamma', 'gamma', setGamma) r = RooRealVar('r', 'r', setR) sigmaE = RooRealVar("sigmaE", "sigmaE", 0.0021) sigmap1 = RooRealVar("sigmap1", "sigmap1", sp1, 0.002, 0.040) scalep2 = RooRealVar("scalep2", "scalep2", 2.00, 1.500, 5.500) scalep3 = RooRealVar("scalep3", "scalep3", 5.00, 3.00, 10.000) scalep2.setVal(sp2) scalep2.setConstant(1) scalep3.setVal(sp3) scalep3.setConstant(1) as12 = RooArgList(sigmap1, scalep2) sigmap2 = RooFormulaVar("sigmap2", "sigma2", "sigmap1*scalep2", as12) as123 = RooArgList(sigmap1, scalep2, scalep3) sigmap3 = RooFormulaVar("sigmap3", "sigma3", "sigmap1*scalep2*scalep3", as123) md = RooRealVar("md", "md", setmd, 1.863, 1.875) f2 = RooRealVar("f2", "f2", fa) f3 = RooRealVar("f3", "f3", fb) al23 = RooArgList(f2, f3) f1 = RooFormulaVar("f1", "f1", "1.0-f2-f3", al23) # Construct signal shape fcn1_1 = RooDLineShape("DLineshape1_1", "DLineShape1_1", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap1, md, res) fcn1_2 = RooDLineShape("DLineshape1_2", "DLineShape1_2", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap2, md, res) fcn1_3 = RooDLineShape("DLineshape1_3", "DLineShape1_3", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap3, md, res) fcn2_1 = RooDLineShape("DLineshape2_1", "DLineShape2_1", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap1, md, res) fcn2_2 = RooDLineShape("DLineshape2_2", "DLineShape2_2", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap2, md, res) fcn2_3 = RooDLineShape("DLineshape2_3", "DLineShape2_3", 4, mbc, ebeam, mres, gamma, r, sigmaE, sigmap3, md, res) alf1_123 = RooArgList(fcn1_1, fcn1_2, fcn1_3) af12 = RooArgList(f1, f2) sigpdf = RooAddPdf("signal1_3", "signal1_3", alf1_123, af12) alf2_123 = RooArgList(fcn2_1, fcn2_2, fcn2_3) sigbarpdf = RooAddPdf("signal2_3", "signal2_3", alf2_123, af12) con0 = RooRealVar('c0', 'constant', -1, 1) con1 = RooRealVar('c1', 'linear', -10, 10) con2 = RooRealVar('c2', 'quadratic', 1) bkgpdf = RooChebychev('bkgpdf', 'Background', mbc, RooArgList(con1, con2)) bkgbarpdf = RooChebychev('bkgbarpdf', 'Background', mbc, RooArgList(con1, con2)) yld = RooRealVar('yld', 'D yield', 100, 0, 2000) bkg = RooRealVar('bkg', 'Background', 100, 0, 1000) sumpdf = RooAddPdf('sumpdf', 'Sum pdf', RooArgList(sigpdf, bkgpdf), RooArgList(yld, bkg)) yldbar = RooRealVar('yldbar', 'Dbar yield', 100, 0, 2000) bkgbar = RooRealVar('bkgbar', 'Background', 100, 0, 1000) sumpdfbar = RooAddPdf('sumpdfbar', 'Sum pdf', RooArgList(sigbarpdf, bkgbarpdf), RooArgList(yldbar, bkgbar)) totalpdf = RooSimultaneous('rs', 'Simultaneous PDF', dflav) totalpdf.addPdf(sumpdf, 'dflav') totalpdf.addPdf(sumpdfbar, 'dbarflav') MINUIT = 'ermh4' if err_type == 'ASYM': MINUIT = 'erh4' if test: sys.stdout.write('Will save epsfile as: %s \n' % epsfile) sys.stdout.write('Will save txtfile as: %s \n' % txtfile) return if dataset.numEntries() == 0: yld.setVal(0) yldbar.setVal(0) else: # Start Fitting fitres = totalpdf.fitTo(dataset, MINUIT) fitres.Print('v') # Save plots canvas = TCanvas('canvas', 'mbc', 400, 400) xframe = mbc.frame(50) ProjWData = RooFit.ProjWData(dataset) RooAbsData.plotOn(dataset, xframe) totalpdf.plotOn(xframe, ProjWData) totalpdf.paramOn(xframe) xframe.Draw() canvas.Print(epsfile) # Save fitting parameters pars = [bkg, bkgbar, con1, md, sigmap1, yld, yldbar] save_fit_result(pars, txtfile, err_type=err_type, verbose=1)
def main(options,args): pt_bins = [[12, 15], [15, 20]] eta_bins = [[0.0,1.4442]] # try to split material dependence # [1.560,2.5]] sieie = RooRealVar(options.showerShapeName,'#sigma_{i #eta i #eta}',.1,0,.15) sieie.setBins(200) pt = RooRealVar(options.ptName,'Photon p_{T}',50,10,1000) eta = RooRealVar(options.etaName,'Photon #eta',0.0,-3.0,3.0) chIso = RooRealVar(options.isoName, 'phoCHIso', 100, 0, 20) fakeMom = RooRealVar(options.momName, 'phohasFakemom', 0,1) #containor for the root variables vars = RooArgSet() vars.add(sieie) vars.add(pt) vars.add(eta) vars.add(chIso) vars.add(fakeMom) allSig = None allBkg = None if options.weight is not None: weight = RooRealVar(options.weight,'',1) vars.add(weight) allSig = RooDataSet('allSig','All Signal Template Events', vars, RooFit.ImportFromFile(options.signalInput, options.sigTreeName), RooFit.WeightVar(options.weight) ) if options.useFakeMCBkg: fake = RooRealVar('Fake','',0.5,1.5) #RooRealVar isSidebands("isSidebands","isSidebands",0,1); #fake = RooRealVar(options.momName,"phohasFakemom",0,1) vars.add(fake) weight.setVal(1) ctauStates = RooCategory('ctauRegion','Cut Region in lifetime') ctauStates.defineType('phohasFakemom',0) #ctauStates.defineType('nonPrompt',1) allBkg = RooDataSet('allBkg','All Background Template Events', RooArgSet(ctauStates,vars), RooFit.ImportFromFile(options.backgroundInput, options.bkgTreeName), RooFit.WeightVar(options.weight) ) else: allSig = RooDataSet('allSig','All Signal Template Events', vars, RooFit.ImportFromFile(options.signalInput, options.sigTreeName) ) allBkg = RooDataSet('allBkg','All Background Template Events', vars, RooFit.ImportFromFile(options.backgroundInput, options.bkgTreeName) ) output = TFile.Open(options.outputFile,'RECREATE') ws = RooWorkspace(options.outputFile[:options.outputFile.find('.root')],'Template Workspace') # put in the raw datasets, no cuts or manipulation getattr(ws,'import')(allSig, RooFit.RenameVariable(options.showerShapeName,'Pho_SigmaIEtaIEta'), RooFit.RenameVariable(options.ptName,'Pho_Pt'), #RooFit.RenameVariable(options.isoName,'phoCHIso'), RooFit.RenameVariable(options.etaName,'Pho_Eta')) getattr(ws,'import')(allBkg, RooFit.RenameVariable(options.showerShapeName,'Pho_SigmaIEtaIEta'), RooFit.RenameVariable(options.ptName,'Pho_Pt'), #RooFit.RenameVariable(options.isoName,'phoCHIso'), RooFit.RenameVariable(options.etaName,'Pho_Eta')) #loop through bins making all templates for etabin in eta_bins: for ptbin in pt_bins: if 'abs(Pho_Eta) < 1.4442': phoselsig = 'abs(Pho_Eta) > %f && abs(Pho_Eta) < %f && Pho_Pt > %f && Pho_Pt < %f'%(etabin[0], etabin[1], ptbin[0], ptbin[1]) # if fake: phoselbkg = 'phoCHIso < 2 && abs(Pho_Eta) > %f && abs(Pho_Eta) < %f && Pho_Pt > %f && Pho_Pt < %f'%(etabin[0], etabin[1], ptbin[0], ptbin[1]) postfix = '_Eta_%.4f_%.4f_Pt_%.2f_%.2f'%(etabin[0],etabin[1],ptbin[0],ptbin[1]) binSig = ws.data('allSig').reduce(RooFit.Cut(phoselsig), RooFit.Name('sigEta'+postfix), RooFit.Title('Signal Template Events')) binBkg = ws.data('allBkg').reduce(RooFit.Cut(phoselbkg), RooFit.Name('bkgEta'+postfix), RooFit.Title('Background Template Events')) #save it all in the workspace getattr(ws,'import')(binSig) getattr(ws,'import')(binBkg) smoothingPars = RooArgList(ws.var('Pho_SigmaIEtaIEta')) #ws.var('Pho_Pt'), print 'Making binSigTemplate'+postfix+' with '+str(binSig.numEntries())+' events.' bSigTempl = None if( binSig.numEntries() <= 80000 ): bSigTempl = RooNDKeysPdf('binSigTemplate'+postfix,'',smoothingPars,binSig,"am") else: bSigTempl = super(RooDataSet,binSig) print 'Making binBkgTemplate'+postfix+' with '+str(binBkg.numEntries())+' events.' bBkgTempl = None if( binBkg.numEntries() <= 80000 ): bBkgTempl = RooNDKeysPdf('binBkgTemplate'+postfix,'',smoothingPars,binBkg,"am") else: bBkgTempl = super(RooDataSet,binBkg) #finely binned histograms so that we can store the results of the smoothing #These will be linearly interpolated by RooHistPdf bsTHist = bSigTempl.createHistogram('binSigSmoothedHist'+postfix, ws.var('Pho_SigmaIEtaIEta'), RooFit.Binning(options.nBins,0,.15) ) getattr(ws,'import')(bsTHist) bbTHist = bBkgTempl.createHistogram('binBkgSmoothedHist'+postfix, ws.var('Pho_SigmaIEtaIEta'), RooFit.Binning(options.nBins,0,.15) ) getattr(ws,'import')(bbTHist) #make RooDataHists for consuption by RooHistPdf Later bsTDHist = RooDataHist('binSigSmoothedDataHist'+postfix, '', RooArgList(ws.var('Pho_SigmaIEtaIEta')), ws.obj('binSigSmoothedHist'+postfix+'__Pho_SigmaIEtaIEta')) getattr(ws,'import')(bsTDHist) bbTDHist = RooDataHist('binBkgSmoothedDataHist'+postfix, '', RooArgList(ws.var('Pho_SigmaIEtaIEta')), ws.obj('binBkgSmoothedHist'+postfix+'__Pho_SigmaIEtaIEta')) getattr(ws,'import')(bbTDHist) ws.Write() output.Close()
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 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()
def dijet(category): channel = 'bb' stype = channel isSB = True # relict from using Alberto's more complex script isData = not ISMC nTupleDir = NTUPLEDIR samples = data if isData else back pd = [] for sample_name in samples: if YEAR == 'run2': pd += sample[sample_name]['files'] else: pd += [x for x in sample[sample_name]['files'] if YEAR in x] print "datasets:", pd if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR) if BIAS: print "Running in BIAS mode" order = 0 RSS = {} X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV") weight = RooRealVar("MANtag_weight", "", -1.e9, 1.e9) variables = RooArgSet(X_mass) variables.add(RooArgSet(weight)) if VARBINS: binsXmass = RooBinning(len(abins) - 1, abins) X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow)) plot_binning = RooBinning( int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) else: X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10)) binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) plot_binning = binsXmass baseCut = "" print stype, "|", baseCut print " - Reading from Tree" treeBkg = TChain("tree") for ss in pd: if os.path.exists(nTupleDir + ss + "_" + BTAGGING + ".root"): treeBkg.Add(nTupleDir + ss + "_" + BTAGGING + ".root") else: print "found no file for sample:", ss setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeBkg)) nevents = setData.sumEntries() dataMin, dataMax = array('d', [0.]), array('d', [0.]) setData.getRange(X_mass, dataMin, dataMax) xmin, xmax = dataMin[0], dataMax[0] lastBin = X_mass.getMax() if VARBINS: for b in narrow_bins: if b > xmax: lastBin = b break print "Imported", ( "data" if isData else "MC" ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax) #xmax = xmax+binsXmass.averageBinWidth() # start form next bin # 1 parameter print "fitting 1 parameter model" p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0., 2000.) modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)", "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1)) normzBkg1 = RooRealVar( modelBkg1.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) #range dependent of actual number of events! modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext", modelBkg1.GetTitle(), modelBkg1, normzBkg1) fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes1.Print() RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass, [fitRes1], normzBkg1.getVal()) # 2 parameters print "fitting 2 parameter model" p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100., 1000.) p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2", p1_1.getVal(), -100., 600.) modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2)", RooArgList(X_mass, p2_1, p2_2)) normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext", modelBkg2.GetTitle(), modelBkg2, normzBkg2) fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes2.Print() RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass, [fitRes2], normzBkg2.getVal()) # 3 parameters print "fitting 3 parameter model" p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1", p2_1.getVal(), -2000., 2000.) p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2", p2_2.getVal(), -400., 2000.) p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5, -500., 500.) modelBkg3 = RooGenericPdf( "Bkg3", "Bkg. fit (4 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))", RooArgList(X_mass, p3_1, p3_2, p3_3)) normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext", modelBkg3.GetTitle(), modelBkg3, normzBkg3) fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes3.Print() RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass, [fitRes3], normzBkg3.getVal()) # 4 parameters print "fitting 4 parameter model" p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1", p3_1.getVal(), -2000., 2000.) p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2", p3_2.getVal(), -2000., 2000.) p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3", p3_3.getVal(), -50., 50.) p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50., 50.) modelBkg4 = RooGenericPdf( "Bkg4", "Bkg. fit (5 par.)", "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))", RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4)) normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext", modelBkg4.GetTitle(), modelBkg4, normzBkg4) fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes4.Print() RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass, [fitRes4], normzBkg4.getVal()) # Normalization parameters are should be set constant, but shape ones should not # if BIAS: # p1_1.setConstant(True) # p2_1.setConstant(True) # p2_2.setConstant(True) # p3_1.setConstant(True) # p3_2.setConstant(True) # p3_3.setConstant(True) # p4_1.setConstant(True) # p4_2.setConstant(True) # p4_3.setConstant(True) # p4_4.setConstant(True) normzBkg1.setConstant(True) normzBkg2.setConstant(True) normzBkg3.setConstant(True) normzBkg4.setConstant(True) #*******************************************************# # # # Fisher # # # #*******************************************************# # Fisher test with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout: fout.write(r"\begin{tabular}{c|c|c|c|c}") fout.write("\n") fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\") fout.write("\n") fout.write("\hline") fout.write("\n") CL_high = False for o1 in range(1, 5): o2 = min(o1 + 1, 5) fout.write("%d par & %.2f & %.2f & %d & " % (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"] - RSS[o1]["npar"])) if o2 > len(RSS): fout.write(r"\\") fout.write("\n") continue #order==0 and CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1., RSS[o1]["nbins"]) fout.write("CL=%.3f " % (CL)) if CL > 0.10: # The function with less parameters is enough if not CL_high: order = o1 #fout.write( "%d par are sufficient " % (o1+1)) CL_high = True else: #fout.write( "%d par are needed " % (o2+1)) if not CL_high: order = o2 fout.write(r"\\") fout.write("\n") fout.write("\hline") fout.write("\n") fout.write(r"\end{tabular}") print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex" #print "-"*25 #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\" #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\" #print "\\hline" #CL_high = False #for o1 in range(1, 5): # o2 = min(o1 + 1, 5) # print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]), # if o2 > len(RSS): # print "\\\\" # continue #order==0 and # CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"]) # print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL), # if CL > 0.10: # The function with less parameters is enough # if not CL_high: # order = o1 # print "%d par are sufficient" % (o1+1), # CL_high=True # else: # print "%d par are needed" % (o2+1), # if not CL_high: # order = o2 # print "\\\\" #print "\\hline" #print "-"*25 #print "@ Order is", order, "("+category+")" #order = min(3, order) #order = 2 if order == 1: modelBkg = modelBkg1 #.Clone("Bkg") modelAlt = modelBkg2 #.Clone("BkgAlt") normzBkg = normzBkg1 #.Clone("Bkg_norm") fitRes = fitRes1 elif order == 2: modelBkg = modelBkg2 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg2 #.Clone("Bkg_norm") fitRes = fitRes2 elif order == 3: modelBkg = modelBkg3 #.Clone("Bkg") modelAlt = modelBkg4 #.Clone("BkgAlt") normzBkg = normzBkg3 #.Clone("Bkg_norm") fitRes = fitRes3 elif order == 4: modelBkg = modelBkg4 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg4 #.Clone("Bkg_norm") fitRes = fitRes4 else: print "Functions with", order + 1, "or more parameters are needed to fit the background" exit() modelBkg.SetName("Bkg_" + YEAR + "_" + category) modelAlt.SetName("Alt_" + YEAR + "_" + category) normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm") print "-" * 25 # Generate pseudo data setToys = RooDataSet() setToys.SetName("data_toys") setToys.SetTitle("Data (toys)") if not isData: print " - Generating", nevents, "events for toy data" setToys = modelBkg.generate(RooArgSet(X_mass), nevents) #setToys = modelAlt.generate(RooArgSet(X_mass), nevents) print "toy data generated" if VERBOSE: raw_input("Press Enter to continue...") #*******************************************************# # # # Plot # # # #*******************************************************# print "starting to plot" c = TCanvas("c_" + category, category, 800, 800) c.Divide(1, 2) setTopPad(c.GetPad(1), RATIO) setBotPad(c.GetPad(2), RATIO) c.cd(1) frame = X_mass.frame() setPadStyle(frame, 1.25, True) if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) signal = getSignal( category, stype, 2000) #replacing Alberto's getSignal by own dummy function graphData = setData.plotOn(frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.Invisible()) modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False), RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("FL"), RooFit.Name("1sigma")) modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelBkg.GetName())) modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613), RooFit.FillColor(609), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName())) if not isSB and signal[0] is not None: # FIXME remove /(2./3.) signal[0].plotOn( frame, RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent), RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629), RooFit.DrawOption("L"), RooFit.Name("Signal")) graphData = setData.plotOn( frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.XErrorSize(0 if not VARBINS else 1), RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2), RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName())) fixData(graphData.getHist(), True, True, not isData) pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True) chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True) #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2)) frame.GetYaxis().SetTitle("Events / ( 100 GeV )") frame.GetYaxis().SetTitleOffset(1.05) frame.Draw() #print "frame drawn" # Get Chi2 # chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName()) # chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName()) # chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName()) # chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName()) frame.SetMaximum(frame.GetMaximum() * 10) frame.SetMinimum(max(frame.GetMinimum(), 1.e-1)) c.GetPad(1).SetLogy() drawAnalysis(category) drawRegion(category, True) #drawCMS(LUMI, "Simulation Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) leg = TLegend(0.575, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.AddEntry(setData.GetName(), setData.GetTitle() + " (%d events)" % nevents, "PEL") leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(), "FL") #.SetTextColor(629) leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L") if not isSB and signal[0] is not None: leg.AddEntry("Signal", signal[0].GetTitle(), "L") leg.SetY1(0.9 - leg.GetNRows() * 0.05) leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextFont(42) if not isSB: latex.DrawLatex(leg.GetX1() * 1.16, leg.GetY1() - 0.04, "HVT model B (g_{V}=3)") # latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb") c.cd(2) frame_res = X_mass.frame() setPadStyle(frame_res, 1.25) frame_res.addPlotable(pulls, "P") setBotStyle(frame_res, RATIO, False) if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) frame_res.GetYaxis().SetRangeUser(-5, 5) frame_res.GetYaxis().SetTitle("pulls(#sigma)") frame_res.GetYaxis().SetTitleOffset(0.3) frame_res.Draw() fixData(pulls, False, True, False) drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True) line = drawLine(X_mass.getMin(), 0, lastBin, 0) if VARBINS: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") else: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# if BIAS: gSystem.Load("libHiggsAnalysisCombinedLimit.so") from ROOT import RooMultiPdf cat = RooCategory("pdf_index", "Index of Pdf which is active") pdfs = RooArgList(modelBkg, modelAlt) roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs) normulti = RooRealVar("roomultipdf_norm", "Number of background events", nevents, 0., 1.e6) normzBkg.setConstant( False ) ## newly put here to ensure it's freely floating in the combine fit # create workspace w = RooWorkspace("Zprime_" + YEAR, "workspace") # Dataset if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs")) else: getattr(w, "import")(setToys, RooFit.Rename("data_obs")) #getattr(w, "import")(setData, RooFit.Rename("data_obs")) if BIAS: getattr(w, "import")(cat, RooFit.Rename(cat.GetName())) getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName())) getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName())) getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName())) getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName())) getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName())) w.writeToFile(WORKDIR + "%s_%s.root" % (DATA_TYPE + "_" + YEAR, category), True) print "Workspace", WORKDIR + "%s_%s.root" % ( DATA_TYPE + "_" + YEAR, category), "saved successfully" if VERBOSE: raw_input("Press Enter to continue...")
def buildTimePdf(config): """ build time pdf, return pdf and associated data in dictionary """ from B2DXFitters.WS import WS print 'CONFIGURATION' for k in sorted(config.keys()): print ' %32s: %32s' % (k, config[k]) # start building the fit ws = RooWorkspace('ws_%s' % config['Context']) one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) # start by defining observables time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0)) qf = WS(ws, RooCategory('qf', 'final state charge')) qf.defineType('h+', +1) qf.defineType('h-', -1) qt = WS(ws, RooCategory('qt', 'tagging decision')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 # HACK (1/2): be careful about lower bound on eta, since mistagpdf below # is zero below a certain value - generation in accept/reject would get # stuck eta = WS( ws, RooRealVar( 'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']), 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qt, qf, time, eta, timeerr] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context']], 'FIT' in config['Context']) # float for fitting if 'GEN' in config['Context']: acc = accnorm # use normalised acceptance for generation # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) # build a (mock) mistag distribution mistagpdfparams = {} # start with parameters of mock distribution for sfx in ('omega0', 'omegaavg', 'f'): mistagpdfparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['TrivialMistagParams'][sfx])) # build mistag pdf itself mistagpdf = WS( ws, MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta, mistagpdfparams['omega0'], mistagpdfparams['omegaavg'], mistagpdfparams['f'])) # build mistag calibration mistagcalibparams = {} # start with parameters of calibration for sfx in ('p0', 'p1', 'etaavg'): mistagcalibparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['MistagCalibParams'][sfx])) for sfx in ('p0', 'p1'): # float calibration paramters mistagcalibparams[sfx].setConstant(False) mistagcalibparams[sfx].setError(0.1) # build mistag pdf itself omega = WS( ws, MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta, mistagcalibparams['p0'], mistagcalibparams['p1'], mistagcalibparams['etaavg'])) # build mock decay time error distribution (~ timeerr^6 * exp(-timerr / # (timerr_av / 7)) terrpdf_shape = WS( ws, RooConstVar('timeerr_ac', 'timeerr_ac', config['DecayTimeResolutionAvg'] / 7.)) terrpdf_truth = WS( ws, RooTruthModel('terrpdf_truth', 'terrpdf_truth', timeerr)) terrpdf_i0 = WS( ws, RooDecay('terrpdf_i0', 'terrpdf_i0', timeerr, terrpdf_shape, terrpdf_truth, RooDecay.SingleSided)) terrpdf_i1 = WS( ws, RooPolynomial('terrpdf_i1', 'terrpdf_i1', timeerr, RooArgList(zero, zero, zero, zero, zero, zero, one), 0)) terrpdf = WS(ws, RooProdPdf('terrpdf', 'terrpdf', terrpdf_i0, terrpdf_i1)) # build the time pdf pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[omega]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=terrpdf, mistagpdf=[mistagpdf], mistagobs=eta) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
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()
scale = 1 elif pidcut.find(' 10') > 0: wt = 'wt3' scale = 10 else: print 'Unknown PID selection. Weights not applied.' wtvar = RooRealVar(wt, 'weight', 0.0, 1.0) # dataset = fill_dataset(RooArgSet(time, wtvar), ftree, wt, wtvar, cutstr) dataset = get_dataset(RooArgSet(time, wtvar), ftree, cutstr, wt, scale) name_title = '{}_{}'.format(dataset.GetName(), mode) dataset.SetNameTitle(name_title, name_title) print '%s is weighted: %s' % (dataset.GetName(), dataset.isWeighted()) dsetlist += [dataset] decaycat = RooCategory('decaycat', 'Decay mode category') decaycat.defineType('DsPi') decaycat.defineType('DsK') varlist += [decaycat] for idx, mode in enumerate(['DsPi', 'DsK']): decaycat.setLabel(mode) dsetlist[idx].addColumn(decaycat) dataset = RooDataSet('dataset', 'Combined dataset (DsK + DsPi)', RooArgSet(time, decaycat), RooFit.Import(dsetlist[0])) dataset.append(dsetlist[1]) for dset in dsetlist:
def run(self, **kwargs): from ROOT import RooArgSet __check_req_kw__("Observables", kwargs) __check_req_kw__("Pdf", kwargs) observables = kwargs.pop("Observables") obs_set = RooArgSet(*observables) pdf = kwargs.pop("Pdf") genPdf = kwargs.pop("GenPdf", pdf) gen_obs_set = RooArgSet() for o in list(observables) + list(genPdf.ConditionalObservables()): gen_obs_set.add(o._target_()) gen_pdf_params = genPdf.getParameters(gen_obs_set).snapshot(True) genPdf = genPdf.clone(genPdf.GetName() + "_toy_clone") genPdf.recursiveRedirectServers(gen_pdf_params) fit_obs_set = RooArgSet() for o in list(observables) + list(pdf.ConditionalObservables()): fit_obs_set.add(o._target_()) params = pdf.getParameters(fit_obs_set) pdf_params = RooArgSet() for p in params: if p.isConstant(): continue pdf_params.add(p) ## for param in pdf_params: ## if param.GetName() not in ['Gamma', 'dGamma']: ## param.setConstant() self._gen_params = pdf_params.snapshot(True) # Make another ArgSet to put the fit results in result_params = RooArgSet(pdf_params, "result_params") transform = self.transform() if transform: trans_params = transform.gen_params(gen_obs_set) for p in trans_params: result_params.add(p) # Some extra numbers of interest from ROOT import RooRealVar NLL = RooRealVar("NLL", "-log(Likelihood)", 1.0) ngen = RooRealVar("ngen", "number of generated events", self.options().nevents) seed = RooRealVar("seed", "random seed", 0.0) from ROOT import RooCategory status = RooCategory("status", "fit status") status.defineType("success", 0) status.defineType("one", 1) status.defineType("two", 2) status.defineType("three", 3) status.defineType("other", 4) result_params.add(status) result_params.add(NLL) result_params.add(ngen) result_params.add(seed) # The dataset to store the results from ROOT import RooDataSet self._data = RooDataSet("result_data", "result_data", result_params) data_params = self._data.get() from ROOT import RooRandom import struct, os while self._data.numEntries() < self.options().ntoys: # Get a good random seed, set it and store it s = struct.unpack("I", os.urandom(4))[0] RooRandom.randomGenerator().SetSeed(s) seed.setVal(s) # Reset pdf parameters to initial values. Note: this does not reset the estimated errors... pdf_params.assignValueOnly(self.gen_params()) args = dict(NumEvents=self.options().nevents) if "ProtoData" in kwargs: args["ProtoData"] = kwargs.pop("ProtoData") genPdf.getParameters(obs_set).assignValueOnly(gen_pdf_params) data = genPdf.generate(obs_set, **args) if transform: data = transform(data) if not data: # Transform has failed transform.set_params(data_params) self._data.add(data_params) continue if data.isWeighted() and "SumW2Error" not in self.fit_opts(): self.fit_opts()["SumW2Error"] = False j = 0 while j < 4: fit_result = pdf.fitTo(data, NumCPU=self.options().ncpu, **(self.fit_opts())) if fit_result.status() == 0: fit_result.Print() break j += 1 if fit_result.status() != 0: print "Fit result status = %s" % fit_result.status() NLL.setVal(fit_result.minNll()) if fit_result.status() < 4: status.setIndex(fit_result.status()) else: status.setIndex(4) for result_param in result_params: data_param = data_params.find(result_param.GetName()) if isinstance(result_param, RooCategory): data_param.setIndex(result_param.getIndex()) else: data_param.setVal(result_param.getVal()) # This sets a symmetric error, but since we don't run Minos, that's ok data_param.setError(result_param.getError()) if transform: transform.set_params(data_params) self._data.add(data_params) return self.data()
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 buildDataAndCategories(ws,options,args): #Get the input data inputData = TChain(options.treeName,'The input data') for arg in args: print 'Adding data from: ',arg inputData.Add(arg) foldname = '' phirange = [0,90] if not options.folded: foldname='' phirange = [-180,180] #variables necessary for j/psi mass,lifetime,polarization fit jPsiMass = RooRealVar('JpsiMass','M [GeV]',2.7,3.5) jPsiRap = RooRealVar('JpsiRap','#nu',-2.3,2.3) jPsiPt = RooRealVar("JpsiPt","pT [GeV]",0,40); jPsicTau = RooRealVar('Jpsict','l_{J/#psi} [mm]',-1,2.5) jPsicTauError = RooRealVar('JpsictErr','Error on l_{J/#psi} [mm]',0,2) jPsiVprob = RooRealVar('JpsiVprob','',.01,1) jPsiHXcosth = None jPsiHXphi = None jPsicTau.setBins(10000,"cache") if options.fitFrame is not None: jPsiHXcosth = RooRealVar('costh_'+options.fitFrame+foldname,'cos(#theta)_{'+options.fitFrame+'}',-1,1) jPsiHXphi = RooRealVar('phi_'+options.fitFrame+foldname,'#phi_{'+options.fitFrame+'}',phirange[0],phirange[1]) else: jPsiHXcosth = RooRealVar('costh_CS'+foldname,'cos(#theta)_{CS}',-1,1) jPsiHXphi = RooRealVar('phi_CS'+foldname,'#phi_{CS}',phirange[0],phirange[1]) #vars needed for on the fly calc of polarization variables jPsimuPosPx = RooRealVar('muPosPx','+ Muon P_{x} [GeV]',0) jPsimuPosPy = RooRealVar('muPosPy','+ Muon P_{y} [GeV]',0) jPsimuPosPz = RooRealVar('muPosPz','+ Muon P_{z} [GeV]',0) jPsimuNegPx = RooRealVar('muNegPx','- Muon P_{x} [GeV]',0) jPsimuNegPy = RooRealVar('muNegPy','- Muon P_{y} [GeV]',0) jPsimuNegPz = RooRealVar('muNegPz','- Muon P_{z} [GeV]',0) #create RooArgSet for eventual dataset creation dataVars = RooArgSet(jPsiMass,jPsiRap,jPsiPt, jPsicTau,jPsicTauError, jPsimuPosPx,jPsimuPosPy,jPsimuPosPz) #add trigger requirement if specified if options.triggerName: trigger = RooRealVar(options.triggerName,'Passes Trigger',0.5,1.5) dataVars.add(trigger) dataVars.add(jPsiVprob) dataVars.add(jPsimuNegPx) dataVars.add(jPsimuNegPy) dataVars.add(jPsimuNegPz) dataVars.add(jPsiHXcosth) dataVars.add(jPsiHXphi) redVars = RooArgSet(jPsiMass,jPsiRap,jPsiPt, jPsicTau,jPsicTauError) redVars.add(jPsiHXcosth) redVars.add(jPsiHXphi) fitVars = redVars.Clone() ### HERE IS WHERE THE BIT FOR CALCULATING POLARIZATION VARS GOES ctauStates = RooCategory('ctauRegion','Cut Region in lifetime') ctauStates.defineType('prompt',0) ctauStates.defineType('nonPrompt',1) massStates = RooCategory('massRegion','Cut Region in mass') massStates.defineType('signal',1) massStates.defineType('separation',0) massStates.defineType('leftMassSideBand',-2) massStates.defineType('rightMassSideBand',-1) states = RooCategory('mlRegion','Cut Region in mass') states.defineType('nonPromptSignal',2) states.defineType('promptSignal',1) states.defineType('separation',0) states.defineType('leftMassSideBand',-2) states.defineType('rightMassSideBand',-1) #define corresponding ranges in roorealvars #mass is a little tricky since the sidebands change definitions in each rap bin #define the names here and change as we do the fits #jPsiMass.setRange('NormalizationRangeFormlfit_promptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_nonPromptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_leftMassSideBand',2.7,3.1) #jPsiMass.setRange('NormalizationRangeFormlfit_rightMassSideBand',3.1,3.5) #want the prompt fit only done in prompt region #non-prompt only in non-prompt region #background over entire cTau range #jPsicTau.setRange('NormalizationRangeFormlfit_promptSignal',-1,.1) #jPsicTau.setRange('NormalizationRangeFormlfit_nonPromptSignal',.1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_leftMassSideBand',-1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_rightMassSideBand',-1,2.5) #redVars.add(ctauStates) #redVars.add(massStates) #redVars.add(states) fitVars.add(ctauStates) fitVars.add(massStates) fitVars.add(states) fullData = RooDataSet('fullData','The Full Data From the Input ROOT Trees', dataVars, ROOT.RooFit.Import(inputData)) for rap_bin in range(1,len(jpsi.pTRange)): yMin = jpsi.rapForPTRange[rap_bin-1][0] yMax = jpsi.rapForPTRange[rap_bin-1][-1] for pt_bin in range(len(jpsi.pTRange[rap_bin])): ptMin = jpsi.pTRange[rap_bin][pt_bin][0] ptMax = jpsi.pTRange[rap_bin][pt_bin][-1] sigMaxMass = jpsi.polMassJpsi[rap_bin] + jpsi.nSigMass*jpsi.sigmaMassJpsi[rap_bin] sigMinMass = jpsi.polMassJpsi[rap_bin] - jpsi.nSigMass*jpsi.sigmaMassJpsi[rap_bin] sbHighMass = jpsi.polMassJpsi[rap_bin] + jpsi.nSigBkgHigh*jpsi.sigmaMassJpsi[rap_bin] sbLowMass = jpsi.polMassJpsi[rap_bin] - jpsi.nSigBkgLow*jpsi.sigmaMassJpsi[rap_bin] ctauNonPrompt = .1 massFun = RooFormulaVar('massRegion','Function that returns the mass state.', '('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+str(sigMinMass)+ ') - ('+jPsiMass.GetName()+' > '+str(sbHighMass)+')'+ '-2*('+jPsiMass.GetName()+' < '+str(sbLowMass)+')', RooArgList(jPsiMass,jPsicTau)) ctauFun = RooFormulaVar('ctauRegion','Function that returns the ctau state.', '('+jPsicTau.GetName()+' > '+str(ctauNonPrompt)+')', RooArgList(jPsiMass,jPsicTau)) mlFun = RooFormulaVar('mlRegion','Function that returns the mass and lifetime state.', '('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+str(sigMinMass)+ ') + ('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+ str(sigMinMass)+' && '+jPsicTau.GetName()+' > '+str(ctauNonPrompt)+ ') - ('+jPsiMass.GetName()+' > '+str(sbHighMass)+')'+ '-2*('+jPsiMass.GetName()+' < '+str(sbLowMass)+')', RooArgList(jPsiMass,jPsicTau)) cutStringPt = '('+jPsiPt.GetName()+' > '+str(ptMin)+' && '+jPsiPt.GetName()+' < '+str(ptMax)+')' cutStringY = '( abs('+jPsiRap.GetName()+') > '+str(yMin)+' && abs('+jPsiRap.GetName()+') < '+str(yMax)+')' #cutStringM1 = '('+jPsiMass.GetName()+' < '+str(sigMinMass)+' && '+jPsiMass.GetName()+' > '+str(sbLowMass)+')' #cutStringM2 = '('+jPsiMass.GetName()+' < '+str(sbHighMass)+' && '+jPsiMass.GetName()+' > '+str(sigMaxMass)+')' #cutStringMT = '!('+cutStringM1+' || '+cutStringM2+')' cutString = cutStringPt+' && '+cutStringY #+' && '+cutStringMT print cutString #get the reduced dataset we'll do the fit on binData = fullData.reduce(ROOT.RooFit.SelectVars(redVars), ROOT.RooFit.Cut(cutString), ROOT.RooFit.Name('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1)), ROOT.RooFit.Title('Data For Fitting')) binDataWithCategory = RooDataSet('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1), 'Data For Fitting', fitVars) #categorize binData.addColumn(ctauStates) binData.addColumn(massStates) binData.addColumn(states) for ev in range(binData.numEntries()): args = binData.get(ev) jPsiMass.setVal(args.find(jPsiMass.GetName()).getVal()) jPsiRap.setVal(args.find(jPsiRap.GetName()).getVal()) jPsiPt.setVal(args.find(jPsiPt.GetName()).getVal()) jPsicTau.setVal(args.find(jPsicTau.GetName()).getVal()) jPsicTauError.setVal(args.find(jPsicTauError.GetName()).getVal()) jPsiHXcosth.setVal(args.find(jPsiHXcosth.GetName()).getVal()) jPsiHXphi.setVal(args.find(jPsiHXphi.GetName()).getVal()) massStates.setIndex(int(massFun.getVal())) ctauStates.setIndex(int(ctauFun.getVal())) states.setIndex(int(mlFun.getVal())) binDataWithCategory.add(fitVars) getattr(ws,'import')(binDataWithCategory)
numDataSets = 40 weightName = '' import P2VV.RooFitWrappers from ROOT import TFile, RooArgSet protoFile = TFile.Open(protoFilePathIn) nTupleFileIn = TFile.Open(nTupleFilePathIn) protoData = protoFile.Get('JpsiKK_sigSWeight') nTupleIn = nTupleFileIn.Get('DecayTree') from ROOT import RooRealVar, RooCategory obsSet = RooArgSet( protoData.get() ) if runPeriods : rp = obsSet.find('runPeriod') if rp : obsSet.remove(rp) rp = RooCategory( 'runPeriod', 'runPeriod' ) for per in runPeriods : rp.defineType( 'p%d' % per, per ) obsSet.add(rp) if KKMassBins : KKCat = obsSet.find('KKMassCat') if KKCat : obsSet.remove(KKCat) KKCat = RooCategory( 'KKMassCat', 'KKMassCat' ) for ind in range( len(KKMassBins) - 1 ) : KKCat.defineType( 'bin%d' % ind, ind ) obsSet.add(KKCat) from array import array KKBinsArray = array( 'd', KKMassBins ) from ROOT import RooBinning KKBinning = RooBinning( len(KKMassBins) - 1, KKBinsArray, 'KKMassBinning' ) obsSet.find('mdau2').setBinning( KKBinning, 'KKMassBinning' )
def buildTimePdf(config): """ build time pdf, return pdf and associated data in dictionary """ from B2DXFitters.WS import WS print 'CONFIGURATION' for k in sorted(config.keys()): print ' %32s: %32s' % (k, config[k]) # start building the fit ws = RooWorkspace('ws_%s' % config['Context']) one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) # start by defining observables time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0)) qf = WS(ws, RooCategory('qf', 'final state charge')) qf.defineType('h+', +1) qf.defineType('h-', -1) qt = WS(ws, RooCategory('qt', 'tagging decision')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qf, qt, time] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context']], 'FIT' in config['Context']) # float for fitting if 'GEN' in config['Context']: acc = accnorm # use normalised acceptance for generation # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) # build the time pdf pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[mistag]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
def buildTimePdf(config): """ build time pdf, return pdf and associated data in dictionary """ from B2DXFitters.WS import WS print 'CONFIGURATION' for k in sorted(config.keys()): print ' %32s: %32s' % (k, config[k]) # start building the fit ws = RooWorkspace('ws_%s' % config['Context']) one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) # start by defining observables time = WS(ws, RooRealVar('time', 'time [ps]', 0.3, 15.0)) qf = WS(ws, RooCategory('qf', 'final state charge')) qf.defineType('h+', +1) qf.defineType('h-', -1) qt = WS(ws, RooCategory('qt', 'tagging decision')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 # HACK (1/2): be careful about lower bound on eta, since mistagpdf below # is zero below a certain value - generation in accept/reject would get # stuck eta = WS(ws, RooRealVar('eta', 'eta', 0.35, 0., 0.5)) mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 1.0)) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.039)) #CHANGE THIS LATER # fit average mistag # add mistagged #ge rid of untagged events by putting restriction on qf or something when reduceing ds # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance if 'GEN' in config['Context']: obs = [qf, qt, time, eta] else: obs = [qf, qt, time] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]], 'FIT' in config['Context']) # float for fitting if 'GEN' in config['Context']: acc = accnorm # use normalised acceptance for generation # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) if 'GEN' in config['Context']: # build a (mock) mistag distribution mistagpdfparams = {} # start with parameters of mock distribution for sfx in ('omega0', 'omegaavg', 'f'): mistagpdfparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['TrivialMistagParams'][sfx])) # build mistag pdf itself mistagpdf = WS( ws, MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta, mistagpdfparams['omega0'], mistagpdfparams['omegaavg'], mistagpdfparams['f'])) mistagcalibparams = {} # start with parameters of calibration for sfx in ('p0', 'p1', 'etaavg'): mistagcalibparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['MistagCalibParams'][sfx])) for sfx in ('p0', 'p1'): # float calibration paramters mistagcalibparams[sfx].setConstant(False) mistagcalibparams[sfx].setError(0.1) # build mistag pdf itself omega = WS( ws, MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta, mistagcalibparams['p0'], mistagcalibparams['p1'], mistagcalibparams['etaavg'])) # build the time pdf if 'GEN' in config['Context']: pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[omega]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=None, mistagpdf=[mistagpdf], mistagobs=eta) else: adet = WS(ws, RooRealVar('adet', 'adet', 0., -.15, .15)) aprod = WS(ws, RooRealVar('aprod', 'aprod', 0., -.15, .15)) adet.setError(0.005) aprod.setError(0.005) pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[eta]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=None, aprod=aprod, adet=adet) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
class SimultaneousFit(): ''' A fit that performs a simultaneous fit in more than one variable. It expects the input of fit_data which is a dictionary of the form {variable_name: FitData()}''' def __init__(self, fit_data): MapStrRootPtr = stl.map(stl.string, "TH1*") StrHist = stl.pair(stl.string, "TH1*") self.fit_data = fit_data self.models = {} self.sample = RooCategory('sample', 'sample') self.roofit_variables = [] input_hists = MapStrRootPtr() # first create observables # Since we are looking for normalisation in equivalent regions # the number of events in each sample has to be identical # Hence, pick one fit_data to create the set of observables fit_data_1 = fit_data.itervalues().next() samples = fit_data_1.samples self.observables = {} N_min = 0 N_max = fit_data_1.n_data() * 2 for sample in samples: self.observables[sample] = Observable( 'n_' + sample, 'number of ' + sample + " events", fit_data_1.normalisation[sample], N_min, N_max, "events") # next create the models for variable, fit_input in fit_data.iteritems(): self.models[variable] = fit_input.get_roofit_model( variable, self.observables) self.sample.defineType(variable) self.sample.setLabel(variable) data = deepcopy(fit_input.real_data_histogram()) input_hists.insert(StrHist(variable, data)) self.roofit_variables.append(fit_input.fit_variable) self.comb_data = RooDataHist( "combData", "combined data", RooArgList(self.roofit_variables[0]), self.sample, input_hists, ) 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 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 fit_mass(data, column, x, sig_pdf=None, bkg_pdf=None, n_sig=None, n_bkg=None, blind=False, nll_profile=False, second_storage=None, log_plot=False, pulls=True, sPlot=False, bkg_in_region=False, importance=3, plot_importance=3): """Fit a given pdf to a variable distribution Parameter --------- data : |hepds_type| The data containing the variable to fit to column : str The name of the column to fit the pdf to sig_pdf : RooFit pdf The signal Probability Density Function. The variable to fit to has to be named 'x'. bkg_pdf : RooFit pdf The background Probability Density Function. The variable to fit to has to be named 'x'. n_sig : None or numeric The number of signals in the data. If it should be fitted, use None. n_bkg : None or numeric The number of background events in the data. If it should be fitted, use None. blind : boolean or tuple(numberic, numberic) If False, the data is fitted. If a tuple is provided, the values are used as the lower (the first value) and the upper (the second value) limit of a blinding region, which will be omitted in plots. Additionally, no true number of signal will be returned but only fake. nll_profile : boolean If True, a Negative Log-Likelihood Profile will be generated. Does not work with blind fits. second_storage : |hepds_type| A second data-storage that will be concatenated with the first one. importance : |importance_type| |importance_docstring| plot_importance : |plot_importance_type| |plot_importance_docstring| Return ------ tuple(numerical, numerical) Return the number of signals and the number of backgrounds in the signal-region. If a blind fit is performed, the signal will be a fake number. If no number of background events is required, -999 will be returned. """ if not (isinstance(column, str) or len(column) == 1): raise ValueError("Fitting to several columns " + str(column) + " not supported.") if type(sig_pdf) == type(bkg_pdf) == None: raise ValueError("sig_pdf and bkg_pdf are both None-> no fit possible") if blind is not False: lower_blind, upper_blind = blind blind = True n_bkg_below_sig = -999 # create data data_name = data.name data_array, _t1, _t2 = data.make_dataset(second_storage, columns=column) del _t1, _t2 # double crystalball variables min_x, max_x = min(data_array[column]), max(data_array[column]) # x = RooRealVar("x", "x variable", min_x, max_x) # create data data_array = np.array([i[0] for i in data_array.as_matrix()]) data_array.dtype = [('x', np.float64)] tree1 = array2tree(data_array, "x") data = RooDataSet("data", "Data", RooArgSet(x), RooFit.Import(tree1)) # # TODO: export somewhere? does not need to be defined inside... # mean = RooRealVar("mean", "Mean of Double CB PDF", 5280, 5100, 5600)#, 5300, 5500) # sigma = RooRealVar("sigma", "Sigma of Double CB PDF", 40, 0.001, 200) # alpha_0 = RooRealVar("alpha_0", "alpha_0 of one side", 5.715)#, 0, 150) # alpha_1 = RooRealVar("alpha_1", "alpha_1 of other side", -4.019)#, -200, 0.) # lambda_0 = RooRealVar("lambda_0", "Exponent of one side", 3.42)#, 0, 150) # lambda_1 = RooRealVar("lambda_1", "Exponent of other side", 3.7914)#, 0, 500) # # # TODO: export somewhere? pdf construction # frac = RooRealVar("frac", "Fraction of crystal ball pdfs", 0.479, 0.01, 0.99) # # crystalball1 = RooCBShape("crystallball1", "First CrystalBall PDF", x, # mean, sigma, alpha_0, lambda_0) # crystalball2 = RooCBShape("crystallball2", "Second CrystalBall PDF", x, # mean, sigma, alpha_1, lambda_1) # doubleCB = RooAddPdf("doubleCB", "Double CrystalBall PDF", # crystalball1, crystalball2, frac) # n_sig = RooRealVar("n_sig", "Number of signals events", 10000, 0, 1000000) # test input if n_sig == n_bkg == 0: raise ValueError("n_sig as well as n_bkg is 0...") if n_bkg is None: n_bkg = RooRealVar("n_bkg", "Number of background events", 10000, 0, 500000) elif n_bkg >= 0: n_bkg = RooRealVar("n_bkg", "Number of background events", int(n_bkg)) else: raise ValueError("n_bkg is not >= 0 or None") if n_sig is None: n_sig = RooRealVar("n_sig", "Number of signal events", 1050, 0, 200000) # START BLINDING blind_cat = RooCategory("blind_cat", "blind state category") blind_cat.defineType("unblind", 0) blind_cat.defineType("blind", 1) if blind: blind_cat.setLabel("blind") blind_n_sig = RooUnblindPrecision("blind_n_sig", "blind number of signals", "wasistdas", n_sig.getVal(), 10000, n_sig, blind_cat) else: # blind_cat.setLabel("unblind") blind_n_sig = n_sig print "n_sig value " + str(n_sig.getVal()) # raw_input("blind value " + str(blind_n_sig.getVal())) # n_sig = blind_n_sig # END BLINDING elif n_sig >= 0: n_sig = RooRealVar("n_sig", "Number of signal events", int(n_sig)) else: raise ValueError("n_sig is not >= 0") # if not blind: # blind_n_sig = n_sig # # create bkg-pdf # lambda_exp = RooRealVar("lambda_exp", "lambda exp pdf bkg", -0.00025, -1., 1.) # bkg_pdf = RooExponential("bkg_pdf", "Background PDF exp", x, lambda_exp) if blind: comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF", RooArgList(sig_pdf, bkg_pdf), RooArgList(blind_n_sig, n_bkg)) else: comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF", RooArgList(sig_pdf, bkg_pdf), RooArgList(n_sig, n_bkg)) # create test dataset # mean_gauss = RooRealVar("mean_gauss", "Mean of Gaussian", 5553, -10000, 10000) # sigma_gauss = RooRealVar("sigma_gauss", "Width of Gaussian", 20, 0.0001, 300) # gauss1 = RooGaussian("gauss1", "Gaussian test dist", x, mean_gauss, sigma_gauss) # lambda_data = RooRealVar("lambda_data", "lambda exp data", -.002) # exp_data = RooExponential("exp_data", "data example exp", x, lambda_data) # frac_data = RooRealVar("frac_data", "Fraction PDF of data", 0.15) # # data_pdf = RooAddPdf("data_pdf", "Data PDF", gauss1, exp_data, frac_data) # data = data_pdf.generate(RooArgSet(x), 30000) # data.printValue() # xframe = x.frame() # data_pdf.plotOn(xframe) # print "n_cpu:", meta_config.get_n_cpu() # input("test") # comb_pdf.fitTo(data, RooFit.Extended(ROOT.kTRUE), RooFit.NumCPU(meta_config.get_n_cpu())) # HACK to get 8 cores in testing c5 = TCanvas("c5", "RooFit pdf not fit vs " + data_name) c5.cd() x_frame1 = x.frame() # data.plotOn(x_frame1) # comb_pdf.pdfList()[1].plotOn(x_frame1) if __name__ == "__main__": n_cpu = 8 else: n_cpu = meta_config.get_n_cpu() print "n_cpu = ", n_cpu # HACK # n_cpu = 8 result_fit = comb_pdf.fitTo(data, RooFit.Minos(ROOT.kTRUE), RooFit.Extended(ROOT.kTRUE), RooFit.NumCPU(n_cpu)) # HACK end if bkg_in_region: x.setRange("signal", bkg_in_region[0], bkg_in_region[1]) bkg_pdf_fitted = comb_pdf.pdfList()[1] int_argset = RooArgSet(x) # int_argset = x # int_argset.setRange("signal", bkg_in_region[0], bkg_in_region[1]) integral = bkg_pdf_fitted.createIntegral(int_argset, RooFit.NormSet(int_argset), RooFit.Range("signal")) bkg_cdf = bkg_pdf_fitted.createCdf(int_argset, RooFit.Range("signal")) bkg_cdf.plotOn(x_frame1) # integral.plotOn(x_frame1) n_bkg_below_sig = integral.getVal(int_argset) * n_bkg.getVal() x_frame1.Draw() if plot_importance >= 3: c2 = TCanvas("c2", "RooFit pdf fit vs " + data_name) c2.cd() x_frame = x.frame() # if log_plot: # c2.SetLogy() # x_frame.SetTitle("RooFit pdf vs " + data_name) x_frame.SetTitle(data_name) if pulls: pad_data = ROOT.TPad("pad_data", "Pad with data and fit", 0, 0.33, 1, 1) pad_pulls = ROOT.TPad("pad_pulls", "Pad with data and fit", 0, 0, 1, 0.33) pad_data.SetBottomMargin(0.00001) pad_data.SetBorderMode(0) if log_plot: pad_data.SetLogy() pad_pulls.SetTopMargin(0.00001) pad_pulls.SetBottomMargin(0.2) pad_pulls.SetBorderMode(0) pad_data.Draw() pad_pulls.Draw() pad_data.cd() else: if log_plot: c2.SetLogy() if blind: # HACK column = 'x' # END HACK x.setRange("lower", min_x, lower_blind) x.setRange("upper", upper_blind, max_x) range_str = "lower,upper" lower_cut_str = str( min_x) + "<=" + column + "&&" + column + "<=" + str(lower_blind) upper_cut_str = str( upper_blind) + "<=" + column + "&&" + column + "<=" + str(max_x) sideband_cut_str = "(" + lower_cut_str + ")" + "||" + "(" + upper_cut_str + ")" n_entries = data.reduce( sideband_cut_str).numEntries() / data.numEntries() # raw_input("n_entries: " + str(n_entries)) if plot_importance >= 3: data.plotOn(x_frame, RooFit.CutRange(range_str), RooFit.NormRange(range_str)) comb_pdf.plotOn( x_frame, RooFit.Range(range_str), RooFit.Normalization(n_entries, RooAbsReal.Relative), RooFit.NormRange(range_str)) if pulls: # pull_hist(pull_frame=x_frame, pad_data=pad_data, pad_pulls=pad_pulls) x_frame_pullhist = x_frame.pullHist() else: if plot_importance >= 3: data.plotOn(x_frame) comb_pdf.plotOn(x_frame) if pulls: pad_pulls.cd() x_frame_pullhist = x_frame.pullHist() pad_data.cd() comb_pdf.plotOn(x_frame, RooFit.Components(sig_pdf.namePtr().GetName()), RooFit.LineStyle(ROOT.kDashed)) comb_pdf.plotOn(x_frame, RooFit.Components(bkg_pdf.namePtr().GetName()), RooFit.LineStyle(ROOT.kDotted)) # comb_pdf.plotPull(n_sig) if plot_importance >= 3: x_frame.Draw() if pulls: pad_pulls.cd() x_frame.SetTitleSize(0.05, 'Y') x_frame.SetTitleOffset(0.7, 'Y') x_frame.SetLabelSize(0.04, 'Y') # c11 = TCanvas("c11", "RooFit\ pulls" + data_name) # c11.cd() # frame_tmp = x_frame frame_tmp = x.frame() # frame_tmp.SetTitle("significance") frame_tmp.SetTitle("Roofit\ pulls\ " + data_name) frame_tmp.addObject(x_frame_pullhist) frame_tmp.SetMinimum(-5) frame_tmp.SetMaximum(5) # frame_tmp.GetYaxis().SetTitle("significance") frame_tmp.GetYaxis().SetNdivisions(5) frame_tmp.SetTitleSize(0.1, 'X') frame_tmp.SetTitleOffset(1, 'X') frame_tmp.SetLabelSize(0.1, 'X') frame_tmp.SetTitleSize(0.1, 'Y') frame_tmp.SetTitleOffset(0.5, 'Y') frame_tmp.SetLabelSize(0.1, 'Y') frame_tmp.Draw() # raw_input("") if not blind and nll_profile: # nll_range = RooRealVar("nll_range", "Signal for nLL", n_sig.getVal(), # -10, 2 * n_sig.getVal()) sframe = n_sig.frame(RooFit.Bins(20), RooFit.Range(1, 1000)) # HACK for best n_cpu lnL = comb_pdf.createNLL(data, RooFit.NumCPU(8)) # HACK end lnProfileL = lnL.createProfile(ROOT.RooArgSet(n_sig)) lnProfileL.plotOn(sframe, RooFit.ShiftToZero()) c4 = TCanvas("c4", "NLL Profile") c4.cd() # input("press ENTER to show plot") sframe.Draw() if plot_importance >= 3: pass params = comb_pdf.getVariables() params.Print("v") # print bkg_cdf.getVal() if sPlot: sPlotData = ROOT.RooStats.SPlot( "sPlotData", "sPlotData", data, # variable fitted to, RooDataSet comb_pdf, # fitted pdf ROOT.RooArgList( n_sig, n_bkg, # NSigB0s )) sweights = np.array([ sPlotData.GetSWeight(i, 'n_sig') for i in range(data.numEntries()) ]) return n_sig.getVal(), n_bkg_below_sig, sweights if blind: return blind_n_sig.getVal(), n_bkg_below_sig, comb_pdf else: return n_sig.getVal(), n_bkg_below_sig, comb_pdf
def add_category(self, name, values): cat = RooCategory(name, name) for val in pd.unique(values): cat.defineType(str(val), int(val)) self.param_list.add(name) setattr(self, name, cat)
# # # Python script to test the taggingutils module # # # # Example usage: # # ./test_taggingutils.py # # # # Author: Eduardo Rodrigues # # Date : 09 / 06 / 2011 # # # # --------------------------------------------------------------------------- # from ROOT import RooCategory, RooRealVar from B2DXFitters.taggingutils import tagEfficiencyWeight mixState = RooCategory( 'mixstate', 'B/Bbar -> D pi mixing state' ) mixState.defineType( "unmixed" , 1 ) mixState.defineType( "mixed" , -1 ) mixState.defineType( "untagged", 0 ) SigTagEff = 0.25 sigTagEff = RooRealVar( "sigTagEff", "Signal tagging efficiency", SigTagEff, 0., 1. ) sigTagWeight = tagEfficiencyWeight( mixState, sigTagEff, 'Bd2DPi' ) sigTagWeight.Print( 'v' ) print '\ntafEff =', sigTagEff.getVal() mixState.setIndex(0) print 'mixState = %2d => tagWeight = %f' % \
dataNames = [ 'JpsiKK_sigSWeight' ] #[ 'JpsiKK', 'JpsiKK_sigSWeight', 'JpsiKK_cbkgSWeight' ] removeObs = [ 'wMC', 'mdau1', 'tagCatP2VV' ] #, 'polarity', 'hlt2_prescale', 'nPVCat', 'BpTCat' ] dataFilePathIn = 'P2VVDataSets20112012Reco14_I2Mass_6KKMassBins_2TagCats_20140309.root' dataFilePathOut = 'P2VVDataSets2012Reco14_I2Mass_6KKMassBins_2TagCats_20140309.root' import P2VV.RooFitWrappers from ROOT import TObject, TFile, RooFit, RooDataSet, RooArgSet, RooCategory dataFile = TFile.Open(dataFilePathIn) newDataFile = TFile.Open( dataFilePathOut, 'RECREATE' ) newData = [ ] print 'read datasets from file "%s"' % dataFile.GetName() for dataName in dataNames : print 'reading dataset "%s"' % dataName data = dataFile.Get(dataName) data.Print() newArgSet = RooArgSet( data.get() ) for name in removeObs : newArgSet.remove( newArgSet.find(name) ) if runPeriod : newArgSet.remove( newArgSet.find('runPeriod') ) rp = RooCategory( 'runPeriod', 'runPeriod' ) rp.defineType( 'p%d' % runPeriod, runPeriod ) newArgSet.add(rp) newData.append( RooDataSet( dataName, dataName, newArgSet, RooFit.Import(data), RooFit.Cut(cut) ) ) newData[-1].Print() newDataFile.Add( newData[-1] ) print 'write dataset to file "%s"' % newDataFile.GetName() newDataFile.Write( dataFilePathOut, TObject.kOverwrite )
elif args[0] not in input_data: print parser.print_usage() sys.exit(-2) from P2VV.Load import LHCbStyle from P2VV.RooFitWrappers import * from ROOT import RooRealVar from ROOT import RooDataSet from ROOT import RooArgSet from ROOT import RooCategory input_data = input_data[args[0]] weight = RooRealVar('sWeights_ipatia', 'sWeights_ipatia', -1e3, 1e3) momentum = RooRealVar('B_P', 'B_P', 0, 1e6, 'MeV') runPeriod = RooCategory('runPeriod', 'runPeriod') runPeriod.defineType('p2011', 2011) runPeriod.defineType('p2012', 2012) from ROOT import TFile if args[0].startswith('MC'): from ROOT import TFile sig_file = TFile(input_data['sig_cache']) sig_data = sig_file.Get(input_data['sig_dataset']) prompt_file = TFile(input_data['prompt_cache']) prompt_data = prompt_file.Get(input_data['prompt_dataset']) else: sig_file = TFile("/project/bfys/jleerdam/data/Bs2Jpsiphi/Reco14/fitNTuple_peakBkg_2011_2012_Reco14_TOS_HLT2B_20140415.root") sig_tree = sig_file.Get("DecayTree") period = 'p' + args[0][:4] sig_data = RooDataSet('sig_data', 'sig_data', RooArgSet(momentum, weight, runPeriod),
metavar='FILE', type=lambda x: is_valid_file(parser, x)) arguments = parser.parse_args() from ROOT import TGraphErrors from ROOT import TFile, TF2, gDirectory, TF1, TH1D, TCanvas, TH2D from ROOT import kBlue, kGreen, kPink from ROOT import RooRealVar, RooArgSet, RooDataSet, RooFit from ROOT import RooGaussian, RooAddModel, RooArgList, RooFormulaVar from ROOT import RooCategory zMagnet = 'zTrueX' input_file = TFile(arguments.input_file[0]) tree = input_file.Get("MatchResidualAlgo/match_zerr") q = RooCategory('q', 'q') q.defineType('minux', -1) q.defineType('plus', 1) q.defineType('neutral', 0) res_x = RooRealVar('res_x', 'res_x', -1000, 1000) res_y = RooRealVar('res_y', 'res_y', -1000, 1000) pull_x = RooRealVar('pull_x', 'pull_x', -20, 20) pull_y = RooRealVar('pull_y', 'pull_y', -20, 20) p_match = RooRealVar('p_match', 'p_{m}', 3., 50.) match_res_x = RooRealVar('match_res_x', 'match_res_x', -1000, 1000) match_res_y = RooRealVar('match_res_y', 'match_res_y', -1000, 1000) match_pull_x = RooRealVar('match_pull_x', 'match_pull_x', -10, 10.) match_pull_x.setRange('narrow', -2, 2) match_pull_x.setRange('wide', match_pull_x.getMin(), match_pull_x.getMax()) match_pull_y = RooRealVar('match_pull_y', 'match_pull_y', -10, 10.) obs = RooArgSet(q, res_x, res_y, pull_x, pull_y, match_res_x, match_res_y,
def buildTimePdf(config, tupleDataSet, tupleDict): from B2DXFitters.WS import WS print 'CONFIGURATION' for k in sorted(config.keys()): print ' %32s: %32s' % (k, config[k]) ws = RooWorkspace('ws_%s' % config['Context']) one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) ###USE FIT CONTEXT """ build time pdf, return pdf and associated data in dictionary """ # start by defining observables time = WS(ws, tupleDataSet.get().find('ct')) #qt = WS(ws, tupleDataSet.get().find('ssDecision')); ''' time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0)) ''' qf = WS(ws, RooCategory('qf', 'final state charge')) qf.defineType('h+', +1) qf.defineType('h-', -1) qt = WS(ws, RooCategory('qt', 'tagging decision')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 # HACK (1/2): be careful about lower bound on eta, since mistagpdf below # is zero below a certain value - generation in accept/reject would get # stuck if 'GEN' in config['Context'] or 'FIT' in config['Context']: eta = WS( ws, RooRealVar( 'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']), 0.5)) mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) terrpdf = WS(ws, tupleDataSet.get().find('cterr')) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) #MISTAGPDF # fit average mistag # add mistagged #ge rid of untagged events by putting restriction on qf or something when reduceing ds # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qf, qt, time] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]], 'FIT' in config['Context']) # float for fitting # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) mistagpdf = WS( ws, RooArgList(tupleDataSet.get().find('ssMistag'), tupleDataSet.get().find('osMistag'))) #??? ''' if 'GEN' in config['Context']: # build a (mock) mistag distribution mistagpdfparams = {} # start with parameters of mock distribution for sfx in ('omega0', 'omegaavg', 'f'): mistagpdfparams[sfx] = WS(ws, RooRealVar( 'Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['TrivialMistagParams'][sfx])) # build mistag pdf itself mistagpdf = WS(ws, [tupleDataSet.reduce('ssMistag'), tupleDataSet.reduce('osMistag')]); mistagcalibparams = {} # start with parameters of calibration for sfx in ('p0', 'p1', 'etaavg'): mistagcalibparams[sfx] = WS(ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,config['MistagCalibParams'][sfx])); for sfx in ('p0', 'p1'): # float calibration paramters mistagcalibparams[sfx].setConstant(False) mistagcalibparams[sfx].setError(0.1) # build mistag pdf itself omega = WS(ws, MistagCalibration( 'Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta, mistagcalibparams['p0'], mistagcalibparams['p1'], mistagcalibparams['etaavg'])) # build the time pdf if 'GEN' in config['Context']: pdf = buildBDecayTimePdf( config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [ [ omega ] ], [ tageff ], Gamma, DGamma, Dm, C = one, D = zero, Dbar = zero, S = zero, Sbar = zero, timeresmodel = resmodel, acceptance = acc, timeerrpdf, mistagpdf = [mistagpdf], mistagobs = eta) else: pdf = buildBDecayTimePdf( config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [ [ eta ] ], [ tageff ], Gamma, DGamma, Dm, C = one, D = zero, Dbar = zero, S = zero, Sbar = zero, timeresmodel = resmodel, acceptance = acc, timeerrpdf = None) ''' pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[eta]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=terrpdf, mistagpdf=[mistagpdf], mistagobs=eta) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
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)