def get_data(zchain=getChains('v11')['z']): 'Get the nominal data that is used for smearing.' ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') mmgMassPhoGenE.SetTitle('threeBodyMass(mu1Pt, mu1Eta, mu1Phi, 0.106, ' ' mu2Pt, mu2Eta, mu2Phi, 0.106, ' ' phoGenE * phoPt / phoE, ' ' phoEta, phoPhi, 0)') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset global data data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmgMassPhoGenE, mmMass, phoERes], [ 'reconstructed m_{#mu#mu#gamma}', 'reconstructed m_{#mu#mu#gamma} with E_{gen}^{#gamma}', 'm_{#mu#mu}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', ], 'GeV GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ global calibrator calibrator = MonteCarloCalibrator(data)
def get_real_data(label): ''' Get real data for the dataset specified by the label: "data" (full 2011A+B), "2011A" or "2011B". ''' global model_tree_version, data_tree_version if model_tree_version == 'v11': data_tree_version = 'v12' if model_tree_version in 'v13 v14 v15'.split(): data_tree_version = 'v15' dchain = getChains(data_tree_version)[label] expression_title_map = { 'weight': '1', 'mmgMass': 'mmgMass', 'mmMass': 'mmMass', } latex_title_map = replace_variable_titles(expression_title_map, w) # weight.SetTitle('1') # mmgMass.SetTitle('mmgMass') # mmMass.SetTitle('mmMass') dataset.variables = [] dataset.cuts = [] data[label] = dataset.get(tree=dchain, cuts=cuts[:], variables=[mmgMass, mmMass], weight=weight) # mmgMass.SetTitle('m_{#mu#mu#gamma}') replace_variable_titles(latex_title_map, w)
def get_data(zchain = getChains('v11')['z']): 'Get the nominal data that is used for smearing.' ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') mmgMassPhoGenE.SetTitle('threeBodyMass(mu1Pt, mu1Eta, mu1Phi, 0.106, ' ' mu2Pt, mu2Eta, mu2Phi, 0.106, ' ' phoGenE * phoPt / phoE, ' ' phoEta, phoPhi, 0)') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset global data data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmgMassPhoGenE, mmMass, phoERes], ['m_{#mu#mu#gamma}', 'm_{#mu#mu#gamma} with E_{gen}^{#gamma}', 'm_{#mu^{+}#mu^{-}}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', ], 'GeV GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ global calibrator calibrator = MonteCarloCalibrator(data, 1)
def get_data(zchain = getChains('v11')['z']): 'Get the nominal data that is used for smearing.' ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset global data data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes,]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmMass, phoERes, phoRes, phoScale], ['m_{#mu#mu#gamma}', 'm_{#mu#mu}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', 'photon energy resolution', 'photon energy scale',], 'GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ ## Enlarge the range of the observable to get vanishing tails. range_save = (phoERes.getMin(), phoERes.getMax()) phoERes.setRange(-90, 150) global calibrator calibrator = MonteCarloCalibrator(data) phoERes.setRange(*range_save)
def getData(version='v1', nentries=-1): chains = getChains(version) data = {} for name, chain in chains.items(): mass = RooRealVar('mass', 'mass', 60, 120) weight = RooRealVar('weight', 'weight', 0, 999) if nentries > 0: cuts = ['Entry$ < %d' % nentries] else: cuts = [] data[name] = dataset.get(tree=chain, variable=mass, weight=weight, cuts=cuts) return data
def getData(self, workspace): """Gets the data and imports it in the workspace.""" ## Pull fitted variable x, its weight w, the model ## and its parameters from the workspace self.x = workspace.var(self.xName) self.x.Print() self.w = workspace.var('w') self.x.SetTitle(self.xExpression) self.data = dataset.get(tree=self.source, variable=self.x, weight=self.w, cuts=self.cuts) self.data.SetName('data_' + self.name) self.data.SetTitle(self.title) workspace.Import(self.data)
def get_data(): global weight, phoERes global data ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree zchain = getChains('v11')['z'] tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes,])
def getData(self, workspace): """Gets the data and imports it in the workspace.""" ## Pull fitted variable x, its weight w, the model ## and its parameters from the workspace self.x = workspace.var(self.xName) self.x.Print() self.w = workspace.var('w') self.x.SetTitle( self.xExpression ) self.data = dataset.get( tree = self.source, variable = self.x, weight = self.w, cuts = self.cuts ) self.data.SetName( 'data_' + self.name ) self.data.SetTitle( self.title ) workspace.Import(self.data)
def get_data(zchain=getChains('v11')['z']): 'Get the nominal data that is used for smearing.' global data, calibrator ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[ mmgMass, mmMass, phoERes, ]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmMass, phoERes], [ 'm_{#mu#mu#gamma}', 'm_{#mu#mu}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', ], 'GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ ## Enlarge the range of the observable to get vanishing tails. # range_save = (phoERes.getMin(), phoERes.getMax()) # phoERes.setRange(-90, 150) calibrator = MonteCarloCalibrator(data) # phoERes.setRange(*range_save) ##-- Set the nominal energy scale and resolution targets ------------------- calibrator.w.loadSnapshot('sr0_mctruth') for i, (s, r) in enumerate(zip(stargets, rtargets)): if s == 'nominal': stargets[i] = calibrator.s0.getVal() if r == 'nominal': rtargets[i] = calibrator.r0.getVal()
def get_data(zchain=getChains('v11')['z']): 'Get the nominal data that is used for smearing.' ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset global data data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[ mmgMass, mmMass, phoERes, ]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmMass, phoERes, phoRes, phoScale], [ 'm_{#mu#mu#gamma}', 'm_{#mu#mu}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', 'photon energy resolution', 'photon energy scale', ], 'GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ ## Enlarge the range of the observable to get vanishing tails. range_save = (phoERes.getMin(), phoERes.getMax()) phoERes.setRange(-90, 150) global calibrator calibrator = MonteCarloCalibrator(data) phoERes.setRange(*range_save)
def get_real_data(label): """ Get real data for the dataset specified by the label: "data" (full 2011A+B), "2011A" or "2011B". """ global model_tree_version global data_tree_version if model_tree_version == "v11": data_tree_version = "v12" if model_tree_version in "v13 v14 v15".split(): data_tree_version = "v15" dchain = getChains(data_tree_version)[label] expression_title_map = {"weight": "1", "mmgMass": "mmgMass", "mmMass": "mmMass"} latex_title_map = replace_variable_titles(expression_title_map, w) # weight.SetTitle('1') # mmgMass.SetTitle('mmgMass') # mmMass.SetTitle('mmMass') dataset.variables = [] dataset.cuts = [] data[label] = dataset.get(tree=dchain, cuts=cuts[:], variables=[mmgMass, mmMass], weight=weight) # mmgMass.SetTitle('m_{#mu#mu#gamma}') replace_variable_titles(latex_title_map, w)
def getData(self, workspace): ## Check if the workspace already has the data self.data = workspace.data('data_' + self.name) if self.data: ## Use the data from the workspace return ## Pull fitted variable x, its weight w, the model ## and its parameters from the workspace x = workspace.var('s') w = workspace.var('w') x.SetTitle(self.expression) self.data = dataset.get( tree=self.source, variable=x, weight=w, cuts=self.cuts + [ '%s > %f' % (self.expression, self.xRange[0]), '%s < %f' % (self.expression, self.xRange[1]), ]) self.data.SetName('data_' + self.name) workspace.Import(self.data)
def get_data(zchain = getChains('v11')['z']): 'Get the nominal data that is used for smearing.' global data, calibrator ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes,]) ## Set units and nice titles for x, t, u in zip([mmgMass, mmMass, phoERes], ['m_{#mu#mu#gamma}', 'm_{#mu#mu}', 'E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1', ], 'GeV GeV %'.split()): x.SetTitle(t) x.setUnit(u) ##-- Get Smeared Data ------------------------------------------------------ ## Enlarge the range of the observable to get vanishing tails. # range_save = (phoERes.getMin(), phoERes.getMax()) # phoERes.setRange(-90, 150) calibrator = MonteCarloCalibrator(data) # phoERes.setRange(*range_save) ##-- Set the nominal energy scale and resolution targets ------------------- calibrator.w.loadSnapshot('sr0_mctruth') for i, (s, r) in enumerate(zip(stargets, rtargets)): if s == 'nominal': stargets[i] = calibrator.s0.getVal() if r == 'nominal': rtargets[i] = calibrator.r0.getVal()
def getData(self, workspace): ## Check if the workspace already has the data self.data = workspace.data( 'data_' + self.name ) if self.data: ## Use the data from the workspace return ## Pull fitted variable x, its weight w, the model ## and its parameters from the workspace x = workspace.var('s') w = workspace.var('w') x.SetTitle( self.expression ) self.data = dataset.get( tree = self.source, variable = x, weight = w, cuts = self.cuts + [ '%s > %f' % (self.expression, self.xRange[0]), '%s < %f' % (self.expression, self.xRange[1]), ] ) self.data.SetName( 'data_' + self.name ) workspace.Import(self.data)
'isFSR'] ## Add a loose cut on photon pt lo = phoPtRange[0] * fRange[0] hi = phoPtRange[1] * fRange[1] cuts.append('%f <= phoPt & phoPt < %f' % (lo, hi)) ## Add an optional cut on number of entries if nentries > 0: cuts.append('Entry$ < %d' % nentries) ## Create a preselected tree tree = mcTree.CopyTree('&'.join(cuts)) ## Get the nominal dataset and those scaled up and down mmgData = dataset.get(tree=tree, variable=mmgMass, weight=weight, cuts = (cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRange])) mmgMass.SetTitle('scaledMmgMass3(%f, mmgMass, mmMass)' % fMin) phoPtRangeMod = (phoPtRange[0] * fMin, phoPtRange[1] * fMin) cutsMod = cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRangeMod] mmgDataMin = dataset.get(variable=mmgMass, cuts=cutsMod) mmgMass.SetTitle('scaledMmgMass3(%f, mmgMass, mmMass)' % fMax) phoPtRangeMod = (phoPtRange[0] * fMin, phoPtRange[1] * fMax) cutsMod = cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRangeMod] mmgDataMax = dataset.get(variable=mmgMass, cuts=cutsMod) ## Split the data in 2 independent halfs n = mmgData.numEntries() mmgData1 = mmgData.reduce(EventRange(0, int(n/2)))
cuts.append('%f <= phoPt & phoPt < %f' % (lo, hi)) ## Add an optional cut on number of entries if nentries > 0: cuts.append('Entry$ < %d' % nentries) ## Create a preselected tree tree = mcTree.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in mcTree.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, variables=[mmgMass, mmMass, mmgMassPhoGenE, phoERes], weight=weight, cuts = (cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRange])) ## Get the photon scale sensitivity factor phoFFunc.SetName('phoF') data.addColumn(phoFFunc) phoFFunc.SetName('phoFFunc') phoF.setVal(data.mean(phoF)) phoF.setConstant() mmgData = data.reduce(RooArgSet(mmgMass)) mmgMassPhoGenEData = data.reduce(RooArgSet(mmgMassPhoGenE)) rename_mmgMassPhoGenE_to_mmgMass = w.factory(''' FormulaVar::rename_mmgMassPhoGenE_to_mmgMass("mmgMassPhoGenE", {mmgMassPhoGenE})''') rename_mmgMassPhoGenE_to_mmgMass.SetName('mmgMass')
hi = phoPtRange[1] * max(fTest) cuts.append('%f <= phoPt & phoPt < %f' % (lo, hi)) ## Add an optional cut on number of entries if nentries > 0: cuts.append('Entry$ < %d' % nentries) ## Create a preselected tree tree = mcTree.CopyTree('&'.join(cuts)) cutsTraining = (cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRange, ## Use 3 of 4 events for training 'Entry$ % 4 != 0']) ## Get the nominal dataset data = dataset.get(tree=tree, variable=mmgMass, weight=weight, cuts = cutsTraining) mmData = dataset.get(variable=mmMass, cuts = cutsTraining) data.merge(mmData) ## Get the photon scale sensitivity factor fPhoFunc.SetName('fPho') data.addColumn(fPhoFunc) fPhoFunc.SetName('fPhoFunc') fPho.setVal(data.mean(fPho)) fPho.setConstant() mmgData = data.reduce(RooArgSet(mmgMass)) ## Put the nominal data in the workspace mmgData.SetName('mmgData')
parameters = model.getParameters(observables) ws1.defineSet("parameters", parameters) ws1.saveSnapshot("initial", parameters, True) ## Initialize latex label latexLabel = TLatex() latexLabel.SetNDC() latexLabel.SetTextSize(0.045) ## Loop over plots for plot in _plots: ## Get the RooDataset x.SetTitle( plot.expression ) data = dataset.get( tree = plot.source, variable = x, weight = w, cuts = plot.cuts ) data.SetName( 'data_' + plot.name ) ws1.Import(data) ## Fit data plot.fitResult = model.fitTo( data, Save(), SumW2Error(kTRUE), PrintLevel(-1) ) ws1.saveSnapshot( plot.name, parameters, True ) ## Make a frame x.SetTitle(plot.xTitle) x.setBins(plot.nBins) frame = x.frame( Range( *plot.xRange ) ) ## Add the data and model to the fram
def main(): global data sw.Start() init() get_data() if reduce_data: reduced_entries = int((1 - fit_data_fraction) * data.numEntries()) data = data.reduce(roo.EventRange(0, int(reduced_entries))) check_timer('1. init and get_data (%d entries)' % data.numEntries()) ## phor_reference_targets = ROOT.RooBinning mmgMass.setBins(1000, 'cache') phoRes.setBins(50, 'cache') # phoScale.setBins(40, 'cache') # phortargets = [0.5 + 0.5 * i for i in range(16)] phortargets = [0.5, 1, 2, 3, 4, 5, 7, 10] # phortargets = [0.5, calibrator.r0.getVal(), 10] # phortargets.append(calibrator.r0.getVal()) phortargets.sort() ROOT.RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-09) ROOT.RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-09) global pm pm = PhosphorModel5('pm5_' + name, 'pm5_' + name, mmgMass, phoScale, phoRes, data, w, 'nominal', phortargets) w.Import(pm) check_timer('2. PhosphorModel5 build') ## ROOT.RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-07) ## ROOT.RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-07) fitdata = calibrator.get_smeared_data(sfit, rfit, 'fitdata', 'title', True) ## RooAdaptiveGaussKronrodIntegrater1D #mmgMass.setRange(40, 140) ## ROOT.RooAbsReal.defaultIntegratorConfig().method1D().setLabel( ## "RooAdaptiveGaussKronrodIntegrator1D" ## ) ## msubs_lo = w.factory('EDIT::msubs_lo(pm5_msubs_0, mmgMass=mmgMassLo[40])') ## msubs_hi = w.factory('EDIT::msubs_hi(pm5_msubs_0, mmgMass=mmgMassHi[140])') # mmgMass.setRange('fit', msubs_lo, msubs_hi) mmgMass.setRange('fit', 60, 120) ## pm.setNormValueCaching(1) ## pm.getVal(ROOT.RooArgSet(mmgMass)) ## rfitdata = fitdata.reduce('60 < mmgMass & mmgMass < 120') if reduce_data == True: fitdata = fitdata.reduce(roo.Range(reduced_entries, fitdata.numEntries())) check_timer('3. get fit data (%d entries)' % fitdata.numEntries()) nll = pm.createNLL(fitdata, roo.Range('fit')) minuit = ROOT.RooMinuit(nll) minuit.setProfile() minuit.setVerbose() phoScale.setError(1) phoRes.setError(1) ## Initial HESSE status = minuit.hesse() fitres = minuit.save(name + '_fitres1_inithesse') w.Import(fitres, fitres.GetName()) check_timer('4. initial hesse (status: %d)' % status) ## Minimization minuit.setStrategy(2) status = minuit.migrad() fitres = minuit.save(name + '_fitres2_migrad') w.Import(fitres, fitres.GetName()) check_timer('5. migrad (status: %d)' % status) ## Parabolic errors status = minuit.hesse() fitres = minuit.save(name + '_fitres3_hesse') w.Import(fitres, fitres.GetName()) check_timer('6. hesse (status: %d)' % status) ## Minos errors ## status = minuit.minos() ## fitres = minuit.save(name + '_fitres4_minos') ## w.Import(fitres, fitres.GetName()) ## check_timer('7. minos (status: %d)' % status) ## fres = pm.fitTo(fitdata, ## roo.Range('fit'), ## roo.Strategy(2), ## roo.InitialHesse(True), ## roo.Minos(), ## roo.Verbose(True), ## roo.NumCPU(8), roo.Save(), roo.Timer()) canvases.next(name + '_phorhist') pm._phorhist.GetXaxis().SetRangeUser(75, 105) pm._phorhist.GetYaxis().SetRangeUser(0, 10) pm._phorhist.GetXaxis().SetTitle('%s (%s)' % (mmgMass.GetTitle(), mmgMass.getUnit())) pm._phorhist.GetYaxis().SetTitle('E^{#gamma} Resolution (%)') pm._phorhist.GetZaxis().SetTitle('Probability Density (1/GeV/%)') pm._phorhist.SetTitle(latex_title) pm._phorhist.GetXaxis().SetTitleOffset(1.5) pm._phorhist.GetYaxis().SetTitleOffset(1.5) pm._phorhist.GetZaxis().SetTitleOffset(1.5) pm._phorhist.SetStats(False) pm._phorhist.Draw('surf1') canvases.next(name + '_mwidth_vs_phor') graph = pm.make_mctrue_graph() graph.GetXaxis().SetTitle('E^{#gamma} resolution (%)') graph.GetYaxis().SetTitle('m_{#mu^{+}#mu^{-}#gamma} effective #sigma (GeV)') graph.SetTitle(latex_title) graph.Draw('ap') canvases.next(name + '_fit') mmgMass.setRange('plot', 70, 110) mmgMass.setBins(80) plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle(latex_title) fitdata.plotOn(plot) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot')) plot.Draw() Latex( [ 'E^{#gamma} Scale', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.s.getVal(), calibrator.s.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} resolution', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.r.getVal(), calibrator.r.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), ], position=(0.2, 0.8) ).draw() check_timer('8. fast plots') ## canvases.next(name + '_nll_vs_phos').SetGrid() ## plot = pm.w.var('phoScale').frame(roo.Range(*get_confint(phoScale))) ## plot.SetTitle(latex_title) ## nll.plotOn(plot, roo.ShiftToZero()) ## # plot.GetYaxis().SetRangeUser(0, 10) ## plot.Draw() ## check_timer('9. nll vs phos') ## canvases.next(name + 'norm') ## norm = pm.getNormObj(ROOT.RooArgSet(), ROOT.RooArgSet(mmgMass)) ## plot = phoScale.frame(roo.Range(*get_confint(phoScale))) ## norm.plotOn(plot) ## plot.GetYaxis().SetRangeUser(0.9995, 1.0005) ## plot.Draw() ## check_timer('10. norm vs phos') ## canvases.next(name + '_nll_vs_phor').SetGrid() ## plot = pm.w.var('phoRes').frame(roo.Range(*get_confint(phoRes))) ## nll.plotOn(plot, roo.ShiftToZero()) ## # plot.GetYaxis().SetRangeUser(0, 10) ## plot.Draw() ## canvases.next(name + '_nll_vs_phor_zoom').SetGrid() ## plot = pm.w.var('phoRes').frame(roo.Range(*get_confint(phoRes,1.5))) ## nll.plotOn(plot, roo.ShiftToZero()) ## # plot.GetYaxis().SetRangeUser(0, 10) ## plot.Draw() ## check_timer('11. nll vs phor') ## canvases.next(name + '_nll2d').SetGrid() ## h2nll = nll.createHistogram( ## 'h2nll', phoScale, roo.Binning(40, *get_confint(phoScale, 2)), ## roo.YVar(phoRes, roo.Binning(40, *get_confint(phoRes, 2))) ## ) ## h2nll.SetStats(False) ## h2nll.Draw('colz') ## check_timer('12. 2d nll') ## Get real data dchain = getChains('v11')['data'] weight.SetTitle('1') mmgMass.SetTitle('mmgMass') dataset.variables = [] dataset.cuts = [] realdata = dataset.get(tree=dchain, cuts=cuts[:-2], variable=mmgMass, weight=weight) mmgMass.SetTitle('m_{#mu#mu#gamma}') ## Fit it! fres_realdata = pm.fitTo(realdata, roo.Range(60, 120), roo.NumCPU(8), roo.Save()) ## Make a plot canvases.next(name + '_real_data') plot = mmgMass.frame(roo.Range(70, 110)) realdata.plotOn(plot) pm.plotOn(plot) pm.paramOn(plot) plot.Draw() outro() check_timer('13. outro')
FormulaVar::mmMean("MZ+mmScale", {MZ,mmScale}), GZ, mmRes)''') ## Get data chains = esChains.getChains('v11') weight = w.factory('dummyWeight[1,0,55]') weight.SetTitle('1') mmgMass = w.var('mmgMass') m1gOplusM2g = w.var('m1gOplusM2g') m1gOplusM2g.SetTitle('sqrt(mmgMass^2-mmMass^2)') isrData = dataset.get(tree=chains['z'], variable=mmMass, weight=weight, cuts=[ '!isFSR', 'mmgMass < 200', 'mmMass < 200', 'phoPt > 15', 'Entry$ < 500000' ]) mmgMassIsrData = dataset.get(variable=mmgMass) m1gOplusM2gIsrData = dataset.get(variable=m1gOplusM2g) isrData.merge(mmgMassIsrData, m1gOplusM2gIsrData) ## Fit the model to the data mmMassPdf.fitTo(isrData, roofit.Range(60, 120)) ## Plot the data and the fit mmPlot = mmMass.frame(roofit.Range(60, 120)) isrData.plotOn(mmPlot) mmMassPdf.plotOn(mmPlot)
def main(): global data sw.Start() init() get_data() mmgMass.setRange('plot', 70, 110) if reduce_data: reduced_entries = int((1 - fit_data_fraction) * data['fsr'].numEntries()) data['fsr'] = data['fsr'].reduce(roo.EventRange(0, int(reduced_entries))) check_timer('1. init and get_data (%d entries)' % data['fsr'].numEntries()) ## phor_reference_targets = ROOT.RooBinning mmgMass.setBins(1000, 'cache') phoRes.setBins(50, 'cache') # phoScale.setBins(40, 'cache') # phortargets = [0.5 + 0.5 * i for i in range(16)] # phortargets = [0.5, 1, 2, 3, 4, 5, 7, 10] phortargets = [0.5, calibrator.r0.getVal(), 10, 20] # phortargets.append(calibrator.r0.getVal()) phortargets.sort() ROOT.RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-09) ROOT.RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-09) ## Build the signal PDF global signal_model signal_model = PhosphorModel5(name + '_signal_model', name + '_signal_model', mmgMass, phoScale, phoRes, data['fsr'], w, 'nominal', phortargets, rho=2) signal_model.getVal(ROOT.RooArgSet(mmgMass)) w.Import(signal_model) ## Build the Z+jets background PDF. data['zj'].SetName(name + '_zj_mc') w.Import(data['zj']) global zj_pdf zj_pdf = ROOT.RooKeysPdf(name + '_zj_pdf', name + '_zj_pdf', mmgMass, data['zj'], ROOT.RooKeysPdf.NoMirror, 1.5) w.Import(zj_pdf) ## Build the PDF for other backgrounds. global bkg_pdf bkg_pdf = w.factory( '''Exponential::{name}_bkg_pdf(mmgMass, {name}_bkg_c[-1,-10,10]) '''.format(name=name) ) ## Build the composite model PDF global pm pm = w.factory( ## '''SUM::{name}_pm5({name}_signal_N[1000,0,1e6] * {name}_signal_model, ## {name}_zj_N [10,0,1e6] * {name}_zj_pdf, ## {name}_bkg_N [10,0,1e6] * {name}_bkg_pdf) ## '''.format(name=name) '''SUM::{name}_pm5({name}_signal_N[1000,0,1e6] * {name}_signal_model, {name}_zj_N[50,0,1e6] * {name}_zj_pdf) '''.format(name=name) ) check_timer('2. PhosphorModel5 build') ROOT.RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-09) ROOT.RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-09) global fitdata fitdata = calibrator.get_smeared_data(sfit, rfit, name + '_fitdata', name + '_fitdata', True) fitdata.reduce(ROOT.RooArgSet(mmgMass, mmMass)) fitdata.append(data['zj']) fitdata.SetName(name + '_fitdata') data['fit'] = fitdata ## RooAdaptiveGaussKronrodIntegrater1D #mmgMass.setRange(40, 140) ## ROOT.RooAbsReal.defaultIntegratorConfig().method1D().setLabel( ## "RooAdaptiveGaussKronrodIntegrator1D" ## ) ## msubs_lo = w.factory('EDIT::msubs_lo(pm5_msubs_0, mmgMass=mmgMassLo[40])') ## msubs_hi = w.factory('EDIT::msubs_hi(pm5_msubs_0, mmgMass=mmgMassHi[140])') # mmgMass.setRange('fit', msubs_lo, msubs_hi) mmgMass.setRange('fit', 60, 120) ## pm.setNormValueCaching(1) ## pm.getVal(ROOT.RooArgSet(mmgMass)) ## rfitdata = fitdata.reduce('60 < mmgMass & mmgMass < 120') if reduce_data == True: fitdata = fitdata.reduce(roo.Range(reduced_entries, fitdata.numEntries())) check_timer('3. get fit data (%d entries)' % fitdata.numEntries()) nll = pm.createNLL(fitdata, roo.Range('fit')) minuit = ROOT.RooMinuit(nll) minuit.setProfile() minuit.setVerbose() phoScale.setError(1) phoRes.setError(1) ## Initial HESSE status = minuit.hesse() fitres = minuit.save(name + '_fitres1_inithesse') w.Import(fitres, fitres.GetName()) check_timer('4. initial hesse (status: %d)' % status) ## Minimization minuit.setStrategy(2) status = minuit.migrad() fitres = minuit.save(name + '_fitres2_migrad') w.Import(fitres, fitres.GetName()) check_timer('5. migrad (status: %d)' % status) ## Parabolic errors status = minuit.hesse() fitres = minuit.save(name + '_fitres3_hesse') w.Import(fitres, fitres.GetName()) check_timer('6. hesse (status: %d)' % status) ## Minos errors status = minuit.minos() fitres = minuit.save(name + '_fitres4_minos') w.Import(fitres, fitres.GetName()) check_timer('7. minos (status: %d)' % status) ## fres = pm.fitTo(fitdata, ## roo.Range('fit'), ## roo.Strategy(2), ## roo.InitialHesse(True), ## roo.Minos(), ## roo.Verbose(True), ## # roo.NumCPU(8), ## roo.Save(), roo.Timer()) signal_model._phorhist.GetXaxis().SetRangeUser(75, 105) signal_model._phorhist.GetYaxis().SetRangeUser(0, 10) signal_model._phorhist.GetXaxis().SetTitle('%s (%s)' % (mmgMass.GetTitle(), mmgMass.getUnit())) signal_model._phorhist.GetYaxis().SetTitle('E^{#gamma} Resolution (%)') signal_model._phorhist.GetZaxis().SetTitle('Probability Density (1/GeV/%)') signal_model._phorhist.SetTitle(latex_title) signal_model._phorhist.GetXaxis().SetTitleOffset(1.5) signal_model._phorhist.GetYaxis().SetTitleOffset(1.5) signal_model._phorhist.GetZaxis().SetTitleOffset(1.5) signal_model._phorhist.SetStats(False) canvases.next(name + '_phorhist') signal_model._phorhist.Draw('surf1') global graph graph = signal_model.make_mctrue_graph() graph.GetXaxis().SetTitle('E^{#gamma} resolution (%)') graph.GetYaxis().SetTitle('m_{#mu^{+}#mu^{-}#gamma} effective #sigma (GeV)') graph.SetTitle(latex_title) canvases.next(name + '_mwidth_vs_phor') graph.Draw('ap') plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle(latex_title) fitdata.plotOn(plot) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot')) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot'), roo.Components('*zj*'), roo.LineStyle(ROOT.kDashed)) canvases.next(name + '_fit') plot.Draw() Latex([ 'E^{#gamma} Scale', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.s.getVal(), calibrator.s.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} resolution', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.r.getVal(), calibrator.r.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), '', 'N_{S} (events)', ' MC Truth: %.0f' % fitdata.sumEntries(), ' #mu#mu#gamma Fit: %.0f #pm %.0f' % ( w.var(name + '_signal_N').getVal(), w.var(name + '_signal_N').getError() ) ], position=(0.2, 0.8) ).draw() check_timer('8. fast plots') ## pm.fitTo(data['fsr'], roo.Verbose(), roo.Save(), roo.SumW2Error(True), ## roo.Range(60, 120), roo.NumCPU(8)) mmgMass.setRange('plot', 70, 110) mmgMass.setBins(80) plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle(latex_title) fitdata.plotOn(plot) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot')) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot'), roo.Components('*zj*'), roo.LineStyle(ROOT.kDashed)) canvases.next(name + '_fit_singal_only') plot.Draw() Latex( [ 'E^{#gamma} Scale', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.s.getVal(), calibrator.s.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} resolution', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.r.getVal(), calibrator.r.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), '', ## 'N_{S} (events)', ## ' MC Truth: %.0f' % fitdata.sumEntries(), ## ' #mu#mu#gamma Fit: %.0f #pm %.0f' % ( ## w.var(name + '_signal_f').getVal() * fitdata.sumEntries(), ## w.var(name + '_signal_f').getError() * fitdata.sumEntries() ## ) 'N_{S} (events)', ' MC Truth: %.1f' % fitdata.sumEntries(), ' #mu#mu#gamma Fit: %.1f #pm %.1f' % ( w.var(name + '_signal_N').getVal(), w.var(name + '_signal_N').getError() ) ], position=(0.2, 0.8) ).draw() canvases.next(name + '_nll_vs_phos').SetGrid() plot = phoScale.frame(roo.Range(*get_confint(phoScale))) plot.SetTitle(latex_title) nll.plotOn(plot, roo.ShiftToZero()) # plot.GetYaxis().SetRangeUser(0, 10) plot.Draw() check_timer('9. nll vs phos') canvases.next(name + 'norm') norm = pm.getNormObj(ROOT.RooArgSet(), ROOT.RooArgSet(mmgMass)) plot = phoScale.frame(roo.Range(*get_confint(phoScale))) norm.plotOn(plot) plot.GetYaxis().SetRangeUser(0.9995, 1.0005) plot.Draw() check_timer('10. norm vs phos') canvases.next(name + '_nll_vs_phor').SetGrid() plot = pm.w.var('phoRes').frame(roo.Range(*get_confint(phoRes))) nll.plotOn(plot, roo.ShiftToZero()) # plot.GetYaxis().SetRangeUser(0, 10) plot.Draw() canvases.next(name + '_nll_vs_phor_zoom').SetGrid() plot = pm.w.var('phoRes').frame(roo.Range(*get_confint(phoRes,1.5))) nll.plotOn(plot, roo.ShiftToZero()) # plot.GetYaxis().SetRangeUser(0, 10) plot.Draw() check_timer('11. nll vs phor') canvases.next(name + '_nll2d').SetGrid() h2nll = nll.createHistogram( 'h2nll', phoScale, roo.Binning(40, *get_confint(phoScale, 2)), roo.YVar(phoRes, roo.Binning(40, *get_confint(phoRes, 2))) ) h2nll.SetStats(False) h2nll.Draw('colz') check_timer('12. 2d nll') ## Get real data dchain = getChains('v12')['data'] weight.SetTitle('1') mmgMass.SetTitle('mmgMass') mmMass.SetTitle('mmMass') dataset.variables = [] dataset.cuts = [] data['real'] = dataset.get(tree=dchain, cuts=cuts[:], variables=[mmgMass, mmMass], weight=weight) mmgMass.SetTitle('m_{#mu#mu#gamma}') ## Fit it! fres_realdata = pm.fitTo(data['real'], roo.Range(60, 120), # roo.NumCPU(8), roo.Save(), roo.Timer(), roo.Verbose()) ## Make a plot mmgMass.setBins(80) plot = mmgMass.frame(roo.Range('plot')) plot.SetTitle(', '.join([latex_title, '2011A+B'])) data['real'].plotOn(plot) pm.plotOn(plot, roo.Range('plot'), roo.NormRange('plot')) canvases.next(name + '_real_data') plot.Draw() Latex([ 'E^{#gamma} Scale', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.s.getVal(), calibrator.s.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoScale.getVal(), phoScale.getError(), phoScale.getErrorHi(), phoScale.getErrorLo() ), '', 'E^{#gamma} resolution', ' MC Truth: %.2f #pm %.2f %%' % (calibrator.r.getVal(), calibrator.r.getError()), ' #mu#mu#gamma Fit: %.2f #pm %.2f ^{+%.2f}_{%.2f} %%' % ( phoRes.getVal(), phoRes.getError(), phoRes.getErrorHi(), phoRes.getErrorLo() ), ], position=(0.2, 0.8) ).draw() outro() check_timer('13. outro')
## Add an optional cut on number of entries if nentries > 0: cuts.append('Entry$ < %d' % nentries) ## Create a preselected tree tree = mcTree.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in mcTree.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## print '## Get the nominal dataset' ## Get the nominal dataset data = dataset.get(tree=tree, variables=[mmgMass, mmgMassShifted, mmMass, mmgMassPhoGenE, mmgMassShiftedPhoGenE, phoERes, mmgMassPhoSmear], weight=weight, cuts = (cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRange])) ## Create a preselected tree for real data tree = dataTree.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in dataTree.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset weight.SetTitle('1') realdata = dataset.get(tree=tree, variables=[mmgMass, mmgMassShifted, mmMass], weight=weight,
def getMassCut(self, workspace): """Uses the mmg invariant mass distribution to center the invariant mass window and adust its size. Appends the invariant mass cut to the list of cuts.""" ## Check if mass window is explicitly given if self.massWindow: ## Append the given mass window to the list of cuts mean = 0.5 * (self.massWindow[0] + self.massWindow[1]) width = 0.5 * (self.massWindow[1] - self.massWindow[0]) self.cuts.append( 'abs(mmgMass-%.2f) < %.2f' % (mean, width) ) ## Return without making the fit return mean = 91.2 width = 4. mmgMass = workspace.var('mmgMass') mmgMass.SetTitle('mmgMass') data = dataset.get( tree = self.source, variable = mmgMass, weight = workspace.var('w'), cuts = self.cuts ) m3Model = workspace.pdf('m3Model') m3Model.fitTo(data, SumW2Error(kTRUE)) workspace.saveSnapshot( 'm3_' + self.name, workspace.set('m3Model_params') ) canvas = TCanvas( 'm3_' + self.name, 'Mass fit, ' + self.title ) self.canvases.append( canvas ) i = len(gROOT.GetListOfCanvases()) canvas.SetWindowPosition(20*(i%50), 20*(i%5)) canvas.SetGrid() ## Extract the approximate mass cut and append it to the current cuts center = workspace.var('mZ').getVal() + workspace.var('#Deltam').getVal() sigmaCB = workspace.var('#sigmaCB').getVal() sigmaBW = workspace.var('#GammaZ').getVal() oplus = lambda x, y: math.sqrt(x*x + y*y) width = self.massWindowScale * oplus(sigmaCB, sigmaBW) ## Tune the position of the mass window by sample the signal pdf nsamples = 1000 xlo, dx = center - width, 2*width/(nsamples-1) signal = workspace.pdf('signal') xmax, ymax = -1, -1 for x in [xlo + i*dx for i in range(nsamples)]: mmgMass.setVal(x) y = signal.getVal() if y > ymax: xmax, ymax = x, y self.cuts.append( 'abs(mmgMass-%.2f) < %.2f' % (xmax, width) ) self.massWindow = (xmax - width, xmax + width) ## Plot the fit result mmgMass.SetTitle('m_{#mu#mu#gamma}') plot = mmgMass.frame(Range(60,120)) plot.SetTitle('') data.plotOn(plot) m3Model.paramOn( plot, Format('NEU', AutoPrecision(2) ), Layout(.65, 0.92, 0.92) ) m3Model.plotOn(plot) plot.Draw() ## Initialize latex label latexLabel = TLatex() latexLabel.SetNDC() ## Font size in pixels latexLabel.SetTextFont(10*(latexLabel.GetTextFont()/10) + 3) latexLabel.SetTextSize(18) ## Add mass window label latexLabel.DrawLatex( 0.65, 0.6 - 5 * 0.055, '%.2f #pm %.2f GeV' % (xmax, width) ) ## Plot the mass window canvas.Update() mmgMass.setVal(center) xlo = xmax - width xhi = xmax + width ylo = 0. yhi = 0.8 * canvas.GetY2() line1 = ROOT.TLine(xlo, ylo, xlo, yhi) line2 = ROOT.TLine(xhi, ylo, xhi, yhi) arrow1 = ROOT.TArrow(xlo, 0.5*yhi, xhi, 0.5*yhi, 0.01, '<>') for piece in [line1, line2, arrow1]: try: self.primitives.append(piece) except AttributeError: self.primitives = [] self.primitives.append(piece) piece.Draw() ## Save the plot if hasattr(self, 'graphicsExtensions'): for ext in self.graphicsExtensions: canvas.Print( 'massFit_' + self.name + '.' + ext )
model = ws1.factory("""CBShape::crystalBall( s, #Deltas[0, -50, 50], #sigma[20, 0.001, 100], #alpha[-1.5, -10, 0], n[1.5, 0.1, 10] )""") # data = dataset.get( tree = esChains.getChains('v4')['data'], # variable = x, # weight = w, # cuts = selection + ['id.run > 160000'], ## No 2010 data # ) data = dataset.get( tree = esChains.getChains('v4')['z'], variable = x, weight = w, cuts = selection, ## No 2010 data ) data.SetName('data') ws1.Import(data) # mc = dataset.get( tree = esChains.getChains('v4')['z'], # variable = x, # weight = w, # cuts = selection ) x.SetTitle( '100 * (phoGenE/(phoPt*cosh(phoEta)*kRatio) - 1)' ) mc = dataset.get( tree = esChains.getChains('v4')['z'], variable = x, weight = w,
## Add an optional cut on number of entries if nentries > 0: cuts.append('Entry$ < %d' % nentries) ## Create a preselected tree tree = mcTree.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in mcTree.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## print '## Get the nominal dataset' ## Get the nominal dataset data = dataset.get(tree=tree, variables=[phoPt, mmgMass, mmgGeom], weight=weight, cuts = (cuts[:] + ['%f < phoPt & phoPt < %f' % phoPtRange])) phoPtPdf1 = w.factory('''SUM::phoPtPdf1( fg[0.25,0,1] * Gaussian::g1(phoPt, m1[10,-100,100], s1[12,5,100]), Exponential::e1(phoPt, tau1[-0.2,-10,10]) )''') ## phoPtPdf2 = w.factory('''SUM::phoPtPdf2( ## fg[0.25,0,1] * Gaussian::g2(phoPt, m2[10,-100,100], s2[12,5,100]), ## fe21[0.9,0.1] * Exponential::e21(phoPt, tau21[-0.2,-10,10]), ## Exponential::e22(phoPt, tau22[-0.1,-10,10]) ## )''') w.Print()
## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree zchain = getChains('v11')['z'] tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[ mmgMass, mmMass, phoERes, ]) ## Give the titles the original meaning phoERes.SetTitle('E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1') phoERes.setUnit('%') ##------------------------------------------------------------------------------ ## Build model phoScale = w.factory('phoScale[0,-50,50]') phoRes = w.factory('phoRes[5,0.01,50]') for x in [phoScale, phoRes]: x.setUnit('%')
chains = getChains('v1') mcTree = chains['mc'] test1Tree = chains['test1'] w = RooWorkspace('w') mass = w.factory('mass[60, 120]') trange = (log(mass.getMin()/91.2), log(mass.getMax()/91.2)) t = w.factory('t[%f,%f]' % trange) t.SetTitle('log(mass/91.2)') weight = w.factory('weight[0, 999]') cuts = ['Entry$ < %d' % nentries] mData = dataset.get(tree=mcTree, variable=mass, weight=weight, cuts=cuts, name='mData') m1Data = dataset.get(tree=test1Tree, variable=mass, weight=weight, cuts=cuts, name='m1Data') tData = dataset.get(tree=mcTree, variable=t , weight=weight, cuts=cuts, name='tData') w.Import(mData) w.Import(tData) # w.Import(m1Data) mPdf = w.factory('KeysPdf::mPdf(mass, mData)') tPdf = w.factory('KeysPdf::tPdf(t, tData)') dt1Pdf = w.factory("""RooLogSqrtGaussian::dt1Pdf( t, #Deltam[1, 0.5, 1.5],
model = ws1.factory("""CBShape::crystalBall( s, #Deltas[0, -50, 50], #sigma[20, 0.001, 100], #alpha[-1.5, -10, 0], n[1.5, 0.1, 10] )""") # data = dataset.get( tree = esChains.getChains('v4')['data'], # variable = x, # weight = w, # cuts = selection + ['id.run > 160000'], ## No 2010 data # ) data = dataset.get( tree=esChains.getChains('v4')['z'], variable=x, weight=w, cuts=selection, ## No 2010 data ) data.SetName('data') ws1.Import(data) # mc = dataset.get( tree = esChains.getChains('v4')['z'], # variable = x, # weight = w, # cuts = selection ) x.SetTitle('100 * (phoGenE/(phoPt*cosh(phoEta)*kRatio) - 1)') mc = dataset.get(tree=esChains.getChains('v4')['z'], variable=x, weight=w,
w = RooRealVar( 'w', '1', 0, 99 ) xw = RooArgSet(x, w) ws1.Import(xw) model = ws1.factory("""CBShape::crystalBall( s, #Deltas[0, -50, 50], #sigma[20, 0.001, 100], #alpha[-1.5, -10, 0], n[1.5, 0.1, 10] )""") ## Get the data for the left plot x.SetTitle( leftPlot.expression ) data1 = dataset.get( tree = leftPlot.source, variable = x, weight = w, cuts = leftPlot.cuts ) data1.SetName('data1') ws1.Import(data1) ## Get the data for the right plot x.SetTitle( rightPlot.expression ) data2 = dataset.get( tree = rightPlot.source, variable = x, weight = w, cuts = rightPlot.cuts ) data2.SetName('data2') ws1.Import(data2) ## Define observables and parameters observables = RooArgSet(x) parameters = model.getParameters(observables) ws1.defineSet("parameters", parameters)
w = RooRealVar('w', '1', 0, 99) xw = RooArgSet(x, w) ws1.Import(xw) model = ws1.factory("""CBShape::crystalBall( s, #Deltas[0, -50, 50], #sigma[20, 0.001, 100], #alpha[-1.5, -10, 0], n[1.5, 0.1, 10] )""") ## Get the data for the left plot x.SetTitle(leftPlot.expression) data1 = dataset.get(tree=leftPlot.source, variable=x, weight=w, cuts=leftPlot.cuts) data1.SetName('data1') ws1.Import(data1) ## Get the data for the right plot x.SetTitle(rightPlot.expression) data2 = dataset.get(tree=rightPlot.source, variable=x, weight=w, cuts=rightPlot.cuts) data2.SetName('data2') ws1.Import(data2) ## Define observables and parameters observables = RooArgSet(x)
phoERes = w.factory('phoERes[-70, 100]') weight = w.factory('weight[1]') ## The TFormula expression defining the data is given in the titles. weight.SetTitle('pileup.weight') phoERes.SetTitle('100 * phoERes') ## Create a preselected tree zchain = getChains('v11')['z'] tree = zchain.CopyTree('&'.join(cuts)) ## Have to copy aliases by hand for a in zchain.GetListOfAliases(): tree.SetAlias(a.GetName(), a.GetTitle()) ## Get the nominal dataset data = dataset.get(tree=tree, weight=weight, cuts=cuts, variables=[mmgMass, mmMass, phoERes,]) ## Give the titles the original meaning phoERes.SetTitle('E_{reco}^{#gamma}/E_{gen}^{#gamma} - 1') phoERes.setUnit('%') ##------------------------------------------------------------------------------ ## Build model phoScale = w.factory('phoScale[0,-50,50]') phoRes = w.factory('phoRes[5,0.01,50]') range_save = (phoERes.getMin(), phoERes.getMax()) ## Enlarge the range of the observable to get vanishing tails. phoERes.setRange(-90, 150) phoEResPdf = ParametrizedKeysPdf('phoEResPdf', 'phoEResPdf', phoERes, phoScale, phoRes, data, ROOT.RooKeysPdf.NoMirror, 1.5)
def get_data(chains=getChains("v11")): """ Get the nominal data that is used for smearing. """ ## TODO: Break this down into several smaller methods. ## Map of variable names and corresponding TTree expressions to ## calculate it. expression_map = { "mmgMass": "mmgMass", "mmMass": "mmMass", "phoERes": "100 * phoERes", "mmgMassPhoGenE": ( "threeBodyMass(mu1Pt, mu1Eta, mu1Phi, 0.106, " " mu2Pt, mu2Eta, mu2Phi, 0.106, " " phoGenE * phoPt / phoE, " " phoEta, phoPhi, 0)" ), "weight": "pileup.weight", } ## The TFormula expression defining the data is given in the titles. # print '+++ DEBUG: before title replacement:', mmgMass.GetTitle() latex_map = replace_variable_titles(expression_map, w) # print '+++ DEBUG: after title replacement:', mmgMass.GetTitle() ## Create a preselected tree tree = {} tree["z"] = chains["z"].CopyTree("&".join(cuts)) # dtree = chains['data']. ## Have to copy aliases by hand for a in chains["z"].GetListOfAliases(): tree["z"].SetAlias(a.GetName(), a.GetTitle()) cuts0 = cuts[:] cuts1 = cuts[:] if use_independent_fake_data: cuts0.append("!(%s)" % fake_data_cut) cuts1.append(fake_data_cut) ## Get the nominal dataset global data data = {} for xvar in [weight, mmgMass, mmMass, phoERes, mmgMassPhoGenE]: print xvar.GetName(), ":", xvar.GetTitle() data["fsr0"] = dataset.get( tree=tree["z"], weight=weight, cuts=cuts0 + ["isFSR"], variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE] ) data["fsr1"] = dataset.get( tree=tree["z"], weight=weight, cuts=cuts1 + ["isFSR"], variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE] ) data["zj0"] = dataset.get(tree=tree["z"], weight=weight, cuts=cuts0 + ["!isFSR"], variables=[mmgMass, mmMass]) data["zj1"] = dataset.get(tree=tree["z"], weight=weight, cuts=cuts1 + ["!isFSR"], variables=[mmgMass, mmMass]) ## Set units and nice titles replace_variable_titles(latex_map, w) ## Do we want to reduce the data? if reduce_data: reduced_entries = int((1 - fit_data_fraction) * data["fsr0"].numEntries()) data["fsr0"] = data["fsr0"].reduce(roo.EventRange(0, int(reduced_entries))) data["zj0"].SetName("zj0_mc") w.Import(data["zj0"]) ##-- Calculate MC Truth Purity --------------------------------------------- if use_independent_fake_data: num_fsr_events = data["fsr1"].sumEntries() num_zj_events = data["zj1"].sumEntries() else: num_fsr_events = data["fsr0"].sumEntries() num_zj_events = data["zj0"].sumEntries() global fsr_purity fsr_purity = 100 * num_fsr_events / (num_fsr_events + num_zj_events) ##-- Get Smeared Data ------------------------------------------------------ old_precision = set_default_integrator_precision(2e-9, 2e-9) global calibrator0, calibrator1, fit_calibrator calibrator0 = MonteCarloCalibrator(data["fsr0"], printlevel=1, rho=1.5) if use_independent_fake_data: calibrator1 = MonteCarloCalibrator(data["fsr1"], printlevel=1, rho=1.5) fit_calibrator = calibrator1 else: fit_calibrator = calibrator0 set_default_integrator_precision(*old_precision) ##-- Check the time ------------------------------------------------------- check_timer( "1. init and get_data (%d entries)" % (data["fsr0"].numEntries() + data["fsr1"].numEntries() + data["zj0"].numEntries() + data["zj1"].numEntries()) )
def get_data(chains = getChains('v11')): ''' Get the nominal data that is used for smearing. ''' global cuts if Globals.debug: print '====== CUTS INSIDE phosphorcalculator ======', cuts ## TODO: Break this down into several smaller methods. ## Map of variable names and corresponding TTree expressions to ## calculate it. expression_map = { 'mmgMass': 'mmgMass', 'mmMass' : 'mmMass' , 'phoERes' : '100 * phoERes', 'mmgMassPhoGenE': ('threeBodyMass(mu1Pt, mu1Eta, mu1Phi, 0.106, ' ' mu2Pt, mu2Eta, mu2Phi, 0.106, ' ' phoGenE * phoPt / phoE, ' ' phoEta, phoPhi, 0)'), 'weight' : 'pileup.weight', } ## The TFormula expression defining the data is given in the titles. # print '+++ DEBUG: before title replacement:', mmgMass.GetTitle() latex_map = replace_variable_titles(expression_map, w) # print '+++ DEBUG: after title replacement:', mmgMass.GetTitle() #global cuts ## Create a preselected tree tree = {} tree['z'] = chains['z'].CopyTree('&'.join(cuts)) # dtree = chains['data']. ## Have to copy aliases by hand for a in chains['z'].GetListOfAliases(): tree['z'].SetAlias(a.GetName(), a.GetTitle()) cuts0 = cuts[:] cuts1 = cuts[:] if use_independent_fake_data: cuts0.append('!(%s)' % fake_data_cut) cuts1.append(fake_data_cut) ## Get the nominal dataset global data data = {} for xvar in [weight, mmgMass, mmMass, phoERes, mmgMassPhoGenE]: print xvar.GetName(), ':', xvar.GetTitle() data['fsr0'] = dataset.get(tree=tree['z'], weight=weight, cuts = cuts0 + ['isFSR'], variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE]) data['fsr1'] = dataset.get(tree=tree['z'], weight=weight, cuts=cuts1 + ['isFSR'], variables=[mmgMass, mmMass, phoERes, mmgMassPhoGenE]) data['zj0'] = dataset.get(tree=tree['z'], weight=weight, cuts=cuts0 + ['!isFSR'], variables=[mmgMass, mmMass]) data['zj1'] = dataset.get(tree=tree['z'], weight=weight, cuts=cuts1 + ['!isFSR'], variables=[mmgMass, mmMass]) ## Set units and nice titles replace_variable_titles(latex_map, w) ## Do we want to reduce the data? if reduce_data: reduced_entries = int( (1 - fit_data_fraction) * data['fsr0'].numEntries() ) data['fsr0'] = data['fsr0'].reduce( roo.EventRange(0, int(reduced_entries)) ) data['zj0'].SetName('zj0_mc') w.Import(data['zj0']) ##-- Calculate MC Truth Purity --------------------------------------------- if use_independent_fake_data: num_fsr_events = data['fsr1'].sumEntries() num_zj_events = data['zj1'].sumEntries() else: num_fsr_events = data['fsr0'].sumEntries() num_zj_events = data['zj0'].sumEntries() global fsr_purity fsr_purity = 100 * num_fsr_events / (num_fsr_events + num_zj_events) ##-- Get Smeared Data ------------------------------------------------------ old_precision = set_default_integrator_precision(2e-9, 2e-9) global calibrator0, calibrator1, fit_calibrator calibrator0 = MonteCarloCalibrator(data['fsr0'], printlevel=1, rho=1.5) if use_independent_fake_data: calibrator1 = MonteCarloCalibrator(data['fsr1'], printlevel=1, rho=1.5) fit_calibrator = calibrator1 else: fit_calibrator = calibrator0 set_default_integrator_precision(*old_precision) ##-- Check the time ------------------------------------------------------- check_timer( '1. init and get_data (%d entries)' % ( data['fsr0'].numEntries() + data['fsr1'].numEntries() + data['zj0'].numEntries() + data['zj1'].numEntries() ) )
# mmMassPdf = w.factory('FCONV::mmMassPdf(mmMass, zmmGenShape, mmMassRes)') mmMassPdf = w.factory('''Voigtian::mmMassPdf(mmMass, FormulaVar::mmMean("MZ+mmScale", {MZ,mmScale}), GZ, mmRes)''') ## Get data chains = esChains.getChains('v11') weight = w.factory('dummyWeight[1,0,55]') weight.SetTitle('1') mmgMass = w.var('mmgMass') m1gOplusM2g = w.var('m1gOplusM2g') m1gOplusM2g.SetTitle('sqrt(mmgMass^2-mmMass^2)') isrData = dataset.get(tree=chains['z'], variable=mmMass, weight=weight, cuts=['!isFSR', 'mmgMass < 200', 'mmMass < 200', 'phoPt > 15', 'Entry$ < 500000']) mmgMassIsrData = dataset.get(variable=mmgMass) m1gOplusM2gIsrData = dataset.get(variable=m1gOplusM2g) isrData.merge(mmgMassIsrData, m1gOplusM2gIsrData) ## Fit the model to the data mmMassPdf.fitTo(isrData, roofit.Range(60,120)) ## Plot the data and the fit mmPlot = mmMass.frame(roofit.Range(60,120)) isrData.plotOn(mmPlot) mmMassPdf.plotOn(mmPlot) canvases.next('mmMass') mmPlot.Draw()