def main():
    dirEmbs = ["."] + [os.path.join("..", d) for d in result.dirEmbs[1:]]
    dirSig = "../"+result.dirSig

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

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

    datasetsEmb.remove(filter(lambda name: "HplusTB" in name, datasetsEmb.getAllDatasetNames()))

    def addSignal(datasetMgr):
        xsect.setHplusCrossSectionsToBR(datasetMgr, br_tH=0.03, br_Htaunu=1) # agreed to use 3 % as with QCD
        plots.mergeWHandHH(datasetMgr)

        ttjets2 = datasetMgr.getDataset("TTJets").deepCopy()
        ttjets2.setName("TTJets2")
        ttjets2.setCrossSection(ttjets2.getCrossSection() - datasetMgr.getDataset("TTToHplus_M120").getCrossSection())
        datasetMgr.append(ttjets2)
        datasetMgr.merge("EWKnoTT", ["WJets", "DYJetsToLL", "SingleTop", "Diboson"], keepSources=True)
        datasetMgr.merge("EWKScaled", ["EWKnoTT", "TTJets2"])
#        for mass in [80, 100]:
        for mass in [80, 90, 100, 120, 140, 150, 155, 160]:
            datasetMgr.merge("EWKSignal_M%d"%mass, ["TTToHplus_M%d"%mass, "EWKScaled"], keepSources=True)
    datasetsEmb.forEach(addSignal)

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

    doCounters(datasetsEmb)
Пример #2
0
def main():
    datasetsEmb = result.DatasetsMany(tauPlotMany.dirEmbs, analysisEmb+"Counters", normalizeMCByLuminosity=True)
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirSig+"/multicrab.cfg", counters=analysisSig+"Counters")

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

    def mergeEWK(datasets):
        datasets.merge("EWKMC", ["WJets", "TTJets"], keepSources=True)
        #datasets.merge("EWKMC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"], keepSources=True)
    mergeEWK(datasetsSig)
    datasetsEmb.forEach(mergeEWK)
    plots._legendLabels["EWKMC"] = "EWK"

    style = tdrstyle.TDRStyle()
    histograms.createLegend.setDefaults(y1=0.93, y2=0.75, x1=0.52, x2=0.93)
    
    tauEmbedding.normalize = True
    tauEmbedding.era = "Run2011A"

    def dop(datasetName):
        doPlots(datasetsEmb, datasetsSig, datasetName)
#        doCounters(datasetsEmb, datasetsSig, datasetName)
        print "%s done" % datasetName
    dop("TTJets")
    dop("WJets")
    dop("DYJetsToLL")
    dop("SingleTop")
    dop("Diboson")
    dop("EWKMC")
def main():
    #    muonDir = "../multicrab_muonDebugAnalysisAod_130503_112555"
    #    muonDir = "../multicrab_muonDebugAnalysisAod_pt41_130506_124929"
    muonDir = "../multicrab_muonDebugAnalysisAod_pt41_muscle_pu_130506_163909"
    tauDir = "."

    if jetSelection:
        muonDir = "../multicrab_muonAnalysis_GenMuonDebug_130506_155845"

    args = {"analysisName": "debugAnalyzer", "dataEra": "Run2011A"}
    muArgs = {}
    muArgs.update(args)
    #muArgs["analysisName"] =  "debugAnalyzerMuscle"

    muonDatasets = dataset.getDatasetsFromMulticrabCfg(directory=muonDir,
                                                       weightedCounters=False,
                                                       **muArgs)
    tauDatasets = dataset.getDatasetsFromMulticrabCfg(directory=tauDir,
                                                      weightedCounters=False,
                                                      **args)

    plots.mergeRenameReorderForDataMC(muonDatasets)
    plots.mergeRenameReorderForDataMC(tauDatasets)

    # 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.8, x1=0.82, x2=0.93)

    doPlots(muonDatasets.getDataset("TTJets"),
            tauDatasets.getDataset("TTJets"))
    doCounters(muonDatasets, tauDatasets, "TTJets")
Пример #4
0
def refinedDataSets(dirs, dataEra, searchMode, analysis, optMode, removeTTJets):
    datasets = dataset.getDatasetsFromMulticrabDirs(dirs,dataEra=dataEra,  searchMode=searchMode, analysisName=analysis, optimizationMode=optMode)

    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()

    datasets.remove(filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "Hplus_taunu_t-channel" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "Hplus_taunu_tW-channel" in name, datasets.getAllDatasetNames()))
    if removeTTJets:
        datasets.remove(filter(lambda name: "TTJets_SemiLept" in name, datasets.getAllDatasetNames()))
        datasets.remove(filter(lambda name: "TTJets_FullLept" in name, datasets.getAllDatasetNames()))
        datasets.remove(filter(lambda name: "TTJets_Hadronic" in name, datasets.getAllDatasetNames()))

    plots.mergeRenameReorderForDataMC(datasets)

    datasets.merge("EWK", [
        "TTJets",
        "WJets",
        "DYJetsToLL",
        "SingleTop",
        "Diboson"
        ])

    return datasets
def main():
#    muonDir = "../multicrab_muonDebugAnalysisAod_130503_112555"
#    muonDir = "../multicrab_muonDebugAnalysisAod_pt41_130506_124929"
    muonDir = "../multicrab_muonDebugAnalysisAod_pt41_muscle_pu_130506_163909"
    tauDir = "."

    if jetSelection:
        muonDir = "../multicrab_muonAnalysis_GenMuonDebug_130506_155845"
    

    args = {
        "analysisName": "debugAnalyzer",
        "dataEra": "Run2011A"
    }
    muArgs = {}
    muArgs.update(args)
    #muArgs["analysisName"] =  "debugAnalyzerMuscle"

    muonDatasets = dataset.getDatasetsFromMulticrabCfg(directory=muonDir, weightedCounters=False, **muArgs)
    tauDatasets = dataset.getDatasetsFromMulticrabCfg(directory=tauDir, weightedCounters=False, **args)

    plots.mergeRenameReorderForDataMC(muonDatasets)
    plots.mergeRenameReorderForDataMC(tauDatasets)

    # 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.8, x1=0.82, x2=0.93)

    doPlots(muonDatasets.getDataset("TTJets"), tauDatasets.getDataset("TTJets"))
    doCounters(muonDatasets, tauDatasets, "TTJets")
def doDataset(datasetsEmb, datasetsSig, optMode):
    global ind
    ind = 0

#    datasetsEmb.loadLuminosities() # not needed for pseudo-multicrab

    datasetsEmb.updateNAllEventsToPUWeighted()
    datasetsSig.updateNAllEventsToPUWeighted()

    plots.mergeRenameReorderForDataMC(datasetsEmb)
    plots.mergeRenameReorderForDataMC(datasetsSig)

    # 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)
    histograms.createLegend.moveDefaults(dx=-0.15, dh=-0.2)
    #histograms.uncertaintyMode.set(histograms.uncertaintyMode.StatOnly)
    #histograms.uncertaintyMode.set(histograms.uncertaintyMode.SystOnly)
    histograms.uncertaintyMode.set(histograms.uncertaintyMode.StatPlusSyst)
    histograms.createLegendRatio.moveDefaults(dh=-0.1, dx=-0.53)
    plots._legendLabels["BackgroundStatError"] = "Truth stat. unc."
    plots._legendLabels["BackgroundStatSystError"] = "Truth stat. unc."
    plots._plotStyles["BackgroundStatSystError"] = plots._plotStyles["BackgroundStatError"]

    plotter = tauEmbedding.CommonPlotter(optMode, "mcembwtaumu", drawPlotCommon)

    def dop(name, addData=False, **kwargs):
        doPlots(datasetsEmb, datasetsSig, name, plotter, optMode, addData, **kwargs)
#        doCounters(datasetsEmb, datasetsSig, name)

    dop("TTJets")
def manageDatasets(datasets):
    '''
    def manageDatasets(datasets):
    Handles the PU weighting, luminosity loading and signal merging of the datatasets.
    '''
    
    ### Since (by default) we use weighted counters, and the analysis job inputs are 
    ### normally skims (as are "v44_4" and "v53_1"), need to update events to PU weighted
    print "\n*** Updating events to PU weighted:"
    datasets.updateNAllEventsToPUWeighted()

    if bMcOnly:
        datasets.remove(datasets.getDataDatasetNames())
        histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    else:
        datasets.loadLuminosities()

    print "\n*** Default merging of dataset components:"
    plots.mergeRenameReorderForDataMC(datasets)
                
    print "\n*** Removing all signal samples, except m=%s" % (signalMass)
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M"+signalMass in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    ### Setup style
    styleGenerator = styles.generator(fill=False)
    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.02, dy=+0.00)

    print "*** Setting signal cross sections, using BR(t->bH+)=%s and BR(H+ -> tau+ nu)=%s" % (BR_tH, BR_Htaunu)
    xsect.setHplusCrossSectionsToBR(datasets, BR_tH, BR_Htaunu)
    print "*** Merging WH and HH signals"
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section
    
    return datasets
def main():
    datasetsEmb = dataset.getDatasetsFromMulticrabCfg(
        cfgfile=dirEmb + "/multicrab.cfg", counters=analysisEmb + "Counters")
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(
        cfgfile=dirSig + "/multicrab.cfg", counters=analysisSig + "Counters")

    datasetsEmb.updateNAllEventsToPUWeighted()
    datasetsSig.updateNAllEventsToPUWeighted()

    datasetsEmb.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasetsEmb)
    plots.mergeRenameReorderForDataMC(datasetsSig)

    style = tdrstyle.TDRStyle()
    histograms.createLegend.setDefaults(y1=0.9, y2=0.75, x1=0.6, x2=0.95)

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

    #    doPlots(datasetsEmb, datasetsSig, "TTJets")
    #    doPlots(datasetsEmb, datasetsSig, "WJets")
    #    doCounters(datasetsEmb, datasetsSig, "TTJets")
    #    doCounters(datasetsEmb, datasetsSig, "WJets")
    #    doCounters(datasetsEmb, datasetsSig, "DYJetsToLL")
    #    doCounters(datasetsEmb, datasetsSig, "SingleTop")
    doCounters(datasetsEmb, datasetsSig, "Diboson")
Пример #9
0
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=analysis+"Counters", weightedCounters=(dataEra!=""))
    if dataEra != "":
        datasets.updateNAllEventsToPUWeighted(era=dataEra)
    datasets.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasets)

    # Remove signal
    datasets.remove(filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames()))

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.04)
    plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD"
    #datasets.remove(["QCD_Pt20_MuEnriched"])
    #histograms.createLegend.moveDefaults(dh=-0.05)

    selectorArgs = [tauEmbedding.tauNtuple.weight[dataEra]]
    ntupleCache = dataset.NtupleCache(analysis+"/tree", "TauAnalysisSelector",
                                      selectorArgs=selectorArgs+[True],
                                      process=False,
                                      #maxEvents=100,
                                      cacheFileName="histogramCacheTauEmb.root"
                                      )
#    doPlots(datasets)
    doCounters(datasets, ntupleCache)
Пример #10
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
#    datasets.loadLuminosities()
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets)

    style = tdrstyle.TDRStyle()
    td = dataset.TreeDraw(analysis+"/tree", weight="weightPileup*weightTrigger*weightPrescale", 
                          selection="genMet_p4.Et() > 20"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 1"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 2"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 3"
                          )

    kwargs = {}
    kwargs["normalizeToLumi"] = 1150

    dist=">>dist(25,0,5)"
    for q in ["Et", "X", "Y", "Phi"]:
        rawRes = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        type1Res = plots.DataMCPlot(datasets, td.clone(varexp="metType1_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        #type1Res = plots.DataMCPlot(datasets, td.clone(varexp="tcMet_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), normalizeToLumi=1150)

        compare(rawRes, type1Res, q, "TTJets")
Пример #11
0
def main():
    # Datasets
    datasetsEmbedding = dataset.getDatasetsFromMulticrabCfg(cfgfile=embeddingDir+"/multicrab.cfg", counters=None)
    datasetsTau = dataset.getDatasetsFromMulticrabCfg(cfgfile=tauDir+"/multicrab.cfg", counters=None)

    datasetsEmbedding.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasetsEmbedding)
    plots.mergeRenameReorderForDataMC(datasetsTau)

    if embeddingData:
        datasetsEmbedding.selectAndReorder(["Data"])
    else:
        datasetsEmbedding.selectAndReorder([mcSample])
    datasetsTau.selectAndReorder([mcSample])

    # Style
    style = tdrstyle.TDRStyle()
    
    def createMuonTauPlot(nameMuon, nameTau):
        return MuonTauPlot(datasetsEmbedding, datasetsTau, embeddingAnalysis, tauAnalysis, nameMuon, nameTau)

    def createTauPlot(nameTau):
        return TauPlot(datasetsEmbedding, datasetsTau, embeddingAnalysis, tauAnalysis, nameTau)

    # Plots
    plotPt(createMuonTauPlot("Muon_Pt", "GenTau_Pt"), opts={"xmin":30, "ymin":5e-4})
    plotPt(createTauPlot("Tau_Pt"))

    plotEta(createMuonTauPlot("Muon_Eta", "GenTau_Eta"), opts={"xmin":-2.1, "xmax": 2.1})
    plotEta(createTauPlot("Tau_Eta"), opts={"xmin":-2.4, "xmax":2.4})

    plotPhi(createMuonTauPlot("Muon_Phi", "GenTau_Phi"))
    plotPhi(createTauPlot("Tau_Phi"))
Пример #12
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)
    print "Int.Lumi",datasets.getDataset("Data").getLuminosity()
#    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
#    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))
    
    style = tdrstyle.TDRStyle()




#    datasets3 = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_4_4/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/multicrab_120607_075512/multicrab.cfg", counters=counters)
#    datasets3.updateNAllEventsToPUWeighted()
#    datasets3.loadLuminosities()
#    plots.mergeRenameReorderForDataMC(datasets3)
#    datasets2.selectAndReorder(["TTJets_TuneZ2_Fall11","TTToHplusBWB_M120_Fall11"])
#    datasets2.rename("TTJets_TuneZ2_Fall11","TTJets2")
#    datasets2.rename("TTToHplusBWB_M120_Fall11","TTToHplusBWB_M120_2")     
#    datasets.extend(datasets2)     

#    plot(datasets, datasets2, datasets3)
    
    plot(datasets)
    printCounters(datasets)
Пример #13
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Include only 120 mass bin of HW and HH datasets
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set BR(t->H) to 0.2, keep BR(H->tau) in 1
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Merge WH and HH datasets to one (for each mass bin)
    # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX"
    plots.mergeWHandHH(datasets)

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    dataMCExample(datasets)
    distComparison(datasets)

    # Script execution can be paused like this, it will continue after
    # user has given some input (which must include enter)
    if drawToScreen:
        raw_input("Hit enter to continue")
Пример #14
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters,
                                                   dataEra=dataEra)
    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()

    #    datasets.getDataset("HplusTB_M180_Fall11").setCrossSection(0.363)
    #    datasets.getDataset("HplusTB_M190_Fall11").setCrossSection(0.2666)
    datasets.getDataset("HplusTB_M200_Fall11").setCrossSection(0.1915)
    #    datasets.getDataset("HplusTB_M250_Fall11").setCrossSection(0.051)
    #    datasets.getDataset("HplusTB_M300_Fall11").setCrossSection(0.0213)

    plots.mergeRenameReorderForDataMC(datasets)
    print "Int.Lumi", datasets.getDataset("Data").getLuminosity()
    #    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    #    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    style = tdrstyle.TDRStyle()

    #    datasets3 = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_4_4/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/multicrab_120607_075512/multicrab.cfg", counters=counters)
    #    datasets3.updateNAllEventsToPUWeighted()
    #    datasets3.loadLuminosities()
    #    plots.mergeRenameReorderForDataMC(datasets3)
    #    datasets2.selectAndReorder(["TTJets_TuneZ2_Fall11","TTToHplusBWB_M120_Fall11"])
    #    datasets2.rename("TTJets_TuneZ2_Fall11","TTJets2")
    #    datasets2.rename("TTToHplusBWB_M120_Fall11","TTToHplusBWB_M120_2")
    #    datasets.extend(datasets2)

    #    plot(datasets, datasets2, datasets3)

    plot(datasets)
    printCounters(datasets)
def doSystematicsVariation(myMulticrabDir,era,searchMode,optimizationMode,syst,myOutputCreator,myShapeString):
    myModuleInfoString = "%s_%s_%s_%s"%(era, searchMode, optimizationMode,syst)
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=myMulticrabDir)
    systDsetMgr = dsetMgrCreator.createDatasetManager(dataEra=era,searchMode=searchMode,optimizationMode=optimizationMode,systematicVariation=syst)
    # Do the usual normalisation
    systDsetMgr.updateNAllEventsToPUWeighted()
    systDsetMgr.loadLuminosities()
    plots.mergeRenameReorderForDataMC(systDsetMgr)
    systDsetMgr.merge("EWK", ["TTJets","WJets","DYJetsToLL","SingleTop","Diboson"])
    myLuminosity = systDsetMgr.getDataset("Data").getLuminosity()
    # Obtain results
    mySystModuleResults = PseudoMultiCrabModule(systDsetMgr, era, searchMode, optimizationMode, syst)
    mySystResult = None
    if massType == "mt":
        mySystResult = QCDFactorisedResultManager(myMtSpecs,systDsetMgr,myLuminosity,myModuleInfoString,shapeOnly=False)
    elif massType == "invmass":
        mySystResult = QCDFactorisedResultManager(myFullMassSpecs,systDsetMgr,myLuminosity,myModuleInfoString,shapeOnly=False)
    mySystModuleResults.addShape(mySystResult.getShape(), myShapeString)
    mySystModuleResults.addShape(mySystResult.getShapeMCEWK(), myShapeString+"_MCEWK")
    mySystModuleResults.addShape(mySystResult.getShapePurity(), myShapeString+"_Purity")
    mySystModuleResults.addDataDrivenControlPlots(mySystResult.getControlPlots(),mySystResult.getControlPlotLabels())
    mySystResult.delete()
    ## Save module info
    myOutputCreator.addModule(mySystModuleResults)
    systDsetMgr.close()
    dsetMgrCreator.close()
    ROOT.gROOT.CloseFiles()
    ROOT.gROOT.GetListOfCanvases().Delete()
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(
        counters=tauAnalysisEmb + "Counters", weightedCounters=(dataEra != ""))
    if dataEra != "":
        datasets.updateNAllEventsToPUWeighted(era=dataEra)
    plots.mergeRenameReorderForDataMC(datasets)

    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)

    isolations = [
        ("Standard", "standard"),
        ("TauLike", "taulike"),
        ("ChargedHadrRel10", "chargedHadrRel10"),
        ("ChargedHadrRel15", "chargedHadrRel15"),
    ]

    for name, isolation in isolations:
        ntupleCache = dataset.NtupleCache(
            tauAnalysisEmb + "/tree",
            "EmbeddingMuonIsolationSelector",
            selectorArgs=[tauEmbedding.tauNtuple.weight[dataEra], isolation],
            cacheFileName="histogramCache-%s.root" % name,
            #maxEvents=100,
            #process=False,
        )

        for datasetName in ["TTJets"]:
            doPlots(datasets, datasetName, name, ntupleCache)
            doCounters(datasets, datasetName, name, ntupleCache)
def main():
    tauDirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.tauDirEmbs[1:]]
    tauDirSig = "../"+tauEmbedding.tauDirSig

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

    datasetsEmb.forEach(plots.mergeRenameReorderForDataMC)
    #datasetsEmb.setLumiFromData()
    datasetsEmb.lumi = 5049
    plots.mergeRenameReorderForDataMC(datasetsSig)

    def mergeEWK(datasets):
        datasets.merge("EWKMC", ["WJets", "TTJets"], keepSources=True)
        #datasets.merge("EWKMC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"], keepSources=True)
    #mergeEWK(datasetsSig)
    #datasetsEmb.forEach(mergeEWK)
    #plots._legendLabels["EWKMC"] = "EWK"

    style = tdrstyle.TDRStyle()
    histograms.createLegend.setDefaults(y1=0.93, y2=0.75, x1=0.52, x2=0.93)
    
    tauEmbedding.normalize = True
    tauEmbedding.era = "Run2011A"

    def dop(datasetName):
#        doPlots(datasetsEmb, datasetsSig, datasetName)
        doCounters(datasetsEmb, datasetsSig, datasetName)
        print "%s done" % datasetName
    dop("TTJets")
Пример #18
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
#    datasets.loadLuminosities()
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    datasets.updateNAllEventsToPUWeighted()
    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets)

    style = tdrstyle.TDRStyle()
    td = dataset.TreeDraw(analysis+"/tree", weight="weightPileup*weightTrigger*weightPrescale", 
                          selection="genMet_p4.Et() > 20"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 1"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 2"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 3"
                          )

    kwargs = {}
    kwargs["normalizeToLumi"] = 1150

    dist=">>dist(25,0,5)"
    for q in ["Et", "X", "Y", "Phi"]:
        rawRes = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        type1Res = plots.DataMCPlot(datasets, td.clone(varexp="metType1_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        #type1Res = plots.DataMCPlot(datasets, td.clone(varexp="tcMet_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), normalizeToLumi=1150)

        compare(rawRes, type1Res, q, "TTJets")
Пример #19
0
def main(opts,signalDsetCreator,era,searchMode,optimizationMode):
    # Make directory for output
    mySuffix = "btagEfficiency_%s_%s_%s_%s"%(opts.dset,era,searchMode,optimizationMode)
    if os.path.exists(mySuffix):
        shutil.rmtree(mySuffix)
    os.mkdir(mySuffix)
    # Create dataset manager
    myDsetMgr = signalDsetCreator.createDatasetManager(dataEra=era,searchMode=searchMode,optimizationMode=optimizationMode)
    # Set as luminosity 1 fb (since one looks only at MC)
    myLuminosity = 1000.0
    # Do merges
    style = tdrstyle.TDRStyle()
    myDsetMgr.updateNAllEventsToPUWeighted()
    plots.mergeRenameReorderForDataMC(myDsetMgr)
    # Set defaults for histograms
    histograms.createLegend.moveDefaults(dx=-0.05)
    histograms.createSignalText.set(xmin=0.4, ymax=0.93, mass=120)
    # Show info of available datasets
    myDsetMgr.printDatasetTree()

    # Create plots
    #distributionPtEta(opts, myDsetMgr, myLuminosity, mySuffix) # FIXME: don't think this is used anymore
    efficiencyplot(opts, myDsetMgr, myLuminosity, mySuffix) # Tested and works

    print HighlightStyle()+"\nResults saved to directory: %s%s"%(mySuffix,NormalStyle())
def main():
    dirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.dirEmbs[1:]]
    dirSig = "../"+tauEmbedding.dirSig
    
    datasetsEmb = tauEmbedding.DatasetsMany(dirEmbs, analysisEmb+"Counters", normalizeMCByLuminosity=True)
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirSig+"/multicrab.cfg", counters=analysisSig+"Counters")
    datasetsSig.updateNAllEventsToPUWeighted()

    del plots._datasetMerge["WW"]
#    del plots._datasetMerge["WZ"]
#    del plots._datasetMerge["ZZ"]

    datasetsEmb.forEach(lambda mgr: plots.mergeRenameReorderForDataMC(mgr, keepSourcesMC=True))
    datasetsEmb.setLumiFromData()
    plots.mergeRenameReorderForDataMC(datasetsSig, keepSourcesMC=True)

    def mergeEWK(datasets):
        datasets.merge("EWKMC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson", "WW"], keepSources=True)
        #datasets.merge("EWKMC", ["WJets", "TTJets"], keepSources=True)
    mergeEWK(datasetsSig)
    datasetsEmb.forEach(mergeEWK)
    plots._legendLabels["EWKMC"] = "EWK"

    datasetsEmb.remove(filter(lambda name: "TTToHplus" in name, datasetsEmb.getAllDatasetNames()))
    datasetsEmb.remove(filter(lambda name: "HplusTB" in name, datasetsEmb.getAllDatasetNames()))

    style = tdrstyle.TDRStyle()
    ROOT.gStyle.SetEndErrorSize(5)
    histograms.createLegend.setDefaults(y1=0.93, y2=0.75, x1=0.52, x2=0.93)

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

    #datasetsEmbCorrected = tauEmbedding.DatasetsDYCorrection(datasetsEmb, datasetsSig, analysisEmb, analysisSig)
    datasetsEmbCorrected = tauEmbedding.DatasetsResidual(datasetsEmb, datasetsSig, analysisEmb, analysisSig, ["DYJetsToLL", "WW"], totalNames=["Data", "EWKMC"])

    def dop(datasetName):
        doPlots(datasetsEmb, datasetsSig, datasetName)
#        doCounters(datasetsEmb, datasetsSig, datasetName)
        print "%s done" % datasetName


    #doPlots(datasetsEmbCorrected, datasetsSig, "EWKMC", addData=True, postfix="_residual")
    doCounters(datasetsEmb, datasetsSig, "EWKMC")
    return
    dop("TTJets")
    dop("WJets")
    #dop("W3Jets")
    dop("DYJetsToLL")
    dop("SingleTop")
    dop("Diboson")
    return
    dop("WW")
    dop("WZ")
    dop("ZZ")

    #doPlots(datasetsEmb, datasetsSig, "EWKMC", doData=True, postfix="_data")
    ##doPlots(datasetsEmb, datasetsSig, "Data")

    doPlots(datasetsEmbCorrected, datasetsSig, "EWKMC", postfix="_dycorrected")
Пример #21
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.loadLuminosities()
    datasets.remove(
        filter(lambda name: "TTToHplus" in name and not "M120" in name,
               datasets.getAllDatasetNames()))
    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets)

    style = tdrstyle.TDRStyle()

    plot = plots.DataMCPlot(datasets, analysis + "/MET/met")
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    plot.createFrame("MET", opts={"ymin": 1e-4, "ymaxfactor": 10})
    plot.getPad().SetLogy(True)

    plot.setLegend(histograms.createLegend())

    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Number of events")

    plot.draw()
    plot.addLuminosityText()

    plot.save()
Пример #22
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.loadLuminosities()
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets)

    style = tdrstyle.TDRStyle()

    plot = plots.DataMCPlot(datasets, analysis+"/MET/met")
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    
    plot.createFrame("MET", opts={"ymin": 1e-4, "ymaxfactor": 10})
    plot.getPad().SetLogy(True)

    plot.setLegend(histograms.createLegend())

    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Number of events")

    plot.draw()
    plot.addLuminosityText()

    plot.save()
def doSystematicsVariation(myMulticrabDir,era,searchMode,optimizationMode,syst,myOutputCreator,myShapeString,myNormFactors):
    myModuleInfoString = "%s_%s_%s_%s"%(era, searchMode, optimizationMode,syst)
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=myMulticrabDir)
    systDsetMgr = dsetMgrCreator.createDatasetManager(dataEra=era,searchMode=searchMode,optimizationMode=optimizationMode,systematicVariation=syst)
    # Do the usual normalisation
    systDsetMgr.updateNAllEventsToPUWeighted()
    systDsetMgr.loadLuminosities()
    plots.mergeRenameReorderForDataMC(systDsetMgr)
    systDsetMgr.merge("EWK", ["TTJets","WJets","DYJetsToLL","SingleTop","Diboson"])
    myLuminosity = systDsetMgr.getDataset("Data").getLuminosity()
    # Obtain results
    mySystModuleResults = pseudoMultiCrabCreator.PseudoMultiCrabModule(systDsetMgr, era, searchMode, optimizationMode, syst)
    mySystResult = qcdInvertedResult.QCDInvertedResultManager(myShapeString, "AfterCollinearCuts", systDsetMgr, myLuminosity, myModuleInfoString, myNormFactors, shapeOnly=False, displayPurityBreakdown=False, noRebin=True)
    mySystModuleResults.addShape(mySystResult.getShape(), myShapeString)
    mySystModuleResults.addShape(mySystResult.getShapeMCEWK(), myShapeString+"_MCEWK")
    mySystModuleResults.addShape(mySystResult.getShapePurity(), myShapeString+"_Purity")
    mySystModuleResults.addDataDrivenControlPlots(mySystResult.getControlPlots(),mySystResult.getControlPlotLabels())
    mySystResult.delete()
    ## Save module info
    myOutputCreator.addModule(mySystModuleResults)
    systDsetMgr.close()
    dsetMgrCreator.close()
    ROOT.gROOT.CloseFiles()
    ROOT.gROOT.GetListOfCanvases().Delete()
    ROOT.gDirectory.GetList().Delete()
Пример #24
0
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    #datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Set the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)

    plots.mergeWHandHH(
        datasets
    )  # merging of WH and HH signals must be done after setting the cross section

    # Create counter
    eventCounter = counter.EventCounter(datasets)

    #eventCounter.normalizeMCByLuminosity()
    eventCounter.normalizeMCToLuminosity(1000)  # in pb^-1

    print "============================================================"
    print "Main counter (MC normalized by collision data luminosity)"
    print eventCounter.getMainCounterTable().format()

    triggerCounter = eventCounter.getSubCounter("Trigger")
    triggerCounter.forEachDataset(printTriggerEfficiency)
Пример #25
0
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
           
    #datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Set the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)
                
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    # Create counter
    eventCounter = counter.EventCounter(datasets)

    #eventCounter.normalizeMCByLuminosity()
    eventCounter.normalizeMCToLuminosity(1000) # in pb^-1

    print "============================================================"
    print "Main counter (MC normalized by collision data luminosity)"
    print eventCounter.getMainCounterTable().format()

    triggerCounter = eventCounter.getSubCounter("Trigger")
    triggerCounter.forEachDataset(printTriggerEfficiency)
Пример #26
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(analysisName=analysis)

    # As we use weighted counters for MC normalisation, we have to
    # update the all event count to a separately defined value because
    # the analysis job uses skimmed pattuple as an input
    datasets.updateNAllEventsToPUWeighted()

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Include only 120 mass bin of HW and HH datasets
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set BR(t->H) to 0.2, keep BR(H->tau) in 1
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Merge WH and HH datasets to one (for each mass bin)
    # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX"
    plots.mergeWHandHH(datasets)

    # Merge EWK datasets
    datasets.merge("EWK", [
            "WJets",
            "TTJets",
            "DYJetsToLL",
            "SingleTop",
            "Diboson"
            ])

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Create the normalized plot of transverse mass
    # Read the histogram from the file
    #mT = plots.DataMCPlot(datasets, "transverseMass")

    # Create the histogram from the tree (and see the selections explicitly)
    td = dataset.TreeDraw("tree", weight="weightPileup*weightTrigger*weightPrescale",
                             selection="met_p4.Et() > 70 && Max$(jets_btag) > 1.7")
    mT = plots.DataMCPlot(datasets, td.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))>>dist(400, 0, 400)"))

    # Rebin before subtracting
    mT.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20))

    # Create the data-EWK histogram and draw it
    dataEwkDiff(mT)

    # Draw the mT distribution
    transverseMass(mT)
Пример #27
0
def main():
    # Read the datasets
    # Take only TT+W from signal analysis, and data from embedding+signal analysis
    datasetsEmbSig = dataset.getDatasetsFromMulticrabCfg(
        cfgfile=embeddingSignalAnalysis + "/multicrab.cfg", counters=counters)
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=signalAnalysis +
                                                      "/multicrab.cfg",
                                                      counters=counters)

    # Select only data from embedded
    datasetsEmbSig.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasetsEmbSig)
    if useData:
        datasetsEmbSig.selectAndReorder(datasetsEmbSig.getDataDatasetNames())
    else:
        mcNames = filter(lambda name: "TTToHplus" not in name,
                         datasetsEmbSig.getMCDatasetNames())
        print "Merging MC"
        print "  " + "\n  ".join(mcNames)
        datasetsEmbSig.merge("MC", mcNames)
        datasetsEmbSig.selectAndReorder(["Data", "MC"])

    # Select only data from original
    datasetsSig.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasetsSig)
    sigLumi = datasetsSig.getDataset("Data").getLuminosity()
    if useData:
        datasetsSig.selectAndReorder(datasetsSig.getDataDatasetNames())
    else:
        datasetsSig.remove(["WW_TuneZ2", "WZ_TuneZ2", "ZZ_TuneZ2"])
        mcNames = filter(lambda name: "TTToHplus" not in name,
                         datasetsSig.getMCDatasetNames())
        print "Merging MC"
        print "  " + "\n  ".join(mcNames)
        datasetsSig.merge("MC", mcNames)
        datasetsSig.selectAndReorder(["Data", "MC"])

    print "Embedding luminosity %f" % datasetsEmbSig.getDataset(
        "Data").getLuminosity()
    print "Normal    luminosity %f" % datasetsSig.getDataset(
        "Data").getLuminosity()

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    histograms.createLegend.setDefaults(y1=0.7)

    # Wrapper to decrease typing and have the common options
    def createPlot(plot, *args):
        kwargs = {}
        kwargs["saveFormats"] = [".png"]
        return Plot(datasetsEmbSig, datasetsSig, analysis + "/" + plot, *args,
                    **kwargs)

    transverseMass(createPlot("transverseMass"), rebin=20)

    print "============================================================"
    print "Main counter"
    print getMainCounterTable(datasetsEmbSig, datasetsSig).format()
def main(argv):
    interactive = True
    interactive = False
    #    HISTONAME = "TauIdJets"
#    HISTONAME = "TauIdBtag"
    HISTONAME = "TauIdBveto"
    
    dirs = []
    if len(sys.argv) < 2:
	usage()

    dirs.append(sys.argv[1])

    

    # Disable batch mode here to have the interactivity (see also the line with 'raw_input') below
    if interactive:
        ROOT.gROOT.SetBatch(False)

    # Create all datasets from a multicrab task
#    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
#    datasets = dataset.getDatasetsFromMulticrabDirs(dirs,counters=counters, dataEra=dataEra)
    datasets = dataset.getDatasetsFromMulticrabDirs(dirs,counters=counters, dataEra=dataEra, analysisbaseName = "signalAnalysisInvertedTau")
  
    # As we use weighted counters for MC normalisation, we have to
    # update the all event count to a separately defined value because
    # the analysis job uses skimmed pattuple as an input
    datasets.updateNAllEventsToPUWeighted()

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Include only 120 mass bin of HW and HH datasets
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set BR(t->H) to 0.2, keep BR(H->tau) in 1
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Merge WH and HH datasets to one (for each mass bin)
    # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX"
    plots.mergeWHandHH(datasets)

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    #dataMCExample(datasets)
    distComparison(datasets)

    # Script execution can be paused like this, it will continue after
    # user has given some input (which must include enter)
    if interactive:
        raw_input("Hit enter to continue")
Пример #29
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    # remove data datasets
    datasets.remove(filter(lambda name: "Tau_" in name, datasets.getAllDatasetNames()))
    # remove heavy H+ datasets
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Define variables and cuts
    tauPt = "tau_p4.Pt()"; tauPtCut = tauPt+" > 40"
    tauLeadingCandPt = "tau_leadPFChargedHadrCand_p4.Pt()"; tauLeadingCandPtCut = tauLeadingCandPt+" > 20"

    met = "met_p4.Et()"; metCut = met+" > 70"

    btagMax = "Max$(jets_btag)"; btagCut = btagMax+" > 1.7"
    btagJetNum17 = "Sum$(jets_btag > 1.7"
    btag2ndMax = "MaxIf(kets_btag, jets_btag < Max$(jets_btag))"

    rtau = "tau_leadPFChargedHadrCand_p4.P()/tau_p4.P()"; rtauCut = rtau+" > 0.65"
    mt = "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))"; mtCut = mt+" > 80"
    deltaPhi = "acos((tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/tau_p4.Pt()/met_p4.Et())*57.2958"; deltaPhiCut = deltaPhi+" < 160"

    npv = "goodPrimaryVertices_n";

    td = dataset.TreeDraw(analysis+"/tree", weight="weightPileup*weightTrigger*weightPrescale")
    lumi = 1145

    def createResult(varexp, selection, weight=None, **kwargs):
        args = {"varexp": varexp, "selection": selection}
        if weight != None:
            args["weight"] = weight
        return Result(datasets, td.clone(**args), normalizeToLumi=lumi, **kwargs)

    # metRes = createResult(met+">>dist(100,0,200)", btagCut, greaterThan=True)
    # metRes.save("met", "MET (GeV)", rebin=10, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # btagRes = createResult(btagMax+">>dist(80, 0, 8)", metCut, greaterThan=True)
    # btagRes.save("btag", "TCHE", rebin=5, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # rtauRes = createResult(rtau+">>dist(110,0,1.1)", metCut+"&&"+btagCut, greaterThan=True)
    # rtauRes.save("rtau", "R_{#tau}", rebin=10, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # mtRes = createResult(mt+">>dist(50,0,200)", metCut+"&&"+btagCut, greaterThan=True)
    # mtRes.save("mt", "M_{T}(#tau, MET) (GeV)", rebin=2, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # deltaPhiRes = createResult(deltaPhi+">>dist(90,0,180)", metCut+"&&"+btagCut, lessThan=True)
    # deltaPhiRes.save("deltaPhi", "#Delta#Phi(#tau, MET) (#circ)", rebin=5, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    pileupRes = createResult(npv+">>dist(4,1,17)", metCut+"&&"+btagCut, weight="", doPassed=False, lessThan=True)
    pileupRes.save("goodPV", "N(good primary vertices)")
def main():

    ### Get the ROOT files for all datasets, merge datasets and reorder them
    print "*** Obtaining ROOT files from:\n    %s" % (multicrabPath)
    datasets = dataset.getDatasetsFromMulticrabCfg(directory=multicrabPath, dataEra="Run2011A")

    printPSet(bPrintPSet, folderName="signalAnalysisRun2011A")

    print "*** Calling datasets.updateNAllEventsToPUWeighted():"
    datasets.updateNAllEventsToPUWeighted()
    print "*** Loading luminosities"
    datasets.loadLuminosities()    
    print "*** Calling plots.mergeRenameReorderForDataMC(datasets):"
    plots.mergeRenameReorderForDataMC(datasets)
    
    if mcOnly:
        datasets.remove(datasets.getDataDatasetNames())
        histograms.cmsTextMode = histograms.CMSMode.SIMULATION

    ### Merge desirable datasets
    if bMergeEwk:
        print "*** Merging EWK MC"
        datasets.merge("EWK MC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"])
        plots._plotStyles["EWK MC"] = styles.ttStyle  #plots._plotStyles["EWK"] = styles.getEWKStyle()
    
    ### Remove signals other than M120
    print "*** Removing all signal except M120"
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    ### Setup style
    print "*** Setting up style"
    styleGenerator = styles.generator(fill=True)
    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.0, dy=+0.0)
    
    ### Merge signals into one histo
    print "*** Merging WH and HH signals into one histogram"
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    ### Print desirable information here
    print "*** Available datasets:\n    %s" % (datasets.getAllDatasetNames())
    if mcOnly:
        print "*** Integrated Luminosity:\n    %s (pb)" % (mcOnlyLumi)
    else:
        print "*** Integrated Luminosity:\n     %s (pb)" % (datasets.getDataset("Data").getLuminosity())

    ### Do all plots defined in histoDict function
    doPlots(datasets, histoDict, JetSelectionCuts, SaveExtension = "JetSelection")
    doPlots(datasets, histoDict, MtCut, SaveExtension = "Mt")
    doPlots(datasets, histoDict, MetBtagDeltaPhiCuts, SaveExtension = "MetBtagDeltaPhi")
    doPlots(datasets, histoDict, MetBtagDeltaPhiMtCuts, SaveExtension = "MetBtagDeltaPhiMt")
        
    ### Keep session alive (otherwise canvases close automatically)
    if bBatchMode == False:
        raw_input("*** Press \"any\" key to exit pyROOT: ")
def main():
    # Apply TDR style
    style = tdrstyle.TDRStyle()
    #    histograms.cmsTextMode = histograms.CMSMode.NONE
    #histograms.uncertaintyMode.set(histograms.Uncertainty.StatOnly)
    histograms.uncertaintyMode.set(histograms.uncertaintyMode.StatAndSyst)
    #histograms.createLegend.moveDefaults(dx=-0.15, dh=0.05)#, dh=-0.05) # QCD removed
    histograms.createLegend.setDefaults(textSize=0.04)
    histograms.createLegend.moveDefaults(dx=-0.25, dh=0.1)#, dh=-0.05) # QCD removed

    histograms.createLegendRatio.setDefaults(ncolumns=2, textSize=0.08, columnSeparation=0.3)
    histograms.createLegendRatio.moveDefaults(dx=-0.35, dh=-0.1, dw=0.25)
    plots._legendLabels["BackgroundStatError"] = "Sim. stat. unc."
    plots._legendLabels["BackgroundStatSystError"] = "Sim. stat.#oplussyst. unc."

    legendLabelsSet = False

    for optMode in [
#        "OptQCDTailKillerNoCuts",
        "OptQCDTailKillerLoosePlus",
#        "OptQCDTailKillerMediumPlus",
#        "OptQCDTailKillerTightPlus",
#            None
    ]:
        # Create the dataset objects
        datasetsEmb = dataset.getDatasetsFromMulticrabCfg(dataEra=dataEra, optimizationMode=optMode)

        # Remove signal and W+3jets datasets
        datasetsEmb.remove(filter(lambda name: "HplusTB" in name, datasetsEmb.getAllDatasetNames()))
        datasetsEmb.remove(filter(lambda name: "TTToHplus" in name, datasetsEmb.getAllDatasetNames()))

        datasetsEmb.updateNAllEventsToPUWeighted()
        plots.mergeRenameReorderForDataMC(datasetsEmb)

        doCounters(datasetsEmb, optMode)

        if not legendLabelsSet:
            def trans(n):
                if n[0:2] in ["W+", "Z/"]:
                    return n
                else:
                    return n[0].lower()+n[1:]

            for d in datasetsEmb.getAllDatasetNames():
                oldName = plots._legendLabels.get(d, d)
                plots._legendLabels[d] = "Embedded "+trans(oldName)

            legendLabelsSet = True

        # Remove QCD for plots
        datasetsEmb.remove(["QCD_Pt20_MuEnriched"])
        outputDir = optMode
        if outputDir is not None:
            outputDir += "_embdatamc"
        doPlots(datasetsEmb, outputDir)

        tauEmbedding.writeToFile(outputDir, "input.txt", "Embedded: %s\n" % os.getcwd())
def doDataset(datasetsSeeds, optMode, labels):
    for d in datasetsSeeds:
        d.updateNAllEventsToPUWeighted()
        plots.mergeRenameReorderForDataMC(d)

    plotter = tauEmbedding.CommonPlotter(optMode, "average", drawPlotCommon)

    doPlots(datasetsSeeds, labels, "Data", plotter)
    doPlots(datasetsSeeds, labels, "TTJets", plotter)
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)

    # Remove signals other than M120
###    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
###    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Set the signal cross sections to a value from MSSM
#    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)

###    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    style = tdrstyle.TDRStyle()

    histograms.cmsTextMode = histograms.CMSMode.SIMULATION

    eventCounter = counter.EventCounter(datasets, counters=counters)
    eventCounter.normalizeMCByCrossSection()
    mainTable = eventCounter.getMainCounterTable()

    wh = [
        "TTToHplusBWB_M80",
#        "TTToHplusBWB_M90",
        "TTToHplusBWB_M100",
        "TTToHplusBWB_M120",
        "TTToHplusBWB_M140",
        "TTToHplusBWB_M150",
#        "TTToHplusBWB_M155",
        "TTToHplusBWB_M160",
        ]
    hh = [
        "TTToHplusBHminusB_M80",
#        "TTToHplusBHminusB_M90",
        "TTToHplusBHminusB_M100",
        "TTToHplusBHminusB_M120",
        "TTToHplusBHminusB_M140",
        "TTToHplusBHminusB_M150",
#        "TTToHplusBHminusB_M155",
        "TTToHplusBHminusB_M160",
        ]
    xvalues = [80,
#               90,
               100, 120, 140, 150,
#               155,
               160]

    doPlots(mainTable, xvalues, wh, "HW", True)
    doPlots(mainTable, xvalues, wh, "HW", False)
    doPlots(mainTable, xvalues, hh, "HH", True)
    doPlots(mainTable, xvalues, hh, "HH", False)
def main():
    
    # Get the ROOT files for all datasets, merge datasets and reorder them
    datasets = dataset.getDatasetsFromMulticrabCfg(directory="/Volumes/disk/attikis/HIG-12-037/TreeAnalysis_v44_4_130113_105229/", dataEra="Run2011A")
    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()    
    plots.mergeRenameReorderForDataMC(datasets)

    # Merge desirable datasets
    datasets.merge("EWK MC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"])
    plots._plotStyles["EWK MC"] = styles.ttStyle  #plots._plotStyles["EWK"] = styles.getEWKStyle()
    
    # Remove signals other than M120
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    # Setup style
    styleGenerator = styles.generator(fill=True)
    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.0, dy=+0.0)
    
    # Merge signals into one histo
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    # Print desirable information here
    print "*** Event weight applied: %s" % (EvtWeight)
    print "*** Available datasets: %s" % (datasets.getAllDatasetNames())
    print "*** WARNING! What about btag scale factor?"
    print "*** Integrated Luminosity: %s (pb)" % (datasets.getDataset("Data").getLuminosity())

    # Define histogram name, expression, and binning here: 
    # { hName": "expression >> hNameTmp(nBins, xMin, xMax) }
    histoDict1 = {
        "sphericity": "sphericity >> sphericity(20, 0.0, 1.0)", 
        "aplanarity": "aplanarity >> aplanarity(20, 0.0, 0.5)", 
        "planarity": "planarity >> planarity(20, 0.0, 0.5)", 
        "circularity": "circularity >> circularity(20, 0.0, 1.0)", 
        "alphaT": "alphaT >> alphaT(20, 0.0, 1.0)", 
        "mT": "%s >> mT(30, 0.0, 600.0)" % (Mt)
        }

    # Do all plots defined in doPlots(datasets) function
#    doPlots(datasets, histoDict1, "", SaveExtension = "JetSelection")
#    doPlots(datasets, histoDict1, MetBtagDeltaPhiCuts, SaveExtension = "Met_Btag_DeltaPhi")
#    doPlots(datasets, histoDict1, MetBtagDeltaPhiCircularityCuts, SaveExtension = "Met_Btag_DeltaPhi_Circularity")
#    doPlots(datasets, histoDict1, TestCuts, SaveExtension = "Test")


    # Do just mT plots
    histoDict2 = {
        "mT": "%s >> mT(30, 0.0, 600.0)" % (Mt)
        }

    for i in range(1, 8):
        cutValue = (i+0.0)/(10.0)
        doPlots(datasets, histoDict2, "circularity <= %f" % (cutValue), SaveExtension = "Circularity%s" % (i))
def doDataset(datasetsSeeds, optMode, labels):
    for d in datasetsSeeds:
        d.updateNAllEventsToPUWeighted()
        plots.mergeRenameReorderForDataMC(d)

    plotter = tauEmbedding.CommonPlotter(optMode, "average", drawPlotCommon)

    doPlots(datasetsSeeds, labels, "Data", plotter)
    doPlots(datasetsSeeds, labels, "TTJets", plotter)
Пример #36
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(analysisName="test")

    # We don't have yet the lumi information handled in NtupleAnalysis, so remove data for now
    datasets.remove(datasets.getDataDatasetNames())

    datasets.getDataset("TBHp_HToTauNu_M_200_13TeV_pythia6").setCrossSection(0.336902*2*0.955592) # pb  
    datasets.getDataset("TTbar_HBWB_HToTauNu_M_160_13TeV_pythia6").setCrossSection(0.336902*2*0.955592) # pb   
    datasets.getDataset("TTJets_MSDecaysCKM_central_Tune4C_13TeV_madgraph_tauola").setCrossSection(245.8) # pb   
    datasets.getDataset("QCD_Pt_50to80_Tune4C_13TeV_pythia8").setCrossSection(8148778.0) # pb   

    # For this we don't have cross section
    datasets.remove(["DYJetsToLL_M10to50_TuneZ2star_Summer12"])
###    datasets.remove(["TBHp_HToTauNu_M_200_13TeV_pythia6"])
    datasets.remove(["QCD_Pt_50to80_TuneZ2star_13TeV_pythia6"])
    datasets.remove(["DYToTauTau_M_20_CT10_TuneZ2star_v2_powheg_tauola_Summer12"])

    # These have 0 events after skim in multicrab_TEST5, and the code crashes because of that
    datasets.remove([
        "QCD_Pt30to50_TuneZ2star_Summer12",
        "QCD_Pt50to80_TuneZ2star_Summer12",
        "QCD_Pt80to120_TuneZ2star_Summer12",
        "QCD_Pt120to170_TuneZ2star_Summer12"
        ])

    # As we use weighted counters for MC normalisation, we have to
    # update the all event count to a separately defined value because
    # the analysis job uses skimmed pattuple as an input
    datasets.updateNAllEventsToPUWeighted(era="Run2012ABCD")

    # At the moment the collision energy must be set by hand
    for dset in datasets.getMCDatasets():
        dset.setEnergy("8")

    # At the moment the cross sections must be set by hand
    xsect.setBackgroundCrossSections(datasets)

    # Default merging and ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)
    datasets.rename("TTJets_MSDecaysCKM_central_Tune4C_13TeV_madgraph_tauola", "TTJets")
    datasets.rename("QCD_Pt_50to80_Tune4C_13TeV_pythia8", "QCD")

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    dataMCExample(datasets)
    MetComparison(datasets)

    # Script execution can be paused like this, it will continue after
    # user has given some input (which must include enter)
    if drawToScreen:
        raw_input("Hit enter to continue")
Пример #37
0
def printMuonOrigin(datasetsMC, selection):
    datasets = datasetsMC.deepCopy()
    plots.mergeRenameReorderForDataMC(datasets)
    
    printMuonOriginHelper(datasets, selection)

    datasets.merge("Ws", ["TTJets", "WJets", "SingleTop"])
    datasets.selectAndReorder(["Ws"])
    printMuonOriginHelper(datasets, selection)
Пример #38
0
def doDataset(datasetsEmb, datasetsSig, optMode):
    datasetsSig.updateNAllEventsToPUWeighted()
    datasetsEmb.updateNAllEventsToPUWeighted()

    plots.mergeRenameReorderForDataMC(datasetsEmb)
    plots.mergeRenameReorderForDataMC(datasetsSig)

    plotter = tauEmbedding.CommonPlotter(optMode+"_embdatasigmc", "embdatasigmc", drawPlotCommon)
    doPlots(datasetsEmb, datasetsSig, plotter, optMode)
def main():
    tauDirEmbs = [os.path.join("..", d) for d in tauEmbedding.tauDirEmbs]
    tauDirSig = "../"+tauEmbedding.tauDirSig

    dirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.dirEmbs[1:]]
    dirSig = "../"+tauEmbedding.dirSig

#    tauDirEmbs = tauDirEmbs[:2]
#    dirEmbs = dirEmbs[:2]

    tauDatasetsEmb = tauEmbedding.DatasetsMany(tauDirEmbs, tauAnalysisEmb+"Counters", normalizeMCByLuminosity=True)
    tauDatasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=tauDirSig+"/multicrab.cfg", counters=tauAnalysisSig+"Counters")
    datasetsEmb = tauEmbedding.DatasetsMany(dirEmbs, analysisEmb+"Counters", normalizeMCByLuminosity=True)
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirSig+"/multicrab.cfg", counters=analysisSig+"Counters")

    tauDatasetsSig.updateNAllEventsToPUWeighted()
    datasetsSig.updateNAllEventsToPUWeighted()

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

    def mergeEWK(datasets):
        datasets.merge("EWKMC", ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"], keepSources=True)
    mergeEWK(tauDatasetsSig)
    mergeEWK(datasetsSig)
    tauDatasetsEmb.forEach(mergeEWK)
    datasetsEmb.forEach(mergeEWK)
    plots._legendLabels["EWKMC"] = "EWK"

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    ROOT.gStyle.SetHatchesLineWidth(2)

    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)
    histograms.createLegend.setDefaults(y1=0.93, y2=0.77, x1=0.45, x2=0.7, textSize=0.04)
    #histograms.createLegend.setDefaults(y1=0.93, y2=0.7, x1=0.45, x2=0.93)
    tauEmbedding.normalize = True
    tauEmbedding.era = "Run2011A"

    def dop(name):
        doTauPlots(tauDatasetsEmb, tauDatasetsSig, name)
        doTauCounters(tauDatasetsEmb, tauDatasetsSig, name)
        doPlots(datasetsEmb, datasetsSig, name)
        doCounters(datasetsEmb, datasetsSig, name)

    dop("TTJets")
    dop("WJets")
    dop("DYJetsToLL")
    dop("SingleTop")
    dop("Diboson")
def main(opts):
    datasets = dataset.getDatasetsFromMulticrabCfg(directory=opts.mdir, dataEra=dataEra, weightedCounters=False)
#    datasets = dataset.getDatasetsFromRootFiles([("TTJets_TuneZ2_Summer11", "histograms.root")], counters=counters, dataEra=dataEra, analysisBaseName=analysis, weightedCounters=False)

    plots.mergeRenameReorderForDataMC(datasets)

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    process(datasets, "TTJets", "Before", ">= 1 genuine tau in acceptance")
def main():
    dirEmbs = ["."] + [os.path.join("..", d) for d in result.dirEmbs[1:]]
    dirSig = "../" + result.dirSig

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

    datasetsEmb.remove(
        filter(lambda name: "HplusTB" in name,
               datasetsEmb.getAllDatasetNames()))
    datasetsEmb.remove(
        filter(lambda name: "TTToHplus" in name,
               datasetsEmb.getAllDatasetNames()))

    #    del plots._datasetMerge["WW"]
    #    del plots._datasetMerge["WZ"]
    #    del plots._datasetMerge["ZZ"]

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

    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.04)
    datasetsEmb.remove(["W3Jets"])
    datasetsEmb.remove(["QCD_Pt20_MuEnriched"])
    #plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD"
    histograms.createLegend.moveDefaults(dh=-0.05)
    #histograms.createLegend.moveDefaults(dx=-0.18, dy=0.05, dh=-0.05)

    tauEmbedding.normalize = True
    #tauEmbedding.normalize=False
    tauEmbedding.era = "Run2011A"

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

    datasetsEmbCorrected = result.DatasetsDYCorrection(datasetsEmb,
                                                       datasetsSig,
                                                       analysisEmb,
                                                       analysisSig)
    datasetsResidual = result.DatasetsResidual(datasetsEmb, datasetsSig,
                                               analysisEmb, analysisSig,
                                               ["DYJetsToLL", "WW"])

    doPlots(datasetsEmb)
def doSystematicsVariation(myMulticrabDir, era, searchMode, optimizationMode,
                           syst, myOutputCreator, myShapeString, myNormFactors,
                           dataDrivenFakeTaus):
    myModuleInfoString = "%s_%s_%s_%s" % (era, searchMode, optimizationMode,
                                          syst)
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=myMulticrabDir)
    systDsetMgr = dsetMgrCreator.createDatasetManager(
        dataEra=era,
        searchMode=searchMode,
        optimizationMode=optimizationMode,
        systematicVariation=syst)
    # Do the usual normalisation
    systDsetMgr.updateNAllEventsToPUWeighted()
    systDsetMgr.loadLuminosities()
    plots.mergeRenameReorderForDataMC(systDsetMgr)
    systDsetMgr.merge(
        "EWK", ["TTJets", "WJets", "DYJetsToLL", "SingleTop", "Diboson"])
    myLuminosity = systDsetMgr.getDataset("Data").getLuminosity()

    myFakeRateCalculator = fakeRate.FakeRateCalculator(
        systDsetMgr,
        myShapeString,
        myNormFactors,
        myLuminosity,
        dataDrivenFakeTaus=dataDrivenFakeTaus)

    # Obtain results
    mySystModuleResults = pseudoMultiCrabCreator.PseudoMultiCrabModule(
        systDsetMgr, era, searchMode, optimizationMode, syst)
    mySystResult = qcdInvertedResult.QCDInvertedResultManager(
        myShapeString,
        "AfterCollinearCuts",
        systDsetMgr,
        myLuminosity,
        myModuleInfoString,
        myFakeRateCalculator.getTotalFakeRateProbabilities(),
        dataDrivenFakeTaus=dataDrivenFakeTaus,
        shapeOnly=False,
        displayPurityBreakdown=False,
        noRebin=True)
    mySystModuleResults.addShape(mySystResult.getShape(), myShapeString)
    mySystModuleResults.addShape(mySystResult.getShapeMCEWK(),
                                 myShapeString + "_MCEWK")
    mySystModuleResults.addShape(mySystResult.getShapePurity(),
                                 myShapeString + "_Purity")
    mySystModuleResults.addDataDrivenControlPlots(
        mySystResult.getControlPlots(), mySystResult.getControlPlotLabels())
    mySystResult.delete()
    ## Save module info
    myOutputCreator.addModule(mySystModuleResults)
    systDsetMgr.close()
    dsetMgrCreator.close()
    ROOT.gROOT.CloseFiles()
    ROOT.gROOT.GetListOfCanvases().Delete()
    ROOT.gDirectory.GetList().Delete()
def doDataset(datasetsAve, datasetsSeeds, optMode):
    ds = [datasetsAve] + datasetsSeeds

    for d in ds:
        d.updateNAllEventsToPUWeighted()
        plots.mergeRenameReorderForDataMC(d)

    plotter = tauEmbedding.CommonPlotter(optMode + "_average", "average",
                                         drawPlotCommon)

    doPlots(datasetsAve, datasetsSeeds, "Data", plotter)
Пример #44
0
 def __init__(self, analyses, mergeAllMC=False):
     self.analyses = analyses
     self.datasetManagers = []
     for an in analyses:
         dm = dataset.getDatasetsFromMulticrabCfg(counters=an +
                                                  "Counters/weighted")
         dm.loadLuminosities()
         plots.mergeRenameReorderForDataMC(dm)
         if mergeAllMC:
             dm.mergeMC()
         self.datasetManagers.append(dm)
Пример #45
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Include only 120 mass bin of HW and HH datasets
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set BR(t->H) to 0.2, keep BR(H->tau) in 1
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Merge WH and HH datasets to one (for each mass bin)
    # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX"
    plots.mergeWHandHH(datasets)

    # Merge EWK datasets
    datasets.merge("EWK", [
            "WJets",
            "TTJets",
            "DYJetsToLL",
            "SingleTop",
            "Diboson"
            ])

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Create the normalized plot of transverse mass
    # Read the histogram from the file
    #mT = plots.DataMCPlot(datasets, analysis+"/transverseMass")

    # Create the histogram from the tree (and see the selections explicitly)
    td = dataset.TreeDraw(analysis+"/tree", weight="weightPileup*weightTrigger*weightPrescale",
                             selection="met_p4.Et() > 70 && Max$(jets_btag) > 1.7")
    mT = plots.DataMCPlot(datasets, td.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))>>dist(400, 0, 400)"))

    # Rebin before subtracting
    mT.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20))

    # Create the data-EWK histogram and draw it
    dataEwkDiff(mT)

    # Draw the mT distribution
    transverseMass(mT)
Пример #46
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)

    #xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.2, br_Htaunu=1)
    # LandS assumes ttbar cross section  for both HW and HH
    #xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # LandS expects that HW and HH are normalized to top cross section

    xsect.setHplusCrossSectionsToTop(datasets)

    # Create data-MC comparison plot to get the proper normalization
    # easily
    mt = plots.DataMCPlot(datasets, analysis + "/transverseMassBeforeFakeMet")

    # Rebin to have the agreed 10 GeV binning
    mt.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Create the output ROOT file
    f = ROOT.TFile.Open(outputFile, "RECREATE")

    # Add the histograms of the wanted datasets to the tree
    for datasetName, outputName in [("Data", "data"),
                                    ("TTToHplusBWB_M100", "hw_100"),
                                    ("TTToHplusBHminusB_M100", "hh_100"),
                                    ("TTToHplusBWB_M120", "hw_120"),
                                    ("TTToHplusBHminusB_M120", "hh_120"),
                                    ("TTToHplusBWB_M160", "hw_160"),
                                    ("TTToHplusBHminusB_M160", "hh_160")]:
        th1 = mt.histoMgr.getHisto(datasetName).getRootHisto().Clone(
            "mt_" + outputName)
        th1.SetDirectory(f)
        th1.Write()

    # Write and close the file
    f.Close()

    print
    print "Wrote transverse mass histograms to %s for LandS" % outputFile
Пример #47
0
def manageDatasets(datasets):
    '''
    def manageDatasets(datasets):
    Handles the PU weighting, luminosity loading and signal merging of the datatasets.
    '''
    
    ### Since (by default) we use weighted counters, and the analysis job inputs are 
    ### normally skims (as are "v44_4" and "v53_1"), need to update events to PU weighted
    print "\n*** Updating events to PU weighted:"
    datasets.updateNAllEventsToPUWeighted()

    if bMcOnly==True:
        datasets.remove(datasets.getDataDatasetNames())
        histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    else:
        datasets.loadLuminosities()

    print "\n*** Default merging of dataset components:"
    plots.mergeRenameReorderForDataMC(datasets)
                
    print "\n*** Removing all signal samples, except m=%s GeV/cc" % (signalMass)
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M"+signalMass in name, datasets.getAllDatasetNames()))
    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    ### Setup style
    styleGenerator = styles.generator(fill=False)
    plots._legendLabels["TTToHplus_M"+signalMass] = "m_{H^{+}} = " + signalMass + " GeV/c^{2}"
    style = tdrstyle.TDRStyle()

    print "*** Setting signal cross sections, using BR(t->bH+)=%s and BR(H+ -> tau+ nu)=%s" % (BR_tH, BR_Htaunu)
    xsect.setHplusCrossSectionsToBR(datasets, BR_tH, BR_Htaunu)
    print "*** Merging WH and HH signals"
    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section
    
    ### Now optionally remove datasets
    if bRemoveEwk:
        mergeEwkMc(datasets)
        datasets.remove(filter(lambda name: "EWK MC" in name, datasets.getAllDatasetNames()))
    else:
        if bMergeEwk==True:
            mergeEwkMc(datasets)

    if bRemoveQcd:
        datasets.remove(filter(lambda name: "QCD" in name, datasets.getAllDatasetNames()))
        
    #if bRemoveSignal: FIXME
    #    datasets.remove(filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames()))
    #    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    print "*** Available datasets: %s" % (datasets.getAllDatasetNames())

    return datasets
Пример #48
0
def main():
    datasetsEmb = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirEmb+"/multicrab.cfg", counters=analysisEmb+"Counters")
    datasetsSig = dataset.getDatasetsFromMulticrabCfg(cfgfile=dirSig+"/multicrab.cfg", counters=analysisSig+"Counters")

    datasetsEmb.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasetsEmb)
    plots.mergeRenameReorderForDataMC(datasetsSig)

    style = tdrstyle.TDRStyle()
    histograms.createLegend.setDefaults(y1=0.93, y2=0.78, x1=0.6, x2=0.95)

    doPlots(datasetsEmb, datasetsSig, "TTJets")
    doPlots(datasetsEmb, datasetsSig, "WJets")
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)
def main(opts):
    #    muonDir = "/opt/data/matti/embedding/v44_5/multicrab_muonDebugAnalysisNtupleAod_130507_141258"
    muonDir = "/opt/data/matti/embedding/v44_5/multicrab_muonDebugAnalysisNtupleAod_130515_104754"
    tauDir = "/opt/data/matti/embedding/v44_5/multicrab_analysisTau_v44_5_GenTauDebug_130508_123329"

    muonDatasets = dataset.getDatasetsFromMulticrabCfg(directory=muonDir,
                                                       weightedCounters=False)
    tauDatasets = dataset.getDatasetsFromMulticrabCfg(directory=tauDir,
                                                      weightedCounters=False)

    plots.mergeRenameReorderForDataMC(muonDatasets)
    plots.mergeRenameReorderForDataMC(tauDatasets)

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    tdrstyle.setDarkBodyRadiatorPalette()
    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    histograms.cmsText[histograms.CMSMode.SIMULATION] = "Simulation"
    histograms.createLegend.setDefaults(y1=0.93, y2=0.8, x1=0.7, x2=0.93)

    selectorArgsMuon = MuonSelectorArgs()
    selectorArgsTau = TauSelectorArgs()

    selectorArgsMuon.set(puWeight="Run2011A")
    selectorArgsTau.set(puWeight="Run2011A")

    args = {
        "process": opts.process,
        #"maxEvents": 100,
        #"printStatus": False
    }
    ntupleCacheMuon = dataset.NtupleCache(
        "tree",
        "EmbeddingDebugMuonAnalysisSelector",
        selectorArgs=selectorArgsMuon,
        cacheFileName="histogramCacheMuon.root",
        macros=["rochcor_wasym_v4.C"],
        **args)
    ntupleCacheTau = dataset.NtupleCache(
        "tree",
        "EmbeddingDebugTauAnalysisSelector",
        selectorArgs=selectorArgsTau,
        cacheFileName="histogramCacheTau.root",
        **args)

    doPlots(muonDatasets.getDataset("TTJets"),
            tauDatasets.getDataset("TTJets"), ntupleCacheMuon, ntupleCacheTau)
    doCounters(muonDatasets, tauDatasets, "TTJets", ntupleCacheMuon,
               ntupleCacheTau)
Пример #51
0
def main(opts,signalDsetCreator,era,searchMode,optimizationMode):
    # Make directory for output
    mySuffix = "phiOscillation_%s_%s_%s"%(era,searchMode,optimizationMode)
    if os.path.exists(mySuffix):
        if os.path.exists("%s_old"%mySuffix):
            shutil.rmtree("%s_old"%mySuffix)
        os.rename(mySuffix, "%s_old"%mySuffix)
    os.mkdir(mySuffix)
    # Create dataset manager
    myDsetMgr = signalDsetCreator.createDatasetManager(dataEra=era,searchMode=searchMode,optimizationMode=optimizationMode)
    myDsetMgr.updateNAllEventsToPUWeighted()
    myDsetMgr.loadLuminosities()

    style = tdrstyle.TDRStyle()
    # Get luminosity
    myLuminosity = 0.0
    myDataDatasets = myDsetMgr.getDataDatasets()
    for d in myDataDatasets:
        myLuminosity += d.getLuminosity()

    # Merge datasets
    plots.mergeRenameReorderForDataMC(myDsetMgr)
    mergeEWK = not True
    
    myAvailableDatasetNames = ["Data", "TTToHplusBWB_M120"]
    if mergeEWK:
        myDsetMgr.merge("EWK", [
                      "TTJets",
                      "WJets",
                      "DYJetsToLL",
                      "SingleTop", 
                      "Diboson"
                      ])
        myAvailableDatasetNames.extend(["EWK"])
    else:
        myAvailableDatasetNames.extend(["TTJets", "WJets"])

    # loop over datasets
    myList = []
    if opts.dirs == None:
        myList.extend(myAvailableDatasetNames)
    else:
        if len(opts.dirs) > 0:
            myList.extend(opts.dirs)
        else:
            myList.extend(myAvailableDatasetNames)
    for d in myList:
        print HighlightStyle()+d+NormalStyle()
        doPlots(d, myDsetMgr.getDataset(d), opts, mySuffix, myLuminosity)