示例#1
0
def createStyles():
    st = [
        styles.StyleCompound(styles=[s, styles.StyleLine(lineWidth=5)])
        for s in styles.getStyles()
    ]
    st[0] = styles.StyleCompound(styles=[st[0], styles.StyleLine(lineStyle=2)])
    return st
示例#2
0
def doPlotsWTauMuRatio(dsetMgr, selectionName, ratios, unweighted,
                       fitFunction):
    prefix = era + "_" + selectionName + "_fitFunction%d" % fitFunction + unweighted + "_"

    st = [s.clone() for s in styles.getStyles()]
    st[0].marker = 33
    st[1].marker = 26
    st[2].marker = 32
    st = [
        styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)])
        for s in st
    ]

    # Do clone to get rid of statistics box
    p = plots.PlotBase([x[0].Clone() for x in ratios])
    p.setEnergy(dsetMgr.getEnergies())
    p.histoMgr.setHistoDrawStyleAll("P")
    p.histoMgr.setHistoLegendStyleAll("P")
    p.histoMgr.forEachHisto(styles.Generator(st))
    for i, x in enumerate(ratios):
        fitLine = x[1]
        st[i].apply(fitLine)
        p.appendPlotObject(fitLine)

    def customize(plot):
        xmin = plot.frame.GetXaxis().GetXmin()
        xmax = plot.frame.GetXaxis().GetXmax()

        val = 1
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

        val = 1 - 0.038479
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kBlue)
        l.SetLineStyle(4)
        plot.prependPlotObject(l)
        plot.appendPlotObject(
            histograms.PlotText(0.18, 0.57, "0.038", size=18,
                                color=ROOT.kBlue))

    plots.drawPlot(p,
                   prefix + "WMuFraction",
                   "Muon p_{T} (GeV/c)",
                   ylabel="W#rightarrow#mu fraction",
                   opts={
                       "ymin": 0.9,
                       "ymax": 1.02
                   },
                   moveLegend={
                       "dh": -0.15,
                       "dx": -0.5
                   },
                   customizeBeforeDraw=customize)
def doPlots(datasetsEmb, datasetsSig, datasetName):
    lumi = datasetsEmb.getLuminosity()

    createPlot = tauEmbedding.PlotCreatorMany(analysisEmb, analysisSig,
                                              datasetsEmb, datasetsSig,
                                              datasetName, styles.getStyles())

    def drawPlot(plot, name, *args, **kwargs):
        drawPlotCommon(plot, "mcembsig_" + datasetName + "_" + name, *args,
                       **kwargs)

    def createDrawPlot(name, *args, **kwargs):
        p = createPlot(name)
        drawPlot(plot, *args, **kwargs)

    opts2def = {"ymin": 0, "ymax": 2}

    def drawControlPlot(path, xlabel, rebin=None, opts2=None, **kwargs):
        opts2_ = opts2def
        if opts2 != None:
            opts_ = opts2
        cargs = {}
        if rebin != None:
            cargs["rebin"] = rebin
        drawPlot(createPlot("ControlPlots/" + path, **cargs),
                 path,
                 xlabel,
                 opts2=opts2_,
                 **kwargs)

    def update(d1, d2):
        tmp = {}
        tmp.update(d1)
        tmp.update(d2)
        return tmp

    # Control plots
    optsdef = {}
    opts = optsdef
    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawControlPlot("SelectedTau_pT_AfterStandardSelections",
                    "#tau-jet p_{T} (GeV/c)",
                    opts=update(opts, {"xmax": 250}),
                    rebin=2,
                    cutBox={
                        "cutValue": 40,
                        "greaterThan": 40
                    },
                    moveLegend=moveLegend)

    opts = {"SingleTop": {"ymax": 1.8}}.get(datasetName, {"ymaxfactor": 1.4})
    moveLegend = {
        "TTJets": {
            "dy": -0.6,
            "dx": -0.2
        },
    }.get(datasetName, {"dx": -0.32})
    drawControlPlot("SelectedTau_eta_AfterStandardSelections",
                    "#tau-jet #eta",
                    opts=update(opts, {
                        "xmin": -2.2,
                        "xmax": 2.2
                    }),
                    ylabel="Events / %.1f",
                    rebin=4,
                    log=False,
                    moveLegend=moveLegend)

    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections",
                    "#tau-jet ldg. charged particle p_{T} (GeV/c)",
                    opts=update(opts, {"xmax": 300}),
                    rebin=2,
                    cutBox={
                        "cutValue": 20,
                        "greaterThan": True
                    },
                    moveLegend=moveLegend)

    opts = {"ymin": 1e-1, "ymaxfactor": 5}
    if datasetName == "Diboson":
        opts["ymin"] = 1e-2
    moveLegend = {"dx": -0.25}
    drawControlPlot("SelectedTau_Rtau_AfterStandardSelections",
                    "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}",
                    opts=update(opts, {
                        "xmin": 0.65,
                        "xmax": 1.05
                    }),
                    rebin=5,
                    ylabel="Events / %.2f",
                    moveLegend=moveLegend,
                    cutBox={
                        "cutValue": 0.7,
                        "greaterThan": True
                    })

    opts = optsdef
    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawControlPlot("Njets_AfterStandardSelections",
                    "Number of jets",
                    ylabel="Events",
                    moveLegend=moveLegend)

    # After Njets
    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawControlPlot("MET",
                    "Uncorrected PF E_{T}^{miss} (GeV)",
                    rebin=5,
                    opts=update(opts, {"xmax": 400}),
                    cutLine=50,
                    moveLegend=moveLegend)

    # after MET
    moveLegend = {"dx": -0.23, "dy": -0.5}
    moveLegend = {
        "WJets": {},
        "DYJetsToLL": {
            "dx": -0.02
        },
        "SingleTop": {},
        "Diboson": {}
    }.get(datasetName, moveLegend)
    drawControlPlot("NBjets",
                    "Number of selected b jets",
                    opts=update(opts, {"xmax": 6}),
                    ylabel="Events",
                    moveLegend=moveLegend,
                    cutLine=1)

    # After BTag
    xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})"

    def customDeltaPhi(h):
        yaxis = h.getFrame().GetYaxis()
        yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset())

    opts2 = opts2def
    opts = {
        # "WJets": {"ymax": 20},
        # "DYJetsToLL": {"ymax": 5},
        # "SingleTop": {"ymax": 2},
        # "Diboson": {"ymax": 0.6},
    }.get(datasetName, {"ymaxfactor": 1.2})
    opts2 = {
        # "WJets": {"ymin": 0, "ymax": 3}
    }.get(datasetName, opts2def)
    moveLegend = {"DYJetsToLL": {"dx": -0.24}}.get(datasetName, {"dx": -0.22})
    drawPlot(createPlot("deltaPhi", rebin=10),
             "deltaPhi_3AfterBTagging",
             xlabel,
             log=False,
             opts=opts,
             opts2=opts2,
             ylabel="Events / %.0f^{o}",
             function=customDeltaPhi,
             moveLegend=moveLegend,
             cutLine=[130, 160])

    # After deltaPhi
    opts = {
        # "EWKMC": {"ymax": 40},
        # "TTJets": {"ymax": 12},
        # #"WJets": {"ymax": 35},
        # "WJets": {"ymax": 25},
        # "SingleTop": {"ymax": 2.2},
        # "DYJetsToLL": {"ymax": 6.5},
        # #"Diboson": {"ymax": 0.9},
        # "Diboson": {"ymax": 0.8},
        # "W3Jets": {"ymax": 5}
    }.get(datasetName, {})
    opts2 = {
        # "TTJets": {"ymin": 0, "ymax": 1.2},
        # "Diboson": {"ymin": 0, "ymax": 3.2},
    }.get(datasetName, opts2)
    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawPlot(createPlot("transverseMass", rebin=10),
             "transverseMass_4AfterDeltaPhi160",
             "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})",
             opts=opts,
             opts2=opts2,
             ylabel="Events / %.0f GeV/c^{2}",
             log=False,
             moveLegend=moveLegend)

    return
    # Tree cut definitions
    treeDraw = dataset.TreeDraw(
        "dummy", weight=tauEmbedding.signalNtuple.weightBTagging)
    tdDeltaPhi = treeDraw.clone(varexp="%s >>tmp(18, 0, 180)" %
                                tauEmbedding.signalNtuple.deltaPhiExpression)
    tdMt = treeDraw.clone(varexp="%s >>tmp(15,0,300)" %
                          tauEmbedding.signalNtuple.mtExpression)

    # DeltapPhi
    xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})"

    def customDeltaPhi(h):
        yaxis = h.getFrame().GetYaxis()
        yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset())

    opts2 = opts2def
    opts = {
        "WJets": {
            "ymax": 20
        },
        "DYJetsToLL": {
            "ymax": 5
        },
        "SingleTop": {
            "ymax": 2
        },
        "Diboson": {
            "ymax": 0.6
        },
    }.get(datasetName, {"ymaxfactor": 1.2})
    opts2 = {"WJets": {"ymin": 0, "ymax": 3}}.get(datasetName, opts2def)
    moveLegend = {"DYJetsToLL": {"dx": -0.24}}.get(datasetName, {"dx": -0.22})
    drawPlot(createPlot(
        tdDeltaPhi.clone(
            selection=And(tauEmbedding.signalNtuple.metCut,
                          tauEmbedding.signalNtuple.bTaggingCut))),
             "deltaPhi_3AfterBTagging",
             xlabel,
             log=False,
             opts=opts,
             opts2=opts2,
             ylabel="Events / %.0f^{o}",
             function=customDeltaPhi,
             moveLegend=moveLegend,
             cutLine=[160])

    # Transverse mass
    selection = And(*[
        tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.
        bTaggingCut, tauEmbedding.signalNtuple.deltaPhi160Cut
    ])
    opts = {
        "EWKMC": {
            "ymax": 40
        },
        "TTJets": {
            "ymax": 12
        },
        #"WJets": {"ymax": 35},
        "WJets": {
            "ymax": 25
        },
        "SingleTop": {
            "ymax": 2.2
        },
        "DYJetsToLL": {
            "ymax": 6.5
        },
        #"Diboson": {"ymax": 0.9},
        "Diboson": {
            "ymax": 0.8
        },
        "W3Jets": {
            "ymax": 5
        }
    }.get(datasetName, {})
    opts2 = {
        "TTJets": {
            "ymin": 0,
            "ymax": 1.2
        },
        "Diboson": {
            "ymin": 0,
            "ymax": 3.2
        },
    }.get(datasetName, opts2)

    p = createPlot(tdMt.clone(selection=selection))
    p.appendPlotObject(
        histograms.PlotText(0.6,
                            0.7,
                            "#Delta#phi(#tau jet, E_{T}^{miss}) < 160^{o}",
                            size=20))
    moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    drawPlot(p,
             "transverseMass_4AfterDeltaPhi160",
             "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})",
             opts=opts,
             opts2=opts2,
             ylabel="Events / %.0f GeV/c^{2}",
             log=False,
             moveLegend=moveLegend)
    def __init__(self, datasets, datasetName, ntupleCache):
        self.datasets = datasets
        self.datasetName = datasetName
        self.ntupleCache = ntupleCache

        self.styles = styles.getStyles()
def createStyles():
    st = [styles.StyleCompound(styles=[s, styles.StyleLine(lineWidth=5)]) for s in styles.getStyles()]
    st[0] = styles.StyleCompound(styles=[st[0], styles.StyleLine(lineStyle=2)])
    return st
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True

import HiggsAnalysis.HeavyChHiggsToTauNu.tools.dataset as dataset
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.counter as counter
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tauEmbedding as tauEmbedding

analysisEmb = "signalAnalysis"
dataEra = "Run2012ABCD"

myStyles = [styles.getDataStyle()]
for st in styles.getStyles():
    myStyles.append(st)
    #myStyles.append(styles.StyleCompound([st, styles.StyleLine(lineStyle=2)]))

def main():
    dirAve = "."
    # dirSeeds = []
    # inputInfoPath = os.path.join(dirAve, "inputInfo.txt")
    # f = open(inputInfoPath)
    # input_re = re.compile("Embedded input directory: (?P<dir>\S+)")
    # for line in f:
    #     m = input_re.search(line)
    #     if m:
    #         dirSeeds.append(os.path.join("..", m.group("dir")))
    # f.close()
    # if len(dirSeeds) == 0:
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True

import HiggsAnalysis.HeavyChHiggsToTauNu.tools.dataset as dataset
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.counter as counter
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tauEmbedding as tauEmbedding

analysisEmb = "signalAnalysis"
dataEra = "Run2012ABCD"

myStyles = [styles.getDataStyle()]
for st in styles.getStyles():
    myStyles.append(st)
    #myStyles.append(styles.StyleCompound([st, styles.StyleLine(lineStyle=2)]))


def main():
    dirAve = "."
    # dirSeeds = []
    # inputInfoPath = os.path.join(dirAve, "inputInfo.txt")
    # f = open(inputInfoPath)
    # input_re = re.compile("Embedded input directory: (?P<dir>\S+)")
    # for line in f:
    #     m = input_re.search(line)
    #     if m:
    #         dirSeeds.append(os.path.join("..", m.group("dir")))
    # f.close()
示例#8
0
def doPlotsWTauMuRatioUncertaintyEstimate(dsetMgr, ratios, analysisName):
    prefix = era + "_"

    st = [s.clone() for s in styles.getStyles()]
    st[0].marker = 33
    st = [
        styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)])
        for s in st
    ]

    # Nominal
    p = plots.PlotBase([ratios[analysisName][0].Clone()])
    p.setEnergy(dsetMgr.getEnergies())
    p.histoMgr.setHistoDrawStyleAll("P")
    p.histoMgr.setHistoLegendStyleAll("P")
    p.histoMgr.forEachHisto(styles.Generator(st))

    fitLine = ratios[analysisName][1]
    st[0].apply(fitLine)
    p.appendPlotObject(fitLine)

    # Stat. unc. from parameters
    pars = [fitLine.GetParameter(i) for i in xrange(0, fitLine.GetNpar())]
    parErrors = [fitLine.GetParError(i) for i in xrange(0, fitLine.GetNpar())]

    def evalPar(x, i, shift):
        pars_ = pars[:]
        pars_[i] += shift
        return fitLine.EvalPar(x, array.array("d", pars_))

    # Fit function
    fits = [
        ratios[analysisName + "SystFunc0"][1],
        ratios[analysisName + "SystFunc1"][1]
    ]

    def maxDiff(x, tf1s, nominal):
        return max([abs(tf1.Eval(x[0]) - nominal) for tf1 in tf1s])

    # Sample
    samples = [
        ratios[analysisName + "SystWJets"][1],
        ratios[analysisName + "SystSingleTop"][1]
    ]

    # Weight systematic variations
    keys = filter(lambda n: "SystVar" in n, ratios.keys())
    weightSources = {}
    for key in keys:
        src = key[key.find("SystVar") + 7:].replace("Plus",
                                                    "").replace("Minus", "")
        #        if src != "TopPtWeight":
        #            continue
        #        if src != "PUWeight":
        #            continue
        #        print src

        if not src in weightSources:
            weightSources[src] = [ratios[key][1]]
        else:
            weightSources[src].append(ratios[key][1])

    def comb(plus, x, p):
        nominal = fitLine.Eval(x[0])
        diff = 0

        # stat unc
        uncStat = 0.0
        for i, parErr in enumerate(parErrors):
            diffI = max(abs(evalPar(x, i, parErr) - nominal),
                        abs(evalPar(x, i, -parErr)) - nominal)
            uncStat += diffI**2
        diff += uncStat

        # Fit function
        diffFit = maxDiff(x, fits, nominal)
        diff += diffFit**2

        # Sample
        diffSample = maxDiff(x, samples, nominal)
        diff += diffSample**2

        # Weights
        for src, tf1s in weightSources.iteritems():
            diffWeight = maxDiff(x, tf1s, nominal)
            diff += diffWeight**2

        diff = math.sqrt(diff)
        if plus:
            ret = nominal + diff
        else:
            ret = nominal - diff

        if ret > 1:
            ret = 1.0
        if ret < 0:
            ret = 0.0


#        if ret > 0:
#            print x[0], (ret-nominal)/ret

        return ret

    p.appendPlotObject(
        ROOT.TF1("combPlus", lambda x, p: comb(True, x, p), fitLine.GetXmin(),
                 fitLine.GetXmax(), fitLine.GetNpar()))
    p.appendPlotObject(
        ROOT.TF1("combMinus", lambda x, p: comb(False, x, p),
                 fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar()))

    # Simple relative uncertainty
    def rel(x):
        return 0.012

    def relUnc(plus, x, p):
        nominal = fitLine.Eval(x[0])
        if plus:
            f = 1 + rel(x[0])
        else:
            f = 1 - rel(x[0])
        return nominal * f

    relPlus = ROOT.TF1("relPlus", lambda x, p: relUnc(True, x, p),
                       fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar())
    relMinus = ROOT.TF1("relMinus", lambda x, p: relUnc(False, x, p),
                        fitLine.GetXmin(), fitLine.GetXmax(),
                        fitLine.GetNpar())
    relPlus.SetLineColor(ROOT.kGreen)
    relMinus.SetLineColor(ROOT.kGreen)
    p.appendPlotObject(relPlus)
    p.appendPlotObject(relMinus)

    def customize(plot):
        xmin = plot.frame.GetXaxis().GetXmin()
        xmax = plot.frame.GetXaxis().GetXmax()
        ymin = plot.frame.GetYaxis().GetXmin()
        ymax = plot.frame.GetYaxis().GetXmax()

        val = 1
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

        l = ROOT.TLine(41, ymin, 41, ymax)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

    plots.drawPlot(
        p,
        prefix + "WMuFractionUncertainty",
        "Muon p_{T} (GeV/c)",
        ylabel="W#rightarrow#mu fraction",
        opts={
            "ymin": 0.9,
            "ymax": 1.02
        },
        createLegend=None,
        #moveLegend={"dh": -0.15, "dx": -0.5},
        customizeBeforeDraw=customize)