def createEtaDistributions(selection, plotName): from centralConfig import runRanges first = False histEEAll = None histMMAll = None backgrounds = ["TT_Powheg"] first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPathNonIso plot = getPlot(plotName) plot.addRegion(selection) plot.addRunRange(runRange) histEE, histMM = getHistograms(path,plot,runRange,backgrounds) if first: histEEAll = histEE.Clone() histMMAll = histMM.Clone() else: histEEAll.Add(histEE, 1.0) histMMAll.Add(histMM, 1.0) if first: first = False plotDistribution(histEEAll, histMMAll, plot)
def produceSimulationScaleFactorTable(): shelvesWZ = readScaleFactorPickle("scaleFactor", runRange, "WZTo3LNu") shelvesZZ = readScaleFactorPickle("scaleFactor", runRange, "ZZTo4L") shelvesTTZ = readScaleFactorPickle("scaleFactor", runRange, "ttZToLL") tableTemplate = r""" \begin{table}[hbp] \caption{3-lepton, 4-lepton and $t\bar{t}Z$ control regions. Signal MC is $WZ\rightarrow $3l$\nu$ in the 3-lepton region, $ZZ\rightarrow$4l in the 4-lepton region and $t\bar{t}Z\rightarrow$2l2$\nu$ in the $t\bar{t}Z$ region} \centering \renewcommand{\arraystretch}{1.2} \begin{tabular}{l||l|ccc} & & WZ CR & ZZ CR & ttZ CR \\ \hline\hline \multirow{5}{*}{%s} & signal MC & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ \\ \cline{2-5} & background MC & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ \\ \cline{2-5}\cline{2-5} & \textbf{data} & \textbf{%d} & \textbf{%d} & \textbf{%d} \\ \cline{2-5} & data-bkg. & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ \\ \cline{2-5}\cline{2-5} &(data-bkg.)/sig.& $%.2f \pm %.2f$ & $%.2f \pm %.2f$ & $%.2f \pm %.2f$ \\ \hline\hline \end{tabular} \label{tab:ScaleFactors} \end{table} """ tab = tableTemplate%( getRunRange(runRange).era, shelvesWZ["WZTo3LNu"],shelvesWZ["WZTo3LNuErr"],shelvesZZ["ZZTo4L"],shelvesZZ["ZZTo4LErr"],shelvesTTZ["ttZToLL"],shelvesTTZ["ttZToLL"], shelvesWZ["background"],shelvesWZ["backgroundErr"],shelvesZZ["background"],shelvesZZ["backgroundErr"],shelvesTTZ["background"],shelvesTTZ["backgroundErr"], int(shelvesWZ["Data"]),int(shelvesZZ["Data"]),int(shelvesTTZ["Data"]), shelvesWZ["signalYield"],shelvesWZ["signalYieldErr"],shelvesZZ["signalYield"],shelvesZZ["signalYieldErr"],shelvesTTZ["signalYield"],shelvesTTZ["signalYieldErr"], shelvesWZ["scaleFac"],shelvesWZ["scaleFacStatErr"],shelvesZZ["scaleFac"],shelvesZZ["scaleFacStatErr"],shelvesTTZ["scaleFac"],shelvesTTZ["scaleFacStatErr"] ) saveTable(tab, "ScaleFactors_%s"%(runRange))
def main(): parser = argparse.ArgumentParser(description='rMuE measurements.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument("-s", "--selection", dest = "selection" , action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.default if len(args.plots) == 0: args.plots = plotLists.default if len(args.selection) == 0: args.selection.append("Inclusive") if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPath cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) plot(path,selection,args.plots,runRange,args.mc,args.backgrounds,cmsExtra)
def getCorrelation(selection, background, var1, var2): from centralConfig import runRanges first = False histSFAll = None first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPathNLL plot = getPlot(var1) plot.addRegion(selection) plot.addRunRange(runRange) plot2 = getPlot(var2) plot2.addRegion(selection) plot2.addRunRange(runRange) histSF = getHistogram(path, plot, plot2, runRange, background) if first: histSFAll = histSF.Clone() else: histSFAll.Add(histSF, 1.0) if first: first = False return histSFAll.GetCorrelationFactor()
def createDistributions(selection, background): from centralConfig import runRanges first = False histSFAll = None first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPath plot = getPlot("metPlot2D") plot.addRegion(selection) plot.addRunRange(runRange) plot2 = getPlot("nJetsPlot2D") plot2.addRegion(selection) plot2.addRunRange(runRange) histSF = getHistogram(path, plot, plot2, runRange, background) if first: histSFAll = histSF.Clone() else: histSFAll.Add(histSF, 1.0) if first: first = False plotDistribution(histSFAll, plot, plot2, background)
def main(): selections = [] selections.append("Inclusive") path = locations.dataSetPathTrigger #~ f = ROOT.TFile("weights_Run2015_25ns.root","recreate") f = ROOT.TFile("data_PU_25ns.root", "recreate") f.cd() histo = TH1F("pileup", "pileup", 60, 0, 60) runRange = getRunRange("Run2015_25ns") result = {} weights = [] weightSum = 0 for selectionName in selections: selection = getRegion(selectionName) plot = getPlot("nVtxPlotWeights") plot.addRegion(selection) plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut histEEMC, histMMMC, histEMMC = getHistograms(path, plot, runRange, True, [], "") histEE, histMM, histEM = getHistograms(path, plot, runRange, False, [], "") histEE.Add(histMM) histEEMC.Add(histMMMC) print histEE.GetEntries(), histEEMC.GetEntries() histEE.Scale(1. / histEE.GetEntries()) histEEMC.Scale(1. / histEEMC.Integral()) for i in range(0, histEE.GetNbinsX() + 1): if histEEMC.GetBinContent(i) > 0: histo.SetBinContent(i, float(histEE.GetBinContent(i))) weights.append( float(histEE.GetBinContent(i)) / histEEMC.GetBinContent(i)) weightSum += (float(histEE.GetBinContent(i)) / histEEMC.GetBinContent(i)) else: histo.SetBinContent(i, float(histEE.GetBinContent(i))) weights.append(1) weightSum += 1 print weights print weightSum f.Write() f.Close()
def main(): parser = argparse.ArgumentParser(description='MC yields in signal region') parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") parser.add_argument("-a", "--useAllMC", action="store_true", dest="useAllMC", default=False, help="Use all MC samples instead of only (rare) on Z") parser.add_argument("-d", "--drellYan", action="store_true", dest="useDY", default=False, help="Use only on Z (not rare)") parser.add_argument("-r", "--runRange", dest="runRanges", action="append", default=[], help="name of run range.") args = parser.parse_args() if args.write: import subprocess bashCommand1 = "cp shelves/RareOnZBG_Run2016_36fb.pkl ../frameWorkBase/shelves" bashCommand2 = "cp shelves/RareOnZBG_Run2017_42fb.pkl ../frameWorkBase/shelves" bashCommand3 = "cp shelves/RareOnZBG_Run2018_60fb.pkl ../frameWorkBase/shelves" process = subprocess.Popen(bashCommand1.split()) process = subprocess.Popen(bashCommand2.split()) process = subprocess.Popen(bashCommand3.split()) else: for rr in args.runRanges: runRange = getRunRange(rr) getYields(runRange)
def createDRDistributions(selection, mllCut=True): from centralConfig import runRanges first = False histEEAll = None histMMAll = None backgrounds = ["TT_Powheg"] first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPath plot = getPlot("deltaRPlot") plot.addRegion(selection) plot.addRunRange(runRange) plot.cuts = plot.cuts.replace("deltaR > 0.1 &&", "") if not mllCut: plot.cuts = plot.cuts.replace("mll > 20 &&", "") print plot.cuts histEE, histMM = getHistograms(path,plot,runRange,backgrounds) if first: histEEAll = histEE.Clone() histMMAll = histMM.Clone() else: histEEAll.Add(histEE, 1.0) histMMAll.Add(histMM, 1.0) if first: first = False plotDistribution(histEEAll, histMMAll, plot, mllCut)
def main(): selections = [] selections.append(regionsToUse.rOutIn.central.name) selections.append(regionsToUse.rOutIn.forward.name) path = locations.dataSetPath runRange = getRunRange("Full2012") result = {} for selectionName in selections: selection = getRegion(selectionName) plot = getPlot("mllPlot") plot.addRegion(selection) plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut cuts = plot.cuts plot.cuts = plot.cuts + "*(nVertices < 13)" histEE, histMM, histEM = getHistograms(path, plot, runRange, False, [], "") print histEE.GetEntries(), histMM.GetEntries(), histEM.GetEntries() plot.cuts = cuts plot.cuts = plot.cuts + "*(nVertices >= 13 && nVertices < 17)" histEE, histMM, histEM = getHistograms(path, plot, runRange, False, [], "") print histEE.GetEntries(), histMM.GetEntries(), histEM.GetEntries() plot.cuts = cuts plot.cuts = plot.cuts + "*(nVertices >= 17)" histEE, histMM, histEM = getHistograms(path, plot, runRange, False, [], "") print histEE.GetEntries(), histMM.GetEntries(), histEM.GetEntries()
def produceTriggerEffTables(): era = getRunRange(runRange).era shelvesTrigger = {"inclusive":readTriggerPickle("triggerEff",triggerRegionNamesLists[era]["inclusive"].name , runRange, baselineTrigger.name)} shelvesTriggerMC = {"inclusive":readTriggerPickle("triggerEff",triggerRegionNamesLists[era]["inclusive"].name, runRange, baselineTrigger.name,MC=True)} tableTemplate =r""" \begin{table}[hbp] \caption{Trigger efficiency values for data and MC with OS, $p_T>25(20)\,\GeV$ and $p_T^\text{miss}>130\,\GeV$.} \centering \renewcommand{\arraystretch}{1.2} \begin{tabular}{l|c|c|c|c|c|c} & \multicolumn{6}{c}{%s data set} \\\hline &\multicolumn{3}{c|}{Data} &\multicolumn{3}{c}{MC} \\ & nominator & denominator & $\epsilon_{trigger} \pm \sigma_{stat}$ & nominator & denominator & $\epsilon_{trigger} \pm \sigma_{stat}$ \\ \hline %s \hline %s \hline \end{tabular} \label{tab:TriggerEffValues} \end{table} """ lineTemplate = r"%s & %d & %d & %.3f$\pm$%.3f & %d & %d & %.3f$\pm$%.3f \\"+"\n" lineTemplateRT = r"$R_{T}$ & \multicolumn{3}{c|}{%.3f$\pm$%.3f} & \multicolumn{3}{c}{%.3f$\pm$%.3f} \\"+"\n" table ="" #~ tableData ="" table += lineTemplate%("ee", shelvesTrigger["inclusive"][runRange]["EE"]["Nominator"], shelvesTrigger["inclusive"][runRange]["EE"]["Denominator"], shelvesTrigger["inclusive"][runRange]["EE"]["Efficiency"], max(shelvesTrigger["inclusive"][runRange]["EE"]["UncertaintyUp"],shelvesTrigger["inclusive"][runRange]["EE"]["UncertaintyDown"]), shelvesTriggerMC["inclusive"][runRange]["EE"]["Nominator"], shelvesTriggerMC["inclusive"][runRange]["EE"]["Denominator"], shelvesTriggerMC["inclusive"][runRange]["EE"]["Efficiency"], max(shelvesTriggerMC["inclusive"][runRange]["EE"]["UncertaintyUp"],shelvesTriggerMC["inclusive"][runRange]["EE"]["UncertaintyDown"]) ) table += lineTemplate%("$\mu\mu$", shelvesTrigger["inclusive"][runRange]["MuMu"]["Nominator"], shelvesTrigger["inclusive"][runRange]["MuMu"]["Denominator"], shelvesTrigger["inclusive"][runRange]["MuMu"]["Efficiency"], max(shelvesTrigger["inclusive"][runRange]["MuMu"]["UncertaintyUp"],shelvesTrigger["inclusive"][runRange]["MuMu"]["UncertaintyDown"]), shelvesTriggerMC["inclusive"][runRange]["MuMu"]["Nominator"], shelvesTriggerMC["inclusive"][runRange]["MuMu"]["Denominator"], shelvesTriggerMC["inclusive"][runRange]["MuMu"]["Efficiency"], max(shelvesTriggerMC["inclusive"][runRange]["MuMu"]["UncertaintyUp"],shelvesTriggerMC["inclusive"][runRange]["MuMu"]["UncertaintyDown"]) ) table += lineTemplate%("e$\mu$", shelvesTrigger["inclusive"][runRange]["EMu"]["Nominator"], shelvesTrigger["inclusive"][runRange]["EMu"]["Denominator"], shelvesTrigger["inclusive"][runRange]["EMu"]["Efficiency"], max(shelvesTrigger["inclusive"][runRange]["EMu"]["UncertaintyUp"],shelvesTrigger["inclusive"][runRange]["EMu"]["UncertaintyDown"]), shelvesTriggerMC["inclusive"][runRange]["EMu"]["Nominator"], shelvesTriggerMC["inclusive"][runRange]["EMu"]["Denominator"], shelvesTriggerMC["inclusive"][runRange]["EMu"]["Efficiency"], max(shelvesTriggerMC["inclusive"][runRange]["EMu"]["UncertaintyUp"],shelvesTriggerMC["inclusive"][runRange]["EMu"]["UncertaintyDown"]) ) RTLine = lineTemplateRT%( shelvesTrigger["inclusive"][runRange]["RT"], (shelvesTrigger["inclusive"][runRange]["RTErrStat"]**2+shelvesTrigger["inclusive"][runRange]["RTErrSyst"]**2)**0.5, shelvesTriggerMC["inclusive"][runRange]["RT"], (shelvesTriggerMC["inclusive"][runRange]["RTErrStat"]**2+shelvesTriggerMC["inclusive"][runRange]["RTErrSyst"]**2)**0.5 ) saveTable(tableTemplate%(era,table,RTLine), "TriggerEffsExclusive_Inclusive_%s"%(runRange))
def main(): parser = argparse.ArgumentParser(description='rSFOF from control region.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument("-s", "--selection", dest = "selection" , action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-c", "--centralValues", action="store_true", dest="central", default=False, help="calculate effinciecy central values") parser.add_argument("-C", "--ptCut",action="store", dest="ptCut", default="pt2515", help="modify the pt cuts") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-d", "--dependencies", action="store_true", dest="dependencies", default= False, help="make dependency plots") parser.add_argument("-l", "--dilepton", action="store_true", dest="dilepton", default=False, help="use dilepton triggers as baseline.") parser.add_argument("-e", "--effectiveArea", action="store_true", dest="effectiveArea", default=False, help="use effective area PU corrections.") parser.add_argument("-D", "--deltaBeta", action="store_true", dest="deltaBeta", default=False, help="use delta beta PU corrections.") parser.add_argument("-R", "--constantConeSize", action="store_true", dest="constantConeSize", default=False, help="use constant cone of R=0.3 for iso.") parser.add_argument("-f", "--fit", action="store_true", dest="fit", default= False, help="do dependecy fit") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-i", "--illustrate", action="store_true", dest="illustrate", default=False, help="plot dependency illustrations.") parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") parser.add_argument("-n", "--nonNormalized", action="store_true", dest="nonNormalized", default=False, help="do not normalize to cross section") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = ["TTJets_Madgraph","TTJets_aMCatNLO","TT_aMCatNLO","TT_Powheg"] if len(args.plots) == 0: args.plots = plotLists.default if len(args.selection) == 0: args.selection.append(regionsToUse.signal.central.name) args.selection.append(regionsToUse.signal.forward.name) args.selection.append(regionsToUse.signal.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPathTrigger if args.dilepton: source = "DiLeptonTrigger" modifier = "DiLeptonTrigger" else: source = "" modifier = "" print args.selection cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) doPlot(source,modifier,path,selection,args.plots,runRange,args.mc,args.backgrounds,cmsExtra)
def produceFactorizationTable(): tableTemplate = """ \\begin{table}[hbtp] \\renewcommand{\\arraystretch}{1.3} \setlength{\\belowcaptionskip}{6pt} \centering \caption{ } \label{tab:factorization} \\begin{tabular}{l| c c| c c } & \multicolumn{2}{c}{Central} & \multicolumn{2}{c}{Forward} \\\\ \n \hline & Data & MC & Data & MC \\\\ \n \hline %s \hline \hline %s \end{tabular} \end{table} """ template = r" %s & %.3f$\pm$%.3f & %.3f$\pm$%.3f & %.3f$\pm$%.3f & %.3f$\pm$%.3f \\" +"\n" templateTrigger = r" %s & %.3f$\pm$%.3f & - & %.3f$\pm$%.3f & - \\" +"\n" tableIngredients ="" tableResult ="" tableIngredients += template%("\\rmue",corrections[getRunRange(runRange).era].rMuE.central.val,corrections[getRunRange(runRange).era].rMuE.central.err,corrections[getRunRange(runRange).era].rMuE.central.valMC,corrections[getRunRange(runRange).era].rMuE.central.errMC,corrections[getRunRange(runRange).era].rMuE.forward.val,corrections[getRunRange(runRange).era].rMuE.forward.err,corrections[getRunRange(runRange).era].rMuE.forward.valMC,corrections[getRunRange(runRange).era].rMuE.forward.errMC) #~ tableIngredients += template%("$R_{T}$",rSFOFTrig.central.val,rSFOFTrig.central.err,rSFOFTrig.central.valMC,rSFOFTrig.central.errMC,rSFOFTrig.forward.val,rSFOFTrig.forward.err,rSFOFTrig.forward.valMC,rSFOFTrig.forward.errMC) tableIngredients += templateTrigger%("$R_{T}$",corrections[getRunRange(runRange).era].rSFOFTrig.central.val,corrections[getRunRange(runRange).era].rSFOFTrig.central.err,corrections[getRunRange(runRange).era].rSFOFTrig.forward.val,corrections[getRunRange(runRange).era].rSFOFTrig.forward.err) tableResult += template%("\Rsfof",corrections[getRunRange(runRange).era].rSFOFFactOld.central.SF.val,corrections[getRunRange(runRange).era].rSFOFFactOld.central.SF.err,corrections[getRunRange(runRange).era].rSFOFFactOld.central.SF.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.central.SF.errMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.SF.val,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.SF.err,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.SF.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.SF.errMC) tableResult += template%("\Reeof",corrections[getRunRange(runRange).era].rSFOFFactOld.central.EE.val,corrections[getRunRange(runRange).era].rSFOFFactOld.central.EE.err,corrections[getRunRange(runRange).era].rSFOFFactOld.central.EE.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.central.EE.errMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.EE.val,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.EE.err,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.EE.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.EE.errMC) tableResult += template%("\Rmmof",corrections[getRunRange(runRange).era].rSFOFFactOld.central.MM.val,corrections[getRunRange(runRange).era].rSFOFFactOld.central.MM.err,corrections[getRunRange(runRange).era].rSFOFFactOld.central.MM.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.central.MM.errMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.MM.val,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.MM.err,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.MM.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.forward.MM.errMC) table = tableTemplate%(tableIngredients,tableResult) saveTable(table,"factorization_result_seperated_%s"%(runRange)) tableTemplate = """ \\begin{table}[hbtp] \\renewcommand{\\arraystretch}{1.3} \setlength{\\belowcaptionskip}{6pt} \centering \caption{Results of the calculations of $R_{SF/OF}$, $R_{ee/OF}$, and $R_{\mu\mu/OF}$ using the factorization method. The factors \rmue and $R_{T}$ which are used in the calculation are also displayed. Since no trigger simulation was available, the data trigger efficiencies are used for the MC prediction.} \label{tab:factorization} \\begin{tabular}{l| c c } & Data & MC \\\\ \n \hline %s \hline \hline %s \end{tabular} \end{table} """ template = r" %s & %.3f$\pm$%.3f & %.3f$\pm$%.3f \\" +"\n" templateTrigger = r" %s & %.3f$\pm$%.3f & - \\" +"\n" tableIngredients ="" tableResult ="" tableIngredients += template%("$r_{\mu e}$",corrections[getRunRange(runRange).era].rMuE.inclusive.val,corrections[getRunRange(runRange).era].rMuE.inclusive.err,corrections[getRunRange(runRange).era].rMuE.inclusive.valMC,corrections[getRunRange(runRange).era].rMuE.inclusive.errMC) tableIngredients += template%("$\\frac{1}{2}$( \rmue + \rmue$^{-1})$",0.5*(corrections[getRunRange(runRange).era].rMuE.inclusive.val+1./corrections[getRunRange(runRange).era].rMuE.inclusive.val),0.5*(1. - (1./(corrections[getRunRange(runRange).era].rMuE.inclusive.val**2)))*corrections[getRunRange(runRange).era].rMuE.inclusive.err,0.5*(corrections[getRunRange(runRange).era].rMuE.inclusive.valMC+1./corrections[getRunRange(runRange).era].rMuE.inclusive.valMC),0.5*(1. - (1./(corrections[getRunRange(runRange).era].rMuE.inclusive.valMC**2)))*corrections[getRunRange(runRange).era].rMuE.inclusive.errMC) #~ tableIngredients += template%("$R_{T}$",rSFOFTrig.inclusive.val,rSFOFTrig.inclusive.err,rSFOFTrig.inclusive.valMC,rSFOFTrig.inclusive.errMC,rSFOFTrig.forward.val,rSFOFTrig.forward.err,rSFOFTrig.forward.valMC,rSFOFTrig.forward.errMC) tableIngredients += templateTrigger%("$R_{T}$",corrections[getRunRange(runRange).era].rSFOFTrig.inclusive.val,corrections[getRunRange(runRange).era].rSFOFTrig.inclusive.err) tableResult += template%("$R_{SF/OF}$",corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.SF.val,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.SF.err,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.SF.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.SF.errMC,) tableResult += template%("$R_{ee/OF}$",corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.EE.val,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.EE.err,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.EE.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.EE.errMC,) tableResult += template%("$R_{\mu\mu/OF}$",corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.MM.val,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.MM.err,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.MM.valMC,corrections[getRunRange(runRange).era].rSFOFFactOld.inclusive.MM.errMC,) table = tableTemplate%(tableIngredients,tableResult) saveTable(table,"factorization_result_%s"%(runRange))
def produceRMuETable(): template = r" %s & %d & %d & %.3f$\pm$%.3f$\pm$%.3f \\" +"\n" shelvesRMuE = {"inclusive":readPickle("rMuE",regionsToUse.rMuE.inclusive.name , runRange),} shelvesRMuEMC = {"inclusive":readPickle("rMuE",regionsToUse.rMuE.inclusive.name , runRange,MC=True)} tableTemplate = """ \\begin{table}[hbtp] \\renewcommand{\\arraystretch}{1.3} \setlength{\\belowcaptionskip}{6pt} \centering \caption{Result of the calculation of \rmue. Shown are the observed event yields in the Drell-Yan control region in the $e^{+}e^{-}$ and $\mu^{+}\mu^{-}$ channels and the resulting values for \rmue. The same quantities derived from simulation are shown for comparison.} \label{tab:rMuE} \\begin{tabular}{l| ccc } & $N_{\mu\mu}$ & $N_{ee}$ & $ r_{\mu e} \\pm \sigma_{\\text{stat.}} \\pm \sigma_{\\text{syst.}}$ \\\\ \n \hline %s %s \end{tabular} \end{table} """ data = template%("Data",shelvesRMuE["inclusive"]["nMM"],shelvesRMuE["inclusive"]["nEE"],shelvesRMuE["inclusive"]["rMuE"],shelvesRMuE["inclusive"]["rMuEStatErr"],shelvesRMuE["inclusive"]["rMuESystErrOld"]) mc = template%("MC",shelvesRMuEMC["inclusive"]["nMM"],shelvesRMuEMC["inclusive"]["nEE"],shelvesRMuEMC["inclusive"]["rMuE"],shelvesRMuEMC["inclusive"]["rMuEStatErr"],shelvesRMuEMC["inclusive"]["rMuESystErrOld"]) table = tableTemplate%(data,mc) saveTable(table,"rMuE_result_%s"%(runRange)) templateFitParameters = r" %s & %s & %.3f$\pm$%.3f& %.3f$\pm$%.3f& %.3f$\pm$%.3f& %.3f$\pm$%.3f& %.3f$\pm$%.3f & %.3f$\pm$%.3f \\" +"\n" shelvesRMuEFitParameters = {"inclusive":readPickle("rMuE_correctionParameters",regionsToUse.rMuE.inclusive.name , runRange)} shelvesRMuEFitParametersMC = {"inclusive":readPickle("rMuE_correctionParameters",regionsToUse.rMuE.inclusive.name , runRange,MC=True)} tableTemplate = """ \\begin{table}[hbtp] \\renewcommand{\\arraystretch}{1.3} \setlength{\\belowcaptionskip}{6pt} \centering \caption{Result of the fit of \\rmue as a function of the \pt of the trailing lepton in the Drell--Yan control region. The same quantaties derived from simulation are shown for comparison. Only statistical uncertainties are given.} \label{tab:rMuEFitParameters} \\begin{tabular}{l|l| cccccc } & & $r_{\mu/e}^0$ & $a_1$ & $b_1$ & $a_2$ & $c_1$ & $c_2$ \\\\ \n \hline %s %s \end{tabular} \end{table} """ from defs import getRunRange data = templateFitParameters%("\multirow{2}{*}{%s}"%(getRunRange(runRange).era),"Data", shelvesRMuEFitParameters["inclusive"]["norm"],shelvesRMuEFitParameters["inclusive"]["normErr"], shelvesRMuEFitParameters["inclusive"]["ptOffset"],shelvesRMuEFitParameters["inclusive"]["ptOffsetErr"], shelvesRMuEFitParameters["inclusive"]["ptFalling"],shelvesRMuEFitParameters["inclusive"]["ptFallingErr"], shelvesRMuEFitParameters["inclusive"]["etaParabolaBase"],shelvesRMuEFitParameters["inclusive"]["etaParabolaBaseErr"], shelvesRMuEFitParameters["inclusive"]["etaParabolaMinus"],shelvesRMuEFitParameters["inclusive"]["etaParabolaMinusErr"], shelvesRMuEFitParameters["inclusive"]["etaParabolaPlus"],shelvesRMuEFitParameters["inclusive"]["etaParabolaPlusErr"], ) mc = templateFitParameters%("","MC", shelvesRMuEFitParametersMC["inclusive"]["norm"],shelvesRMuEFitParametersMC["inclusive"]["normErr"], shelvesRMuEFitParametersMC["inclusive"]["ptOffset"],shelvesRMuEFitParametersMC["inclusive"]["ptOffsetErr"], shelvesRMuEFitParametersMC["inclusive"]["ptFalling"],shelvesRMuEFitParametersMC["inclusive"]["ptFallingErr"], shelvesRMuEFitParametersMC["inclusive"]["etaParabolaBase"],shelvesRMuEFitParametersMC["inclusive"]["etaParabolaBaseErr"], shelvesRMuEFitParametersMC["inclusive"]["etaParabolaMinus"],shelvesRMuEFitParametersMC["inclusive"]["etaParabolaMinusErr"], shelvesRMuEFitParametersMC["inclusive"]["etaParabolaPlus"],shelvesRMuEFitParametersMC["inclusive"]["etaParabolaPlusErr"], ) table = tableTemplate%(data,mc) saveTable(table,"rMuE_fitParameters_%s"%(runRange))
def main(): parser = argparse.ArgumentParser(description='rMuE measurements.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() plots = plotLists.fake selections = ["Region"] if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.fakeDataSetPath #~ path = "/home/jan/Trees/sw538v0477" cmsExtra = "" if args.private: cmsExtra = "Private Work" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) #~ fakeRate(path,selection,plots,runRange,cmsExtra) #~ fakeRateCentral(path,selection,plots,runRange,cmsExtra) path = locations.dataSetPath for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) #~ promptRate(path,selection,plots,runRange,cmsExtra) #~ promptRateCentral(path,selection,plots,runRange,cmsExtra) selections = ["SignalCentral", "SignalForward"] for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) nonPromptPrediction(path, selection, plots, runRange, cmsExtra)
def main(): parser = argparse.ArgumentParser(description='edge fitter reloaded.') parser.add_argument("-r", "--runRange", dest="runRange", action="store", default=None, help="name of run range.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="selection which to apply.") backgroundZZ = "RareZZOnZ" backgroundVV = "RareZZLowMassOnZ" # taking only the onZ part from this one args = parser.parse_args() runRange = getRunRange(args.runRange) if args.plots == []: args.plots = ["mllPlot", "mllWidePlotC"] if args.selection == []: args.selection = [ "SignalLowNLL24HighMT2ZeroB", "SignalLowNLL24HighMT2OneB", "SignalHighNLL24HighMT2ZeroB", "SignalHighNLL24HighMT2OneB" ] path = locations[runRange.era].dataSetPathNLL #path = locations[runRange.era].dataSetPath eventCounts = totalNumberOfGeneratedEvents(path, "", "") procZZ = Process(getattr(Backgrounds[runRange.era], backgroundZZ), eventCounts) procVV = Process(getattr(Backgrounds[runRange.era], backgroundVV), eventCounts) for selectionName in args.selection: selection = getRegion(selectionName) for plotName in args.plots: plot = getPlot(plotName) plot.addRegion(selection) plot.addRunRange(runRange) plot.cuts = plot.cuts.replace("metFilterSummary > 0 &&", "") plot.cuts = plot.cuts.replace("&& metFilterSummary > 0", "") #plot.cuts = plot.cuts.replace("chargeProduct < 0", "chargeProduct < 0 && mll > 40 && mll < 60") treesEE = readTrees(path, "EE") treesMM = readTrees(path, "MuMu") treesEM = readTrees(path, "EMu") template = plotTemplate() picklePath = "/home/home4/institut_1b/teroerde/Doktorand/SUSYFramework/frameWorkBase/shelves/scaleFactor_{runRange}_ZZTo4L.pkl" with open(picklePath.format(runRange=runRange.label), "r") as fi: scaleFac = pickle.load(fi) sf = scaleFac["scaleFac"] histZZ = procZZ.createCombinedHistogram(runRange.lumi, plot, treesEE, treesMM, shift=1., scalefacTree1=sf, scalefacTree2=sf) #print histZZ.GetEntries() histVV = procVV.createCombinedHistogram(runRange.lumi, plot, treesEE, treesMM, shift=1., scalefacTree1=sf, scalefacTree2=sf) # rMuE subtraction from corrections import corrections corrs = corrections[runRange.era].rMuELeptonPt.inclusive corrMap = {} corrMap["offset"] = corrs.ptOffset corrMap["falling"] = corrs.ptFalling corrMap["etaParabolaBase"] = corrs.etaParabolaBase corrMap["etaParabolaMinus"] = corrs.etaParabolaMinus corrMap["etaParabolaPlus"] = corrs.etaParabolaPlus corrMap["norm"] = corrs.norm rt = corrections[runRange.era].rSFOFTrig.inclusive.val RT = "%.3f" % (rt) rMuEDummy = "({norm:.3f}*(({offset:.3f} + {falling:.3f}/{pt})*({etaParabolaBase} + ({eta}<-1.6)*{etaParabolaMinus:.3f}*pow({eta}+1.6, 2)+({eta}>1.6)*{etaParabolaPlus:.3f}*pow({eta}-1.6,2) )))" rMuE_El = rMuEDummy.format(pt="pt1", eta="eta1", **corrMap) rMuE_Mu = rMuEDummy.format(pt="pt2", eta="eta2", **corrMap) rMuEWeight = "(0.5*(%s + pow(%s, -1)))*%s" % (rMuE_El, rMuE_Mu, RT) plot.cuts = plot.cuts.replace("weight*", "weight*%s*" % (rMuEWeight)) histVV_OF = procVV.createCombinedHistogram(runRange.lumi, plot, treesEM, "None", shift=1., scalefacTree1=sf, scalefacTree2=sf) histVV.Add(histVV_OF, -1) #normalize in Z-peak region (only properly works for mll plots and with correct binning) ZZCount = histZZ.Integral(histZZ.FindBin(86 + 0.1), histZZ.FindBin(96 - 0.1)) VVCount = histVV.Integral(histVV.FindBin(86 + 0.1), histVV.FindBin(96 - 0.1)) #histVV.Scale(ZZCount/VVCount) print ZZCount / VVCount if "Wide" in plotName: print selectionName, ZZCount / VVCount histZZ.SetLineColor(ROOT.kRed) histZZ.SetLineWidth(2) histZZ.SetMarkerSize(0) histZZ.SetFillStyle(0) histVV.SetLineColor(ROOT.kBlack) histVV.SetLineWidth(2) histVV.SetMarkerSize(0) histVV.SetFillStyle(0) template.setPrimaryPlot(histZZ, "histE", "ZZTo2L2Nu") template.addSecondaryPlot(histVV, "histE", "ZZTo2L2NuMass18") template.hasLegend = True template.cutsText = selection.labelSubRegion template.lumiInt = runRange.printval template.maximumScale = 1e3 template.logY = True template.minimumY = 0.01 template.setFolderName("compareMCSamples") template.draw() template.saveAs("comparison_%s_%s_%s" % (plotName, selection.name, runRange.label)) template.clean()
def main(): parser = argparse.ArgumentParser( description='produce cut & count event yields.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-B", "--blind", action="store_true", dest="blind", default=False, help="Blind SR in data") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.default if len(args.plots) == 0: args.plots = plotLists.signal if len(args.selection) == 0: args.selection.append(regionsToUse.signal.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) for runRangeName in args.runRange: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPathNLL for selectionName in args.selection: selection = getRegion(selectionName) if args.write: import subprocess bashCommand = "cp shelves/cutAndCountNLL_%s_%s.pkl %s/shelves" % ( selection.name, runRange.label, pathes.basePath) process = subprocess.Popen(bashCommand.split()) else: counts = cutAndCountForRegion(path, selection, args.plots, runRange, args.mc, args.backgrounds, args.blind) outFile = open( "shelves/cutAndCountNLL_%s_%s.pkl" % (selection.name, runRange.label), "w") pickle.dump(counts, outFile) outFile.close()
def getResultsNLL(shelves, signalRegion): NLLRegions = ["lowNLL","highNLL",] massRegions = ["mass20To60","mass60To86","mass96To150","mass150To200","mass200To300","mass300To400","mass400"] nBJetsRegions = [ "zeroBJets","oneOrMoreBJets",] MT2Regions = ["highMT2"] result = {} region = "inclusive" runRanges = shelves.keys() runRange = runRanges[0] if "2016" in runRange: result["onZPrediction_lowNLL_highMT2_zeroBJets"] = 28.9*0.72 result["onZPrediction_lowNLL_highMT2_zeroBJets_Err"] = 10.1*0.72 result["onZPrediction_highNLL_highMT2_zeroBJets"] = 28.9*0.28 result["onZPrediction_highNLL_highMT2_zeroBJets_Err"] = 10.1*0.28 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets"] = 12.5*0.72 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets_Err"] = 4.75*0.72 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets"] = 12.5*0.28 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets_Err"] = 4.75*0.28 if "2017" in runRange: result["onZPrediction_lowNLL_highMT2_zeroBJets"] = 71.5*0.72 result["onZPrediction_lowNLL_highMT2_zeroBJets_Err"] = 26.7*0.72 result["onZPrediction_highNLL_highMT2_zeroBJets"] = 71.5*0.28 result["onZPrediction_highNLL_highMT2_zeroBJets_Err"] = 26.7*0.28 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets"] = 42.8*0.72 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets_Err"] = 17.0*0.72 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets"] = 42.8*0.28 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets_Err"] = 17.0*0.28 if "2018" in runRange: result["onZPrediction_lowNLL_highMT2_zeroBJets"] = 64.4*0.72 result["onZPrediction_lowNLL_highMT2_zeroBJets_Err"] = 23.7*0.72 result["onZPrediction_highNLL_highMT2_zeroBJets"] = 64.4*0.28 result["onZPrediction_highNLL_highMT2_zeroBJets_Err"] = 23.7*0.28 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets"] = 45.6*0.72 result["onZPrediction_lowNLL_highMT2_oneOrMoreBJets_Err"] = 19.2*0.72 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets"] = 45.6*0.28 result["onZPrediction_highNLL_highMT2_oneOrMoreBJets_Err"] = 19.2*0.28 for selection in NLLRegions: result[selection] = {} for MT2Region in MT2Regions: for nBJetsRegion in nBJetsRegions: for massRegion in massRegions: currentBin = getattr(theCuts.mt2Cuts,MT2Region).name+"_"+getattr(theCuts.nBJetsCuts,nBJetsRegion).name+"_"+getattr(theCuts.massCuts,massRegion).name resultsBinName = "%s_%s_%s"%(MT2Region,nBJetsRegion,massRegion) print resultsBinName print currentBin result[selection]["%s_EE"%(resultsBinName)] = 0.0 result[selection]["%s_MM"%(resultsBinName)] = 0.0 result[selection]["%s_SF"%(resultsBinName)] = 0.0 result[selection]["%s_OF"%(resultsBinName)] = 0.0 result[selection]["%s_OFRMuEScaled"%(resultsBinName)] = 0.0 result[selection]["%s_OFRMuEScaledErrRT"%(resultsBinName)] = 0.0 result[selection]["%s_OFRMuEScaledErrFlat"%(resultsBinName)] = 0.0 result[selection]["%s_OFRMuEScaledErrPt"%(resultsBinName)] = 0.0 result[selection]["%s_OFRMuEScaledErrEta"%(resultsBinName)] = 0.0 for runRangeName in runRanges: shelve = shelves[runRangeName] result[selection]["%s_EE"%(resultsBinName)] += shelve[signalRegion][selection][currentBin]["EE"] result[selection]["%s_MM"%(resultsBinName)] += shelve[signalRegion][selection][currentBin]["MM"] result[selection]["%s_SF"%(resultsBinName)] += shelve[signalRegion][selection][currentBin]["EE"] + shelve[signalRegion][selection][currentBin]["MM"] result[selection]["%s_OF"%(resultsBinName)] += shelve[signalRegion][selection][currentBin]["EM"] result[selection]["%s_OFRMuEScaled"%(resultsBinName)] += shelve[signalRegion][selection][currentBin]["EMRMuEScaled"] runRange = getRunRange(runRangeName) RT = corrections[runRange.era].rSFOFTrig.inclusive.val RTErr = corrections[runRange.era].rSFOFTrig.inclusive.err rmuepred = shelve[signalRegion][selection][currentBin]["EMRMuEScaled"] OFRMuEScaledErrRT = shelve[signalRegion][selection][currentBin]["EMRMuEScaled"]*RTErr/RT OFRMuEScaledErrFlat = max(abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledUpFlat"]-rmuepred), abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledDownFlat"]-rmuepred)) OFRMuEScaledErrPt = max(abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledUpPt"]-rmuepred), abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledDownPt"]-rmuepred)) OFRMuEScaledErrEta = max(abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledUpEta"]-rmuepred), abs(shelve[signalRegion][selection][currentBin]["EMRMuEScaledDownEta"]-rmuepred)) result[selection]["%s_OFRMuEScaledErrRT"%(resultsBinName)] = (result[selection]["%s_OFRMuEScaledErrRT"%(resultsBinName)] + OFRMuEScaledErrRT**2)**0.5 result[selection]["%s_OFRMuEScaledErrFlat"%(resultsBinName)] = (result[selection]["%s_OFRMuEScaledErrFlat"%(resultsBinName)]**2 + OFRMuEScaledErrFlat**2)**0.5 result[selection]["%s_OFRMuEScaledErrPt"%(resultsBinName)] = (result[selection]["%s_OFRMuEScaledErrPt"%(resultsBinName)]**2 + OFRMuEScaledErrPt**2)**0.5 result[selection]["%s_OFRMuEScaledErrEta"%(resultsBinName)] = (result[selection]["%s_OFRMuEScaledErrEta"%(resultsBinName)]**2 + OFRMuEScaledErrEta**2)**0.5 shelve=None # safety so it is not used outside the loop yield_up = ROOT.Double(1.) yield_down = ROOT.Double(1.) ## calculate poisson error for FS prediction ROOT.RooHistError.instance().getPoissonInterval(int(result[selection]["%s_OF"%(resultsBinName)]),yield_down,yield_up,1.) ## calculate poisson error for observed data yieldSF_up = ROOT.Double(1.) yieldSF_down = ROOT.Double(1.) ROOT.RooHistError.instance().getPoissonInterval(int(result[selection]["%s_SF"%(resultsBinName)]),yieldSF_down,yieldSF_up,1.) result[selection]["%s_SFUp"%(resultsBinName)] = yieldSF_up - result[selection]["%s_SF"%(resultsBinName)] result[selection]["%s_SFDown"%(resultsBinName)] = result[selection]["%s_SF"%(resultsBinName)] - yieldSF_down # fs backgrounds result[selection]["%s_PredFactSF"%(resultsBinName)] = result[selection]["%s_OFRMuEScaled"%(resultsBinName)] if result[selection]["%s_OF"%(resultsBinName)] > 0: eff_rsfof = result[selection]["%s_PredFactSF"%(resultsBinName)]/result[selection]["%s_OF"%(resultsBinName)] result[selection]["%s_PredFactStatUpSF"%(resultsBinName)] = yield_up*eff_rsfof - result[selection]["%s_PredFactSF"%(resultsBinName)] result[selection]["%s_PredFactStatDownSF"%(resultsBinName)] = result[selection]["%s_PredFactSF"%(resultsBinName)] - yield_down*eff_rsfof systErrFact = (result[selection]["%s_OFRMuEScaledErrRT"%(resultsBinName)]**2 + result[selection]["%s_OFRMuEScaledErrFlat"%(resultsBinName)]**2 + result[selection]["%s_OFRMuEScaledErrPt"%(resultsBinName)]**2 + result[selection]["%s_OFRMuEScaledErrEta"%(resultsBinName)]**2)**0.5 result[selection]["%s_PredFactSystErrSF"%(resultsBinName)] = systErrFact else: result[selection]["%s_PredFactStatUpSF"%(resultsBinName)] = 1.8 result[selection]["%s_PredFactStatDownSF"%(resultsBinName)] = yield_down result[selection]["%s_PredFactSystErrSF"%(resultsBinName)] = 0 if result[selection]["%s_OF"%(resultsBinName)] > 0: result[selection]["%s_RSFOF_Fact"%(resultsBinName)] = result[selection]["%s_PredFactSF"%(resultsBinName)] / result[selection]["%s_OF"%(resultsBinName)] result[selection]["%s_RSFOF_Fact_Err"%(resultsBinName)] = result[selection]["%s_PredFactSystErrSF"%(resultsBinName)] / result[selection]["%s_OF"%(resultsBinName)] else: result[selection]["%s_RSFOF_Fact"%(resultsBinName)] = 0. result[selection]["%s_RSFOF_Fact_Err"%(resultsBinName)] = 0. result[selection]["%s_PredSF"%(resultsBinName)] = result[selection]["%s_PredFactSF"%(resultsBinName)] if result[selection]["%s_PredSF"%(resultsBinName)] > 0: result[selection]["%s_PredStatUpSF"%(resultsBinName)] = result[selection]["%s_PredFactStatUpSF"%(resultsBinName)] else: result[selection]["%s_PredStatUpSF"%(resultsBinName)] = 1.8 result[selection]["%s_PredStatDownSF"%(resultsBinName)] = result[selection]["%s_PredFactStatDownSF"%(resultsBinName)] result[selection]["%s_PredSystErrSF"%(resultsBinName)] = result[selection]["%s_PredFactSystErrSF"%(resultsBinName)] # Drell-Yan rOutIn = corrections["Combined"].rOutIn onZPredName = "onZPrediction_%s_%s_%s"%(selection,MT2Region,nBJetsRegion) onZPredErrName = "onZPrediction_%s_%s_%s_Err"%(selection,MT2Region,nBJetsRegion) result[selection]["%s_ZPredSF"%(resultsBinName)] = result[onZPredName]*getattr(getattr(rOutIn,massRegion),region).val result[selection]["%s_ZPredErrSF"%(resultsBinName)] = ((result[onZPredName]*getattr(getattr(rOutIn,massRegion),region).err)**2 + (result[onZPredErrName] * getattr(getattr(rOutIn,massRegion),region).val)**2 )**0.5 # ttz,wz,zz result[selection]["%s_RarePredSF"%(resultsBinName)] = 0.0 result[selection]["%s_RarePredErrSF"%(resultsBinName)] = 0.0 rarePredName ="%s_%s_%s_%s"%(massRegion,selection,MT2Region,nBJetsRegion) for runRangeName in runRanges: shelve = shelves[runRangeName] rarePred = shelve["Rares"]["%s_SF"%(rarePredName)] - shelve["Rares"]["%s_OF"%(rarePredName)] rareUp = shelve["Rares"]["%s_SF_Up"%(rarePredName)] - shelve["Rares"]["%s_OF_Up"%(rarePredName)] rareDown = shelve["Rares"]["%s_SF_Down"%(rarePredName)] - shelve["Rares"]["%s_OF_Down"%(rarePredName)] result[selection]["%s_RarePredSF"%(resultsBinName)] += rarePred errRare = max(abs(rareUp-rarePred), abs(rarePred-rareDown)) statErrRare = shelve["Rares"]["%s_SF_Stat"%(rarePredName)] result[selection]["%s_RarePredErrSF"%(resultsBinName)] = (result[selection]["%s_RarePredErrSF"%(resultsBinName)]**2 + errRare**2 + statErrRare**2)**0.5 result[selection]["%s_TotalPredSF"%(resultsBinName)] = result[selection]["%s_PredSF"%(resultsBinName)] + result[selection]["%s_ZPredSF"%(resultsBinName)] + result[selection]["%s_RarePredSF"%(resultsBinName)] result[selection]["%s_TotalPredErrUpSF"%(resultsBinName)] = ( result[selection]["%s_PredStatUpSF"%(resultsBinName)]**2 + result[selection]["%s_PredSystErrSF"%(resultsBinName)]**2 + result[selection]["%s_ZPredErrSF"%(resultsBinName)]**2 + result[selection]["%s_RarePredErrSF"%(resultsBinName)]**2)**0.5 result[selection]["%s_TotalPredErrDownSF"%(resultsBinName)] = ( result[selection]["%s_PredStatDownSF"%(resultsBinName)]**2 + result[selection]["%s_PredSystErrSF"%(resultsBinName)]**2 + result[selection]["%s_ZPredErrSF"%(resultsBinName)]**2 + result[selection]["%s_RarePredErrSF"%(resultsBinName)]**2)**0.5 return result
def main(): parser = argparse.ArgumentParser(description='R(out/in) measurements.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-s", "--selection", dest = "selection" , action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = ["DrellYan", "RareTTZOnZ","RareZZLowMassOnZ","RareWZOnZ"] args.runRange = [RR["2016"].name, RR["2017"].name ,RR["2018"].name] args.selection = ["DrellYanControl", "SignalHighMT2DeltaPhiJetMetFit"] template = plotTemplate() histos = {} merged = {} runRanges = [getRunRange(runRangeName) for runRangeName in args.runRange] for selectionName in args.selection: histos[selectionName] = {} selection = getRegion(selectionName) for runRangeName in args.runRange: runRange = getRunRange(runRangeName) plot = getPlot("mllPlot") plot.addRegion(selection) plot.cleanCuts() plot.addRunRange(runRange) histo = getHistogram(plot, runRange, args.backgrounds, "Inclusive") histos[selectionName][runRangeName] = histo for i,runRangeName in enumerate(args.runRange): if i == 0: merged[selectionName] = histos[selectionName][runRangeName].Clone() else: merged[selectionName].Add(histos[selectionName][runRangeName], 1) merged[selectionName].Scale(1.0/merged[selectionName].Integral()) #["DrellYanControl", "SignalInclusiveHighMT2"] merged["DrellYanControl"].SetLineColor(ROOT.kBlack) merged["DrellYanControl"].SetLineWidth(2) merged["DrellYanControl"].SetLineStyle(2) merged["DrellYanControl"].SetMarkerSize(0) merged["SignalHighMT2DeltaPhiJetMetFit"].SetLineColor(ROOT.kRed) merged["SignalHighMT2DeltaPhiJetMetFit"].SetLineWidth(2) merged["SignalHighMT2DeltaPhiJetMetFit"].SetMarkerSize(0) template.setPrimaryPlot(merged["DrellYanControl"], "histE", label="Z backgrounds in CR") template.addSecondaryPlot(merged["SignalHighMT2DeltaPhiJetMetFit"], "histE", label="Z backgrounds in fit SR") template.labelX = "mll [GeV]" template.labelY = "a.u." template.hasLegend = True template.logY = True template.maximumY = 3 template.minimumY = 1e-5 template.setFolderName("onZMllShapes") template.draw() template.saveAs("cr_fitsr")
def main(): parser = argparse.ArgumentParser(description='rSFOF from control region.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-d", "--dependencies", action="store_true", dest="dependencies", default=False, help="SF/OF dependency crosschecks.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="add MC.") parser.add_argument("-c", "--control", action="store_true", dest="control", default=False, help="use control region.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-e", "--edgeShape", action="store_true", dest="edgeShape", default=False, help="add 8 TeV excess shape.") parser.add_argument("-s", "--edgeShapeMC", action="store_true", dest="edgeShapeMC", default=False, help="add 13 TeV MC signals") parser.add_argument( "-D", "--differentEdgePositions", action="store_true", dest="differentEdgePositions", default=False, help="add 13 TeV MC signals at different edge positions") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.rSFOF if len(args.plots) == 0: args.plots = plotLists.default selections = [] if args.control: selections.append(regionsToUse.rSFOF.central.name) selections.append(regionsToUse.rSFOF.forward.name) selections.append(regionsToUse.rSFOF.inclusive.name) else: selections.append(regionsToUse.signalOld.central.name) #~ selections.append(regionsToUse.signal.forward.name) #~ selections.append(regionsToUse.signal.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPathTrigger cmsExtra = "" if args.private: cmsExtra = "Private Work" else: cmsExtra = "Preliminary" #~ cmsExtra = "" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) if args.dependencies: makeDependencyPlot(path, selection, args.plots, args.mc, args.backgrounds, runRange, cmsExtra) else: makeResultPlot( path, selection, runRange, cmsExtra, edgeShape=args.edgeShape, edgeShapeMC=args.edgeShapeMC, differentEdgePositions=args.differentEdgePositions)
def main(): parser = argparse.ArgumentParser( description='Trigger efficiency measurements.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument( "-n", "--new", action="store_true", dest="new", default=False, help="new approach, using single lepton for dependencies.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-c", "--centralValues", action="store_true", dest="central", default=False, help="calculate effinciecy central values") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-d", "--dependencies", action="store_true", dest="dependencies", default=False, help="make dependency plots") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.trigger if len(args.plots) == 0: args.plots = plotLists.trigger if len(args.selection) == 0: args.selection.append(regionsToUse.triggerEfficiencies.central.name) args.selection.append(regionsToUse.triggerEfficiencies.forward.name) args.selection.append(regionsToUse.triggerEfficiencies.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.triggerDataSetPath if args.mc: path = locations.dataSetPath source = baselineTrigger.name log.logHighlighted( "Calculating trigger efficiencies on %s triggered dataset" % source) log.logHighlighted("Using trees from %s " % path) cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) if args.central: centralVal = centralValues(source, path, selection, runRange, args.mc, args.backgrounds) if args.mc: outFilePkl = open( "shelves/triggerEff_%s_%s_%s_MC.pkl" % (selection.name, source, runRange.label), "w") else: outFilePkl = open( "shelves/triggerEff_%s_%s_%s.pkl" % (selection.name, source, runRange.label), "w") pickle.dump(centralVal, outFilePkl) outFilePkl.close() if args.dependencies: dependencies(source, path, selection, args.plots, runRange, args.mc, args.backgrounds, cmsExtra) if args.write: import subprocess if args.mc: bashCommand = "cp shelves/triggerEff_%s_%s_%s_MC.pkl %s/shelves" % ( selection.name, source, runRange.label, pathes.basePath) else: bashCommand = "cp shelves/triggerEff_%s_%s_%s.pkl %s/shelves" % ( selection.name, source, runRange.label, pathes.basePath) process = subprocess.Popen(bashCommand.split())
def main(): parser = argparse.ArgumentParser(description='rSFOF from control region.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-d", "--dependencies", action="store_true", dest="dependencies", default=False, help="SF/OF dependency crosschecks.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="add MC.") parser.add_argument("-c", "--control", action="store_true", dest="control", default=False, help="use control region.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.rSFOF if len(args.plots) == 0: args.plots = plotLists.default selections = [] if args.control: selections.append(regionsToUse.rSFOF.central.name) selections.append(regionsToUse.rSFOF.forward.name) selections.append(regionsToUse.rSFOF.inclusive.name) else: selections.append("SignalATLAS") #~ selections.append(regionsToUse.signal.central.name) #~ selections.append(regionsToUse.signal.forward.name) #~ selections.append(regionsToUse.signal.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPath path = "/home/jan/Trees/sw538v0477/" cmsExtra = "" if args.private: cmsExtra = "Private Work" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) if args.dependencies: makeDependencyPlot(path,selection,args.plots,args.mc,args.backgrounds,runRange,cmsExtra) else: makeResultPlot(path,selection,runRange,cmsExtra)
def main(): parser = argparse.ArgumentParser(description='rSFOF from control region.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-l", "--lowMass", action="store_true", dest="lowMass", default=False, help="plot low mass dependency") parser.add_argument("-o", "--highMass", action="store_true", dest="highMass", default=False, help="plot high mass dependency") parser.add_argument("-c", "--control", action="store_true", dest="control", default=False, help="use control region") parser.add_argument("-b", "--bins", action="store_true", dest="bins", default=False, help="plot in bins instead of cumulative") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() plotName = "" if args.lowMass: plotName = "mllPlotLowMass" elif args.highMass: plotName = "mllPlotHighMass" selections = [] if args.control: selections.append(regionsToUse.rSFOF.central.name) selections.append(regionsToUse.rSFOF.forward.name) selections.append(regionsToUse.rSFOF.inclusive.name) else: selections.append(regionsToUse.signal.central.name) selections.append(regionsToUse.signal.forward.name) selections.append(regionsToUse.signal.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPath cmsExtra = "" if args.private: cmsExtra = "Private Work" else: cmsExtra = "Preliminary" print cmsExtra for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in selections: selection = getRegion(selectionName) lumiDependency(path, plotName, selection, runRange, cmsExtra, args.bins)
def __init__(self,plot,plot2=None,region="Inclusive",runName = "Run2015_25ns",plotData=True,normalizeToData=False,plotRatio=True,signals=None,useTriggerEmulation=False,personalWork=False,doTopReweighting=False,preliminary=True,forPAS=False,forTWIKI=False,backgrounds = [],produceTheoUncert=False,dontScaleTrig=False,plotSyst=False,doPUWeights=False,jzbType = "None",responseCorr = False ,puCorr = False, peakCorr = False, correctMET = True): sys.path.append(pathes.basePath) if jzbType == "None": jzbType = dataMCConfig.jzbType self.jzbType = jzbType self.prefix = jzbType self.responseCorr = responseCorr self.puCorr = puCorr self.peakCorr = peakCorr self.correctMET = correctMET self.dataSetPath = locations.dataSetPath if dontScaleTrig: self.dataSetPath = locations.dataSetPathTrigger self.runRange = getRunRange(runName) self.selection = getRegion(region) self.plotData = plotData plotList = None if "#" in plot: plotList = plot.split("#") plot = plotList[0] plotList = plotList[1:] self.plot = getPlot(plot) self.plot.addRegion(self.selection) self.plot.cleanCuts() self.plot.cuts = self.plot.cuts % self.runRange.runCut if plotList != None: self.plot.cuts = self.plot.cuts[:-1] for l in plotList: self.plot.cuts = self.plot.cuts + "&& %s"%(cutString[l]) self.plot.cuts = self.plot.cuts + ")" if plot2 != None: plotList = None if "#" in plot2: plotList = plot2.split("#") plot2 = plotList[0] plotList = plotList[1:] self.plot2 = getPlot(plot2) self.plot2.addRegion(self.selection) self.plot2.cleanCuts() self.plot2.cuts = self.plot2.cuts % self.runRange.runCut if plotList != None: self.plot2.cuts = self.plot2.cuts[:-1] for l in plotList: self.plot2.cuts = self.plot2.cuts + " && %s"%(cutString[l]) self.plot2.cuts = self.plot2.cuts + ")" if "Inclusive" in region: self.direction = "Inclusive" elif "Central" in region: self.direction = "Central" elif "Forward" in region: self.direction = "Forward" configurePlot(self.plot, self.jzbType, self.plotData, self.direction, self.responseCorr, self.puCorr, self.peakCorr, self.correctMET, self.correctionMode) if plot2 != None: configurePlot(self.plot2, self.jzbType, self.plotData, self.direction, self.responseCorr, self.puCorr, self.peakCorr, self.correctMET, self.correctionMode) self.normalizeToData = normalizeToData self.plotRatio = plotRatio self.signals = signals if self.signals is not None: self.plotSignal = True self.backgrounds = backgrounds self.useTriggerEmulation = useTriggerEmulation self.personalWork = personalWork self.preliminary = preliminary self.doTopReweighting = doTopReweighting self.forPAS = forPAS self.forTWIKI = forTWIKI self.DontScaleTrig = dontScaleTrig self.doPUWeights = doPUWeights from corrections import rSFOF self.rSFOF = rSFOF
def plotIsolation(selection): from centralConfig import runRanges first = False histEEPromptAll = None histMMPromptAll = None histEEHeavyFlavourAll = None histMMHeavyFlavourAll = None histEEFakeAll = None histMMFakeAll = None fake = "!((pt1 < pt 2)*(abs(pdgId1)==11 || abs(pdgId1)==13 || (abs(pdgId1) == 22 && (abs(motherPdgId1) == 11 || abs(motherPdgId1) == 13 ))) || (pt1 > pt 2)*(abs(pdgId2)==11 || abs(pdgId2)==13) || (abs(pdgId2) == 22 && (abs(motherPdgId2) == 11 || abs(motherPdgId2) == 13 )))" dilep = "((pt1 < pt 2)*(abs(motherPdgId1)== 24 || abs(motherPdgId1)== 23 || abs(grandMotherPdgId1)== 24 || abs(grandMotherPdgId1)== 23) || (pt1 > pt 2)*(abs(motherPdgId2)== 24 || abs(motherPdgId2)== 23 || abs(grandMotherPdgId2)== 24 || abs(grandMotherPdgId2)== 23))" backgrounds = ["TT_Powheg"] first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) path = locations[runRange.era].dataSetPathNonIso plot = getPlot("trailingIsoPlot") plot.addRegion(selection) plot.addRunRange(runRange) tmpCuts = plot.cuts plot.cuts = plot.cuts + "*(%s && !%s && !(pdgId1 == -9999 || pdgId2 == -9999))" % ( dilep, fake) histEEPrompt, histMMPrompt = getHistograms(path, plot, runRange, backgrounds) if first: histEEPromptAll = histEEPrompt.Clone() histMMPromptAll = histMMPrompt.Clone() else: histEEPromptAll.Add(histEEPrompt, 1.0) histMMPromptAll.Add(histMMPrompt, 1.0) plot.cuts = tmpCuts + "*(!%s && !%s && !(pdgId1 == -9999 || pdgId2 == -9999))" % ( dilep, fake) histEEHeavyFlavour, histMMHeavyFlavour = getHistograms( path, plot, runRange, backgrounds) if first: histEEHeavyFlavourAll = histEEHeavyFlavour.Clone() histMMHeavyFlavourAll = histMMHeavyFlavour.Clone() else: histEEHeavyFlavourAll.Add(histEEHeavyFlavour, 1.0) histMMHeavyFlavourAll.Add(histMMHeavyFlavour, 1.0) plot.cuts = tmpCuts + "*(%s && !(pdgId1 == -9999 || pdgId2 == -9999))" % ( fake) histEEFake, histMMFake = getHistograms(path, plot, runRange, backgrounds) #~ if first: histEEFakeAll = histEEFake.Clone() histMMFakeAll = histMMFake.Clone() else: histEEFakeAll.Add(histEEFake, 1.0) histMMFakeAll.Add(histMMFake, 1.0) if first: first = False plotDistribution(histEEPromptAll, histEEHeavyFlavourAll, histEEFakeAll, "electrons") plotDistribution(histMMPromptAll, histMMHeavyFlavourAll, histMMFakeAll, "muons")
def main(): parser = argparse.ArgumentParser(description='rMuE measurements.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.default if len(args.plots) == 0: args.plots = plotLists.default if len(args.selection) == 0: args.selection.append("Inclusive") if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPath cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) plot(path, selection, args.plots, runRange, args.mc, args.backgrounds, cmsExtra)
def main(): parser = argparse.ArgumentParser( description='create cut justification plots.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.Loose if len(args.selection) == 0: args.selection.append("Region") if len(args.runRange) == 0: args.runRange.append(runRanges.name) path = locations.dataSetPathLoose cmsExtra = "" if args.private: cmsExtra = "#splitline{Private Work}{Simulation}" else: cmsExtra = "Simulation" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) plotIsolationEff(path, selection, runRange, cmsExtra, args.backgrounds)
import corrections from ROOT import TGraphAsymmErrors from locations import locations import ratios ptCut = "pt1 > 20 && pt2 > 20"#(pt1 > 10 && pt2 > 20 || pt1 > 20 && pt2 > 10) ptCutLabel = "20"#"20(10)" variable = "p4.M()" cuts = "weight*(chargeProduct < 0 && %s && abs(eta1) < 2.4 && abs(eta2) < 2.4 && p4.M() > 20 && ((abs(eta1) < 1.4 || abs(eta1) > 1.6) && (abs(eta2) < 1.4 || abs(eta2) > 1.6)))"%(ptCut) SampleName = "TT_Powheg" runRange = getRunRange("Run2015_25ns") plot = getPlot("mllPlot") selection = getRegion("SignalInclusive") plot.addRegion(selection) plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut eventCounts = totalNumberOfGeneratedEvents(path) processes = [Process(getattr(Backgrounds,"TT_Powheg"),eventCounts)] treesEE = readTrees(path,"EE") treesEM = readTrees(path,"EMu") treesMM = readTrees(path,"MuMu")
def getEventCount(selection, addCut, plotName, useNLL = False): from centralConfig import runRanges histTT = None histDY = None sigHists = {} for point in sigPoints: sigHists["%s_%s_%s"%(point[0], point[1], point[2])] = None first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) if useNLL: path = locations[runRange.era].dataSetPathNLL else: path = locations[runRange.era].dataSetPath plot = getPlot(plotName) plot.addRegion(selection) plot.addRunRange(runRange) plot.cuts = plot.cuts.replace("deltaR > 0.1 &&", "deltaR > 0.1 && (%s) &&"%(addCut)) histSF = getHistogram(path,plot,runRange,"TT_Powheg") if first: histTT = histSF.Clone() else: histTT.Add(histSF, 1.0) for point in sigPoints: if useNLL: path = locations[runRange.era]["dataSetPathSignalNLL%s"%point[0]] else: path = locations[runRange.era]["dataSetPathSignal%s"%point[0]] plot = getPlot(plotName) plot.addRegion(selection) plot.addRunRange(runRange) plot.cuts = plot.cuts.replace("deltaR > 0.1 &&", "deltaR > 0.1 && (%s) &&"%(addCut)) histSF = getSignalHistogram(path, plot, runRange, point[0], point[1], point[2]) if first: sigHists["%s_%s_%s"%(point[0], point[1], point[2])] = histSF.Clone() else: sigHists["%s_%s_%s"%(point[0], point[1], point[2])].Add(histSF, 1) if first: first = False sf_yield = ctypes.c_double(1.0) counts = {} count = histTT.IntegralAndError(1, histTT.GetNbinsX()+1, sf_yield) err = sf_yield.value counts["TT_Powheg"] = (count, err) for point in sigPoints: count = sigHists["%s_%s_%s"%(point[0], point[1], point[2])].IntegralAndError(1, histTT.GetNbinsX()+1, sf_yield) err = sf_yield.value counts["%s_%s_%s"%(point[0], point[1], point[2])] = (count, err) return counts
def countEvents(selection): from centralConfig import runRanges first = False dataEEAll = None dataMMAll = None dataSFAll = None backgrounds = [ "Rare", "SingleTop", "TT_Powheg", "Diboson", "DrellYanTauTau", "DrellYan" ] histEEAll = {} histMMAll = {} histSFAll = {} for backgroundName in backgrounds: histEEAll[backgroundName] = None histMMAll[backgroundName] = None histSFAll[backgroundName] = None first = True for runRangeName in runRanges.allNames: runRange = getRunRange(runRangeName) plot = getPlot("mllPlot") plot.addRegion(selection) plot.addRunRange(runRange) if "met > 150" in plot.cuts or "met > 100" in plot.cuts: path = locations[runRange.era].dataSetPathNLL else: path = locations[runRange.era].dataSetPath dataEE, dataMM = getHistograms(path, plot, runRange, False, backgrounds) if first: dataEEAll = dataEE.Clone() dataMMAll = dataMM.Clone() else: dataEEAll.Add(dataEE, 1.0) dataMMAll.Add(dataMM, 1.0) for backgroundName in backgrounds: histEE, histMM = getHistograms(path, plot, runRange, True, [ backgroundName, ]) if first: histEEAll[backgroundName] = histEE.Clone() histMMAll[backgroundName] = histMM.Clone() else: histEEAll[backgroundName].Add(histEE, 1.0) histMMAll[backgroundName].Add(histMM, 1.0) if first: first = False dataSFAll = dataEEAll.Clone() dataSFAll.Add(dataMMAll, 1.0) firstProc = True histMCSFAll = None histMCEEAll = None histMCMMAll = None for backgroundName in backgrounds: histSFAll[backgroundName] = histEEAll[backgroundName].Clone() histSFAll[backgroundName].Add(histMMAll[backgroundName], 1.0) if firstProc: histMCSFAll = histSFAll[backgroundName].Clone() histMCEEAll = histEEAll[backgroundName].Clone() histMCMMAll = histMMAll[backgroundName].Clone() firstProc = False else: histMCSFAll.Add(histSFAll[backgroundName].Clone(), 1) histMCEEAll.Add(histEEAll[backgroundName].Clone(), 1) histMCMMAll.Add(histMMAll[backgroundName].Clone(), 1) print "Data: " print "EE: ", dataEEAll.Integral() print "MM: ", dataMMAll.Integral() print "SF: ", dataSFAll.Integral() print "" print "MC: " print "EE: ", histMCEEAll.Integral() print "MM: ", histMCMMAll.Integral() print "SF: ", histMCSFAll.Integral() for backgroundName in backgrounds: print "" print backgroundName print "EE: ", histEEAll[backgroundName].Integral( ), histEEAll[backgroundName].Integral() / histMCEEAll.Integral() print "MM: ", histMMAll[backgroundName].Integral( ), histMMAll[backgroundName].Integral() / histMCMMAll.Integral() print "SF: ", histSFAll[backgroundName].Integral( ), histSFAll[backgroundName].Integral() / histMCSFAll.Integral()
def main(): parser = argparse.ArgumentParser(description='rSFOF from control region.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument("-s", "--selection", dest="selection", action="append", default=[], help="selection which to apply.") parser.add_argument("-p", "--plot", dest="plots", action="append", default=[], help="select dependencies to study, default is all.") parser.add_argument("-r", "--runRange", dest="runRange", action="append", default=[], help="name of run range.") parser.add_argument("-c", "--centralValues", action="store_true", dest="central", default=False, help="calculate effinciecy central values") parser.add_argument("-C", "--ptCut", action="store", dest="ptCut", default="pt2515", help="modify the pt cuts") parser.add_argument("-b", "--backgrounds", dest="backgrounds", action="append", default=[], help="backgrounds to plot.") parser.add_argument("-d", "--dependencies", action="store_true", dest="dependencies", default=False, help="make dependency plots") parser.add_argument("-l", "--dilepton", action="store_true", dest="dilepton", default=False, help="use dilepton triggers as baseline.") parser.add_argument("-e", "--effectiveArea", action="store_true", dest="effectiveArea", default=False, help="use effective area PU corrections.") parser.add_argument("-D", "--deltaBeta", action="store_true", dest="deltaBeta", default=False, help="use delta beta PU corrections.") parser.add_argument("-R", "--constantConeSize", action="store_true", dest="constantConeSize", default=False, help="use constant cone of R=0.3 for iso.") parser.add_argument("-f", "--fit", action="store_true", dest="fit", default=False, help="do dependecy fit") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-i", "--illustrate", action="store_true", dest="illustrate", default=False, help="plot dependency illustrations.") parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") parser.add_argument("-n", "--nonNormalized", action="store_true", dest="nonNormalized", default=False, help="do not normalize to cross section") args = parser.parse_args() if len(args.backgrounds) == 0: args.backgrounds = backgroundLists.rSFOF if len(args.plots) == 0: args.plots = plotLists.rSFOF if len(args.selection) == 0: #~ args.selection.append(regionsToUse.rSFOF.central.name) #~ args.selection.append(regionsToUse.rSFOF.forward.name) args.selection.append(regionsToUse.rSFOF.inclusive.name) if len(args.runRange) == 0: args.runRange.append(runRanges.name) if args.mc: path = locations.dataSetPathMC else: path = locations.dataSetPath if args.dilepton: source = "DiLeptonTrigger" modifier = "DiLeptonTrigger" else: source = "" modifier = "" #~ if args.constantConeSize: #~ if args.effectiveArea: #~ source = "EffAreaIso%s"%source #~ elif args.deltaBeta: #~ source = "DeltaBetaIso%s"%source #~ else: #~ print "Constant cone size (option -R) can only be used in combination with effective area (-e) or delta beta (-D) pileup corrections." #~ print "Using default miniIso cone with PF weights instead" #~ else: #~ if args.effectiveArea: #~ source = "MiniIsoEffAreaIso%s"%source #~ elif args.deltaBeta: #~ source = "MiniIsoDeltaBetaIso%s"%source #~ else: #~ source = "MiniIsoPFWeights%s"%source cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: cmsExtra = "Preliminary" for runRangeName in args.runRange: runRange = getRunRange(runRangeName) for selectionName in args.selection: selection = getRegion(selectionName) if args.central: centralVal = centralValues(source, modifier, path, selection, runRange, args.mc, args.nonNormalized, args.backgrounds, cmsExtra) if args.mc: outFilePkl = open( "shelves/rSFOF_%s_%s_MC.pkl" % (selection.name, runRange.label), "w") #~ outFilePkl = open("shelves/rSFOF_%s_%s_MC_old.pkl"%(selection.name,runRange.label),"w") else: outFilePkl = open( "shelves/rSFOF_%s_%s.pkl" % (selection.name, runRange.label), "w") #~ outFilePkl = open("shelves/rSFOF_%s_%s_old.pkl"%(selection.name,runRange.label),"w") pickle.dump(centralVal, outFilePkl) outFilePkl.close() if args.dependencies: dependencies(source, modifier, path, selection, args.plots, runRange, args.mc, args.nonNormalized, args.backgrounds, cmsExtra, args.fit, args.ptCut) if args.illustrate: illustration(selectionName) if args.write: import subprocess if args.mc: bashCommand = "cp shelves/rSFOF_%s_%s_MC.pkl %s/shelves" % ( selection.name, runRange.label, pathes.basePath) else: bashCommand = "cp shelves/rSFOF_%s_%s.pkl %s/shelves" % ( selection.name, runRange.label, pathes.basePath) process = subprocess.Popen(bashCommand.split())
def main(): parser = argparse.ArgumentParser(description='edge fitter reloaded.') parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose mode.") parser.add_argument("-m", "--mc", action="store_true", dest="mc", default=False, help="use MC, default is to use data.") parser.add_argument( "-u", "--use", action="store_true", dest="useExisting", default=False, help="use existing datasets from pickle, default is false.") ### MT2 changes the mll shape, but the effect on the Z shape is small ### Used a control region definition with MT2 cut in my thesis, but ### the plots do not look well when using MC due to lacking statistics ### or a missing sample. You have to check which CR to use. The impact ### on the fit results is negligible. Adapt y-range accordingly parser.add_argument( "-s", "--selection", dest="selection", action="store", default="DrellYanControl", #parser.add_argument("-s", "--selection", dest = "selection" , action="store", default="DrellYanControlNoMT2Cut", help="selection which to apply.") parser.add_argument("-r", "--runRange", dest="runRanges", action="append", default=[], help="name of run range.") parser.add_argument("-c", "--combine", dest="combine", action="store_true", default=False, help="combined runRanges or not") parser.add_argument("-x", "--private", action="store_true", dest="private", default=False, help="plot is private work.") parser.add_argument("-w", "--write", action="store_true", dest="write", default=False, help="write results to central repository") args = parser.parse_args() if not args.verbose: ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING) ROOT.RooMsgService.instance().setSilentMode(ROOT.kTRUE) cmsExtra = "" if args.private: cmsExtra = "Private Work" if args.mc: cmsExtra = "#splitline{Private Work}{Simulation}" elif args.mc: cmsExtra = "Simulation" else: #~ cmsExtra = "Preliminary" cmsExtra = "Supplementary" useExistingDataset = args.useExisting lumi = 0 runRangeName = "_".join(args.runRanges) lumis = [] for runRange in args.runRanges: lumis.append(getRunRange(runRange).printval) #lumi = "+".join(lumis) lumi = "137" from edgeConfig import edgeConfig theConfig = edgeConfig(region=args.selection, runNames=args.runRanges, useMC=args.mc) if args.private: theConfig.ownWork = True # init ROOT # uncomment this if you want a segmentation violation #gROOT.Reset() gROOT.SetStyle("Plain") setTDRStyle() ROOT.gROOT.SetStyle("tdrStyle") # get data theDataInterface = dataInterface.DataInterface(theConfig.runRanges) treeOFOS = None treeEE = None treeMM = None #print ROOT.gDirectory.GetList() if not useExistingDataset: w = ROOT.RooWorkspace("w", ROOT.kTRUE) inv = ROOT.RooRealVar("inv", "inv", (theConfig.maxInv - theConfig.minInv) / 2, theConfig.minInv, theConfig.maxInv) getattr(w, 'import')(inv, ROOT.RooCmdArg()) w.factory("weight[1.,0.,10.]") vars = ROOT.RooArgSet(inv, w.var('weight')) if (theConfig.useMC): log.logHighlighted("Using MC instead of data.") datasets = theConfig.mcdatasets # ["TTJets", "ZJets", "DibosonMadgraph", "SingleTop"] (treeEM, treeEE, treeMM) = tools.getTrees(theConfig, datasets) else: treeMMraw = theDataInterface.getTreeFromDataset( "MergedData", "MuMu", cut=theConfig.selection.cut) treeEMraw = theDataInterface.getTreeFromDataset( "MergedData", "EMu", cut=theConfig.selection.cut) treeEEraw = theDataInterface.getTreeFromDataset( "MergedData", "EE", cut=theConfig.selection.cut) # convert trees treeEM = dataInterface.DataInterface.convertDileptonTree(treeEMraw) treeEE = dataInterface.DataInterface.convertDileptonTree(treeEEraw) treeMM = dataInterface.DataInterface.convertDileptonTree(treeMMraw) print "EM", treeEM.GetEntries() print "EE", treeEE.GetEntries() print "MM", treeMM.GetEntries() histEM = createFitHistoFromTree( treeEM, "inv", "weight", int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv, theConfig.maxInv) histEE = createFitHistoFromTree( treeEE, "inv", "weight", int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv, theConfig.maxInv) histMM = createFitHistoFromTree( treeMM, "inv", "weight", int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv, theConfig.maxInv) dataHistEE = ROOT.RooDataHist("dataHistEE", "dataHistEE", ROOT.RooArgList(w.var('inv')), histEE) dataHistMM = ROOT.RooDataHist("dataHistMM", "dataHistMM", ROOT.RooArgList(w.var('inv')), histMM) getattr(w, 'import')(dataHistEE, ROOT.RooCmdArg()) getattr(w, 'import')(dataHistMM, ROOT.RooCmdArg()) if theConfig.useMC: w.writeToFile("workspaces/dyControl_%s_MC.root" % (runRangeName)) else: w.writeToFile("workspaces/dyControl_%s_Data.root" % (runRangeName)) else: if theConfig.useMC: f = ROOT.TFile("workspaces/dyControl_%s_MC.root" % (runRangeName)) else: f = ROOT.TFile("workspaces/dyControl_%s_Data.root" % (runRangeName)) w = f.Get("w") #~ vars = ROOT.RooArgSet(w.var("inv"), w.var('weight'), w.var('genWeight')) vars = ROOT.RooArgSet(w.var("inv"), w.var('weight')) ### For some reason we never switched from the hard coded maximum. ### Might want to change this in the future yMaximum = 5 * 10000 ### 2016+2017+2018 data with MT2 cut yMinimum = 0.1 ### 2016+2017+2018 data with MT2 cut #yMaximum = histEE.GetMaximum()*1e10 #yMinimum = 10 global nBinsDY nBinsDY = 240 # global histoytitle histoytitle = 'Events / %.1f GeV' % ( (theConfig.maxInv - theConfig.minInv) / float(nBinsDY)) #histoytitle = 'Events / 4 GeV' ROOT.gSystem.Load("shapes/RooDoubleCB_cxx.so") ROOT.gSystem.Load("libFFTW.so") ## 2 GeV binning for DY compared to 5 GeV in main fit w.var('inv').setBins(nBinsDY) #~ w.var('inv').setBins(140) # We know the z mass # z mass and width # mass resolution in electron and muon channels #w.factory("zmean[91.1876, 90.1876, 92.1876]") w.factory("zmean[91.1876]") #w.factory("zmean[91.1876,89,93]") w.factory("cbmeanMM[3.0,-5,5]") w.factory("cbmeanEE[3.0,-5,5]") w.factory("zwidthMM[2.4952]") w.factory("zwidthEE[2.4952]") w.factory("sMM[1.6.,0.,20.]") w.factory("BreitWigner::zShapeMM(inv,zmean,zwidthMM)") w.factory("sEE[1.61321382563436089e+00,0,20.]") w.factory("BreitWigner::zShapeEE(inv,zmean,zwidthEE)") w.factory("nMML[3.,0.,10]") w.factory("alphaMML[1.15,0,10]") w.factory("nMMR[1.,0,10]") w.factory("alphaMMR[2.5,0,10]") w.factory( "DoubleCB::cbShapeMM(inv,cbmeanMM,sMM,alphaMML,nMML,alphaMMR,nMMR)") w.factory("nEEL[2.903,0.,10]") w.factory("alphaEEL[1.1598,0,5]") w.factory("nEER[1.0,0,10]") w.factory("alphaEER[2.508,0,5]") w.factory( "DoubleCB::cbShapeEE(inv,cbmeanEE,sEE,alphaEEL,nEEL,alphaEER,nEER)") Abkg = ROOT.RooRealVar("Abkg", "Abkg", 1, 0.01, 10) getattr(w, 'import')(Abkg, ROOT.RooCmdArg()) #~ w.var("inv").setBins(250,"cache") w.factory("cContinuumEE[%f,%f,%f]" % (-0.02, -0.1, 0)) w.factory("nZEE[100000.,500.,%s]" % (2000000)) #~ w.factory("nZEE[100000.,300.,%s]" % (2000000)) w.factory("Exponential::offShellEE(inv,cContinuumEE)") convEE = ROOT.RooFFTConvPdf("peakModelEE", "zShapeEE (x) cbShapeEE", w.var("inv"), w.pdf("zShapeEE"), w.pdf("cbShapeEE")) getattr(w, 'import')(convEE, ROOT.RooCmdArg()) w.pdf("peakModelEE").setBufferFraction(5.0) w.factory("zFractionEE[0.9,0,1]") expFractionEE = ROOT.RooFormulaVar('expFractionEE', '1-@0', ROOT.RooArgList(w.var('zFractionEE'))) getattr(w, 'import')(expFractionEE, ROOT.RooCmdArg()) w.factory( "SUM::modelEE1(zFractionEE*peakModelEE,expFractionEE*offShellEE)") w.factory("SUM::modelEE(nZEE*modelEE1)") w.factory("cContinuumMM[%f,%f,%f]" % (-0.02, -0.1, 0)) w.factory("Exponential::offShellMM(inv,cContinuumMM)") w.factory("nZMM[100000.,500.,%s]" % (2000000)) w.factory("nOffShellMM[100000.,500.,%s]" % (2000000)) #~ w.factory("nZMM[100000.,300.,%s]" % (2000000)) #~ w.factory("nOffShellMM[100000.,300.,%s]" % (2000000)) convMM = ROOT.RooFFTConvPdf("peakModelMM", "zShapeMM (x) cbShapeMM", w.var("inv"), w.pdf("zShapeMM"), w.pdf("cbShapeMM")) getattr(w, 'import')(convMM, ROOT.RooCmdArg()) w.pdf("peakModelMM").setBufferFraction(5.0) w.factory("zFractionMM[0.9,0,1]") expFractionMM = ROOT.RooFormulaVar('expFractionMM', '1-@0', ROOT.RooArgList(w.var('zFractionMM'))) getattr(w, 'import')(expFractionMM, ROOT.RooCmdArg()) w.factory( "SUM::modelMM1(zFractionMM*peakModelMM,expFractionMM*offShellMM)") w.factory("SUM::modelMM(nZMM*modelMM1)") print "3" fitEE = w.pdf('modelEE').fitTo( w.data('dataHistEE'), #ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(2.0)) ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(ROOT.kFALSE), ROOT.RooFit.Extended(ROOT.kTRUE)) parametersToSave["nParEE"] = fitEE.floatParsFinal().getSize() print "3.1" fitMM = w.pdf('modelMM').fitTo( w.data('dataHistMM'), #ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(2.0)) ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(ROOT.kTRUE), ROOT.RooFit.Extended(ROOT.kTRUE)) parametersToSave["nParMM"] = fitMM.floatParsFinal().getSize() print "3.2" w.var("inv").setRange("zPeak", 81, 101) w.var("inv").setRange("fullRange", 20, 500) #~ w.var("inv").setRange("fullRange",20,300) w.var("inv").setRange("lowMass", 20, 70) argSet = ROOT.RooArgSet(w.var("inv")) peakIntEE = w.pdf("modelEE").createIntegral(argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("zPeak")) peakEE = peakIntEE.getVal() lowMassIntEE = w.pdf("modelEE").createIntegral( argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("lowMass")) lowMassEE = lowMassIntEE.getVal() peakIntMM = w.pdf("modelMM").createIntegral(argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("zPeak")) peakMM = peakIntMM.getVal() lowMassIntMM = w.pdf("modelMM").createIntegral( argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("lowMass")) lowMassMM = lowMassIntMM.getVal() log.logHighlighted("Peak: %.3f LowMass: %.3f (ee)" % (peakEE, lowMassEE)) log.logHighlighted("Peak: %.3f LowMass: %.3f (mm)" % (peakMM, lowMassMM)) log.logHighlighted("R(out,in): %.3f (ee) %.3f (mm)" % (lowMassEE / peakEE, lowMassMM / peakMM)) frameEE = w.var('inv').frame( ROOT.RooFit.Title('Invariant mass of ee lepton pairs')) frameEE.GetXaxis().SetTitle('m_{ee} [GeV]') frameEE.GetYaxis().SetTitle("Events / 2.5 GeV") #ROOT.RooAbsData.plotOn(w.data('dataHistEE'), frameEE, ROOT.RooFit.Binning(120)) ROOT.RooAbsData.plotOn(w.data('dataHistEE'), frameEE) w.pdf('modelEE').plotOn(frameEE) sizeCanvas = 800 #~ parametersToSave["chi2EE"] = 1.1*frameEE.chiSquare(int(parametersToSave["nParEE"])) parametersToSave["chi2EE"] = frameEE.chiSquare( int(parametersToSave["nParEE"])) parametersToSave["chi2ProbEE"] = TMath.Prob( parametersToSave["chi2EE"] * (nBinsDY - int(parametersToSave["nParEE"])), nBinsDY - int(parametersToSave["nParEE"])) log.logHighlighted("Floating parameters EE: %f" % parametersToSave["nParEE"]) log.logHighlighted("Chi2 EE: %f" % parametersToSave["chi2EE"]) log.logHighlighted("Chi2 probability EE: %f" % parametersToSave["chi2ProbEE"]) cEE = ROOT.TCanvas("ee distribtution", "ee distribution", sizeCanvas, int(1.25 * sizeCanvas)) cEE.cd() pads = formatAndDrawFrame(w, theConfig, frameEE, title="EE", pdf=w.pdf("modelEE"), yMin=0, yMax=0.05 * yMaximum) dLeg = ROOT.TH1F() dLeg.SetMarkerStyle(ROOT.kFullCircle) dLeg.SetMarkerColor(ROOT.kBlack) dLeg.SetLineWidth(2) fullModelLeg = dLeg.Clone() fullModelLeg.SetLineColor(ROOT.kBlue) expLeg = dLeg.Clone() expLeg.SetLineColor(ROOT.kGreen + 2) peakLeg = dLeg.Clone() peakLeg.SetLineColor(ROOT.kRed) nLegendEntries = 4 leg = tools.myLegend(0.35, 0.89 - 0.07 * nLegendEntries, 0.92, 0.91, borderSize=0) leg.SetTextAlign(22) if (theConfig.useMC): leg.AddEntry(dLeg, 'Simulation', "pe") else: leg.AddEntry(dLeg, 'Data', "pe") leg.AddEntry(fullModelLeg, 'Full Z/#gamma* model', "l") leg.AddEntry(expLeg, 'Exponential component', "l") leg.AddEntry(peakLeg, 'DSCB #otimes BW component', "l") leg.Draw("same") goodnessOfFitEE = '#chi^{2}-prob. = %.3f' % parametersToSave["chi2ProbEE"] annotationsTitle = [ (0.92, 0.47, "%s" % (theConfig.selection.latex)), #~ (0.92, 0.52, "%s" % (theConfig.selection.latex)), (0.92, 0.44, "%s" % goodnessOfFitEE), ] tools.makeCMSAnnotation(0.18, 0.88, lumi, mcOnly=theConfig.useMC, preliminary=theConfig.isPreliminary, year=theConfig.year, ownWork=theConfig.ownWork) tools.makeAnnotations(annotationsTitle, color=tools.myColors['AnnBlue'], textSize=0.04, align=31) tools.storeParameter("expofit", "dyExponent_EE", "expo", w.var('cContinuumEE').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "cbMean", w.var('cbmeanEE').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "nL", w.var('nEEL').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "nR", w.var('nEER').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "alphaL", w.var('alphaEEL').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "alphaR", w.var('alphaEER').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "nZ", w.var('nZEE').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "zFraction", w.var('zFractionEE').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "s", w.var('sEE').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "sErr", w.var('sEE').getError(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "chi2", parametersToSave["chi2EE"], basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_EE", "chi2Prob", parametersToSave["chi2ProbEE"], basePath="dyShelves/" + runRangeName + "/") eeName = "fig/expoFitEE_%s" % (runRangeName) if theConfig.useMC: eeName = "fig/expoFitEE_%s_MC" % (runRangeName) cEE.Print(eeName + ".pdf") cEE.Print(eeName + ".root") for pad in pads: pad.Close() pads = formatAndDrawFrame(w, theConfig, frameEE, title="EE", pdf=w.pdf("modelEE"), yMin=yMinimum, yMax=yMaximum) leg.Draw("same") tools.makeCMSAnnotation(0.18, 0.88, lumi, mcOnly=theConfig.useMC, preliminary=theConfig.isPreliminary, year=theConfig.year, ownWork=theConfig.ownWork) tools.makeAnnotations(annotationsTitle, color=tools.myColors['AnnBlue'], textSize=0.04, align=31) pads[0].SetLogy(1) eeName = "fig/expoFitEE_Log_%s" % (runRangeName) if theConfig.useMC: eeName = "fig/expoFitEE_Log_%s_MC" % (runRangeName) cEE.Print(eeName + ".pdf") cEE.Print(eeName + ".root") for pad in pads: pad.Close() frameMM = w.var('inv').frame( ROOT.RooFit.Title('Invariant mass of #mu#mu lepton pairs')) frameMM.GetXaxis().SetTitle('m_{#mu#mu} [GeV]') frameMM.GetYaxis().SetTitle("Events / 2.5 GeV") ROOT.RooAbsData.plotOn(w.data("dataHistMM"), frameMM) #ROOT.RooAbsData.plotOn(w.data("dataHistMM"), frameMM, ROOT.RooFit.Binning(120)) w.pdf('modelMM').plotOn(frameMM) sizeCanvas = 800 #~ parametersToSave["chi2MM"] = 1.1*frameMM.chiSquare(int(parametersToSave["nParMM"])) parametersToSave["chi2MM"] = frameMM.chiSquare( int(parametersToSave["nParMM"])) parametersToSave["chi2ProbMM"] = TMath.Prob( parametersToSave["chi2MM"] * (nBinsDY - int(parametersToSave["nParMM"])), nBinsDY - int(parametersToSave["nParMM"])) log.logHighlighted("Chi2 MM: %f" % parametersToSave["chi2MM"]) log.logHighlighted("Chi2 probability MM: %f" % parametersToSave["chi2ProbMM"]) goodnessOfFitMM = '#chi^{2}-prob. = %.3f' % parametersToSave["chi2ProbMM"] annotationsTitle = [ (0.92, 0.47, "%s" % (theConfig.selection.latex)), #~ (0.92, 0.52, "%s" % (theConfig.selection.latex)), (0.92, 0.44, "%s" % goodnessOfFitMM), ] residualMode = "pull" cMM = ROOT.TCanvas("#mu#mu distribtution", "#mu#mu distribution", sizeCanvas, int(1.25 * sizeCanvas)) cMM.cd() pads = formatAndDrawFrame(w, theConfig, frameMM, title="MM", pdf=w.pdf("modelMM"), yMin=0, yMax=0.05 * yMaximum) leg.Draw("same") tools.makeCMSAnnotation(0.18, 0.88, lumi, mcOnly=theConfig.useMC, preliminary=theConfig.isPreliminary, year=theConfig.year, ownWork=theConfig.ownWork) tools.makeAnnotations(annotationsTitle, color=tools.myColors['AnnBlue'], textSize=0.04, align=31) tools.storeParameter("expofit", "dyExponent_MM", "expo", w.var('cContinuumMM').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "cbMean", w.var('cbmeanMM').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "cbMeanErr", w.var('cbmeanMM').getError(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "nL", w.var('nMML').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "nR", w.var('nMMR').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "alphaL", w.var('alphaMML').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "alphaR", w.var('alphaMMR').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "nZ", w.var('nZMM').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "zFraction", w.var('zFractionMM').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "s", w.var('sMM').getVal(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "sErr", w.var('sMM').getError(), basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "chi2", parametersToSave["chi2MM"], basePath="dyShelves/" + runRangeName + "/") tools.storeParameter("expofit", "dyExponent_MM", "chi2Prob", parametersToSave["chi2ProbMM"], basePath="dyShelves/" + runRangeName + "/") mmName = "fig/expoFitMM_%s" % (runRangeName) if theConfig.useMC: mmName = "fig/expoFitMM_%s_MC" % (runRangeName) cMM.Print(mmName + ".pdf") cMM.Print(mmName + ".root") for pad in pads: pad.Close() pads = formatAndDrawFrame(w, theConfig, frameMM, title="MM", pdf=w.pdf("modelMM"), yMin=yMinimum, yMax=yMaximum) legend = ROOT.TLegend(0.5, 0.6, 0.95, 0.94) legend.SetFillStyle(0) legend.SetBorderSize(0) entryHist = ROOT.TH1F() entryHist.SetFillColor(ROOT.kWhite) legend.AddEntry(entryHist, "Drell-Yan enriched region", "h") dataHist = ROOT.TH1F() entryHist.SetFillColor(ROOT.kWhite) legend.AddEntry(dataHist, "data", "p") fitHist = ROOT.TH1F() fitHist.SetLineColor(ROOT.kBlue) legend.AddEntry(fitHist, "Full Z model", "l") expoHist = ROOT.TH1F() expoHist.SetLineColor(ROOT.kGreen) legend.AddEntry(expoHist, "Exponential component", "l") bwHist = ROOT.TH1F() bwHist.SetLineColor(ROOT.kRed) legend.AddEntry(bwHist, "DSCB #otimes BW component", "l") leg.Draw("same") tools.makeCMSAnnotation(0.18, 0.88, lumi, mcOnly=theConfig.useMC, preliminary=theConfig.isPreliminary, year=theConfig.year, ownWork=theConfig.ownWork) tools.makeAnnotations(annotationsTitle, color=tools.myColors['AnnBlue'], textSize=0.04, align=31) pads[0].SetLogy(1) mmName = "fig/expoFitMM_Log_%s" % (runRangeName) if theConfig.useMC: mmName = "fig/expoFitMM_Log_%s_MC" % (runRangeName) cMM.Print(mmName + ".pdf") cMM.Print(mmName + ".root") for pad in pads: pad.Close() if theConfig.useMC: w.writeToFile("dyWorkspace_MC.root") else: w.writeToFile("dyWorkspace.root") return w
def __init__(self, plot, region="SignalInclusive", runName="Full2012", plotData=True, plotMC=True, normalizeToData=False, plotRatio=True, signals=None, stackSignal=False, useTriggerEmulation=False, useDataTrigEff=False, doTopReweighting=False, personalWork=False, preliminary=True, forPAS=False, forTWIKI=False, backgrounds=[], dontScaleTrig=False, plotSyst=False, doPUWeights=False, normalizeToBinWidth=False): sys.path.append(pathes.basePath) #~ self.dataSetPath = locations.dataSetPathNLL self.dataSetPath = locations.dataSetPath if dontScaleTrig: self.dataSetPath = locations.dataSetPath #~ self.dataSetPath = locations.dataSetPathNLL self.runRange = getRunRange(runName) if "Central" in region: self.etaRegion = "central" elif "Forward" in region: self.etaRegion = "forward" else: self.etaRegion = "inclusive" self.selection = getRegion(region) self.plot = getPlot(plot) self.plot.addRegion(self.selection) self.plot.cleanCuts() self.plot.cuts = self.plot.cuts % self.runRange.runCut self.plotData = plotData self.plotMC = plotMC self.plotSyst = plotSyst self.normalizeToData = normalizeToData self.plotRatio = plotRatio self.signals = signals self.stackSignal = stackSignal if self.signals is not None: self.plotSignal = True self.backgrounds = backgrounds self.useTriggerEmulation = useTriggerEmulation self.useDataTrigEff = useDataTrigEff self.personalWork = personalWork self.preliminary = preliminary self.doTopReweighting = doTopReweighting self.forPAS = forPAS self.forTWIKI = forTWIKI self.DontScaleTrig = dontScaleTrig self.doPUWeights = doPUWeights self.normalizeToBinWidth = normalizeToBinWidth from corrections import rSFOF self.rSFOF = rSFOF