def createPlot(name):
        name2Emb = name
        name2Sig = name
        if isinstance(name, basestring):
            name2Emb = analysisEmb+"/"+name
            name2Sig = analysisSig+"/"+name
        else:
            name2Emb = name.clone(tree=analysisEmb+"/tree")
            name2Sig = name.clone(tree=analysisSig+"/tree")

        (emb, embVar) = datasetsEmb.getHistogram(datasetName, name2Emb)
        sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig)
        sig.normalizeToLuminosity(lumi)
        sig = sig.getHistogram()

        emb.SetName("Embedded")
        sig.SetName("Normal")

        p = plots.ComparisonPlot(emb, sig)
        p.histoMgr.forEachHisto(styles.generator())
        legLabel = plots._legendLabels.get(datasetName, datasetName)+" MC"
        p.histoMgr.setHistoLegendLabelMany({
                "Embedded": "Embedded "+legLabel,
                "Normal":   "Normal "+legLabel
                })

        return p
    def __init__(self, datasets, datasetsTau, directory, directoryTau, name):
        h = datasets.getDatasetRootHistos(directory + "/" + name)[0]
        h.setName(name + "Embedded")
        hTau = datasetsTau.getDatasetRootHistos(directoryTau + "/" + name)[0]
        hTau.setName(name + "Tau")
        plots.ComparisonPlot.__init__(self, h, hTau, saveFormats=saveFormats)

        self.histoMgr.normalizeToOne()
        self.histoMgr.forEachHisto(styles.generator())

        self.embeddingAnalysis = directory.replace("/", "_")
        self.tauAnalysis = directoryTau.replace("/", "_")

        self.plotName = mcSample + "_" + self.embeddingAnalysis + "_" + self.tauAnalysis + "_" + name
        self.ratioLabel = "Embedded/true"

        label = dataLabel
        if not embeddingData:
            label = mcLabel

        self.histoMgr.setHistoLegendLabelMany({
            name + "Embedded":
            "Embedded #tau (%s)" % label,
            name + "Tau":
            "True #tau (%s)" % mcLabel
        })
Beispiel #3
0
def rtauGen(h, name, rebin=5, ratio=False):
    #h.setDefaultStyles()
    h.histoMgr.forEachHisto(styles.generator())

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "R_{#tau}"
    if "Mass" in name:
        xlabel = "m (GeV/c^{2})"
    elif "Pt" in name:
        xlabel = "p_{T}(GeV/c)"
    elif "vertices" in name:
        xlabel = "N_{vertices}"
    ylabel = "Events / %.2f" % h.binWidth()

    if "gen" in name:
        kwargs = {"ymin": 0.1, "xmax": 1.1}        
    elif "Pt" in name:
        kwargs = {"ymin": 0.1, "xmax": 400}
    elif "Mass" in name:
        kwargs = {"ymin": 0.1, "xmax": 500}
        
    kwargs = {"ymin": 0.1, "xmax": 500}
#    kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}}
    if ratio:
        kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
        kwargs["createRatio"] = True
#    name = name+"_log"

    h.createFrame(name, **kwargs)
#    h.getPad().SetLogy(True)
    h.setLegend(histograms.createLegend(0.2, 0.75, 0.4, 0.9))
    common(h, xlabel, ylabel, addLuminosityText=False)
    def __init__(self, datasetsEmbSig, datasetsSig, path, normalizeToOne=False, **kwargs):
        dataset = "Data"
        if not useData:
            dataset = "MC"

        self.name = path.split("/")[-1]
        hEmb = datasetsEmbSig.getDataset(dataset).getDatasetRootHisto(path)
        hEmb.setName(self.name+"Embedded")
        hSig = datasetsSig.getDataset(dataset).getDatasetRootHisto(path)
        hSig.setName(self.name+"Normal")
        if not useData:
            hEmb.normalizeToLuminosity(datasetsEmbSig.getDataset("Data").getLuminosity())
            hSig.normalizeToLuminosity(datasetsSig.getDataset("Data").getLuminosity())

        plots.ComparisonPlot.__init__(self, hEmb, hSig, **kwargs)

        self.normalizeToOne = normalizeToOne
        if normalizeToOne:
            self.histoMgr.normalizeToOne()

        sg = styles.generator()
        sg.reset(1)
        self.histoMgr.forHisto(self.name+"Embedded", sg)
        self.histoMgr.forHisto(self.name+"Normal", styles.dataStyle)
        self.histoMgr.setHistoDrawStyleAll("EP")
        self.histoMgr.setHistoLegendStyleAll("p")

        s = "(Data)"
        if not useData:
            s = "(MC)"

        self.histoMgr.setHistoLegendLabelMany({self.name+"Embedded": "Embedded "+s,
                                               self.name+"Normal": "Normal "+s})

        self.histoMgr.forHisto(self.name+"Embedded", lambda h: normaliseEmbedding(h.getRootHisto()))
Beispiel #5
0
def rtauGen(h, name, rebin=5, ratio=False):
    #h.setDefaultStyles()
    h.histoMgr.forEachHisto(styles.generator())

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "R_{#tau}"
    if "Mass" in name:
        xlabel = "m (GeV/c^{2})"
    elif "Pt" in name:
        xlabel = "p_{T}(GeV/c)"
    elif "vertices" in name:
        xlabel = "N_{vertices}"
    ylabel = "Events / %.2f" % h.binWidth()

    if "gen" in name:
        kwargs = {"ymin": 0.1, "xmax": 1.1}
    elif "Pt" in name:
        kwargs = {"ymin": 0.1, "xmax": 400}
    elif "Mass" in name:
        kwargs = {"ymin": 0.1, "xmax": 500}

    kwargs = {"ymin": 0.1, "xmax": 500}
    #    kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}}
    if ratio:
        kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
        kwargs["createRatio"] = True


#    name = name+"_log"

    h.createFrame(name, **kwargs)
    #    h.getPad().SetLogy(True)
    h.setLegend(histograms.createLegend(0.2, 0.75, 0.4, 0.9))
    common(h, xlabel, ylabel, addLuminosityText=False)
def rtauGen(h, name, rebin=2, ratio=False, defaultStyles=True):
    if defaultStyles:
        h.setDefaultStyles()
        h.histoMgr.forEachHisto(styles.generator())

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))


    xlabel = "PF E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f" % h.binWidth()
    if "LeptonsInMt" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "NoLeptonsRealTau" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "Mass" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()

        
    kwargs = {"ymin": 0.1, "ymax": 1000}
    if "LeptonsInMt" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "NoLeptonsRealTau" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "Rtau" in name:
        kwargs = {"ymin": 0.0001, "xmax": 1.1}   
        kwargs = {"ymin": 0.1, "xmax": 1.1}     
        h.getPad().SetLogy(True)

#    kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}}
    if ratio:
        kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
        kwargs["createRatio"] = True
#    name = name+"_log"

    h.createFrame(name, **kwargs)

#    histograms.addText(0.65, 0.7, "BR(t #rightarrow bH^{#pm})=0.05", 20)
    h.getPad().SetLogy(True)
    
    leg = histograms.createLegend(0.6, 0.75, 0.8, 0.9)
 
    if "LeptonsInMt" in name:
        h.getPad().SetLogy(False)
        leg = histograms.moveLegend(leg, dx=-0.18)
        histograms.addText(0.5, 0.65, "TailKiller cut: Tight", 20)
  
    h.setLegend(leg)
    plots._legendLabels["MetNoJetInHole"] = "Jets outside dead cells"
    plots._legendLabels["MetJetInHole"] = "Jets within dead cells"
    histograms.addText(300, 300, "p_{T}^{jet} > 50 GeV/c", 20)
    kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
    kwargs["createRatio"] = True
#    if ratio:
#        h.createFrameFraction(name, opts=opts, opts2=opts2)
#    h.setLegend(leg)

    common(h, xlabel, ylabel)
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 createTransverseMassPlotInternal(dset, name, postfix, normalizeToOne, nominalSelection, compareSelection, nominalLegend="Nominal", compareLegend="Compare", moveLegend={}):
    datasetName = dset.getName()
    treeDraw = dataset.TreeDraw("tree", varexp="TauMETTransverseMass >>tmp(10,0,200)")

    tdNominal = treeDraw.clone(selection=nominalSelection)#selection="Obj2Type == 3 && LeptonVetoStatus == 0 && (TauIDStatus == 1 || TauIDStatus == 2 || TauIDStatus == 3)") # FIXME
    tdCompare = treeDraw.clone(selection=compareSelection)

    drhNominal = dset.getDatasetRootHisto(tdNominal)
    drhCompare = dset.getDatasetRootHisto(tdCompare)

    integrate = lambda h: h.Integral(0, h.GetNbinsX()+1)
    nNominal = integrate(drhNominal.getHistogram())
    nCompare = integrate(drhCompare.getHistogram())

    if normalizeToOne:
        drhNominal.normalizeToOne()
        drhCompare.normalizeToOne()

    drhNominal.setName("Nominal")
    drhCompare.setName("Compare")

    p = plots.ComparisonPlot(drhNominal, drhCompare)

    p.histoMgr.forEachHisto(styles.generator())
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))
    p.histoMgr.setHistoLegendLabelMany({
            "Nominal": nominalLegend+ " (%d)" % int(nNominal),
            "Compare": compareLegend+ " (%d)" % int(nCompare)
            })

    pfix = postfix
    if normalizeToOne:
        pfix += "_unit"
    p.createFrame("mt_"+datasetName+"_"+name+"_"+pfix, createRatio=normalizeToOne, invertRatio=True, opts2={"ymin": 0, "ymax": 2})
    p.frame.GetXaxis().SetTitle("Transverse mass (GeV/c^{2})")
    if normalizeToOne:
        p.frame.GetYaxis().SetTitle("Arbitrary units")
    else:
        p.frame.GetYaxis().SetTitle("MC events")
    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.93, y2=0.80, x1=0.45, x2=0.85), **moveLegend))

    nomErr = p.histoMgr.getHisto("Nominal").getRootHisto().Clone("Nominal_err")
    nomErr.SetFillColor(ROOT.kBlue-7)
    nomErr.SetFillStyle(3004)
    nomErr.SetMarkerSize(0)
    p.prependPlotObject(nomErr, "E2")

    comErr = p.histoMgr.getHisto("Compare").getRootHisto().Clone("Compare_err")
    comErr.SetFillColor(ROOT.kRed-7)
    comErr.SetFillStyle(3013)
    comErr.SetMarkerSize(0)
    p.prependPlotObject(comErr, "E2")

    if normalizeToOne:
        p.appendPlotObject(histograms.PlotText(0.6, 0.75, "Normalized to unit area", size=17))

    p.draw()
    p.save()
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 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: ")
Beispiel #11
0
    def __init__(self, datasets, directory, names):
        PlotBase.__init__(self)

        self.prefix = directory.replace("/", "_")+"_"

        for name in names:
            self.histoMgr.append(getHisto(datasets, directory+"/"+name, name))

        self.histoMgr.forEachHisto(styles.generator())
Beispiel #12
0
    def __init__(self, datasets, directory, names):
        PlotBase.__init__(self)

        self.prefix = directory.replace("/", "_") + "_"

        for name in names:
            self.histoMgr.append(
                getHisto(datasets, directory + "/" + name, name))

        self.histoMgr.forEachHisto(styles.generator())
Beispiel #13
0
    def __init__(self, datasets, datasetsTau, directories, name):
        PlotBase.__init__(self)

        self.histoMgr.append(getHisto(datasets, directories[0]+"/"+name, name+"Embedded"))
        self.histoMgr.append(getHisto(datasetsTau, directories[1]+"/"+name, name+"Tau"))

        self.histoMgr.forEachHisto(styles.generator())

        self.histoMgr.setHistoLegendLabelMany({name+"Embedded": "Embedded #tau",
                                               name+"Tau": "Real #tau"})
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 getBool("bRemoveData"):
        datasets.remove(datasets.getDataDatasetNames())
        histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    else:
        datasets.loadLuminosities()

    print "\n*** Default merging of dataset components:"
    plots.mergeRenameReorderForDataMC(datasets)
                
    if getBool("bRemoveSignal"): 
        print "\n*** Removing all signal samples"
        datasets.remove(filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames()))
        datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))
    else:
        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()))
        plots._legendLabels["TTToHplus_M"+signalMass] = "m_{H^{#pm}} = " + signalMass + " GeV/c^{2}"

    ### Setup style
    styleGenerator = styles.generator(fill=False)
    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 getBool("bRemoveEwk"):
        mergeEwkMc(datasets)
        datasets.remove(filter(lambda name: "EWK MC" in name, datasets.getAllDatasetNames()))
    else:
        if getBool("bMergeEwk"):
            mergeEwkMc(datasets)
    if getBool("bRemoveQcd"):
        datasets.remove(filter(lambda name: "QCD" in name, datasets.getAllDatasetNames()))
        
    print "*** Available datasets: %s" % (datasets.getAllDatasetNames())

    return datasets
Beispiel #15
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
Beispiel #16
0
    def __init__(self, datasets, datasetsTau, directories, name):
        PlotBase.__init__(self)

        self.histoMgr.append(
            getHisto(datasets, directories[0] + "/" + name, name + "Embedded"))
        self.histoMgr.append(
            getHisto(datasetsTau, directories[1] + "/" + name, name + "Tau"))

        self.histoMgr.forEachHisto(styles.generator())

        self.histoMgr.setHistoLegendLabelMany({
            name + "Embedded": "Embedded #tau",
            name + "Tau": "Real #tau"
        })
Beispiel #17
0
    def __init__(self, datasets, prefix, directories, name, normalizeToOne):
        PlotBase.__init__(self)

        self.prefix = prefix+"_"
        self.name = name
        self.postfix = ""

        for d in directories:
            self.histoMgr.append(getHisto(datasets, d+"/"+name, d))

        if normalizeToOne:
            self.histoMgr.normalizeToOne()
            self.postfix += "_one"

        self.histoMgr.forEachHisto(styles.generator())
Beispiel #18
0
    def __init__(self, datasets, prefix, directories, name, normalizeToOne):
        PlotBase.__init__(self)

        self.prefix = prefix + "_"
        self.name = name
        self.postfix = ""

        for d in directories:
            self.histoMgr.append(getHisto(datasets, d + "/" + name, d))

        if normalizeToOne:
            self.histoMgr.normalizeToOne()
            self.postfix += "_one"

        self.histoMgr.forEachHisto(styles.generator())
Beispiel #19
0
    def __init__(self,
                 datasetsEmbSig,
                 datasetsSig,
                 path,
                 normalizeToOne=False,
                 **kwargs):
        dataset = "Data"
        if not useData:
            dataset = "MC"

        self.name = path.split("/")[-1]
        hEmb = datasetsEmbSig.getDataset(dataset).getDatasetRootHisto(path)
        hEmb.setName(self.name + "Embedded")
        hSig = datasetsSig.getDataset(dataset).getDatasetRootHisto(path)
        hSig.setName(self.name + "Normal")
        if not useData:
            hEmb.normalizeToLuminosity(
                datasetsEmbSig.getDataset("Data").getLuminosity())
            hSig.normalizeToLuminosity(
                datasetsSig.getDataset("Data").getLuminosity())

        plots.ComparisonPlot.__init__(self, hEmb, hSig, **kwargs)

        self.normalizeToOne = normalizeToOne
        if normalizeToOne:
            self.histoMgr.normalizeToOne()

        sg = styles.generator()
        sg.reset(1)
        self.histoMgr.forHisto(self.name + "Embedded", sg)
        self.histoMgr.forHisto(self.name + "Normal", styles.dataStyle)
        self.histoMgr.setHistoDrawStyleAll("EP")
        self.histoMgr.setHistoLegendStyleAll("p")

        s = "(Data)"
        if not useData:
            s = "(MC)"

        self.histoMgr.setHistoLegendLabelMany({
            self.name + "Embedded":
            "Embedded " + s,
            self.name + "Normal":
            "Normal " + s
        })

        self.histoMgr.forHisto(self.name + "Embedded",
                               lambda h: normaliseEmbedding(h.getRootHisto()))
    def createPlot(name):
        if mtOnly and "shapeTransverseMass" not in name:
            return None

        drhEmb = dsetEmb.getDatasetRootHisto(syst.histogram(name))
        drhSig = dsetSig.getDatasetRootHisto(name)
        drhEmb.normalizeToLuminosity(lumi)
        drhSig.normalizeToLuminosity(lumi)
        drhEmb.setName("Embedded")
        drhSig.setName("Normal")
        if addData:
            drhEmbData = dsetEmbData.getDatasetRootHisto(name)
            drhEmbData.setName("Embedded data")

        if addData:
            p = plots.ComparisonManyPlot(drhSig, [drhEmb, drhEmbData])
        else:
            p = plots.ComparisonManyPlot(drhSig, [drhEmb])
        p.setLuminosity(lumi)

        if True:
            # zero the stat uncertainty 
            th1 = p.histoMgr.getHisto("Embedded").getRootHistoWithUncertainties().getRootHisto()
            for b in xrange(0, th1.GetNbinsX()+1):
                th1.SetBinError(b, 0)

        legLabel = plots._legendLabels.get(datasetName, datasetName)
        #legEmb = "Embedded "+legLabel
        #legSig = "Normal "+legLabel
        legEmb = "W#rightarrow#tau#rightarrow#mu correction"
        legSig = "W#rightarrow#mu truth"
        if addEventCounts:
            legEmb += " ("+strIntegral(drhEmb.getHistogram())+")"
            legSig += " ("+strIntegral(drhSig.getHistogram())+")"
        p.histoMgr.setHistoLegendLabelMany({
                "Embedded": legEmb,
                "Normal": legSig,
                })
        p.histoMgr.forEachHisto(styles.generator())
        if addData:
            p.histoMgr.setHistoLegendLabelMany({"Embedded data": "Embedded data ("+strIntegral(drhEmbData.getHistogram())+")"})
            p.histoMgr.forHisto("Embedded data", styles.dataStyle)
            p.histoMgr.setHistoDrawStyle("Embedded data", "EP")
            p.histoMgr.setHistoLegendStyle("Embedded data", "P")
            p.histoMgr.reorderDraw(["Embedded data"])
        p.setDrawOptions(ratioYlabel="Corr./Truth")
        return p
def main():
    counters = analysis+"Counters"
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    tauEmbedding.updateAllEventsToWeighted(datasets)

    #datasets.remove(filter(lambda name: name != "SingleMu_Mu_166374-167043_Prompt" and name != "TTJets_TuneZ2_Summer11", datasets.getAllDatasetNames()))
    if era == "EPS":
        datasets.remove([
            "SingleMu_Mu_170722-172619_Aug05",
            "SingleMu_Mu_172620-173198_Prompt",
            "SingleMu_Mu_173236-173692_Prompt",
        ])
    elif era == "Run2011A-EPS":
        datasets.remove([
            "SingleMu_Mu_160431-163261_May10",
            "SingleMu_Mu_163270-163869_May10",
            "SingleMu_Mu_165088-166150_Prompt",
            "SingleMu_Mu_166161-166164_Prompt",
            "SingleMu_Mu_166346-166346_Prompt",
            "SingleMu_Mu_166374-167043_Prompt",
            "SingleMu_Mu_167078-167913_Prompt",

#            "SingleMu_Mu_170722-172619_Aug05",
#            "SingleMu_Mu_172620-173198_Prompt",
#            "SingleMu_Mu_173236-173692_Prompt",
            ])
    elif era == "Run2011A":
        pass

    #datasets.remove(datasets.getMCDatasetNames())
    datasets.loadLuminosities()

    #datasetsMC = datasets.deepCopy()
    #datasetsMC.remove(datasets.getDataDatasetNames())
    
    plots.mergeRenameReorderForDataMC(datasets)
    
    styleGenerator = styles.generator(fill=True)

    style = tdrstyle.TDRStyle()
    #histograms.createLegend.moveDefaults(dx=-0.15)
    plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD"
    histograms.createLegend.moveDefaults(dx=-0.02)

    doPlots(datasets)
    printCounters(datasets)
def genBquark_Pt(h, name, rebin=5, ratio=False):
    h.histoMgr.forEachHisto(styles.generator())
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "p_{T}^{top} (GeV/c)"
    ylabel = "Events /%.1f GeV/c" % h.binWidth()
    
    opts = {"ymin": 0.0001, "xmax": 400, "ymaxfactor": 1.1}
    opts2 = {"ymin": 0.01, "ymax": 1.5}
#    name = name+"_log"
    if ratio:
        h.createFrameFraction(name, opts=opts, opts2=opts2)
    else:
        h.createFrame(name, opts=opts)
#    h.createFrame(name)
    h.getPad().SetLogy(False)
    h.setLegend(histograms.createLegend())
    common(h, xlabel, ylabel, False)
Beispiel #23
0
def genBquark_Pt(h, name, rebin=5, ratio=False):
    h.histoMgr.forEachHisto(styles.generator())
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "p_{T}^{top} (GeV/c)"
    ylabel = "Events /%.1f GeV/c" % h.binWidth()

    opts = {"ymin": 0.0001, "xmax": 400, "ymaxfactor": 1.1}
    opts2 = {"ymin": 0.01, "ymax": 1.5}
    #    name = name+"_log"
    if ratio:
        h.createFrameFraction(name, opts=opts, opts2=opts2)
    else:
        h.createFrame(name, opts=opts)


#    h.createFrame(name)
    h.getPad().SetLogy(False)
    h.setLegend(histograms.createLegend())
    common(h, xlabel, ylabel, False)
Beispiel #24
0
def genBquark_DeltaRTau(h, name, rebin=10, ratio=False):
    h.histoMgr.forEachHisto(styles.generator())
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "#Delta_{R} to #tau"
    ylabel = "Events /%.2f" % h.binWidth()

    #    scaleMCfromWmunu(h)

    opts = {"ymin": 0.0001, "xmax": 8, "ymaxfactor": 1.1}
    opts2 = {"ymin": 0.01, "ymax": 1.5}
    #    name = name+"_log"
    if ratio:
        h.createFrameFraction(name, opts=opts, opts2=opts2)
    else:
        h.createFrame(name, opts=opts)
#    h.createFrame(name)
    h.getPad().SetLogy(False)
    h.setLegend(histograms.createLegend())
    common(h, xlabel, ylabel, False)
def genBquark_DeltaRTau(h, name, rebin=10, ratio=False):
    h.histoMgr.forEachHisto(styles.generator())
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "#Delta_{R} to #tau"
    ylabel = "Events /%.2f" % h.binWidth()
    
#    scaleMCfromWmunu(h)  

    opts = {"ymin": 0.0001, "xmax": 8, "ymaxfactor": 1.1}
    opts2 = {"ymin": 0.01, "ymax": 1.5}
#    name = name+"_log"
    if ratio:
        h.createFrameFraction(name, opts=opts, opts2=opts2)
    else:
        h.createFrame(name, opts=opts)
#    h.createFrame(name)
    h.getPad().SetLogy(False)
    h.setLegend(histograms.createLegend())
    common(h, xlabel, ylabel, False)
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 __init__(self, passedPlots, names, legendLabels={}):
        plots.PlotBase.__init__(self, [], passedPlots[0].saveFormats)

        legends = {
            "sumIsoRel": "Rel iso",
            "pfSumIsoRel": "PF rel iso",
        }
        legends.update(legendLabels)

        with SetTH1Directory(False):
            rootHistos = []
            for plot, name in zip(passedPlots, names):
                mcSum = histograms.sumRootHistos([getSumOrRootHisto(histo) for histo in filter(lambda h: h.isMC(), plot.histoMgr.getHistos())])
                qcdHisto = plot.histoMgr.getHisto("QCD_Pt20_MuEnriched")
                qcd = getSumOrRootHisto(qcdHisto).Clone(name+"_QCDfraction")
                qcd.Divide(mcSum) # qcd/mcSum
                h = histograms.Histo(qcdHisto.getDataset(), qcd, name)
                h.setLegendLabel(legends.get(name, ""))
                self.histoMgr.appendHisto(h)

            self.histoMgr.forEachHisto(styles.generator())
            self.histoMgr.setHistoLegendStyleAll("l")
    def __init__(self, datasets, datasetsTau, directory, directoryTau, name, nameTau):
        h = datasets.getDatasetRootHistos(directory+"/"+name)[0]
        h.setName(name+"Embedded")
        hTau = datasetsTau.getDatasetRootHistos(directoryTau+"/"+nameTau)[0]
        hTau.setName(nameTau+"Tau")
        plots.ComparisonPlot.__init__(self, h, hTau, saveFormats=saveFormats)

        self.histoMgr.normalizeToOne()
        self.histoMgr.forEachHisto(styles.generator())

        self.embeddingAnalysis = directory.replace("/", "_")
        self.tauAnalysis = directoryTau.replace("/", "_")

        self.plotName = mcSample+"_"+self.embeddingAnalysis+"_"+name+"_"+self.tauAnalysis+"_"+nameTau
        self.ratioLabel = "Selected #mu/gen #tau"

        label = dataLabel
        if not embeddingData:
            label = mcLabel

        self.histoMgr.setHistoLegendLabelMany({name+"Embedded": "Selected #mu (%s)"%label,
                                               nameTau+"Tau": "Gen #tau (%s)"%mcLabel})
Beispiel #29
0
    def createPlot(name):
        name2Emb = name
        name2Sig = name
        if isinstance(name, basestring):
            name2Emb = analysisEmb+"/"+name
            name2Sig = analysisSig+"/"+name
        else:
            name2Emb = name.clone(tree=analysisEmb+"/tree")
            name2Sig = name.clone(tree=analysisSig+"/tree")
        emb = datasetsEmb.getDataset(datasetName).getDatasetRootHisto(name2Emb)
        emb.setName("Embedded")
        sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig)
        sig.setName("Normal")
        p = plots.ComparisonPlot(emb, sig)
        p.histoMgr.normalizeMCToLuminosity(lumi)
        p.histoMgr.setHistoLegendLabelMany({
                "Embedded": "Embedded "+plots._legendLabels[datasetName],
                "Normal":   "Normal "+plots._legendLabels[datasetName],
                })
        p.histoMgr.forEachHisto(styles.generator())

        return p
def main():
    counters = analysis+"Counters"
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    if era == "EPS":
        datasets.remove([
            "SingleMu_Mu_170722-172619_Aug05",
            "SingleMu_Mu_172620-173198_Prompt",
            "SingleMu_Mu_173236-173692_Prompt",
        ])
    elif era == "Run2011A-EPS":
        datasets.remove([
            "SingleMu_Mu_160431-163261_May10",
            "SingleMu_Mu_163270-163869_May10",
            "SingleMu_Mu_165088-166150_Prompt",
            "SingleMu_Mu_166161-166164_Prompt",
            "SingleMu_Mu_166346-166346_Prompt",
            "SingleMu_Mu_166374-167043_Prompt",
            "SingleMu_Mu_167078-167913_Prompt",
            ])
    elif era == "Run2011A":
        pass

    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)
    
    styleGenerator = styles.generator(fill=True)

    style = tdrstyle.TDRStyle()

    plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD multi-jet"
    histograms.createLegend.moveDefaults(dx=-0.04)

    doPlots(datasets)
Beispiel #31
0
def main():
    counters = analysis + "Counters"
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    if era == "EPS":
        datasets.remove([
            "SingleMu_Mu_170722-172619_Aug05",
            "SingleMu_Mu_172620-173198_Prompt",
            "SingleMu_Mu_173236-173692_Prompt",
        ])
    elif era == "Run2011A-EPS":
        datasets.remove([
            "SingleMu_Mu_160431-163261_May10",
            "SingleMu_Mu_163270-163869_May10",
            "SingleMu_Mu_165088-166150_Prompt",
            "SingleMu_Mu_166161-166164_Prompt",
            "SingleMu_Mu_166346-166346_Prompt",
            "SingleMu_Mu_166374-167043_Prompt",
            "SingleMu_Mu_167078-167913_Prompt",
        ])
    elif era == "Run2011A":
        pass

    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)

    styleGenerator = styles.generator(fill=True)

    style = tdrstyle.TDRStyle()

    plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD multi-jet"
    histograms.createLegend.moveDefaults(dx=-0.04)

    doPlots(datasets)
    def compare(step):
        if step is None:
            path = "shapeTransverseMass"
        else:
            path = "CommonPlots/AtEveryStep/%s/MET_MET" % step

        #bins = range(0, 200, 20) + [200, 250, 300, 500]
        bins = systematics.getBinningForPlot("shapeTransverseMass")

        def getTH1(ds):
            drh = ds.getDatasetRootHisto(path)
            drh.normalizeToLuminosity(lumi)
            th1 = drh.getHistogram()
            #th1.Rebin(2)
            #return th1
            return th1.Rebin(len(bins)-1, th1.GetName(), array.array("d", bins))

        th1NormalNum = getTH1(dsetNormalNum)
        th1NormalDenom = getTH1(dsetNormalDenom)

        #print th1NormalNum.Integral(0, th1NormalNum.GetNbinsX()+1), th1NormalDenom.Integral(0, th1NormalDenom.GetNbinsX()+1)

        th1EmbNum = getTH1(dsetEmbNum)
        th1EmbDenom = getTH1(dsetEmbDenom)

        #print th1EmbNum.Integral(0, th1EmbNum.GetNbinsX()+1), th1EmbDenom.Integral(0, th1EmbDenom.GetNbinsX()+1)

        effNormal = ROOT.TGraphAsymmErrors(th1NormalNum, th1NormalDenom, "n")
        effEmb = ROOT.TGraphAsymmErrors(th1EmbNum, th1EmbDenom, "n")

        effNormal.SetName("Normal ttbar")
        effEmb.SetName("Embedded ttbar")

        p = plots.ComparisonManyPlot(effNormal, [effEmb])
        p.setLuminosity(lumi)
        p.histoMgr.forEachHisto(styles.generator())
        #p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack, ROOT.kFullCircle))
        #p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed, ROOT.kFullSquare))
        p.histoMgr.setHistoDrawStyleAll("EP")
        p.histoMgr.setHistoLegendStyleAll("EPL")

        unc1 = 1.12
        unc2 = 0.88
        p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, unc1, bins[-1], unc1)))
        p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, unc2, bins[-1], unc2)))
        p.appendPlotObject(histograms.PlotText(x=0.6, y=0.6, text="CaloMET > 70 GeV", size=20))

        global ind
        ind += 1
        # plots.drawPlot(p, "calometComparison/eff_%02d_calomet_%s"%(ind, step), xlabel="Type I PF MET (GeV)", ylabel="CaloMET cut efficiency",
        #                ratio=True, ratioYlabel="Norm./emb.", ratioType="errorScale",
        #                opts={"xmin": 0, "xmax": 500},
        #                opts2={"ymin": 0.8, "ymax": 1.2},
        #                addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5})


        plots.drawPlot(p, "calometComparison/eff_%d_calomet_shapeTransverseMass"%ind, xlabel="Transverse mass (GeV)", ylabel="CaloMET cut efficiency",
                       ratio=True, ratioYlabel="Emb./Norm.", ratioCreateLegend=True, ratioType="errorScale",
                       opts={"ymax": 1.2},
                       opts2={"ymin": 0.8, "ymax": 1.2},
                       addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5})
Beispiel #33
0
def doPlotsWTauMu(datasets,
                  name,
                  datasetName,
                  ntupleCache,
                  selectorName,
                  unweighted,
                  fitFunction,
                  rebin=None):
    ds = datasets.getDataset(datasetName)

    # Take first unweighted histograms for the fraction plot
    drh_all = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection" + unweighted,
                              selectorName))
    drh_pure = ds.getDatasetRootHisto(
        ntupleCache.histogram(
            "selectedMuonPt_AfterJetSelection_MuFromW" + unweighted,
            selectorName))

    def Rebin(th1, div=False):
        if rebin is None:
            return th1
        else:
            h = th1.Rebin(
                len(rebin) - 1, th1.GetName(), array.array("d", rebin))
            if div:
                h.Scale(1, "width")
            return h

    def createTEfficiency(drhAll, drhPure):
        hallUn = Rebin(drhAll.getHistogram())
        hpureUn = Rebin(drhPure.getHistogram())
        teff = ROOT.TEfficiency(hpureUn, hallUn)
        teff.SetDirectory(0)
        teff.SetWeight(drhAll.getDataset().getCrossSection())
        return teff

    teffs = drh_all.forEach(createTEfficiency, drh_pure)
    #coll = ROOT.TList()
    #for o in teffs:
    #    coll.AddLast(o)
    #ratio = ROOT.TEfficiency.Combine(coll)
    ratio = teffs[0]
    for e in teffs[1:]:
        ratio.Add(e)
    styles.getDataStyle().apply(ratio)
    ratio.SetName(datasetName)

    ROOT.gStyle.SetStatY(0.99)
    ROOT.gStyle.SetStatX(0.52)
    ROOT.gStyle.SetStatW(0.18)
    ROOT.gStyle.SetStatH(0.23)

    expFit = ROOT.TF1("purityFit", [
        "1/(1+[0]*exp(-[1]*x))",
        "1-[0]*exp(-[1]*x)",
        "1-([0]/(x^[1]))",
    ][fitFunction], aux.th1Xmin(ratio.GetPassedHistogram()),
                      aux.th1Xmax(ratio.GetPassedHistogram()))
    expFit.SetParameter(0, 0.05)
    ratio.Fit(expFit, "N")
    expFit.SetLineColor(ROOT.kRed)
    expFit.SetLineWidth(2)
    #    expFit = None

    # Then the correctly weighted for the main plot
    drh_all = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection",
                              selectorName))
    drh_pure = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection_MuFromW",
                              selectorName))
    if mcOnly:
        lumi = mcLuminosity
    else:
        lumi = datasets.getDataset("Data").getLuminosity()
    drh_all.normalizeToLuminosity(lumi)
    drh_pure.normalizeToLuminosity(lumi)
    hall = Rebin(drh_all.getHistogram(), div=True)
    hpure = Rebin(drh_pure.getHistogram(), div=True)

    hall.SetName("All")
    hpure.SetName("Pure")

    p = plots.ComparisonPlot(hall, hpure)
    p.setLuminosity(lumi)
    p.setEnergy(ds.getEnergy())
    p.histoMgr.setHistoLegendLabelMany({
        "All": "All muons",
        #            "Pure": "W#rightarrow#tau#rightarrow#mu"
        "Pure": "W#rightarrow#mu"
    })
    p.histoMgr.forEachHisto(styles.generator())

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue - 7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed - 7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(era + "_" + name +
                  "_selectedMuonPt_AFterJetSelection_MuFromW_%s_fit%d" %
                  (datasetName, fitFunction) + unweighted,
                  createRatio=True,
                  opts={
                      "ymin": 1e-1,
                      "ymaxfactor": 2
                  },
                  opts2={
                      "ymin": 0.9,
                      "ymax": 1.05
                  })
    p.setRatios([ratio])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1 - 0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.appendPlotObjectToRatio(
        histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue))
    if expFit is not None:
        p.appendPlotObjectToRatio(expFit)
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.getPad().SetLogy(True)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)")
    p.frame.GetYaxis().SetTitle("Events / #Deltap_{T} %.0f-%.0f GeV/c" %
                                (min(p.binWidths()), max(p.binWidths())))
    p.appendPlotObject(
        histograms.PlotText(0.5,
                            0.9,
                            plots._legendLabels.get(datasetName, datasetName),
                            size=18))

    p.draw()
    p.addStandardTexts()
    p.save()

    # Clear list of functions
    ratio.GetListOfFunctions().Delete()

    return (ratio, expFit)
Beispiel #34
0
def main(opts):
    datasets = dataset.getDatasetsFromMulticrabCfg(directory=muonDir,
                                                   weightedCounters=doWeighted,
                                                   dataEra=era,
                                                   analysisName=analysis,
                                                   useAnalysisNameOnly=True)
    args = {}
    if doTopPtReweighting:
        args["topPtWeightType"] = PileupWeightType.NOMINAL

        if topPtReweightingScheme != "":
            ttjetsName = filter(lambda n: "TTJets" in n,
                                datasets.getMCDatasetNames())[0]
            datasets.getDataset(ttjetsName).info[
                "topPtReweightScheme"] = topPtReweightingScheme
    datasets.updateNAllEventsToPUWeighted(era=era, **args)

    #keepOnly = "SingleMu_Mu_160431-163261_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_163270-163869_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_165088-166150_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_166161-166164_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_166346-166346_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_166374-167043_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_167078-167913_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_170722-172619_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_172620-173198_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_173236-173692_2011A_Nov08"
    #keepOnly = "SingleMu_Mu_173693-177452_2011B_Nov19"
    #keepOnly = "SingleMu_Mu_177453-178380_2011B_Nov19"
    #keepOnly = "SingleMu_Mu_178411-179889_2011B_Nov19"
    #keepOnly = "SingleMu_Mu_179942-180371_2011B_Nov19"
    #datasets.remove(filter(lambda name: name != keepOnly, datasets.getDataDatasetNames()))

    #datasets.remove(datasets.getMCDatasetNames())
    if mcOnly:
        datasets.remove(datasets.getDataDatasetNames())
    else:
        datasets.loadLuminosities()

    #datasetsMC = datasets.deepCopy()
    #datasetsMC.remove(datasets.getDataDatasetNames())

#    splitWJets(datasets)
#    splitDYJets(datasets)

    if mergeMC:
        plots.mergeRenameReorderForDataMC(datasets)

    styleGenerator = styles.generator(fill=True)

    style = tdrstyle.TDRStyle()
    #histograms.createLegend.moveDefaults(dx=-0.15)
    plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD"
    histograms.createLegend.moveDefaults(dx=-0.04)

    wtaumuRatioFile = ROOT.TFile.Open("embedding-wtaumuRatio.root", "RECREATE")
    #    ROOT.TH1.AddDirectory(False)

    selectorArgs = tauEmbedding.MuonAnalysisSelectorArgs(
        era=era,
        isolationMode="chargedHadrRel10",
        topPtReweighting=doTopPtReweighting,
        topPtReweightingScheme=topPtReweightingBranch)
    args = {}
    if opts.cache is not None:
        args["cacheFileName"] = opts.cache
    ntupleCache = dataset.NtupleCache(
        "tree",
        "MuonAnalysisSelector",
        selectorArgs=selectorArgs,
        process=opts.process,
        #maxEvents=1000,
        **args)

    ntupleCache.addSelector("FullStandardIso", "MuonAnalysisSelector",
                            selectorArgs.clone(isolationMode="standard"))
    variations = []
    if doVariations:

        def doVar(name, **kwargs):
            ntupleCache.addSelector(name, "MuonAnalysisSelector",
                                    selectorArgs.clone(**kwargs))
            variations.append(name)

        doVar("SystVarPUWeightPlus", puVariation="up")
        doVar("SystVarPUWeightMinus", puVariation="down")
        if doTopPtReweighting:
            doVar("SystVarTopPtWeightPlus",
                  topPtReweightingScheme=topPtReweightingBranch + "Plus")
            doVar("SystVarTopPtWeightMinus",
                  topPtReweightingScheme=topPtReweightingBranch + "Minus")

    selections = [
        #        ("FullTauLike", "taulike"),
        #        ("FullNoIso", "disabled"),
        #        ("FullStandardIso", "standard"),
        #        ("FullChargedHadrRelIso10", "chargedHadrRel10"),
        #        ("FullChargedHadrRelIso15", "chargedHadrRel15"),
        ("FullStandardIso", "FullStandardIso"),
        ("FullChargedHadrRelIso10", None)
    ]
    for v in variations:
        selections.append(("FullChargedHadrRelIso10" + v, v))

    print selections

    #    for name, isolation in selections:
    allRatios = {}
    for name, selectorName in selections:
        # ntupleCache = dataset.NtupleCache("tree", "MuonAnalysisSelector",
        #                                   ,
        #                                   cacheFileName="histogramCache-%s.root" % name,
        #                                   process=opts.process,
        #                                   #maxEvents=10000,
        #                                   )
        # ntupleCache.setDatasetSelectorArgs({
        #         "WJets_NoB": tauEmbedding.MuonAnalysisSelectorArgs(bquarkMode="breject"),
        #         "WJets_B": tauEmbedding.MuonAnalysisSelectorArgs(bquarkMode="baccept"),
        #         "DYJetsToLL_NoB": tauEmbedding.MuonAnalysisSelectorArgs(bquarkMode="breject"),
        #         "DYJetsToLL_B": tauEmbedding.MuonAnalysisSelectorArgs(bquarkMode="baccept"),
        #         })

        #        doPlots(datasets, name, ntupleCache, selectorName)
        #        printCounters(datasets, name, ntupleCache, selectorName)
        #        printCounters(datasets, name, ntupleCache, onlyDataset="TTJets")

        if True and "FullChargedHadrRelIso10" in name:

            def dop(unweighted, fitFunction):
                directory = wtaumuRatioFile.mkdir(name)
                ratios = []
                rebin = {
                    "TTJets":
                    range(0, 350, 10) + [350, 400],
                    "WJets":
                    range(0, 260, 10) + range(260, 300, 20) + [300, 350, 400],
                    "SingleTop":
                    range(0, 200, 10) + range(200, 300, 20) + [300, 400]
                }
                for dname in ["TTJets", "WJets", "SingleTop"]:
                    #for dname in ["TTJets"]:
                    (ratio, fit) = doPlotsWTauMu(datasets,
                                                 name,
                                                 dname,
                                                 ntupleCache,
                                                 selectorName,
                                                 unweighted,
                                                 fitFunction,
                                                 rebin=rebin[dname])
                    cl = ratio.Clone()
                    cl.SetDirectory(directory)
                    ratios.append((ratio, fit, dname))

                doPlotsWTauMuRatio(datasets, name, ratios, unweighted,
                                   fitFunction)
                return ratios

            #dop("", 2)
            if "SystVar" in name:
                tmp = dop("", 2)
                for ratio, fit, dname in tmp:
                    if dname == "TTJets":
                        allRatios[name] = (ratio, fit)
            else:
                for w in ["", "_Unweighted"]:
                    for fitFunction in [0, 1, 2]:
                        tmp = dop(w, fitFunction)
                        #                        break
                        if w == "":
                            n = name
                            if fitFunction != 2:
                                n += "SystFunc%d" % fitFunction
                            for ratio, fit, dname in tmp:
                                if dname == "TTJets":
                                    allRatios[n] = (ratio, fit)
                                elif fitFunction == 2:
                                    allRatios[name + "Syst" + dname] = (ratio,
                                                                        fit)


#                    break

    keys = allRatios.keys()
    keys.sort()
    print "\n".join(keys)
    doPlotsWTauMuRatioUncertaintyEstimate(datasets, allRatios,
                                          "FullChargedHadrRelIso10")
    fitLine = allRatios["FullChargedHadrRelIso10"][1]
    print "Fit result: p0 %f, p1 %f" % (fitLine.GetParameter(0),
                                        fitLine.GetParameter(1))

    wtaumuRatioFile.Write()
    wtaumuRatioFile.Close()
Beispiel #35
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(weightedCounters=False)
    datasets.loadLuminosities()

    #mc = "WJets"
    mc = "QCD"
    data = "2010"
    #data = "2011"

#    maxVtx = 15
    maxVtx = 20

    if data == "2010":
        datasets.remove(filter(lambda name: "Prompt" in name, datasets.getAllDatasetNames()))
    elif data == "2011":
        datasets.remove(filter(lambda name: "Dec22" in name, datasets.getAllDatasetNames()))

    plots.mergeRenameReorderForDataMC(datasets)

    style = tdrstyle.TDRStyle()

    if mc == "QCD":
        datasets.remove(["WJets"])
    elif mc == "WJets":
        datasets.remove(["QCD"])
    
    h = histograms.HistoManager(datasets, "signalAnalysis/verticesBeforeWeight")
    h.normalizeToOne()

    h.forEachMCHisto(styles.generator())
    h.forHisto("Data", styles.getDataStyle())
    h.setHistoDrawStyle("Data", "EP")
    h.setHistoLegendStyle("Data", "p")

    cf = histograms.CanvasFrame(h, "vertex_%s_%s" % (data, mc), xmax=maxVtx)
    cf.frame.GetXaxis().SetTitle("N(vtx)")
    cf.frame.GetYaxis().SetTitle("A.u.")

    legend = histograms.createLegend()
    h.addToLegend(legend)
    h.draw()
    legend.Draw()

    cf.canvas.SaveAs(".png")
    cf.canvas.SaveAs(".eps")
    cf.canvas.SaveAs(".C")

    # Weight

    dataHisto = h.getHisto("Data").getRootHisto()
    mcHisto = h.getHisto(mc).getRootHisto()

    # For normalization, see https://twiki.cern.ch/twiki/bin/view/CMS/PileupReweighting
    weightHisto = dataHisto.Clone("weights")
    weightHisto.Divide(mcHisto)
    print "Weight histo integral", weightHisto.Integral()
    #weightHisto.Scale(1/dataHisto.Integral())
    #weightHisto.Scale(1/weightHisto.Integral())
    print "Weight histo integral", weightHisto.Integral()
    print "Sum of [weight*prob]", sum([weightHisto.GetBinContent(bin)*mcHisto.GetBinContent(bin) for bin in xrange(1, weightHisto.GetNbinsX())])

    print "weights = cms.vdouble(%s)" % ", ".join(["%.8f" % weightHisto.GetBinContent(bin) for bin in xrange(1, min(maxVtx, weightHisto.GetNbinsX())+1)])

    h = histograms.HistoManager(datasetRootHistos=[])
    h.appendHisto(histograms.Histo(weightHisto, "Weight", "", "HIST"))
    h.forEachHisto(styles.generator())

    cf = histograms.CanvasFrame(h, "vertex_weight_%s_%s" % (data, mc), xmax=maxVtx)
    cf.frame.GetXaxis().SetTitle("N(vtx)")
    cf.frame.GetYaxis().SetTitle("Weight")

    h.draw()

    cf.canvas.SaveAs(".png")
    cf.canvas.SaveAs(".eps")
    cf.canvas.SaveAs(".C")
def doPlotsWTauMu(datasets, name):
    selection = And(muonSelection, muonVeto, electronVeto, jetSelection)
    td = treeDraw.clone(varexp="muons_p4.Pt() >> tmp(40,0,400)")

    ds = datasets.getDataset(name)
    # Take first unweighted histograms for the fraction plot
    drh_all = ds.getDatasetRootHisto(td.clone(selection=selection, weight=""))
    drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24"), weight=""))
    hallUn = drh_all.getHistogram()
    hpureUn = drh_pure.getHistogram()

    # Then the correctly weighted for the main plot
    drh_all = ds.getDatasetRootHisto(td.clone(selection=selection))
    drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24")))
    lumi = datasets.getDataset("Data").getLuminosity()
    drh_all.normalizeToLuminosity(lumi)
    drh_pure.normalizeToLuminosity(lumi)
    hall = drh_all.getHistogram()
    hpure = drh_pure.getHistogram()

    hall.SetName("All")
    hpure.SetName("Pure")

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
            "All": "All muons",
            "Pure": "W#rightarrow#tau#rightarrow#mu"
#            "Pure": "W#rightarrow#mu"
            })
    p.histoMgr.forEachHisto(styles.generator())

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue-7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed-7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame("muonPt_wtaumu_"+name, createRatio=True, opts={"ymin": 1e-1, "ymaxfactor": 2}, opts2={"ymin": 0.9, "ymax": 1.05}
                  )
    p.setRatios([plots._createRatio(hpureUn, hallUn, "", isBinomial=True)])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1-0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.getPad().SetLogy(True)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c" % p.binWidth())
    p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18))

    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
drh_correctId.normalizeToLuminosity(mcOnlyLumi)
drh_incorrectId.normalizeToLuminosity(mcOnlyLumi)

h_correctId = drh_correctId.getHistogram()  # returns TH1
h_incorrectId = drh_incorrectId.getHistogram()

#h_reco.SetName("Reco")
#h_gen.SetName("Gen")
h_correctId.SetName("#splitline{ID good}{#Delta R < 0.4}")
h_incorrectId.SetName("#splitline{ID bad}{#Delta R > 0.4}")

h = plots.ComparisonPlot(
    h_correctId,
    h_incorrectId)  # QUESTION: how does rebinning work in a comparison plot?
h.histoMgr.forEachHisto(styles.generator())

# Stack MC histograms
#h.stackMCHistograms()
#h.stackMCHistograms(stackSignal=True)

#h.addMCUncertainty()

# # Create canvas and frame for only the distributions
h.createFrame("Full_Higgs_mass")
h.frame.GetXaxis().SetTitle("m(b, #tau, #nu_{#tau}) (GeV)")
h.frame.GetYaxis().SetTitle("Events")

# # Create legend
h.setLegend(histograms.createLegend())
h.addEnergyText()
Beispiel #38
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg()
    datasets.loadLuminosities()

    #mc = "WJets"
    mc = "QCD"
    data = "2010"
    #data = "2011"

    #    maxVtx = 15
    maxVtx = 20

    if data == "2010":
        datasets.remove(
            filter(lambda name: "Prompt" in name,
                   datasets.getAllDatasetNames()))
    elif data == "2011":
        datasets.remove(
            filter(lambda name: "Dec22" in name,
                   datasets.getAllDatasetNames()))

    plots.mergeRenameReorderForDataMC(datasets)

    style = tdrstyle.TDRStyle()

    if mc == "QCD":
        datasets.remove(["WJets"])
    elif mc == "WJets":
        datasets.remove(["QCD"])

    h = histograms.HistoManager(datasets,
                                "signalAnalysis/verticesBeforeWeight")
    h.normalizeToOne()

    h.forEachMCHisto(styles.generator())
    h.forHisto("Data", styles.getDataStyle())
    h.setHistoDrawStyle("Data", "EP")
    h.setHistoLegendStyle("Data", "p")

    cf = histograms.CanvasFrame(h, "vertex_%s_%s" % (data, mc), xmax=maxVtx)
    cf.frame.GetXaxis().SetTitle("N(vtx)")
    cf.frame.GetYaxis().SetTitle("A.u.")

    legend = histograms.createLegend()
    h.addToLegend(legend)
    h.draw()
    legend.Draw()

    cf.canvas.SaveAs(".png")
    cf.canvas.SaveAs(".eps")
    cf.canvas.SaveAs(".C")

    # Weight

    dataHisto = h.getHisto("Data").getRootHisto()
    mcHisto = h.getHisto(mc).getRootHisto()

    # For normalization, see https://twiki.cern.ch/twiki/bin/view/CMS/PileupReweighting
    weightHisto = dataHisto.Clone("weights")
    weightHisto.Divide(mcHisto)
    print "Weight histo integral", weightHisto.Integral()
    #weightHisto.Scale(1/dataHisto.Integral())
    #weightHisto.Scale(1/weightHisto.Integral())
    print "Weight histo integral", weightHisto.Integral()
    print "Sum of [weight*prob]", sum([
        weightHisto.GetBinContent(bin) * mcHisto.GetBinContent(bin)
        for bin in xrange(1, weightHisto.GetNbinsX())
    ])

    print "weights = cms.vdouble(%s)" % ", ".join([
        "%.8f" % weightHisto.GetBinContent(bin)
        for bin in xrange(1,
                          min(maxVtx, weightHisto.GetNbinsX()) + 1)
    ])

    h = histograms.HistoManager(datasetRootHistos=[])
    h.appendHisto(histograms.Histo(weightHisto, "Weight", "", "HIST"))
    h.forEachHisto(styles.generator())

    cf = histograms.CanvasFrame(h,
                                "vertex_weight_%s_%s" % (data, mc),
                                xmax=maxVtx)
    cf.frame.GetXaxis().SetTitle("N(vtx)")
    cf.frame.GetYaxis().SetTitle("Weight")

    h.draw()

    cf.canvas.SaveAs(".png")
    cf.canvas.SaveAs(".eps")
    cf.canvas.SaveAs(".C")
Beispiel #39
0
### Normalize the area of *all* histograms to 1
#TauIsoMaxlTrkPt.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
TauIsoMaxlTrkPt.setHistoLegendLabelMany(
    legendLabels)  # many datasets, with dict

### Example how to modify legend styles
TauIsoMaxlTrkPt.setHistoLegendStyleAll("F")
TauIsoMaxlTrkPt.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
TauIsoMaxlTrkPt.forEachMCHisto(styles.generator(
    fill=True))  # Apply SetFillColor too, needed for histogram stacking
TauIsoMaxlTrkPt.forHisto("Data", styles.getDataStyle())
#TauIsoMaxlTrkPt.setHistoDrawStyle("Data", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
#TauIsoMaxlTrkPt.stackMCDatasets()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(TauIsoMaxlTrkPt,
                 "TauIsoMaxlTrkPt",
                 ymin=0.01,
                 ymax=None,
                 xmin=0.0,
                 xmax=20.0)

### Set the frame options, e.g. axis labels
Beispiel #40
0
    def compare(step):
        if step is None:
            path = "shapeTransverseMass"
        else:
            path = "CommonPlots/AtEveryStep/%s/MET_MET" % step

        #bins = range(0, 200, 20) + [200, 250, 300, 500]
        bins = systematics.getBinningForPlot("shapeTransverseMass")

        def getTH1(ds):
            drh = ds.getDatasetRootHisto(path)
            drh.normalizeToLuminosity(lumi)
            th1 = drh.getHistogram()
            #th1.Rebin(2)
            #return th1
            return th1.Rebin(
                len(bins) - 1, th1.GetName(), array.array("d", bins))

        th1NormalNum = getTH1(dsetNormalNum)
        th1NormalDenom = getTH1(dsetNormalDenom)

        #print th1NormalNum.Integral(0, th1NormalNum.GetNbinsX()+1), th1NormalDenom.Integral(0, th1NormalDenom.GetNbinsX()+1)

        th1EmbNum = getTH1(dsetEmbNum)
        th1EmbDenom = getTH1(dsetEmbDenom)

        #print th1EmbNum.Integral(0, th1EmbNum.GetNbinsX()+1), th1EmbDenom.Integral(0, th1EmbDenom.GetNbinsX()+1)

        effNormal = ROOT.TGraphAsymmErrors(th1NormalNum, th1NormalDenom, "n")
        effEmb = ROOT.TGraphAsymmErrors(th1EmbNum, th1EmbDenom, "n")

        effNormal.SetName("Normal ttbar")
        effEmb.SetName("Embedded ttbar")

        p = plots.ComparisonManyPlot(effNormal, [effEmb])
        p.setLuminosity(lumi)
        p.histoMgr.forEachHisto(styles.generator())
        #p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack, ROOT.kFullCircle))
        #p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed, ROOT.kFullSquare))
        p.histoMgr.setHistoDrawStyleAll("EP")
        p.histoMgr.setHistoLegendStyleAll("EPL")

        unc1 = 1.12
        unc2 = 0.88
        p.prependPlotObjectToRatio(
            doLineStyle(ROOT.TLine(0, unc1, bins[-1], unc1)))
        p.prependPlotObjectToRatio(
            doLineStyle(ROOT.TLine(0, unc2, bins[-1], unc2)))
        p.appendPlotObject(
            histograms.PlotText(x=0.6, y=0.6, text="CaloMET > 70 GeV",
                                size=20))

        global ind
        ind += 1
        # plots.drawPlot(p, "calometComparison/eff_%02d_calomet_%s"%(ind, step), xlabel="Type I PF MET (GeV)", ylabel="CaloMET cut efficiency",
        #                ratio=True, ratioYlabel="Norm./emb.", ratioType="errorScale",
        #                opts={"xmin": 0, "xmax": 500},
        #                opts2={"ymin": 0.8, "ymax": 1.2},
        #                addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5})

        plots.drawPlot(p,
                       "calometComparison/eff_%d_calomet_shapeTransverseMass" %
                       ind,
                       xlabel="Transverse mass (GeV)",
                       ylabel="CaloMET cut efficiency",
                       ratio=True,
                       ratioYlabel="Emb./Norm.",
                       ratioCreateLegend=True,
                       ratioType="errorScale",
                       opts={"ymax": 1.2},
                       opts2={
                           "ymin": 0.8,
                           "ymax": 1.2
                       },
                       addLuminosityText=True,
                       moveLegend={
                           "dx": -0.2,
                           "dy": -0.5
                       })
Beispiel #41
0
ylabel = "Events"

### Normalize the area of *all* histograms to 1
#NSelJets.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
NSelJets.setHistoLegendLabelMany(legendLabels) # many datasets, with dict

### Example how to modify legend styles
NSelJets.setHistoLegendStyleAll("F")
NSelJets.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
NSelJets.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking
NSelJets.forHisto("Data", styles.getDataStyle())
#NSelJets.setHistoDrawStyle("Data", "EP")
NSelJets.forHisto("BTau_146240-147116", styles.getDataStyle())
NSelJets.setHistoDrawStyle("BTau_146240-147116", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
NSelJets.stackMCHistograms()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(NSelJets, "NSelJets", ymin=0.01, ymax=None, xmin=0.0, xmax=10.0)

### Set the frame options, e.g. axis labels
cf.frame.GetXaxis().SetTitle("Number of Selected Jets")
cf.frame.GetYaxis().SetTitle(ylabel)
Beispiel #42
0
# TTJets
drh_reco = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(analysis+"/FullHiggsMass/HiggsMass")
drh_gen = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(analysis+"/GenParticleAnalysis/genFullHiggsMass")

drh_reco.normalizeToLuminosity(mcOnlyLumi)
drh_gen.normalizeToLuminosity(mcOnlyLumi)

h_reco = drh_reco.getHistogram() # returns TH1
h_gen = drh_gen.getHistogram()

h_reco.SetName("Reco")
h_gen.SetName("Gen")

h = plots.ComparisonPlot(h_reco, h_gen)
h.histoMgr.forEachHisto(styles.generator())

# Stack MC histograms
#h.stackMCHistograms()
#h.stackMCHistograms(stackSignal=True)

#h.addMCUncertainty()

# # Create canvas and frame for only the distributions
h.createFrame("Full_Higgs_mass")
# h.frame.GetXaxis().SetTitle("m_H (GeV)")
# h.frame.GetYaxis().SetTitle("events / ? GeV")

# # Create legend
h.setLegend(histograms.createLegend())
Beispiel #43
0
ylabel = "Events"

### Normalize the area of *all* histograms to unity. Canno be used with mergeDatasets
#transverseMass.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
transverseMass.setHistoLegendLabelMany(legendLabels) # many datasets, with dict

### Example how to modify legend styles
transverseMass.setHistoLegendStyleAll("F")
transverseMass.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
transverseMass.forEachMCHisto(styles.generator(fill=True))
transverseMass.forHisto("Data", styles.getDataStyle())
#transverseMass.setHistoDrawStyle("Data", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
#transverseMass.stackMCHistograms()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(transverseMass, "transverseMass", ymin=0.01, ymax=None, xmin=0.0, xmax=300.0)

### Set the frame options, e.g. axis labels
cf.frame.GetXaxis().SetTitle("M_{T} GeV/c^{2}")
cf.frame.GetYaxis().SetTitle(ylabel)

### Legend
legend = createLegend(0.7, 0.5, 0.9, 0.8)
def doPlotsWTauMu(datasetsEmb, name, btag=True):
    
    if btag:
        selection = And(metCut, bTaggingCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger*weightBTagging")
    else:
        selection = And(metCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger")
    tdMt = treeDraw.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)")

    (hall, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=selection))
    (hpure, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")))

    tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff"))
    heff = datasetsEmb.getEfficiency(name, tdEff.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")), tdEff.clone(selection=selection))

    hall.SetName("All")
    hpure.SetName("Pure")

    nall = hall.Integral(0, hall.GetNbinsX())
    npure = hpure.Integral(0, hall.GetNbinsX())

    print {True: "Btagging", False: "NoBTag"}[btag], npure/nall, (1-npure/nall)*100

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
            "All": "All muons",
            "Pure": "W#rightarrow#mu"
            })
    p.histoMgr.forEachHisto(styles.generator())
    if btag:
        fname = "transverseMass_4AfterDeltaPhi160_wtaumu_"+name
    else:
        fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_"+name

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue-7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed-7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05})
    styles.getDataStyle().apply(heff)
    p.setRatios([heff])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1-0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    p.appendPlotObjectToRatio(histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth())
    p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18))
    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
    selectionsAco = muonJetMetAoc


datasets = getDatasetsFromMulticrabCfg(counters=None)
#datasets.getDataset("Mu_135821-144114").setLuminosity(3051760.115/1e6) # ub^-1 -> pb^-1
#datasets.getDataset("Mu_146240-147116").setLuminosity(4390660.197/1e6)
#datasets.getDataset("Mu_147196-149442").setLuminosity(27384630.974/1e6)

#datasets.getDataset("Mu_135821-144114").setLuminosity(2863224.758/1e6) # ub^-1 -> pb^-1
datasets.getDataset("Mu_146240-147116").setLuminosity(3977060.866/1e6)
#datasets.getDataset("Mu_147196-149442").setLuminosity(27907588.871/1e6)
#datasets.loadLuminosities("lumis.txt")

datasets.mergeData()

styleGenerator = styles.generator(fill=True)

#textDefaults.setCmsPreliminaryDefaults()
textDefaults.setEnergyDefaults(x=0.17)
textDefaults.setLuminosityDefaults(x=0.4, size=0.04)
createLegend.setDefaults(x1=0.65,y1=0.7)

style = TDRStyle()

class Histo:
    def __init__(self, datasets, name, lumi=None):
        self.histos = HistoManager(datasets, name)
        #print "\n".join(histos.getDatasetNames())

        if lumi == None:
            self.histos.normalizeMCByLuminosity()
Beispiel #46
0
### Normalize the area of *all* histograms to 1
#TauNTrksVSPtcut.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
TauNTrksVSPtcut.setHistoLegendLabelMany(
    legendLabels)  # many datasets, with dict

### Example how to modify legend styles
TauNTrksVSPtcut.setHistoLegendStyleAll("F")
TauNTrksVSPtcut.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
TauNTrksVSPtcut.forEachMCHisto(styles.generator(
    fill=True))  # Apply SetFillColor too, needed for histogram stacking
TauNTrksVSPtcut.forHisto("Data", styles.getDataStyle())
#TauNTrksVSPtcut.setHistoDrawStyle("Data", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
#TauNTrksVSPtcut.stackMCHistograms()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(TauNTrksVSPtcut,
                 "TauNTrksVSPtcut",
                 ymin=0.01,
                 ymax=None,
                 xmin=0.0,
                 xmax=20.0)

### Set the frame options, e.g. axis labels
ylabel = "??"

### Normalize the area of *all* histograms to 1
#TauIsoltrkPtsumVSPtcut.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
TauIsoltrkPtsumVSPtcut.setHistoLegendLabelMany(legendLabels) # many datasets, with dict

### Example how to modify legend styles
TauIsoltrkPtsumVSPtcut.setHistoLegendStyleAll("F")
TauIsoltrkPtsumVSPtcut.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
TauIsoltrkPtsumVSPtcut.forEachMCHisto(styles.generator(fill=True)) # Apply SetFillColor too, needed for histogram stacking
TauIsoltrkPtsumVSPtcut.forHisto("Data", styles.getDataStyle())
#TauIsoltrkPtsumVSPtcut.setHistoDrawStyle("Data", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
#TauIsoltrkPtsumVSPtcut.stackMCDatasets()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(TauIsoltrkPtsumVSPtcut, "TauIsoltrkPtsumVSPtcut", ymin=0.01, ymax=None, xmin=0.0, xmax=20.0)

### Set the frame options, e.g. axis labels
cf.frame.GetXaxis().SetTitle("???")
cf.frame.GetYaxis().SetTitle(ylabel)

### Legend
legend = createLegend(0.7, 0.5, 0.9, 0.8)
### Normalize the area of *all* histograms to unity. Canno be used with mergeDatasets
#transverseMass.normalizeToOne()
#ylabel = "a.u"

############################### STYLES ###############################
### Example how to set legend labels from defaults
transverseMass.setHistoLegendLabelMany(
    legendLabels)  # many datasets, with dict

### Example how to modify legend styles
transverseMass.setHistoLegendStyleAll("F")
transverseMass.setHistoLegendStyle("Data", "p")

### Apply the default styles (for all histograms, for MC histograms, for a single histogram)
transverseMass.forEachMCHisto(styles.generator(fill=True))
transverseMass.forHisto("Data", styles.getDataStyle())
#transverseMass.setHistoDrawStyle("Data", "EP")

### Example how to stack all MC datasets. NOTE: this MUST be done after all legend/style manipulation
#transverseMass.stackMCHistograms()

### Create TCanvas and TH1F such that they cover all histograms
cf = CanvasFrame(transverseMass,
                 "transverseMass",
                 ymin=0.01,
                 ymax=None,
                 xmin=0.0,
                 xmax=300.0)

### Set the frame options, e.g. axis labels
def doPlotsWTauMu(datasetsEmb, name, btag=True):

    if btag:
        selection = And(metCut, bTaggingCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(
            analysisEmb + "/tree",
            weight="weightPileup*weightTrigger*weightBTagging")
    else:
        selection = And(metCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb + "/tree",
                                    weight="weightPileup*weightTrigger")
    tdMt = treeDraw.clone(
        varexp=
        "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)"
    )

    (hall, tmp) = datasetsEmb.getHistogram(name,
                                           tdMt.clone(selection=selection))
    (hpure, tmp) = datasetsEmb.getHistogram(
        name,
        tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")))

    tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff"))
    heff = datasetsEmb.getEfficiency(
        name,
        tdEff.clone(
            selection=And(selection, "abs(temuon_mother_pdgid) == 24")),
        tdEff.clone(selection=selection))

    hall.SetName("All")
    hpure.SetName("Pure")

    nall = hall.Integral(0, hall.GetNbinsX())
    npure = hpure.Integral(0, hall.GetNbinsX())

    print {
        True: "Btagging",
        False: "NoBTag"
    }[btag], npure / nall, (1 - npure / nall) * 100

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
        "All": "All muons",
        "Pure": "W#rightarrow#mu"
    })
    p.histoMgr.forEachHisto(styles.generator())
    if btag:
        fname = "transverseMass_4AfterDeltaPhi160_wtaumu_" + name
    else:
        fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_" + name

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue - 7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed - 7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05})
    styles.getDataStyle().apply(heff)
    p.setRatios([heff])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1 - 0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    p.appendPlotObjectToRatio(
        histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth())
    p.appendPlotObject(
        histograms.PlotText(0.5,
                            0.9,
                            plots._legendLabels.get(name, name),
                            size=18))
    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
Beispiel #50
0
# Normalize the area of *all* histograms to 1
# tauPts.normalizeToOne()
# ylabel = "A.u."

# Example how to set legend labels from defaults
# tauPts.setHistoLegendLabel("TTbar_Htaunu_M80", "H^{#pm} M=80") # one dataset at a time
tauPts.setHistoLegendLabelMany(legendLabels)  # many datasets, with dict

# Example how to modify legend styles
tauPts.setHistoLegendStyleAll("F")
tauPts.setHistoLegendStyle("Data", "p")

# Apply the default styles (for all histograms, for MC histograms, for a single histogram)
# tauPts.forEachHisto(styles.generator())
# tauPts.forEachMCHisto(styles.generator(fill=True, fillStyle=3002)) # Example how to set non-default fill style
tauPts.forEachMCHisto(styles.generator(fill=True))  # Apply SetFillColor too, needed for histogram stacking
tauPts.forHisto("Data", styles.getDataStyle())
tauPts.setHistoDrawStyle("Data", "EP")


# Example how to stack all MC datasets
# Note: this MUST be done after all legend/style manipulation
tauPts.stackMCHistograms()

# Example how to add MC uncertainty
tauPts.addMCUncertainty(styles.getErrorStyle())
# tauPts.addMCUncertainty(styles.getErrorStyle(), "MC uncertainty")

# Create TCanvas and TH1F such that they cover all histograms
cf = histograms.CanvasFrame(tauPts, "taupt")
# cf = histograms.CanvasFrame(tauPts, "taupt", ymin=10, ymax=1e9) # for logy
        selections = muonJetMet
    selectionsAco = muonJetMetAoc

datasets = getDatasetsFromMulticrabCfg(counters=None)
#datasets.getDataset("Mu_135821-144114").setLuminosity(3051760.115/1e6) # ub^-1 -> pb^-1
#datasets.getDataset("Mu_146240-147116").setLuminosity(4390660.197/1e6)
#datasets.getDataset("Mu_147196-149442").setLuminosity(27384630.974/1e6)

#datasets.getDataset("Mu_135821-144114").setLuminosity(2863224.758/1e6) # ub^-1 -> pb^-1
datasets.getDataset("Mu_146240-147116").setLuminosity(3977060.866 / 1e6)
#datasets.getDataset("Mu_147196-149442").setLuminosity(27907588.871/1e6)
#datasets.loadLuminosities("lumis.txt")

datasets.mergeData()

styleGenerator = styles.generator(fill=True)

#textDefaults.setCmsPreliminaryDefaults()
textDefaults.setEnergyDefaults(x=0.17)
textDefaults.setLuminosityDefaults(x=0.4, size=0.04)
createLegend.setDefaults(x1=0.65, y1=0.7)

style = TDRStyle()


class Histo:
    def __init__(self, datasets, name, lumi=None):
        self.histos = HistoManager(datasets, name)
        #print "\n".join(histos.getDatasetNames())

        if lumi == None: