def main(): 'test the get function' import JPsi.MuMu.common.energyScaleChains as chains trees = chains.getChains('v11') global canvases canvases = [] #gROOT.Set w = RooWorkspace('w', 'w') #s = w.factory('s[-5,5]') kRatio = w.factory('kRatio[-20,20]') mmgMass = w.factory('mmgMass[40,140]') mmMass = w.factory('mmMass[10,140]') # s.SetTitle('1/kRatio - 1') get(tree=trees['z'], variables=[kRatio, mmgMass, mmMass]) canvases.append( TCanvas('kRatio', 'kRatio') ) plot(kRatio) canvases.append( TCanvas('mmgMass', 'mmgMass') ) plot(mmgMass) canvases.append( TCanvas('mmMass', 'mmMass') ) plot(mmMass)
def init_cfg_file(): ''' Initialize workspace and common variables and functions. ''' #define_globals() #from common import * global cuts cuts = Globals.cuts print '===============CUTS======================', cuts global model_tree_version, data_tree_version data_tree_version = model_tree_version = Globals.model_tree_version print '====================Model Tree Version===========================', model_tree_version global name, output, latex_title name = Globals.name latex_title = Globals.latex_title outputfile = 'phosphor5_model_and_fit_' + name + '.root' define_workspace() print '===================Name===========================', name global inputfile, outputfile inputfile = 'phosphor5_model_and_fit_' + name + '.root' outputfile = 'phosphor5_model_and_fit_' + name + '.root' define_data_observables() define_model_parameters() define_mass_derivative_function_and_mean() set_ranges_for_data_observables() set_signal_model_normalization_integral_cache_binnings() get_data(getChains(model_tree_version)) build_model()
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 main(): ''' Main entry point for execution. ''' global reduced_tree tree = getChains(tree_version)['z'] reduced_tree = tree.CopyTree('(' + ')&('.join(cuts) + ')') for a in tree.GetListOfAliases(): reduced_tree.SetAlias(a.GetName(), a.GetTitle()) p = ROOT.RooStats.SignificanceToPValue(1) quantilex = array.array('d', [p, 0.5, 1. - p]) quantiley = array.array('d', [1., 2., 3.]) for lo, hi in zip(bin_edges[:-1], bin_edges[1:]): selection = '%d <= phoPt & phoPt < %d' % (lo, hi) tree.Draw('phoPt', 'pileup.weight * (%s)' % selection, 'goff') htemp = ROOT.gROOT.FindObject('htemp') htemp.GetQuantiles(3, quantiley, quantilex) bin_low .append(quantiley[1] - quantiley[0]) bin_center.append(quantiley[1]) bin_high .append(quantiley[2] - quantiley[1]) print 'center:', bin_center print 'low:', bin_low print 'high:', bin_high
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 main(): 'test the get function' import JPsi.MuMu.common.energyScaleChains as chains trees = chains.getChains('v11') global canvases canvases = [] #gROOT.Set w = RooWorkspace('w', 'w') #s = w.factory('s[-5,5]') kRatio = w.factory('kRatio[-20,20]') mmgMass = w.factory('mmgMass[40,140]') mmMass = w.factory('mmMass[10,140]') # s.SetTitle('1/kRatio - 1') get(tree=trees['z'], variables=[kRatio, mmgMass, mmMass]) canvases.append(TCanvas('kRatio', 'kRatio')) plot(kRatio) canvases.append(TCanvas('mmgMass', 'mmgMass')) plot(mmgMass) canvases.append(TCanvas('mmMass', 'mmMass')) plot(mmMass)
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_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 init(): ''' Initialize workspace and common variables and functions. ''' define_globals() define_workspace() define_data_observables() define_model_parameters() define_mass_derivative_function_and_mean() set_ranges_for_data_observables() set_signal_model_normalization_integral_cache_binnings() get_data(getChains(model_tree_version)) build_model()
def init_from_file(filename): ''' Initialize workspace and common variables and functions from a file of the given filename. ''' define_globals() read_workspace_from_file(filename) read_data_observables_from_workspace(w) read_model_parameters_from_workspace(w) read_mass_derivative_function_and_mean_from_workspace(w) set_ranges_for_data_observables() set_signal_model_normalization_integral_cache_binnings() get_data(getChains(model_tree_version)) read_model_from_workspace(w)
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 get_samples(self): '''Get the MC and data samples and import them in the workspace.''' ## Yong's trees with the default CMSSW photon cluster corrections chains = esChains.getChains('v13') ## Map of variable names and corresponding TTree expressions to ## calculate it. expression_map = { 'mmg': 'mmg', 'mm': 'mm', 'gpt': 'gamenergy/cosh(gameta)', 'geta': 'gameta', 'r9': 'gamr9', 'sihih': '100*gamsigmaIetaIeta', 'weight': 'evtweight', 'sphi': 'gamscphiWidth', 'seta': 'gamscetaWidth', } # Change titles to TTree expressions while saving the original titles. title_map = self.replace_variable_titles(expression_map) variables = [ self.w.var(xname) for xname in expression_map if xname != 'weight' ] weight = self.w.var('weight') data = dataset.get(tree=chains['data'], variables=variables, weight=weight, cuts=self.cuts[:], name='data') mc = dataset.get(tree=chains['z'], variables=variables, weight=weight, cuts=self.cuts[:], name='mc') # Change the titles back to their original values. self.replace_variable_titles(title_map) self.w.Import(data) self.w.Import(mc)
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 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_samples(self): '''Get the MC and data samples and import them in the workspace.''' ## Yong's trees with the default CMSSW photon cluster corrections chains = esChains.getChains('v13') ## Map of variable names and corresponding TTree expressions to ## calculate it. expression_map = { 'mmg': 'mmg', 'mm' : 'mm' , 'gpt' : 'gamenergy/cosh(gameta)', 'geta' : 'gameta', 'r9' : 'gamr9' , 'sihih' : '100*gamsigmaIetaIeta', 'weight' : 'evtweight', 'sphi' : 'gamscphiWidth', 'seta' : 'gamscetaWidth', } # Change titles to TTree expressions while saving the original titles. title_map = self.replace_variable_titles(expression_map) variables = [self.w.var(xname) for xname in expression_map if xname != 'weight'] weight = self.w.var('weight') data = dataset.get(tree=chains['data'], variables=variables, weight=weight, cuts=self.cuts[:], name='data') mc = dataset.get(tree=chains['z'], variables=variables, weight=weight, cuts=self.cuts[:], name='mc') # Change the titles back to their original values. self.replace_variable_titles(title_map) self.w.Import(data) self.w.Import(mc)
def init_cfg_file(): ''' Initialize workspace and common variables and functions. ''' global cuts, model_tree_version, data_tree_version, latex_title, latex_labels, outputfile, name cuts = Globals.cuts data_tree_version = model_tree_version = Globals.model_tree_version name = latex_title = latex_labels = Globals.latex_title outputfile = Globals.outputfile if Globals.debug: print '======Model Tree Version======', model_tree_version print '======Cuts Inside phosphorcalculator======', cuts print '======Latex Title Inside phosphorcalculator======', latex_title print '======Output File Inside phosphorcalculator======', outputfile print '===== name =====', name define_workspace() define_data_observables() define_model_parameters() define_mass_derivative_function_and_mean() set_ranges_for_data_observables() set_signal_model_normalization_integral_cache_binnings() get_data(getChains(model_tree_version)) build_model()
gSystem.Load("libJPsiMuMu") # gROOT.LoadMacro('tools.C+') gStyle.SetPadTopMargin(0.1) setattr(RooWorkspace, "Import", getattr(RooWorkspace, "import")) ## Here starts the meat. nentries = -1 ## Pairs of photon scale and extra smearing. sTest = [-2, 0.5] rTest = [1, 0.5] phoPtRange = (15, 20) chains = getChains("v11") mcTree = chains["z"] dataTree = chains["data"] w = RooWorkspace("w") massShift = 90 + 1.03506 ## Define variables mmgMass = w.factory("mmgMass[40, 180]") mmgMassShifted = w.factory("mmgMassShifted[-50, 90]") mmgGenMass = w.factory("mmgGenMass[0, 300]") mmgMassPhoGenE = w.factory("mmgMassPhoGenE[0, 300]") mmgMassShiftedPhoGenE = w.factory("mmgMassShiftedPhoGenE[-90, 210]") mmgMassPhoSmear = w.factory("mmgMassPhoSmear[-30,30]") mmgMassPhoSmear.SetTitle("mmgMass - mmgMassPhoGenE")
MZ[91.2], GZ[2.5])''') ## Dimuon mass resolution mmMassRes = w.factory('''Gaussian::mmMassRes(mmMass, mmScale[0,-10,10], mmRes[1.5,0.1,10])''') ## Model for the reconstructed dimuon invariant mass mmMass = w.var('mmMass') mmMass.setBins(1000, 'fft') # 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)
import os from ROOT import * from array import array import JPsi.MuMu.common.energyScaleChains as esChains ## get trees tree = {} tree = esChains.getChains('v4') esChainsV2 = esChains.getChains('v2') tree['w'] = esChainsV2['w'] tree['tt'] = esChainsV2['tt'] tree['qcd'] = esChainsV2['qcd'] tree['hgg'] = TTree('gg', 'gg tree excerpt') #tree['hgg'].ReadFile('phoPt/F:phoEta:phoHaxPixelMatch/I') cweight = { "data": 1., 'z' : 0.17175592557735 * 1795714. / 2008540., ## read events Spring11 / Summer11 'tt' : 0.019860956416475, 'w' : 0.54974976060237, 'qcd': 0.27884236321449, } puWeight = { 'data': '1.', 'z' : 'pileup.weightOOT', 'tt' : 'pileup.weightOOT', 'w' : 'pileup.weightOOT',
from JPsi.MuMu.common.cmsstyle import cmsstyle from JPsi.MuMu.common.energyScaleChains import getChains from JPsi.MuMu.common.latex import Latex from JPsi.MuMu.escale.montecarlocalibrator import MonteCarloCalibrator name = 'tsv_mc_EE_lowR9_pt10to12_v13' plots = [] calibrators0, calibrators1 = [], [] for label in ['evt%dof4' % i for i in range(1,2)]: ph.name = name + '_' + label ph.define_globals() ph.define_workspace() ph.define_data_observables() ph.set_ranges_for_data_observables() ph.get_data(getChains(ph.model_tree_version)) ph.phoERes.setRange('plot', -15, 35) plot = ph.phoERes.frame(roo.Range('plot')) plot.SetTitle('Fit ' + label) ph.data['fsr1'].plotOn(plot) ph.calibrator1.phoEResPdf.plotOn(plot) ph.calibrator1.phoEResPdf.paramOn(plot) canvases.next('fit_' + label).SetGrid() plot.Draw() plots.append(plot) plot = ph.phoERes.frame(roo.Range('plot')) plot.SetTitle('Train ' + label) ph.data['fsr0'].plotOn(plot)
import os import JPsi.MuMu.common.dataset as dataset import JPsi.MuMu.common.energyScaleChains as esChains from JPsi.MuMu.common.basicRoot import * from JPsi.MuMu.common.roofit import * from JPsi.MuMu.common.plotData import PlotData from JPsi.MuMu.scaleFitterGauss import ScaleFitterGauss ## Get the data _chains = esChains.getChains('v8') ## Cuts common to all plots _commonCuts = [ 'abs(mmgMass-91.2) < 4', '10 < phoPt', 'phoPt < 15', ] defaultFit = ScaleFitterGauss( name = 'dummy', title = 'Barrel, R9 > 0.94, Powheg S4', source = _chains['z'], expression = '100 * (phoE/phoGenE - 1)', cuts = _commonCuts + ['phoIsEB', 'phoR9 > 0.94'], labels = [ 'Barrel', 'R_{9}^{#gamma} > 0.94', 'Powheg S4' ], ) ## ---------------------------------------------------------------------------- ## Customize below _fits = [ ## Barrel, MC
import os import JPsi.MuMu.common.dataset as dataset import JPsi.MuMu.common.energyScaleChains as esChains from JPsi.MuMu.common.basicRoot import * from JPsi.MuMu.common.roofit import * from JPsi.MuMu.common.plotData import PlotData ## Get the data _chains = esChains.getChains('v7') ## Cuts common to all plots _commonCuts = [ 'abs(1/kRatio - 1) < 0.5', 'abs(mmgMass-91.2) < 4', ] ## Add common data class SFitPlotData(PlotData): def __init__(self, name, title, source, expression, cuts, labels): PlotData.__init__(self, name, title, source, expression, cuts, labels) self.xTitle = 's = E_{RECO}/E_{KIN} - 1' self.nBins = 40 self.xRange = (-30, 50) ## ---------------------------------------------------------------------------- ## Customize below _plots = [ ## Barrel, Data SFitPlotData(
raise RuntimeError, "Unknown label `%s'" % label 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'],
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')
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() ) )
gSystem.Load('libJPsiMuMu') # gROOT.LoadMacro('tools.C+') gStyle.SetPadTopMargin(0.1) setattr(RooWorkspace, "Import", getattr(RooWorkspace, "import")) ## Here starts the meat. nentries = -1 ## Pairs of photon scale and extra smearing. sTest = [-2, 0.5] rTest = [1, 0.5] phoPtRange = (15,20) chains = getChains('v11') mcTree = chains['z'] dataTree = chains['data'] w = RooWorkspace('w') massShift = 90 + 1.03506 ## Define variables mmgMass = w.factory('mmgMass[40, 180]') mmgMassShifted = w.factory('mmgMassShifted[-50, 90]') mmgGenMass = w.factory('mmgGenMass[0, 300]') mmgMassPhoGenE = w.factory('mmgMassPhoGenE[0, 300]') mmgMassShiftedPhoGenE = w.factory('mmgMassShiftedPhoGenE[-90, 210]') mmgMassPhoSmear = w.factory('mmgMassPhoSmear[-30,30]') mmgMassPhoSmear.SetTitle('mmgMass - mmgMassPhoGenE')
return self def next(self): name = self.categories.next() data = self.data[name] daughter = copy.deepcopy(self.mother) daughter.name += '_%s' % name daughter.title += ', %s' % data['title'] daughter.labels += data['labels'] daughter.cuts += data['cuts'] return daughter ## end of SubdetFitters if __name__ == '__main__': _chains = esChains.getChains('v10') test_fitter = ScaleFitter( name = 's', title = 's-Fit', source = '_chains["z"]', expression = '100 * (1/kRatio - 1)', cuts = ['mmMass < 80'], # 'phoR9 < 0.94', '30 < phoPt', 'phoPt < 9999'], labels = [#'R_{9}^{#gamma} < 0.94', #'E_{T}^{#gamma} #in [X,Y] GeV', 'Powheg S4', 'Test Model'], xRange = (-20, 40), nBins = 120, fitRange = (-100, 100), pdf = 'lognormal', # graphicsExtensions = ['png', 'eps'],
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')
from JPsi.MuMu.scaleFitter import ScaleFitter from JPsi.MuMu.scaleFitter import PhoEtBin from JPsi.MuMu.scaleFitter import Model from JPsi.MuMu.scaleFitter import DimuonMassMax from JPsi.MuMu.scaleFitter import subdet_r9_categories from JPsi.MuMu.scaleFitModels import ws1 gROOT.LoadMacro("tools.C+") gROOT.LoadMacro("CMSStyle.C") ROOT.CMSstyle() ## Get the data ## 715/pb for Vg Summer conferences # _chains = esChains.getChains('v7') ## 2/fb of LP11 dataset _chains = esChains.getChains("v11") ## Default fit of s = Ereco / Ekin - 1 srecofit = ScaleFitter( name="sreco_mc", title="sreco-Fit, Powheg S4", labels=["Powheg S4"], cuts=[], source=_chains["z"], xName="s", xTitle="s_{reco} = E^{#gamma}_{reco}/E^{kin}_{reco} - 1", xExpression="100 * (1/kRatio - 1)", xRange=(-50, 100), xUnit="%", nBins=150, # fitRange = (-50, 100),
## Define data variables mmgMass = w.factory('mmgMass[40, 140]') mmMass = w.factory('mmMass[10, 140]') phoERes = w.factory('phoERes[-70, 100]') weight = w.factory('weight[1]') for x, u in zip([mmMass, mmMass, phoERes], ['GeV', 'GeV', '%']): x.setUnit(u) ## 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 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()) )
from JPsi.MuMu.scaleFitter import Model from JPsi.MuMu.scaleFitter import DimuonMassMax from JPsi.MuMu.scaleFitter import subdet_r9_categories as subdet_r9_categories_generator from JPsi.MuMu.scaleFitModels import ws1 gROOT.LoadMacro("tools.C+") gROOT.LoadMacro("CMSStyle.C") ROOT.CMSstyle() subdet_r9_categories = list(subdet_r9_categories_generator) ## Get the data ## 715/pb for Vg Summer conferences # _chains = esChains.getChains('v7') ## 2/fb of LP11 dataset _chains = esChains.getChains("v13") ## Default fit of s = Ereco / Ekin - 1 srecofit = ScaleFitter( name="sreco_mc", title="sreco-Fit, Powheg S4", labels=["Powheg S4"], cuts=[], source=_chains["z"], xName="s", xTitle="s_{reco} = E^{#gamma}_{reco}/E^{kin}_{reco} - 1", xExpression="100 * (1/kRatio - 1)", xRange=(-50, 100), xUnit="%", nBins=150, pdf="cbShape",
## Create the default workspace w = ROOT.RooWorkspace('w') ## Define data variables mmgMass = w.factory('mmgMass[40, 140]') mmMass = w.factory('mmMass[10, 140]') 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
Returns a RooDataSet extracted from the tree given the expressions in variable and categories titles. ''' import os import sys import ROOT import JPsi.MuMu.common.energyScaleChains as esChains from JPsi.MuMu.common.basicRoot import * from JPsi.MuMu.common.roofit import * gROOT.LoadMacro( 'datasetUtilities.cc+' ) ## Configuration tree = esChains.getChains('v4')['data'] variable = RooRealVar( 's', '100*(1/kRatio-1)', 0, -50, 50, "%" ) weight = RooRealVar( 'w', '1', 0, 999 ) ## Default/example categories _r9 = RooCategory( 'r9', 'isHighR9(phoIsEB, phoR9)' ) _r9.defineType( 'High', 1 ) _r9.defineType( 'Low', 0 ) _subdet = RooCategory( 'subdet', 'phoIsEB' ) _subdet.defineType( 'Barrel' , 1 ) _subdet.defineType( 'Endcaps', 0 ) # categories = [ _r9, _subdet ] categories = []
from JPsi.MuMu.scaleFitter import ScaleFitter from JPsi.MuMu.scaleFitter import PhoEtBin from JPsi.MuMu.scaleFitter import Model from JPsi.MuMu.scaleFitter import DimuonMassMax from JPsi.MuMu.scaleFitter import subdet_r9_categories from JPsi.MuMu.scaleFitModels import ws1 gROOT.LoadMacro('tools.C+'); gROOT.LoadMacro("CMSStyle.C") ROOT.CMSstyle() ## Get the data ## 715/pb for Vg Summer conferences # _chains = esChains.getChains('v7') ## 2/fb of LP11 dataset _chains = esChains.getChains('v11') ## Default fit of strue = Ereco / Egen - 1 struefit = ScaleFitter( name = 'strue_mc_NominalFitRange68', ## name = 'strue_mc_FitRangePositive', title = 'strue-Fit, Powheg S4', labels = ['Powheg S4 Summer11 MC'], source = _chains['z'], xName = 's', xTitle = 's_{true} = E^{#gamma}_{reco}/E^{#gamma}_{gen} - 1', xExpression = '100 * (phoE/phoGenE - 1)', cuts = ['isFSR', 'phoGenE > 0'], xRange = (-50, 100), xUnit = '%',
def next(self): name = self.categories.next() data = self.data[name] daughter = copy.deepcopy(self.mother) daughter.name += '_%s' % name daughter.title += ', %s' % data['title'] daughter.labels += data['labels'] daughter.cuts += data['cuts'] return daughter ## end of SubdetFitters if __name__ == '__main__': _chains = esChains.getChains('v10') test_fitter = ScaleFitter( name='s', title='s-Fit', source='_chains["z"]', expression='100 * (1/kRatio - 1)', cuts=['mmMass < 80'], # 'phoR9 < 0.94', '30 < phoPt', 'phoPt < 9999'], labels=[ #'R_{9}^{#gamma} < 0.94', #'E_{T}^{#gamma} #in [X,Y] GeV', 'Powheg S4', 'Test Model' ], xRange=(-20, 40), nBins=120, fitRange=(-100, 100),
gStyle.SetStatW(0.2) gStyle.SetStatH(0.2) canvases = [] report = [] oplus = lambda x, y: math.sqrt(x * x + y * y) def customizeStats(stats): stats.SetX1NDC(0.65) stats.SetY1NDC(0.7) ## Read data set chains = esChains.getChains() tdata = chains['data'] tmc = chains['z'] ################# # Barrel ################# name = '42x data' subdet = "Barrel" c1 = TCanvas(name + "_" + subdet, name + " " + subdet) tdata.Draw("1/k>>ik_data_eb(40,0,2)", "abs(m3-91.2)<4 & isEB & (%s)" % ebselection) histo = gDirectory.Get("ik_data_eb") histo.Fit("gaus") fit = histo.GetFunction("gaus")
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] )""") ## Categories catTitleCut = { 'highR9_eb' : ('high R9 barrel' , 'subdet == subdet::Barrel && r9 == r9::High'), 'highR9_ee' : ('high R9 endcaps', 'subdet == subdet::Endcaps && r9 == r9::High'), 'lowR9_eb' : ('low R9 barrel' , 'subdet == subdet::Barrel && r9 == r9::Low' ), 'lowR9_ee' : ('low R9 endcaps' , 'subdet == subdet::Endcaps && r9 == r9::Low' ), } ## Get data data = dataset.get( tree = esChains.getChains('v4')['data'], variable = x, weight = w, categories = myCategories ) data.SetName('realData') data.SetTitle('scale real data 750/pb') ws1.Import(data) ## Get data in categories realData = {} for cat, (title, cut) in catTitleCut.items(): realData[cat] = data.reduce( Cut(cut), Name('data_' + cat), Title(title) ) ## Get MC w.SetTitle('pileup.weightOOT') data = dataset.get( tree = esChains.getChains('v4')['z'],