def doCounters(datasets, massPoints): eventCounter = counter.EventCounter(datasets) eventCounter.normalizeMCByLuminosity() rows1 = [ "Trigger and HLT_MET cut", "taus == 1", "trigger scale factor", "electron veto", "muon veto", "njets", "MET" ] rows2 = [ "btagging scale factor", "deltaPhiTauMET<160", "deltaPhiTauMET<130", ] tableAll = eventCounter.getMainCounterTable() tableAll.keepOnlyRows(rows1+rows2) tableWH = counter.CounterTable() tableHH = counter.CounterTable() for mass in massPoints: tableWH.appendColumn(tableAll.getColumn(name="TTToHplusBWB_M%d"%mass)) tableHH.appendColumn(tableAll.getColumn(name="TTToHplusBHminusB_M%d"%mass)) tableWH2 = tableWH.clone() tableWH.keepOnlyRows(rows1) tableWH2.keepOnlyRows(rows2) tableHH2 = tableHH.clone() tableHH.keepOnlyRows(rows1) tableHH2.keepOnlyRows(rows2) format1 = counter.TableFormatText(counter.CellFormatTeX(valueFormat="%.0f", valueOnly=True)) format12 = counter.TableFormatText(counter.CellFormatTeX(valueFormat="%.1f", valueOnly=True)) format2 = counter.TableFormatText(counter.CellFormatTeX(valueFormat="%.2f", withPrecision=1)) print "tt -> bW bH+" print tableWH.format(format1) print tableWH2.format(format2) print print print "tt -> bH+ bH-" print tableHH.format(format12) print tableHH2.format(format2)
def main(): dirEmbs = ["."] + [os.path.join("..", d) for d in result.dirEmbs[1:]] tauEmbedding.normalize = True tauEmbedding.era = "Run2011A" table = counter.CounterTable() for i in xrange(len(dirEmbs)): tmp = dirEmbs[:] del tmp[i] row = doCounters(tmp) row.setName("Removed embedding %d" % i) table.appendRow(row) arows = [] arows.append(counter.meanRow(table)) arows.append(counter.maxRow(table)) arows.append(counter.minRow(table)) arows.append(counter.subtractRow("Max-mean", arows[1], arows[0])) arows.append(counter.subtractRow("Mean-min", arows[0], arows[2])) for r in arows: table.appendRow(r) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.3f')) print "DeltaPhi < 160" print print table.format(cellFormat)
def doCounters(datasetsEmb, outputDir): eventCounter = counter.EventCounter(datasetsEmb) eventCounter.normalizeMCToLuminosity( datasetsEmb.getDataset("Data").getLuminosity()) table = eventCounter.getMainCounterTable() table.keepOnlyRows([ "Trigger and HLT_MET cut", "taus > 0", "tau trigger scale factor", "electron veto", "muon veto", "njets", "MET trigger scale factor", "QCD tail killer collinear", "MET", "btagging", "btagging scale factor", "Embedding: mT weight", "QCD tail killer back-to-back", "Selected events" ]) addMcSum(table) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2)) txt = table.format(cellFormat) print txt d = outputDir if d is None: d = "." if not os.path.exists(d): os.makedirs(d) f = open(os.path.join(d, "counters.txt"), "w") f.write(txt) f.write("\n")
def doCounters(opts, dsetMgr, moduleInfoString, myDir, luminosity, normFactors): def printSubCounterTable(eventCounter, subCounterName, cellFormat): # Check existence if subCounterName in eventCounter.getSubCounterNames(): # Subcounter exists, go ahead and print it return eventCounter.getSubCounterTable(subCounterName).format( cellFormat) else: return "Subcounter '%s' does not exist (please note that for optimization runs subcounters are not saved)" % subCounterName eventCounter = counter.EventCounter(dsetMgr) eventCounter.normalizeMCToLuminosity(myLuminosity) print "============================================================" print "Main counter (MC normalized by collision data luminosity)" mainTable = eventCounter.getMainCounterTable() # No uncertainties cellFormat = counter.TableFormatText(cellFormat=counter.CellFormatText( valueOnly=True)) myOutput = "" myOutput += mainTable.format(cellFormat) + "\n\n" myOutput += printSubCounterTable(eventCounter, "b-tagging", cellFormat) + "\n\n" myOutput += printSubCounterTable(eventCounter, "Jet selection", cellFormat) + "\n\n" myOutput += printSubCounterTable(eventCounter, "Jet main", cellFormat) + "\n\n" # Write the output to file f = open(os.path.join(myDir, "counterOutput.txt"), "w") f.write(myOutput) f.close() # Write the output to screen print myOutput
def printCounters(datasets): print "============================================================" print "Dataset info: " datasets.printInfo() eventCounter = counter.EventCounter(datasets) if True: selection = "Sum$(%s) >= 1" % muonKinematics eventCounter.getMainCounter().appendRow("Muon kinematics", treeDraw.clone(selection=selection)) selection = "Sum$(%s && %s) >= 1" % (muonKinematics, muondB) eventCounter.getMainCounter().appendRow("Muon IP", treeDraw.clone(selection=selection)) selection = "Sum$(%s && %s && %s) >= 1" % (muonKinematics, muondB, muonIsolation) eventCounter.getMainCounter().appendRow("Muon isolation", treeDraw.clone(selection=selection)) selection = "Sum$(%s && %s && %s) == 1" % (muonKinematics, muondB, muonIsolation) print selection eventCounter.getMainCounter().appendRow("One selected muon", treeDraw.clone(selection=selection)) selection += "&&" +muonVeto print selection eventCounter.getMainCounter().appendRow("Muon veto", treeDraw.clone(selection=selection)) selection += "&&" +electronVeto print selection eventCounter.getMainCounter().appendRow("Electron veto", treeDraw.clone(selection=selection)) selection += "&&" +jetSelection print selection eventCounter.getMainCounter().appendRow("Jet selection", treeDraw.clone(selection=selection)) eventCounter.normalizeMCByLuminosity() table = eventCounter.getMainCounterTable() addSumColumn(table) cellFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.3f')) print table.format(cellFormat)
def printCounters(datasets, selectionName, ntupleCache, selectorName, onlyDataset=None): global printed if not printed: print "============================================================" print "Dataset info: " datasets.printInfo() printed = True if not doWeighted: eventCounter = counter.EventCounter(datasets, counters=counters) counterPath = "counters/counter" else: eventCounter = counter.EventCounter(datasets) counterPath = "counters/weighted/counter" if onlyDataset != None: eventCounter.removeColumns( filter(lambda n: n != onlyDataset, datasets.getAllDatasetNames())) eventCounter.getMainCounter().appendRows( ntupleCache.histogram(counterPath, selectorName)) if mergeMC: if mcOnly: eventCounter.normalizeMCToLuminosity(mcLuminosity) else: eventCounter.normalizeMCByLuminosity() table = eventCounter.getMainCounterTable() mcDatasets = filter(lambda n: n != "Data", table.getColumnNames()) if len(mcDatasets) != 0: col = 1 if mcOnly: col = 0 table.insertColumn( col, counter.sumColumn( "MCSum", [table.getColumn(name=name) for name in mcDatasets])) cellFormat = counter.TableFormatText( counter.CellFormatText(valueFormat='%.3f')) # cellFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.1f')) output = table.format(cellFormat) print print "########################################" print "Selection", selectionName print output prefix = era + "_" + selectionName + "_counters" if not doWeighted: prefix += "_nonweighted" f = open(prefix + ".txt", "w") f.write(output) f.close()
def doCounters(datasets, ntupleCache): # Counters eventCounter = counter.EventCounter(datasets) mainCounter = eventCounter.getMainCounter(); counters = "counters/counter" if dataEra != "": counters = "counters/weighted/counter" mainCounter.appendRows(ntupleCache.histogram(counters)) format = counter.TableFormatText(counter.CellFormatText(valueFormat="%.0f")) table = mainCounter.getTable() print table.format(format) effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat="%.2f", withPrecision=2)) teffs = mainCounter.constructTEfficiencies(createTEfficiency) table = counter.efficiencyTableFromTEfficiencies(teffs, mainCounter.getColumnNames(), rowNames) table.multiply(100) print table.format(effFormat)
def doCounters(myDsetMgr, mySuffix, isSystematicVariation): eventCounter = counter.EventCounter(myDsetMgr) # append row from the tree to the main counter # eventCounter.getMainCounter().appendRow("MET > 70", treeDraw.clone(selection="met_p4.Et() > 70")) ewkDatasets = [ "WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson" ] if myDsetMgr.hasDataset("W1Jets"): ewkDatasets.extend(["W1Jets", "W2Jets", "W3Jets", "W4Jets"]) if mcOnly: eventCounter.normalizeMCToLuminosity(mcOnlyLumi) else: eventCounter.normalizeMCByLuminosity() print "============================================================" print mySuffix print "============================================================" out = open(os.path.join(mySuffix, "counters.txt"), "w") def printAndSave(line): print line out.write(line) out.write("\n") printAndSave("Main counter (MC normalized by collision data luminosity)") mainTable = eventCounter.getMainCounterTable() mainTable.insertColumn(2, counter.sumColumn("EWKMCsum", [mainTable.getColumn(name=name) for name in ewkDatasets])) # Default # cellFormat = counter.TableFormatText() # No uncertainties cellFormat = counter.TableFormatText(cellFormat=counter.CellFormatText(valueOnly=False)) printAndSave(mainTable.format(cellFormat)) if not isSystematicVariation: # printAndSave(eventCounter.getSubCounterTable("tauIDTauSelection").format()) printAndSave(eventCounter.getSubCounterTable("TauIDPassedEvt::TauSelection_HPS").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("TauIDPassedJets::TauSelection_HPS").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("b-tagging").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("Jet selection").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("Jet main").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("VetoTauSelection").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("MuonSelection").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("MCinfo for selected events").format(cellFormat)) printAndSave(eventCounter.getSubCounterTable("ElectronSelection").format(cellFormat)) # printAndSave(eventCounter.getSubCounterTable("top").format(cellFormat)) out.close()
def doCounters(datasets): eventCounter = counter.EventCounter(datasets) eventCounter.normalizeMCByLuminosity() # eventCounter.normalizeMCToLuminosity(73) print "============================================================" print "Main counter (MC normalized by collision data luminosity)" mainTable = eventCounter.getMainCounterTable() # No uncertainties cellFormat = counter.TableFormatText(cellFormat=counter.CellFormatText( valueOnly=True)) print mainTable.format(cellFormat) print eventCounter.getSubCounterTable("b-tagging").format(cellFormat) print eventCounter.getSubCounterTable("Jet selection").format(cellFormat) print eventCounter.getSubCounterTable("Jet main").format(cellFormat)
def doCounters(myDsetMgr, mySuffix): eventCounter = counter.EventCounter(myDsetMgr) # append row from the tree to the main counter # eventCounter.getMainCounter().appendRow("MET > 70", treeDraw.clone(selection="met_p4.Et() > 70")) ewkDatasets = [ "WJets", "W1Jets", "W2Jets", "W3Jets", "W4Jets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson" ] if mcOnly: eventCounter.normalizeMCToLuminosity(mcOnlyLumi) else: eventCounter.normalizeMCByLuminosity() print "============================================================" print mySuffix print "============================================================" print "Main counter (MC normalized by collision data luminosity)" mainTable = eventCounter.getMainCounterTable() mainTable.insertColumn( 2, counter.sumColumn( "EWKMCsum", [mainTable.getColumn(name=name) for name in ewkDatasets])) # Default # cellFormat = counter.TableFormatText() # No uncertainties cellFormat = counter.TableFormatText(cellFormat=counter.CellFormatText( valueOnly=False)) print mainTable.format(cellFormat) # print eventCounter.getSubCounterTable("tauIDTauSelection").format() print eventCounter.getSubCounterTable( "TauIDPassedEvt::TauSelection_HPS").format(cellFormat) print eventCounter.getSubCounterTable( "TauIDPassedJets::TauSelection_HPS").format(cellFormat) print eventCounter.getSubCounterTable("b-tagging").format(cellFormat) print eventCounter.getSubCounterTable("Jet selection").format(cellFormat) print eventCounter.getSubCounterTable("Jet main").format(cellFormat) print eventCounter.getSubCounterTable("VetoTauSelection").format( cellFormat) print eventCounter.getSubCounterTable("MuonSelection").format(cellFormat) print eventCounter.getSubCounterTable("MCinfo for selected events").format( cellFormat) print eventCounter.getSubCounterTable("ElectronSelection").format( cellFormat)
def printCounters(datasets): print "============================================================" print "Dataset info: " datasets.printInfo() eventCounter = counter.EventCounter(datasets) selection = "Sum$(%s) >= 1" % muonKinematics selection = "Sum$(%s && %s) >= 1" % (muonKinematics, muondB) selection = "Sum$(%s && %s && %s) >= 1" % (muonKinematics, muondB, muonIsolation) selection = "Sum$(%s && %s && %s) == 1" % (muonKinematics, muondB, muonIsolation) selection += "&&" + muonVeto selection += "&&" + electronVeto selection += "&&" + jetSelection eventCounter.getMainCounter().appendRow( "Selected control sample", treeDraw.clone(selection=selection)) eventCounter.normalizeMCByLuminosity() table = eventCounter.getMainCounterTable() mcDatasets = filter(lambda n: n != "Data", table.getColumnNames()) table.insertColumn( 1, counter.sumColumn("MCSum", [table.getColumn(name=name) for name in mcDatasets])) table.keepOnlyRows("Selected control sample") # reorder columns qcd = table.getColumn(name="QCD_Pt20_MuEnriched") table.removeColumn(table.getColumnNames().index("QCD_Pt20_MuEnriched")) table.insertColumn(5, qcd) table.transpose() # result = counter.CounterTable() # def addRow(name, value): # result.appendRow(counter.CounterRow(name, ["Number of events"], [value])) # for name in ["Data", "MCSum", "WJets", "TTJets", "DYJetsToLL", "QCD_Pt20_MuEnriched", "SingleTop", "Diboson"]: # addRow(name, table.getColumn(name=name).getCount(0)) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.1f')) print table.format(cellFormat)
def doCounters(datasetsEmb): eventCounter = result.EventCounterMany(datasetsEmb, counters=analysisEmb + counters, scaleNormalization=True) mainTable = eventCounter.getMainCounterTable() ewkDatasets = ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"] def ewkSum(table): table.insertColumn( 1, counter.sumColumn( "EWKMCsum", [table.getColumn(name=name) for name in ewkDatasets])) ewkSum(mainTable) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.3f')) print mainTable.format(cellFormat)
def doCountersOld(datasetsEmb, counterName="counter"): datasetNames = datasetsEmb.getAllDatasetNames() table = counter.CounterTable() for name in datasetNames: table.appendColumn( datasetsEmb.getCounter( name, analysisEmb + "Counters/weighted/" + counterName)) ewkDatasets = ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"] table.insertColumn( 2, counter.sumColumn("EWKMCsum", [table.getColumn(name=name) for name in ewkDatasets])) print "============================================================" if isinstance(datasetsEmb, result.DatasetsDYCorrection): print "DY correction applied" cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.3f')) print table.format(cellFormat)
def doCounters(datasets): # Create EventCounter object, holds all counters of all datasets eventCounter = counter.EventCounter(datasets) # Normalize counters if mcOnly: eventCounter.normalizeMCToLuminosity(mcOnlyLumi) else: eventCounter.normalizeMCByLuminosity() # Create LaTeX format, automatically adjust value precision by uncertainty latexFormat = counter.TableFormatLaTeX( counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2)) plainFormat = counter.TableFormatText( counter.CellFormatText(valueOnly=True)) #table = eventCounter.getMainCounterTable() #print table.format() table = eventCounter.getSubCounterTable("FullHiggsMassCalculator") #table.renameRows(counterLabels) print table.format(latexFormat)
def printCounters(datasets): eventCounter = counter.EventCounter(datasets) eventCounter.normalizeMCByLuminosity() ewkDatasets = ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"] print "============================================================" print "Main counter (MC normalized by collision data luminosity)" mainTable = eventCounter.getMainCounterTable() mainTable.insertColumn( 2, counter.sumColumn( "EWKMCsum", [mainTable.getColumn(name=name) for name in ewkDatasets])) # Default # cellFormat = counter.TableFormatText() # No uncertainties cellFormat = counter.TableFormatText(cellFormat=counter.CellFormatText( valueOnly=True)) print mainTable.format(cellFormat) print eventCounter.getSubCounterTable("MCinfo for selected events").format( cellFormat)
def doCountersResidual(datasetsResidual): eventCounter = result.EventCounterResidual(datasetsResidual, counters=analysisEmb + counters) mainTable = eventCounter.getMainCounterTable() names = ["Data", "DYJetsToLL residual", "WW residual"] mainTable.insertColumn( 1, counter.sumColumn("Data+residual", [mainTable.getColumn(name=name) for name in names])) if "EWKMC" in datasetsResidual.getAllDatasetNames(): names = ["EWKMC", "DYJetsToLL residual", "WW residual"] mainTable.insertColumn( 3, counter.sumColumn( "EWKMC+residual", [mainTable.getColumn(name=name) for name in names])) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.3f')) print mainTable.format(cellFormat)
def main(): dirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.dirEmbs[1:]] # dirEmbs = dirEmbs[:2] tauEmbedding.normalize=True tauEmbedding.era = "Run2011A" table = counter.CounterTable() for i in xrange(len(dirEmbs)): tmp = dirEmbs[:] del tmp[i] row = doCounters(tmp) row.setName("Removed embedding %d"%i) table.appendRow(row) arows = [] arows.append(counter.meanRow(table)) arows.append(counter.maxRow(table)) arows.append(counter.minRow(table)) arows.append(counter.subtractRow("Max-mean", arows[1], arows[0])) arows.append(counter.subtractRow("Mean-min", arows[0], arows[2])) for r in arows: table.appendRow(r) cellFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.3f')) print "DeltaPhi < 160" print print table.format(cellFormat) print print # Format the table as in AN ftable = counter.CounterTable() def addRow(name): col = table.getColumn(name=name) minimum = col.getCount(name="Min") maximum = col.getCount(name="Max") # Maximum deviation from average dev1 = col.getCount(name="Max-mean") dev2 = col.getCount(name="Mean-min") if dev2.value() > dev1.value(): dev1 = dev2 dev1.divide(col.getCount(name="Mean")) dev1.multiply(dataset.Count(100)) ftable.appendRow(counter.CounterRow(name, ["Minimum", "Maximum", "Largest deviation from average (%)"], [minimum, maximum, dev1])) addRow("Data") addRow("EWKMCsum") addRow("TTJets") addRow("WJets") addRow("DYJetsToLL") addRow("SingleTop") addRow("Diboson") cellFormat2 = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2)) cellFormat2.setColumnFormat(counter.CellFormatTeX(valueFormat="%.1f", valueOnly=True), index=2) print ftable.format(cellFormat2)
def main(): dirEmbs = result.dirEmbs[:] if onlyWjets: dirEmbs.extend(dirEmbsWjets) dirEmbs = ["."] + [os.path.join("..", d) for d in dirEmbs[1:]] # dirEmbs = dirEmbs[0:2] style = tdrstyle.TDRStyle() tauEmbedding.normalize = normalize tauEmbedding.era = "Run2011A" ts = dataset.TreeScan(analysisEmb + "/tree", function=None, selection=And(metCut, bTaggingCut, deltaPhi160Cut)) def printPickEvent(f, tree): f.write("%d:%d:%d\n" % (tree.run, tree.lumi, tree.event)) table = counter.CounterTable() for i, d in enumerate(dirEmbs): datasets = dataset.getDatasetsFromMulticrabCfg( cfgfile=d + "/multicrab.cfg", counters=analysisEmb + "Counters") if onlyWjets: datasets.remove( filter(lambda n: n != "WJets_TuneZ2_Summer11", datasets.getAllDatasetNames())) else: if mcEvents: datasets.remove( filter( lambda n: n != "WJets_TuneZ2_Summer11" and n != "TTJets_TuneZ2_Summer11" and not "SingleMu" in n, datasets.getAllDatasetNames())) datasets.loadLuminosities() datasets.remove( filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames())) datasets.remove( filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames())) tauEmbedding.updateAllEventsToWeighted(datasets) plots.mergeRenameReorderForDataMC(datasets) # for ds in datasets.getAllDatasets(): # f = open("pickEvents_%s_%d.txt" % (ds.getName(), i), "w") # ds.getDatasetRootHisto(ts.clone(function=lambda tree: printPickEvent(f, tree))) # f.close() row = doCounters(datasets) row.setName("Embedding %d" % i) table.appendRow(row) doPlots(table) arows = [] arows.append(counter.meanRow(table)) arows.extend(counter.meanRowFit(table)) arows.append(counter.maxRow(table)) arows.append(counter.minRow(table)) for r in arows: table.appendRow(r) # csvSplitter = counter.TableSplitter([" \pm "]) # cellFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.3f'), columnSeparator=",") cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.3f')) print "DeltaPhi < 160" print print table.format(cellFormat)
def doCounters(datasets): # Counters eventCounter = counter.EventCounter(datasets, counters=counters) mainCounter = eventCounter.getMainCounter() selectionsCumulative = [] tauSelectionsCumulative = [] td = treeDraw.clone(weight="") def sel(name, selection): selectionsCumulative.append(selection) sel = selectionsCumulative[:] if len(tauSelectionsCumulative) > 0: sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)] mainCounter.appendRow(name, td.clone(selection="&&".join(sel))) def tauSel(name, selection): tauSelectionsCumulative.append(selection) sel = selectionsCumulative[:] if len(tauSelectionsCumulative) > 0: sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)] mainCounter.appendRow(name, td.clone(selection="&&".join(sel))) sel("Primary vertex", pvSelection) sel(">= 1 tau candidate", "Length$(taus_p4) >= 1") tauSel("Decay mode finding", decayModeFinding) tauSel("pT > 15", "(taus_p4.Pt() > 15)") tauSel("pT > 40", tauPtCut) # tauSel("eta < 2.1", tauEtaCut) tauSel("leading track pT > 20", tauLeadPt) tauSel("ECAL fiducial", ecalFiducial) tauSel("againstElectron", electronRejection) # tauSel("againstMuon", muonRejection) tauSel("isolation", tightIsolation) # tauSel("oneProng", oneProng) # tauSel("Rtau", rtau) # sel("3 jets", jetEventSelection) sel("MET", metSelection) sel("btag", btagEventSelection) sel("deltaPhi<160", deltaPhi160Selection) fullSelection = "&&".join( selectionsCumulative + ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]) fullSelectionCaloMetNoHF = fullSelection + "&&" + caloMetNoHF fullSelectionCaloMet = fullSelection + "&&" + caloMet #print fullSelection f = open("pickEvents.txt", "w") def printPickEvent(tree): f.write("%d:%d:%d\n" % (tree.run, tree.lumi, tree.event)) ts = dataset.TreeScan(td.tree, function=printPickEvent, selection=fullSelection) ts2 = dataset.TreeScan(td.tree, function=printPickEvent, selection=fullSelectionCaloMetNoHF) ts3 = dataset.TreeScan(td.tree, function=printPickEvent, selection=fullSelectionCaloMet) ts4 = dataset.TreeDrawCompound( ts2, { "SingleMu_Mu_170722-172619_Aug05": ts3, "SingleMu_Mu_172620-173198_Prompt": ts3, "SingleMu_Mu_173236-173692_Prompt": ts3, }) datasets.getDataset("Data").getDatasetRootHisto(ts4) f.close() ewkDatasets = [ "WJets", "TTJets", # "DYJetsToLL", "SingleTop", "Diboson" ] eventCounter.normalizeMCByLuminosity() mainTable = eventCounter.getMainCounterTable() #mainTable.insertColumn(2, counter.sumColumn("EWKMCsum", [mainTable.getColumn(name=name) for name in ewkDatasets])) cellFormat = counter.TableFormatText( counter.CellFormatText(valueFormat='%.3f', #valueOnly=True ), # columnSeparator = ";", ) print mainTable.format(cellFormat) return effFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.4f')) effTable = counter.CounterTable() col = table.getColumn(name="Data") effTable.appendColumn(col) effTable.appendColumn(counter.efficiencyColumn(col.getName() + " eff", col)) col = table.getColumn(name="EWKMCsum") effTable.appendColumn(col) effTable.appendColumn(counter.efficiencyColumn(col.getName() + " eff", col)) print effTable.format(effFormat)
print "============================================================" print "Main counter (MC normalized by collision data luminosity)" print eventCounter.getMainCounterTable().format() # Example how to print all subcounter names for subCounterName in eventCounter.getSubCounterNames(): print "============================================================" print "Subcounter %s (MC normalized by collision data luminosity)" % subCounterName print eventCounter.getSubCounterTable(subCounterName).format() print "============================================================" print "Main counter (examples of the same table)" # Change the value format (printf style) print eventCounter.getMainCounterTable().format( counter.TableFormatText(counter.CellFormatText(valueFormat="%.1f"))) # No uncertainties print eventCounter.getMainCounterTable().format( counter.TableFormatText( counter.CellFormatText(valueFormat="%.0e", valueOnly=True))) # LaTeX table (tabular), default format print eventCounter.getMainCounterTable().format(counter.TableFormatLaTeX()) # LaTeX table, change value and uncertainty formats print eventCounter.getMainCounterTable().format( counter.TableFormatLaTeX( counter.CellFormatTeX(valueFormat="%.2e", uncertaintyFormat="%.1e", uncertaintyPrecision=1)))
def doCounters(datasetsEmb): # All embedded events eventCounterAll = counter.EventCounter( datasetsEmb.getFirstDatasetManager(), counters=analysisEmbAll + counters) eventCounterAll.normalizeMCByLuminosity() tableAll = eventCounterAll.getMainCounterTable() tableAll.keepOnlyRows([ "All events", ]) tableAll.renameRows({"All events": "All embedded events"}) # Mu eff + Wtau mu eventCounterMuEff = counter.EventCounter( datasetsEmb.getFirstDatasetManager(), counters=analysisEmbNoTauEff + counters) eventCounterMuEff.normalizeMCByLuminosity() tauEmbedding.scaleNormalization(eventCounterMuEff) tableMuEff = eventCounterMuEff.getMainCounterTable() tableMuEff.keepOnlyRows(["All events"]) tableMuEff.renameRows({"All events": "mu eff + Wtaumu"}) # Event counts after embedding normalization, before tau trigger eff, # switch to calculate uncertainties of the mean of 10 trials eventCounterNoTauEff = tauEmbedding.EventCounterMany( datasetsEmb, counters=analysisEmbNoTauEff + counters) tableNoTauEff = eventCounterNoTauEff.getMainCounterTable() tableNoTauEff.keepOnlyRows([ "Trigger and HLT_MET cut", "njets", ]) tableNoTauEff.renameRows({ "Trigger and HLT_MET cut": "caloMET > 60", "njets": "tau ID" }) # Event counts after tau trigger eff eventCounter = tauEmbedding.EventCounterMany(datasetsEmb, counters=analysisEmb + counters) table = eventCounter.getMainCounterTable() table.keepOnlyRows([ "njets", "MET", "btagging scale factor", "deltaPhiTauMET<160", "deltaPhiTauMET<130" ]) table.renameRows({ "njets": "Tau trigger efficiency", "btagging scale factor": "b tagging" }) # Combine the rows to one table result = counter.CounterTable() for tbl in [tableAll, tableMuEff, tableNoTauEff, table]: for iRow in xrange(tbl.getNrows()): result.appendRow(tbl.getRow(index=iRow)) addMcSum(result) cellFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2)) print result.format(cellFormat)
def process(datasets, datasetName, postfix, countName): # Handle counter eventCounter = counter.EventCounter(datasets) mainTable = eventCounter.getMainCounterTable() neventsCount = mainTable.getCount(rowName=countName, colName=datasetName) nevents = neventsCount.value() # column = eventCounter.getSubCounterTable("Classification"+postfix).getColumn(name=datasetName) # # columnFraction = column.clone() # columnFraction.setName("Fraction (%)") # # # Consistency check, and do the division # tmp = 0 # for irow in xrange(column.getNrows()): # tmp += column.getCount(irow).value() # # frac = dataset.divideBinomial(columnFraction.getCount(irow), neventsCount) # frac.multiply(dataset.Count(100)) # columnFraction.setCount(irow, frac) # # if int(nevents) != int(tmp): # raise Exception("Consistency check failed: nevents = %d, tmp = %d" % (int(nevents), int(tmp))) # table = counter.CounterTable() # table.appendColumn(column) # table.appendColumn(columnFraction) # cellFormat = counter.CellFormatText(valueFormat='%.4f', withPrecision=2) tableFormat = counter.TableFormatText(cellFormat) print print "Dataset %s, step %s, nevents %d" % (datasetName, postfix, int(nevents)) print table.format(tableFormat) # Make plots dset = datasets.getDataset(datasetName) tmp = Counts() oldCanvasDefW = ROOT.gStyle.GetCanvasDefW() ROOT.gStyle.SetCanvasDefW(int(oldCanvasDefW*1.5)) # (tauID, leptonVeto) def usualRejected(obj2): _tauIDLabels = tauIDLabels(obj2) ret = [("None", "None"), ("None", "#tau_{1}")] ret.extend([(x, "#tau_{1}") for x in _tauIDLabels[4:]]) ret.extend([(x, obj2) for x in _tauIDLabels]) ret.extend([(x, "Other") for x in _tauIDLabels]) return ret usualEmbedding = [("#tau_{1}", "None"), ("#tau_{1}+other (corr. sel.)", "None")] def usualFakeTau(obj2): return [(x, "None") for x in tauIDLabels(obj2)[4:]] doubleFakeTau = [("Other", "None")] usualCase1 = [(x, "#tau_{1}") for x in tauIDLabels("")[1:4]] usualCase3 = [("#tau_{1}+other (wrong sel.)", "None")] embCase4 = [(x, "None") for x in tauIDLabels("")[1:4]] def doubleCase2(obj2): return [(obj2, "None"), (obj2+"+other", "None")] selectionStep = {"Before": "", "AfterJetSelection": "passJetSelection", "AfterMET": "passMET", "AfterBTag": "passBTag", "AfterAllSelections": "passDeltaPhi"}[postfix] treeDraw = dataset.TreeDraw("tree", varexp="LeptonVetoStatus:TauIDStatus >>htemp(%d,0,%d, %d,0,%d" % (Enum.tauSize, Enum.tauSize, Enum.leptonSize, Enum.leptonSize)) for name, obj2, obj2Type in [ ("tau1_electron2", "e_{2}", Enum.obj2Electron), ("tau1_quark2", "q_{2}", Enum.obj2Quark), ("tau1_muon2_nonEmb", "#mu_{2}", Enum.obj2Muon), ]: tmp += calculatePlot(dset, neventsCount, name, postfix, treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%obj2Type, selectionStep), binLabelsX=tauIDLabels(obj2), binLabelsY=leptonVetoLabels(obj2)), rejected=usualRejected(obj2), embedding=usualEmbedding, faketau=usualFakeTau(obj2), case1=usualCase1, case3=usualCase3) tmp += calculatePlot(dset, neventsCount, "tau1_muon2_Emb", postfix, treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%Enum.obj2MuonEmb, selectionStep), binLabelsX=tauIDLabels("#mu_{2}"), binLabelsY=leptonVetoLabels("#mu_{2}")), rejected=usualRejected("#mu_{2}")+usualCase1, faketau=usualFakeTau("#mu_{2}"), case4=embCase4) # createMuon2Plot(dset, "tau1_muon2_Emb", postfix) for name, obj2, obj2Type in [ ("tau1_tau2_notInAcceptance", "#tau_{2}", Enum.obj2TauNotInAcceptance), ("tau1_tauh2", "#tau_{h,2}", Enum.obj2Tauh), ("tau1_taue2", "#tau_{e,2}", Enum.obj2Taue), ("tau1_taumu2_nonEmb", "#tau_{#mu,2}", Enum.obj2Taumu), ]: tmp += calculatePlot(dset, neventsCount, name, postfix, treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%obj2Type, selectionStep), binLabelsX=tauIDLabels(obj2), binLabelsY=leptonVetoLabels(obj2)), rejected=usualRejected(obj2), embedding=usualEmbedding, faketau=doubleFakeTau, case1=usualCase1, case3=usualCase3, case2=doubleCase2(obj2)) tmp += calculatePlot(dset, neventsCount, "tau1_taumu2_Emb", postfix, treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%Enum.obj2TaumuEmb, selectionStep), binLabelsX=tauIDLabels("#tau_{#mu,2}"), binLabelsY=leptonVetoLabels("#tau_{#mu,2}")), rejected=usualRejected("#tau_{#mu,2}")+usualCase1, faketau=doubleFakeTau, case4=embCase4) ROOT.gStyle.SetCanvasDefW(oldCanvasDefW) ## Ntuple stuff embeddingSelection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonNone, Or(*["TauIDStatus == %d" % x for x in [Enum.tauTau1, Enum.tauTau1OtherCorrect]])) for obj2 in [Enum.obj2Electron, Enum.obj2Quark, Enum.obj2Muon, Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]]) case1Selection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonTau1, Or(*["TauIDStatus == %d" % x for x in [Enum.tauTau1, Enum.tauTau1OtherCorrect, Enum.tauTau1OtherWrong]])) for obj2 in [Enum.obj2Electron, Enum.obj2Quark, Enum.obj2Muon, Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]]) case2Selection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonNone, Or(*["TauIDStatus == %d" % x for x in [Enum.tauObj2, Enum.tauObj2Other]])) for obj2 in [Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]]) embeddingSelection = And(selectionStep, embeddingSelection) case1Selection = And(selectionStep, case1Selection) case2Selection = And(selectionStep, case2Selection) createTransverseMassPlot(dset, "case1", postfix, nominalSelection=embeddingSelection, compareSelection=case1Selection, nominalLegend="Embedding (correct)", compareLegend="Case 1") createTransverseMassPlot(dset, "case2", postfix, nominalSelection=embeddingSelection, compareSelection=case2Selection, nominalLegend="Embedding (correct)", compareLegend="Case 2") # plotNames = [ # "tau1_electron2", # "tau1_quark2", # "tau1_muon2_nonEmb", # "tau1_muon2_Emb", # "tau1_tau2_notInAcceptance", # "tau1_tauh2", # "tau1_taue2", # "tau1_taumu2_nonEmb", # "tau1_taumu2_Emb" # ] # for name in plotNames: # tmp += calculatePlot(dset, neventsCount, name, postfix) if int(nevents) != int(tmp.all): raise Exception("Consistency check failed: nevents = %d, tmp = %d" % (int(nevents), int(tmp.all))) tmp.printResults() print tmp.printLegend() tmp.crossCheck() allEmbeddingIncluded = int(tmp.embedding) + int(tmp.case1) + int(tmp.case3) print print "So, the number of events included by embedding is %d" % allEmbeddingIncluded print "Of these," frac = dataset.divideBinomial(dataset.Count(int(tmp.embedding)), dataset.Count(allEmbeddingIncluded)) frac.multiply(dataset.Count(100)) print " * %d (%s %%) are included correctly" % (int(tmp.embedding), cellFormat.format(frac)) frac = dataset.divideBinomial(dataset.Count(int(tmp.case3)), dataset.Count(allEmbeddingIncluded)) frac.multiply(dataset.Count(100)) print " * %d (%s %%) are included correctly, but wrong object is chosen as tau_h" % (int(tmp.case3), cellFormat.format(frac)) frac = dataset.divideBinomial(dataset.Count(int(tmp.case1)), dataset.Count(allEmbeddingIncluded)) frac.multiply(dataset.Count(100)) print " * %d (%s %%) are included incorrectly (tau_1 identified in lepton veto)" % (int(tmp.case1), cellFormat.format(frac)) print "In addition, the following events are incorrectly rejected" # Note that these ratios are NOT binomial! # Although apparently, in practice, the result is the same #frac = dataset.divideBinomial(dataset.Count(int(tmp.case2)), dataset.Count(allEmbeddingIncluded)) frac = dataset.Count(tmp.case2, math.sqrt(tmp.case2)) frac.divide(dataset.Count(allEmbeddingIncluded, math.sqrt(allEmbeddingIncluded))) frac.multiply(dataset.Count(100)) print " * %d (%s %%): tau_1 not identified as tau_h, but decay of tau_2 would be" % (int(tmp.case2), cellFormat.format(frac)) #frac = dataset.divideBinomial(dataset.Count(int(tmp.case4)), dataset.Count(allEmbeddingIncluded)) frac = dataset.Count(tmp.case4, math.sqrt(tmp.case4)) frac.divide(dataset.Count(allEmbeddingIncluded, math.sqrt(allEmbeddingIncluded))) frac.multiply(dataset.Count(100)) print " * %d (%s %%): mu_2 would be accepted for embedding, and is not identified in lepton veto" % (int(tmp.case4), cellFormat.format(frac))
def doCounters(datasets, MyCuts, MyCutsName): ### Define the counters to be used #eventCounter = counter.EventCounter(datasets, counters=myAnalysis + myDataEra + "/counters") eventCounter = counter.EventCounter(datasets) ### Normalise the MC sample to a luminosity before creating a table eventCounter.normalizeMCToLuminosity(GetLumi(datasets)) myRowNames = [] for iCut, iCutName in zip(MyCuts, MyCutsName): #print "*** Cut: %s\n*** CutName: %s" % (iCut, iCutName) print "*** Processing TCut with:\n Name = \"%s\" \n Expr = \"%s\"" % ( iCutName, iCut) ### Define the event "weight" to be used EvtWeight = GetEventWeight(iCut) ### Define the TTree to be used treePath = "tree" # treePath = myAnalysis+"/tree" treeDraw = dataset.TreeDraw(treePath, weight=EvtWeight, selection=iCut) ### Append custom rows to the event counter. An asterisk denotes that the counter row was added. Informative and makes things easier myRowName = iCutName #"*" + iCutName myRowNames.append(myRowName) eventCounter.getMainCounter().appendRow(myRowName, treeDraw) ### Get table with all default rows removed and manage the table format myTable = GetCustomTable(eventCounter, myRowNames) if getBool("bMergeEwk"): DataMinusEwkMc = counter.subtractColumn( "DataMinusEwkMc", myTable.getColumn(name="Data"), myTable.getColumn(name="EWK MC")) QcdPurity = counter.divideColumn("QCD Purity", DataMinusEwkMc, myTable.getColumn(name="Data")) myTable.appendColumn(QcdPurity) ### See http://docs.python.org/2/library/string.html for string format cellTextFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.2E', valueOnly=True)) #%.2e cellLaTeXFormat = counter.TableFormatLaTeX( counter.CellFormatTeX(valueFormat='%.2E', valueOnly=True)) #%.2e purityFormat = counter.CellFormatTeX(valueFormat='%.2f', valueOnly=True) ### Customise the "QCD Purity" column cellTextFormat.setColumnFormat(purityFormat, name="QCD Purity") #does nothing cellLaTeXFormat.setColumnFormat(purityFormat, name="QCD Purity") #does nothing # between construction of table format and table format ### Print the final table with the desired format print "============================================================" print "Data-Era: %s (%s pb-1)" % (myDataEra, GetLumi(datasets)) print "============================================================" print myTable.format(cellTextFormat) print "============================================================" print "Data-Era: %s (%s pb-1)" % (myDataEra, GetLumi(datasets)) print "============================================================" print myTable.format(cellLaTeXFormat) return
def doPlots(datasetsEmb, datasetsSig, datasetName): lumi = datasetsEmb.getDataset("Data").getLuminosity() plots._legendLabels[datasetName+"_Embedded"] = "Embedded "+plots._legendLabels[datasetName] plots._legendLabels[datasetName+"_Normal"] = "Normal "+plots._legendLabels[datasetName] def createPlot(name): name2Emb = name name2Sig = name if isinstance(name, basestring): name2Emb = analysisEmb+"/"+name name2Sig = analysisSig+"/"+name else: name2Emb = name.clone(tree=analysisEmb+"/tree") name2Sig = name.clone(tree=analysisSig+"/tree") emb = datasetsEmb.getDataset(datasetName).getDatasetRootHisto(name2Emb) emb.setName("Embedded") sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig) sig.setName("Normal") p = plots.ComparisonPlot(emb, sig) p.histoMgr.normalizeMCToLuminosity(lumi) p.histoMgr.setHistoLegendLabelMany({ "Embedded": "Embedded "+plots._legendLabels[datasetName], "Normal": "Normal "+plots._legendLabels[datasetName], }) p.histoMgr.forEachHisto(styles.generator()) return p opts2 = {"ymin": 0, "ymax": 2} def drawControlPlot(path, xlabel, **kwargs): drawPlot(createPlot("ControlPlots/"+path), "mcembsig_"+datasetName+"_"+path, xlabel, opts2=opts2, **kwargs) # Control plots drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={"cutValue": 40, "greaterThan": 40}) drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts={"xmin": -2.2, "xmax": 2.2}, ylabel="Events / %.1f", rebin=4, log=False, moveLegend={"dy":-0.6, "dx":-0.2}) drawControlPlot("SelectedTau_phi_AfterStandardSelections", "#tau-jet #phi", rebin=10, ylabel="Events / %.2f", log=False) drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts={"xmax": 300}, rebin=2, cutBox={"cutValue": 20, "greaterThan": True}) drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts={"xmin": 0.65, "xmax": 1.05, "ymin": 1e-1, "ymaxfactor": 5}, rebin=5, ylabel="Events / %.2f", moveLegend={"dx":-0.3}, cutBox={"cutValue":0.7, "greaterThan":True}) drawControlPlot("SelectedTau_p_AfterStandardSelections", "#tau-jet p (GeV/c)", rebin=2) drawControlPlot("SelectedTau_LeadingTrackP_AfterStandardSelections", "#tau-jet ldg. charged particle p (GeV/c)", rebin=2) #drawControlPlot("IdentifiedElectronPt_AfterStandardSelections", "Electron p_{T} (GeV/c)") #drawControlPlot("IdentifiedMuonPt_AfterStandardSelections", "Muon p_{T} (GeV/c)") drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") drawControlPlot("MET", "Uncorredted PF E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50) drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", moveLegend={"dx":-0.3, "dy":-0.5}, cutLine=1) treeDraw = dataset.TreeDraw("dummy", weight="weightPileup") tdDeltaPhi = treeDraw.clone(varexp="acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 >>tmp(18, 0, 180)") tdMt = treeDraw.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,200)") # DeltaPhi xlabel = "#Delta#phi(#tau, MET) (^{#circ})" def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8*yaxis.GetTitleOffset()) drawPlot(createPlot(tdDeltaPhi.clone()), "mcembsig_"+datasetName+"_deltaPhi_1AfterTauID", xlabel, log=False, opts2=opts2, ylabel="Events / %.0f^{#circ}", function=customDeltaPhi, moveLegend={"dx":-0.22}, cutLine=[130, 160]) # mT xlabel = "m_{T} (#tau jet, E_{T}^{miss}) (GeV/c^{2})" drawPlot(createPlot(tdMt.clone()), "mcembsig_"+datasetName+"_transverseMass_1AfterTauID", xlabel, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}") # After all cuts metCut = "(met_p4.Et() > 50)" bTaggingCut = "passedBTagging" selection = "&&".join([metCut, bTaggingCut]) drawPlot(createPlot(treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), "mcembsig_"+datasetName+"_selectedTauPt_3AfterBTagging", "#tau-jet p_{T} (GeV/c)", opts2={"ymin": 0, "ymax": 2}) drawPlot(createPlot(treeDraw.clone(varexp="met_p4.Pt() >>tmp(16,0,400)", selection=selection)), "mcembsig_"+datasetName+"_MET_3AfterBTagging", "E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", opts2={"ymin": 0, "ymax": 2}) drawPlot(createPlot(tdMt.clone(selection=selection)), "mcembsig_"+datasetName+"_transverseMass_3AfterBTagging", xlabel, opts2={"ymin": 0, "ymax": 2}, ylabel="Events / %.0f GeV/c^{2}") eventCounterEmb = counter.EventCounter(datasetsEmb, counters=analysisEmb+"Counters") eventCounterSig = counter.EventCounter(datasetsSig, counters=analysisSig+"Counters") eventCounterEmb.normalizeMCToLuminosity(lumi) eventCounterSig.normalizeMCToLuminosity(lumi) #effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.4f')) #effFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat='%.4f')) effFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.4f')) for function, cname in [ (lambda c: c.getMainCounterTable(), "Main"), (lambda c: c.getSubCounterTable("TauIDPassedEvt::tauID_HPSTight"), "Tau") ]: tableEmb = function(eventCounterEmb) tableSig = function(eventCounterSig) table = counter.CounterTable() col = tableEmb.getColumn(name=datasetName) col.setName("Embedded") table.appendColumn(col) col = tableSig.getColumn(name=datasetName) col.setName("Normal") table.appendColumn(col) print "%s counters" % cname print table.format() if cname == "Main": #map(lambda t: t.keepOnlyRows([ table.keepOnlyRows([ "All events", "Trigger and HLT_MET cut", "taus == 1", #"trigger scale factor", "electron veto", "muon veto", "MET", "njets", "btagging", "btagging scale factor", "JetsForEffs", "METForEffs", "BTagging", "DeltaPhi < 160", "DeltaPhi < 130" ])#, [tableEmb, tableSig]) else: #map(lambda t: t.keepOnlyRows([ table.keepOnlyRows([ "AllTauCandidates", "DecayModeFinding", "TauJetPt", "TauJetEta", #"TauLdgTrackExists", "TauLdgTrackPtCut", "TauECALFiducialCutsCracksAndGap", "TauAgainstElectronCut", "TauAgainstMuonCut", #"EMFractionCut", "HPS", "TauOneProngCut", "TauRtauCut", ])#, [tableEmb, tableSig]) col = table.getColumn(name="Embedded") table.insertColumn(1, counter.efficiencyColumn(col.getName()+" eff", col)) col = table.getColumn(name="Normal") table.appendColumn(counter.efficiencyColumn(col.getName()+" eff", col)) print "%s counters" % cname print table.format(effFormat)
def printCountersOld(datasets, datasetsMC, analysisPrefix, normalizeToLumi=None): print "============================================================" print "Dataset info: " datasets.printInfo() eventCounter = makeEventCounter(datasets) if normalizeToLumi == None: eventCounter.normalizeMCByLuminosity() else: eventCounter.normalizeMCToLuminosity(normalizeToLumi) mainCounterMap = { "allEvents": "All events", "passedTrigger": "Triggered", "passedScrapingVeto": "Scaping veto", "passedHBHENoiseFilter": "HBHE noise filter", "passedPrimaryVertexFilter": "PV filter", analysisPrefix+"countAll": "All events", analysisPrefix+"countTrigger": "Triggered", analysisPrefix+"countPrimaryVertex": "Good primary vertex", analysisPrefix+"countGlobalTrackerMuon": "Global \& tracker muon", analysisPrefix+"countMuonKin": "Muon \pT, $\eta$ cuts", analysisPrefix+"countMuonQuality": "Muon quality cuts", analysisPrefix+"countMuonIP": "Muon transverse IP", analysisPrefix+"countMuonVertexDiff": "Muon dz", analysisPrefix+"countJetMultiplicityCut": "Njets", analysisPrefix+"countMETCut": "MET cut" } latexFormat = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat="%.0f")) latexFormat2 = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat="%.1f")) #latexFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat="%.0f", valueOnly=True)) print "============================================================" print "Main counter (%s)" % eventCounter.getNormalizationString() #eventCounter.getMainCounter().printCounter() table = eventCounter.getMainCounterTable() # addSumColumn(table) # addTtwFractionColumn(table) # addPurityColumn(table) # addDyFractionColumn(table) # addQcdFractionColumn(table) # reorderCounterTable(table) # print table.format() print table.format(latexFormat) # print table.format(latexFormat2) return #print "------------------------------------------------------------" #print counterEfficiency(eventCounter.getMainCounterTable()).format(FloatDecimalFormat(4)) # mainTable = eventCounter.getMainCounterTable() # effTable = counterEfficiency(mainTable) # for icol in xrange(0, effTable.getNcolumns()): # column = effTable.getColumn(icol) # column.setName(column.getName()+" eff") # mainTable.insertColumn(icol*2+1, column) # print "------------------------------------------------------------" # printCounter(mainTable, FloatDecimalFormat(4)) eventCounter = makeEventCounter(datasetsMC) print "============================================================" print "Main counter (%s)" % eventCounter.getNormalizationString() print eventCounter.getMainCounterTable().format(counter.TableFormatText(counter.CellFormatText(valueOnly=True, valueFormat="%.0f"))) # Make the Data column entries comparable to the MC table.renameRows(mainCounterMap) dataCol = table.getColumn(0) table.removeColumn(0) dataCol.removeRow(2) # scraping dataCol.removeRow(2) # HBHE dataCol.removeRow(2) # pv filter dataCol.removeRow(2) # all events dataCol.removeRow(2) # triggered table.insertColumn(0, dataCol) addDataMcRatioColumn(table) # LaTeX tables for note latexFormat.setColumnFormat(counter.CellFormatTeX(valueFormat="%.3f"), name="Data/MCsum") latexFormat.setColumnFormat(counter.CellFormatTeX(valueFormat="%.1f"), name="SingleTop") tableDataMc = counter.CounterTable() tableDataMc.appendColumn(table.getColumn(name="Data")) tableDataMc.appendColumn(table.getColumn(name="MCsum")) tableDataMc.appendColumn(table.getColumn(name="Data/MCsum")) print tableDataMc.format(latexFormat) tableMc = counter.CounterTable() #tableMc.appendColumn(table.getColumn(name="MCsum")) for mcName in datasets.getMCDatasetNames(): tableMc.appendColumn(table.getColumn(name=mcName)) print tableMc.format(latexFormat) tableRatio = counter.CounterTable() for cname in ["TTJets/(TTJets+WJets)", "Purity", "QCD/MCsum", "DY/MCsum"]: tableRatio.appendColumn(table.getColumn(name=cname)) latexFormat.setColumnFormat(counter.CellFormatTeX(valueFormat="%.2f", valueOnly=True), name=cname) print tableRatio.format(latexFormat)
def doTauCounters(datasetsEmb, datasetsSig, datasetName, ntupleCacheEmb, ntupleCacheSig, normalizeEmb=True): lumi = datasetsEmb.getLuminosity() # Take unweighted counters for embedded, to get a handle on the muon isolation efficiency eventCounterEmb = tauEmbedding.EventCounterMany( datasetsEmb, counters="/" + tauAnalysisEmb + "Counters", normalize=normalizeEmb) eventCounterSig = counter.EventCounter(datasetsSig, counters="/" + tauAnalysisEmb + "Counters") def isNotThis(name): return name != datasetName eventCounterEmb.removeColumns( filter(isNotThis, datasetsEmb.getAllDatasetNames())) eventCounterSig.removeColumns( filter(isNotThis, datasetsSig.getAllDatasetNames())) eventCounterEmb.mainCounterAppendRows( ntupleCacheEmb.histogram("counters/weighted/counter")) eventCounterSig.getMainCounter().appendRows( ntupleCacheSig.histogram("counters/weighted/counter")) eventCounterSig.normalizeMCToLuminosity(lumi) table = counter.CounterTable() col = eventCounterEmb.getMainCounterTable().getColumn(name=datasetName) col.setName("Embedded") table.appendColumn(col) col = eventCounterSig.getMainCounterTable().getColumn(name=datasetName) col.setName("Normal") table.appendColumn(col) lastCountEmb = table.getCount(colName="Embedded", irow=table.getNrows() - 1) lastCountNormal = table.getCount(colName="Normal", irow=table.getNrows() - 1) postfix = "" if not normalizeEmb: postfix = "_notEmbNormalized" effFormat = counter.TableFormatLaTeX( counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2)) countFormat = counter.TableFormatText( counter.CellFormatText(valueFormat="%.4f"), #columnSeparator=" ;" ) fname = "counters_tau_" + datasetName + postfix + ".txt" f = open(fname, "w") f.write(table.format(countFormat)) f.write("\n") try: ratio = lastCountNormal.clone() ratio.divide(lastCountEmb) f.write("Normal/embedded = %.4f +- %.4f\n\n" % (ratio.value(), ratio.uncertainty())) except ZeroDivisionError: pass f.close() print "Printed tau counters to", fname if not normalizeEmb: return tableEff = counter.CounterTable() tableEff.appendColumn( counter.efficiencyColumn("Embedded eff", table.getColumn(name="Embedded"))) tableEff.appendColumn( counter.efficiencyColumn("Normal eff", table.getColumn(name="Normal"))) embeddingMuonIsolationEff = tableEff.getCount( rowName="tauEmbeddingMuonsCount", colName="Embedded eff") embeddingTauIsolationEff = tableEff.getCount(rowName="Isolation", colName="Embedded eff") embeddingTotalIsolationEff = embeddingMuonIsolationEff.clone() embeddingTotalIsolationEff.multiply(embeddingTauIsolationEff) # Remove unnecessary rows rowNames = [ # "All events", "Decay mode finding", "Eta cut", "Pt cut", "Leading track pt", "Against electron", "Against muon", "Isolation", "One prong", "Rtau", ] tableEff.keepOnlyRows(rowNames) rowIndex = tableEff.getRowNames().index("Isolation") tableEff.insertRow( rowIndex, counter.CounterRow("Mu isolation (emb)", ["Embedded eff", "Normal eff"], [embeddingMuonIsolationEff, None])) tableEff.insertRow( rowIndex + 1, counter.CounterRow("Tau isolation (emb)", ["Embedded eff", "Normal eff"], [embeddingTauIsolationEff, None])) tableEff.setCount2(embeddingTotalIsolationEff, rowName="Isolation", colName="Embedded eff") #tableEff.setCount2(None, rowName="pT > 15", colName="Normal eff") #print table.format(effFormat) fname = "counters_tau_" + datasetName + "_eff.txt" f = open(fname, "w") f.write(tableEff.format(effFormat)) f.write("\n") f.close() print "Printed tau efficiencies to", fname
print print print "From Data" run(signalAreaEventsFactor, lambda h: h.getHisto("Data").getRootHisto()) #print #print "From all MC" #run(signalAreaEventsFactor, lambda h: h.getHisto("StackedMC").getSumRootHisto()) import sys sys.exit(0) # Table formatting tableFormat = counter.TableFormatText() for i in xrange(1, 19, 2): tableFormat.setColumnFormat(counter.CellFormatText(valueFormat="%.5f"), index=i) #tableFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueOnly=True)) def addEffs(table): eff = counter.counterEfficiency(table) colnames = eff.getColumnNames() mapping = {} for n in colnames: mapping[n] = n + "_eff" eff.renameColumns(mapping) for icol in xrange(0, eff.getNcolumns()):
def doCounters(datasetsEmb, datasetsSig, datasetName, normalizeEmb=True): lumi = datasetsEmb.getLuminosity() # Counters eventCounterEmb = tauEmbedding.EventCounterMany( datasetsEmb, normalize=normalizeEmb) #, counters=analysisEmb+"/counters") eventCounterSig = counter.EventCounter(datasetsSig) def isNotThis(name): return name != datasetName eventCounterEmb.removeColumns( filter(isNotThis, datasetsEmb.getAllDatasetNames())) eventCounterSig.removeColumns( filter(isNotThis, datasetsSig.getAllDatasetNames())) eventCounterSig.normalizeMCToLuminosity(lumi) tdCount = dataset.TreeDraw("dummy", weight=tauEmbedding.signalNtuple.weightBTagging) tdCountMET = tdCount.clone(weight=tauEmbedding.signalNtuple.weight, selection=tauEmbedding.signalNtuple.metCut) tdCountBTagging = tdCount.clone( selection=And(tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut)) tdCountDeltaPhi160 = tdCount.clone(selection=And( tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple. bTaggingCut, tauEmbedding.signalNtuple.deltaPhi160Cut)) tdCountDeltaPhi130 = tdCount.clone(selection=And( tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple. bTaggingCut, tauEmbedding.signalNtuple.deltaPhi130Cut)) def addRow(name, td): tdEmb = td.clone(tree=analysisEmb + "/tree") tdSig = td.clone(tree=analysisSig + "/tree") eventCounterEmb.mainCounterAppendRow(name, tdEmb) eventCounterSig.getMainCounter().appendRow(name, tdSig) # addRow("JetsForEffs", tdCount.clone(weight=tauEmbedding.signalNtuple.weight)) # addRow("METForEffs", tdCountMET) # addRow("BTagging (SF)", tdCountBTagging) # addRow("DeltaPhi < 160", tdCountDeltaPhi160) # addRow("BTagging (SF) again", tdCountBTagging) # addRow("DeltaPhi < 130", tdCountDeltaPhi130) table = counter.CounterTable() col = eventCounterEmb.getMainCounterTable().getColumn(name=datasetName) col.setName("Embedded") table.appendColumn(col) col = eventCounterSig.getMainCounterTable().getColumn(name=datasetName) col.setName("Normal") table.appendColumn(col) tableTau = counter.CounterTable() tmp = "TauIDPassedEvt::TauSelection_HPS" col = eventCounterEmb.getSubCounterTable(tmp).getColumn(name=datasetName) col.setName("Embedded") tableTau.appendColumn(col) col = eventCounterSig.getSubCounterTable(tmp).getColumn(name=datasetName) col.setName("Normal") tableTau.appendColumn(col) postfix = "" if not normalizeEmb: postfix = "_notEmbNormalized" fname = "counters_selections_%s%s.txt" % (datasetName, postfix) f = open(fname, "w") f.write(table.format()) f.write("\n") f.write(tableTau.format()) f.close() print "Printed selection counters to", fname if not normalizeEmb: return # Calculate efficiencies table.keepOnlyRows([ "njets", "MET", "btagging", "btagging scale factor", "DeltaPhi(Tau,MET) upper limit" ]) # btag SF efficiency w.r.t. MET row = table.getRow(name="MET") row.setName("METForEff") table.insertRow(3, row) tableEff = counter.CounterTable() tableEff.appendColumn( counter.efficiencyColumn("Embedded eff", table.getColumn(name="Embedded"))) tableEff.appendColumn( counter.efficiencyColumn("Normal eff", table.getColumn(name="Normal"))) tableEff.removeRow(name="METForEff") effFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2)) # print table.format(effFormat) fname = "counters_selections_%s_eff.txt" % datasetName f = open(fname, "w") f.write(tableEff.format(effFormat)) f.close() print "Printed selection efficiencies to", fname
def doCounters(datasetsEmb2, datasetsSig2, datasetName): lumi = datasetsEmb2.getDataset("Data").getLuminosity() datasetsEmb = datasetsEmb2.deepCopy() datasetsSig = datasetsSig2.deepCopy() datasetsEmb.remove( filter(lambda name: name != datasetName, datasetsEmb.getAllDatasetNames())) datasetsSig.remove( filter(lambda name: name != datasetName, datasetsSig.getAllDatasetNames())) # Counters eventCounterEmb = counter.EventCounter(datasetsEmb, counters=analysisEmb + "Counters") eventCounterSig = counter.EventCounter(datasetsSig, counters=analysisSig + "Counters") eventCounterEmb.normalizeMCToLuminosity(lumi) eventCounterSig.normalizeMCToLuminosity(lumi) #effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.4f')) #effFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat='%.4f')) effFormat = counter.TableFormatText( counter.CellFormatTeX(valueFormat='%.4f')) counterEmb = eventCounterEmb.getMainCounter() counterSig = eventCounterSig.getMainCounter() treeDraw = dataset.TreeDraw("dummy") tdEmb = treeDraw.clone(tree=analysisEmb + "/tree") tdSig = treeDraw.clone(tree=analysisSig + "/tree") selectionsCumulative = [] tauSelectionsCumulative = [] def sel(name, selection): selectionsCumulative.append(selection) sel = selectionsCumulative[:] if len(tauSelectionsCumulative) > 0: sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)] sel = "&&".join(sel) counterEmb.appendRow(name, tdEmb.clone(selection=sel)) counterSig.appendRow(name, tdSig.clone(selection=sel)) def tauSel(name, selection): tauSelectionsCumulative.append(selection) sel = selectionsCumulative[:] if len(tauSelectionsCumulative) > 0: sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)] sel = "&&".join(sel) counterEmb.appendRow(name, tdEmb.clone(selection=sel)) counterSig.appendRow(name, tdSig.clone(selection=sel)) # sel("Primary vertex", tauPlot.pvSelection) sel(">= 1 tau candidate", "Length$(taus_p4) >= 1") tauSel("Decay mode finding", tauPlot.decayModeFinding) tauSel("pT > 15", "(taus_p4.Pt() > 15)") tauSel("pT > 40", tauPlot.tauPtCut) tauSel("eta < 2.1", tauPlot.tauEtaCut) tauSel("leading track pT > 20", tauPlot.tauLeadPt) tauSel("ECAL fiducial", tauPlot.ecalFiducial) tauSel("againstElectron", tauPlot.electronRejection) tauSel("againstMuon", tauPlot.muonRejection) tauSel("isolation", tauPlot.tightIsolation) tauSel("oneProng", tauPlot.oneProng) tauSel("Rtau", tauPlot.rtau) sel("3 jets", tauPlot.jetEventSelection) sel("MET", tauPlot.metSelection) sel("btag", tauPlot.btagEventSelection) table = counter.CounterTable() col = counterEmb.getTable().getColumn(name=datasetName) col.setName("Embedded") table.appendColumn(col) col = counterSig.getTable().getColumn(name=datasetName) col.setName("Normal") table.appendColumn(col) col = table.getColumn(name="Embedded") table.insertColumn(1, counter.efficiencyColumn(col.getName() + " eff", col)) col = table.getColumn(name="Normal") table.appendColumn(counter.efficiencyColumn(col.getName() + " eff", col)) print "%s counters" % datasetName print table.format(effFormat)
eventCounter.normalizeMCToLuminosity(33.69) # Example how to print the main counter with the default formatting print "============================================================" print "Main counter (MC normalized by collision data luminosity)" print eventCounter.getMainCounterTable().format() # Example how to print all subcounter names for subCounterName in eventCounter.getSubCounterNames(): print "============================================================" print "Subcounter %s (MC normalized by collision data luminosity)" % subCounterName print eventCounter.getSubCounterTable(subCounterName).format() print "============================================================" print "Main counter (examples of the same table)" # Change the value format (printf style) print eventCounter.getMainCounterTable().format(counter.TableFormatText(counter.CellFormatText(valueFormat="%.1f"))) # No uncertainties print eventCounter.getMainCounterTable().format(counter.TableFormatText(counter.CellFormatText(valueFormat="%.0e", valueOnly=True))) # LaTeX table (tabular), default format print eventCounter.getMainCounterTable().format(counter.TableFormatLaTeX()) # LaTeX table, change value and uncertainty formats print eventCounter.getMainCounterTable().format(counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat="%.2e", uncertaintyFormat="%.1e", uncertaintyPrecision=1)))