Exemple #1
0
def doCounters(datasetsEmb):
    eventCounter = tauEmbedding.EventCounterMany(datasetsEmb, normalize=True)

    #row = "btagging scale factor"
    row = "deltaPhiTauMET<160"
    #row = "deltaPhiTauMET<130"
    table = eventCounter.getMainCounterTable()
    table.keepOnlyRows([row])

    result = counter.CounterTable()
    def addRow(name, newktt, nsignal):
        fraction = None
        if nsignal != None:
            fraction = nsignal.clone()
            total = nsignal.clone()
            total.add(newktt)
            fraction.divide(total)
            fraction.multiply(dataset.Count(100))
        result.appendRow(counter.CounterRow(name, ["EWK+tt events", "Signal events", "Signal fraction (\%)"], [newktt, nsignal, fraction]))
    addRow("No signal", table.getCount(irow=0, colName="EWKMC"), None)
    ewkWithSignal = table.getCount(irow=0, colName="EWKScaled")
    for mass in [80, 90, 100, 120, 140, 150, 155, 160]:
        addRow("H+ M%d"%mass, ewkWithSignal, table.getCount(irow=0, colName="TTToHplus_M%d"%mass))

    #cellFormat = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat='%.3f'))
    cellFormat = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2))
    print result.format(cellFormat)
Exemple #2
0
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()

    # Get table (counter.CounterTable) of the main counter, format it
    # with default formatting, and print
    #print eventCounter.getMainCounterTable().format()

    # Create LaTeX format, automatically adjust value precision by uncertainty
    latexFormat = counter.TableFormatLaTeX(
        counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2))

    # Get table of a subcounter, format it with a predefined format,
    # and print
    #print eventCounter.getSubCounterTable("TauIDPassedEvt::TauSelection_HPS").format(latexFormat)

    # Create EventCounter from one dataset
    eventCounter = counter.EventCounter(datasets.getAllDatasets()[0])
    if mcOnly:
        eventCounter.normalizeMCToLuminosity(mcOnlyLumi)
    else:
        eventCounter.normalizeMCByLuminosity()
Exemple #3
0
def doCounters(datasetsEmb, datasetsSig):
    rows = [
        "njets", "MET", "btagging scale factor", "deltaPhiTauMET<160",
        "deltaPhiTauMET<130"
    ]
    residuals = ["DYJetsToLL residual", "WW residual"]

    # Normal MC
    eventCounterNormal = counter.EventCounter(datasetsSig)
    eventCounterNormal.normalizeMCToLuminosity(datasetsEmb.getLuminosity())
    tableNormal = eventCounterNormal.getMainCounterTable()
    tableNormal.keepOnlyRows(rows)

    # Embedded data and MC, residual MC
    eventCounter = tauEmbedding.EventCounterResidual(datasetsEmb)
    table = eventCounter.getMainCounterTable()
    table.keepOnlyRows(rows)

    # Build the result
    result = counter.CounterTable()

    c = table.getColumn(name="Data")
    c.setName("Embedded data")
    result.appendColumn(c)
    #result.appendColumn(table.getColumn(name="EWKMC"))
    for name in residuals:
        result.appendColumn(table.getColumn(name=name))

    result.appendColumn(
        counter.sumColumn(
            "Emb. data + res. MC",
            [table.getColumn(name=name) for name in ["Data"] + residuals]))
    result.appendColumn(
        counter.sumColumn(
            "Emb. MC + res. MC",
            [table.getColumn(name=name) for name in ["EWKMC"] + residuals]))

    c = tableNormal.getColumn(name="EWKMC")
    c.setName("Normal MC")
    result.appendColumn(c)

    # Final formatting
    result.renameRows({
        "njets": "tau-jet identification",
        "btagging scale factor": "b tagging"
    })

    cellFormat = counter.TableFormatLaTeX(
        counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2))
    print result.format(cellFormat)
def main():
    dirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.dirEmbs[1:]]
    dirSig = "../" + tauEmbedding.dirSig
    #    dirEmbs = dirEmbs[:2]

    datasetsEmb = tauEmbedding.DatasetsMany(dirEmbs,
                                            analysisEmb + "/counters",
                                            normalizeMCByLuminosity=True)
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(
        cfgfile=dirSig + "/multicrab.cfg", counters=analysisSig + "/counters")
    datasetsSig.updateNAllEventsToPUWeighted()

    datasetsEmb.forEach(plots.mergeRenameReorderForDataMC)
    datasetsEmb.setLumiFromData()
    plots.mergeRenameReorderForDataMC(datasetsSig)

    def mergeEWK(datasets):
        datasets.merge(
            "EWKMC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"],
            keepSources=True)

    mergeEWK(datasetsSig)
    datasetsEmb.forEach(mergeEWK)
    plots._legendLabels["EWKMC"] = "EWK"

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    histograms.cmsText[histograms.CMSMode.SIMULATION] = "Simulation"
    histograms.createLegend.setDefaults(y1=0.93, y2=0.75, x1=0.52, x2=0.93)
    tauEmbedding.normalize = True
    tauEmbedding.era = "Run2011AB"

    table = counter.CounterTable()

    def dop(name):
        doPlots(datasetsEmb, datasetsSig, name)
        tbl = doCounters(datasetsEmb, datasetsSig, name)
        for icol in xrange(tbl.getNcolumns()):
            table.appendColumn(tbl.getColumn(icol))

    dop("TTJets")
    dop("WJets")
    dop("DYJetsToLL")
    dop("SingleTop")
    dop("Diboson")

    cellFormat = counter.TableFormatLaTeX(
        counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2))
    print table.format(cellFormat)
Exemple #5
0
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 do(onlyWjets, mcEvents, normalize, formatCounters, formatPlots):
    dirEmbs = tauEmbedding.dirEmbs[:]
    if onlyWjets:
        dirEmbs.extend(dirEmbsWjets)
    dirEmbs = ["."] + [os.path.join("..", d) for d in dirEmbs[1:]]
#    dirEmbs = dirEmbs[0:2]

    # Read luminosity
    datasets = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirEmbs[0]+"/multicrab.cfg", counters=analysisEmb+"Counters", weightedCounters=False)
    datasets.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasets)
    lumi = datasets.getDataset("Data").getLuminosity()


    style = tdrstyle.TDRStyle()
    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    histograms.cmsText[histograms.cmsTextMode] = "Simulation"

    tauEmbedding.normalize=normalize
    tauEmbedding.era = "Run2011A"

    table = counter.CounterTable()
    for i, d in enumerate(dirEmbs):
        datasets = dataset.getDatasetsFromMulticrabCfg(cfgfile=d+"/multicrab.cfg", counters=analysisEmb+"Counters", weightedCounters=False)
        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)

        row = doCounters(datasets, onlyWjets, mcEvents, normalize, lumi)
        row.setName("Embedding %d" % i)
        table.appendRow(row)

    if formatPlots:
        doPlots(table, onlyWjets, mcEvents, normalize, lumi)

    if not formatCounters:
        return

    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)

    print table.format()

    ftable = counter.CounterTable()
    def addRow(name):
        col = table.getColumn(name=name)

        minimum = col.getCount(name="Min")
        maximum = col.getCount(name="Max")
        mean = col.getCount(name="Mean")

        ftable.appendRow(counter.CounterRow(name,
                                            ["Mean", "Minimum", "Maximum"],
                                            [mean, minimum, maximum]))
    addRow("Data")
    addRow("EWKMCsum")
    addRow("TTJets")
    addRow("WJets")
    addRow("DYJetsToLL")
    addRow("SingleTop")
    addRow("Diboson")

    cellFormat2 = counter.TableFormatLaTeX(counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2))
    print ftable.format(cellFormat2)
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
Exemple #8
0
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 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)
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)))


Exemple #11
0
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)
Exemple #12
0
def doTauCounters(datasetsEmb, datasetsSig, datasetName):
    lumi = datasetsEmb.getLuminosity()
    treeDraw = dataset.TreeDraw(
        "dummy", weight=tauEmbedding.tauNtuple.weight[tauEmbedding.era])

    eventCounterEmb = tauEmbedding.EventCounterMany(datasetsEmb)
    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)

    effFormat = counter.TableFormatLaTeX(
        counter.CellFormatTeX(valueFormat="%.4f", withPrecision=2))

    tdEmb = treeDraw.clone(tree=tauAnalysisEmb + "/tree")
    tdSig = treeDraw.clone(tree=tauAnalysisSig + "/tree")
    selectionsCumulative = []
    tauSelectionsCumulative = []
    rowNames = []

    def sel(name, selection):
        selectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        eventCounterEmb.mainCounterAppendRow(name, tdEmb.clone(selection=sel))
        eventCounterSig.getMainCounter().appendRow(name,
                                                   tdSig.clone(selection=sel))
        rowNames.append(name)

    def tauSel(name, selection):
        tauSelectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        eventCounterEmb.mainCounterAppendRow(name, tdEmb.clone(selection=sel))
        eventCounterSig.getMainCounter().appendRow(name,
                                                   tdSig.clone(selection=sel))
        rowNames.append(name)

    sel(">= 1 tau candidate", "Length$(taus_p4) >= 1")
    tauSel("Decay mode finding", tauEmbedding.tauNtuple.decayModeFinding)
    tauSel("pT > 15", "taus_p4.Pt() > 15")
    tauSel("pT > 40", tauEmbedding.tauNtuple.tauPtCut)
    tauSel("eta < 2.1", tauEmbedding.tauNtuple.tauEtaCut)
    tauSel("leading track pT > 20", tauEmbedding.tauNtuple.tauLeadPt)
    tauSel("ECAL fiducial", tauEmbedding.tauNtuple.ecalFiducial)
    tauSel("againstElectron", tauEmbedding.tauNtuple.electronRejection)
    tauSel("againstMuon", tauEmbedding.tauNtuple.muonRejection)
    tauSel("isolation", tauEmbedding.tauNtuple.tightIsolation)
    tauSel("oneProng", tauEmbedding.tauNtuple.oneProng)
    tauSel("Rtau", tauEmbedding.tauNtuple.rtau)
    sel("MET", tauEmbedding.tauNtuple.metSelection)

    table = counter.CounterTable()
    col = eventCounterEmb.getMainCounterTable().getColumn(name=datasetName)
    table.appendColumn(counter.efficiencyColumn("Embedded eff", col))
    col = eventCounterSig.getMainCounterTable().getColumn(name=datasetName)
    table.appendColumn(counter.efficiencyColumn("Normal eff", col))

    embeddingMuonIsolationEff = table.getCount(
        rowName="tauEmbeddingMuonsCount", colName="Embedded eff")
    embeddingTauIsolationEff = table.getCount(rowName="isolation",
                                              colName="Embedded eff")
    embeddingTotalIsolationEff = embeddingMuonIsolationEff.clone()
    embeddingTotalIsolationEff.multiply(embeddingTauIsolationEff)

    # Remove unnecessary rows
    del rowNames[0]
    table.keepOnlyRows(rowNames)
    rowIndex = table.getRowNames().index("isolation")
    table.insertRow(
        rowIndex,
        counter.CounterRow("Mu isolation (emb)",
                           ["Embedded eff", "Normal eff"],
                           [embeddingMuonIsolationEff, None]))
    table.insertRow(
        rowIndex + 1,
        counter.CounterRow("Tau isolation (emb)",
                           ["Embedded eff", "Normal eff"],
                           [embeddingTauIsolationEff, None]))
    table.setCount2(embeddingTotalIsolationEff,
                    rowName="isolation",
                    colName="Embedded eff")
    table.setCount2(None, rowName="pT > 15", colName="Normal eff")

    #print table.format(effFormat)
    fname = "counters_tau_" + datasetName + ".txt"
    f = open(fname, "w")
    f.write(table.format(effFormat))
    f.write("\n")
    f.close()
    print "Printed tau counters to", fname