コード例 #1
0
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]
    kwargs = GetHistoKwargs(saveName, opts)

    # Create the plot
    if "Data" in datasetsMgr.getAllDatasetNames():
        p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
    else:
        if opts.normalizeToLumi:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])
        elif opts.normalizeByCrossSection:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeByCrossSection=True,
                             saveFormats=[],
                             **{})
        elif opts.normalizeToOne:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToOne=True,
                             saveFormats=[],
                             **{})
        else:
            raise Exception(
                "One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\")."
            )

    # Customise z-axis
    if 0:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().GetZaxis().SetTitle(kwargs["zlabel"]))
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3))

    # Drawing style
    if 1:
        p.histoMgr.setHistoDrawStyleAll("AP")
        p.histoMgr.setHistoLegendStyleAll("LP")
    else:
        p.histoMgr.setHistoDrawStyleAll("HIST")
        p.histoMgr.setHistoLegendStyleAll("F")

    # Add dataset name on canvas
    # p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset], bold=True, size=22))

    # Draw the plot
    plots.drawPlot(p, saveName,
                   **kwargs)  #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"])
    return
コード例 #2
0
def MCPlot(datasetsMgr, json):
    Verbose("Creating MC plot")
        
    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    if json["normalization"]=="normalizeToLumi":
        kwargs = {}
        p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=float(json["luminosity"]), **kwargs)
    else:
        kwargs = {json["normalization"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)

    # Label size (optional. Commonly Used in counters)
    xlabelSize = None
    if "xlabelsize" in json:
        xlabelSize = json["xlabelsize"]
    ylabelSize = None
    if "ylabelsize" in json:
        ylabelSize = json["ylabelsize"]

    # Draw a customised plot
    saveName = os.path.join(json["saveDir"], json["title"])
    plots.drawPlot(p, 
                   saveName,                  
                   xlabel            = json["xlabel"], 
                   ylabel            = json["ylabel"],
                   rebinX            = json["rebinX"],
                   rebinY            = json["rebinY"], 
                   stackMCHistograms = json["stackMCHistograms"]=="True", 
                   addMCUncertainty  = json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne",
                   addLuminosityText = json["normalization"]=="normalizeToLumi",
                   addCmsText        = json["addCmsText"]=="True",
                   cmsExtraText      = json["cmsExtraText"],
                   opts              = json["opts"],
                   log               = json["logY"]=="True", 
                   errorBarsX        = json["errorBarsX"]=="True", 
                   moveLegend        = json["moveLegend"],
                   # cutLine           = json["cutValue"], #cannot have this and "cutBox" defined
                   cutBox            = {"cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"]=="True", "line": json["cutLine"]=="True", "greaterThan": json["cutGreaterThan"]=="True"},
                   xlabelsize        = xlabelSize,
                   ylabelsize        = ylabelSize,
                   )
    
    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") )

    # Save in all formats chosen by user
    saveFormats = json["saveFormats"]
    for i, ext in enumerate(saveFormats):
        Print("%s" % saveName + ext, i==0)
    p.saveAs(saveName, formats=saveFormats)
    return
コード例 #3
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None

    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.0}
    
    logY = True

    if "_Pt" in histo: 
        _opts["xmax"] = 1000
        _rebinX = 1
        logY = False
        _xlabel = "p_{T} (GeV)"

    elif "Eta" in histo:
        _xlabel = "#eta"
        logY = False
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
        _rebinX = 2
        _format = "%0.2f"
        
    elif "_E" in histo: 
        _opts["xmax"] = 2000
        _rebinX = 1
        logY = False
        _xlabel = "E (GeV)"
        
    elif "Phi" in histo:
        _rebinX = 2
        _format = "%0.2f"
        _xlabel = "#phi"
        logY = False
        _opts["xmin"] = -4.0
        _opts["xmax"] = 4.0

    
    elif "tau21" in histo:
         _rebinX = 2
        _format = "%0.2f"
        logY = False
        _xlabel = "#tau_{2}/#tau_{1}"
コード例 #4
0
def PlotHistograms(datasetsMgr, histoName, signalsList, cutDir):

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]
    kwargs   = GetHistoKwargs(saveName, opts)

    # Create the plot    
    if "Data" in datasetsMgr.getAllDatasetNames():
        p1 = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
    else:
        if opts.normalizeToLumi:
            p1 = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[])
        #elif opts.normalizeByCrossSection:
        #    p1 = plots.MCPlot(datasetsMgr, histoName, normalizeByCrossSection=True, saveFormats=[], **{})
        else:
            raise Exception("One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\").")
            
    # Create significance plots
    hList = []
    for s in signalsList:
        hList.append(GetSignificanceHisto(p1, datasetsMgr, cutDir=cutDir, signalDataset=s))
    #p2 = plots.ComparisonManyPlot(hList[0], hList[1:])
    p2 = plots.PlotBase(hList, saveFormats=[])
    p2.setLuminosity(opts.intLumi)

    # Drawing style
    # p2.histoMgr.setHistoDrawStyleAll("LP")
    # p2.histoMgr.setHistoLegendStyleAll("LP")
    p2.histoMgr.setHistoDrawStyleAll("HIST")
    p2.histoMgr.setHistoLegendStyleAll("L")
    p2.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0))
    p2.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    p2.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle))

    # Draw the plot
    style.setLogX(opts.logX)
    style.setLogY(opts.logY)
    plots.drawPlot(p1, saveName, **kwargs)
    # SavePlot(p1, saveName, os.path.join(opts.saveDir), [".png", ".pdf"] )

    # Draw the significance
    xMax, yMax = getXMaxYMax(hList)
    kwargs["opts"]["ymax"] = yMax*kwargs["opts"]["ymaxfactor"]
    kwargs["cutBox"]       = {"cutValue": xMax, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
    kwargs["cutBoxY"]      = {"cutValue": yMax, "fillColor": 16, "box": False, "line": True, "greaterThan": True, "mainCanvas": True, "ratioCanvas": False}
    kwargs["moveLegend"]["dh"] = -0.15
    
    for s in signalsList:
        p2.histoMgr.setHistoLegendLabelMany({
                s:  plots._legendLabels[s]
                })

    if cutDir == ">=":
        name = saveName + "_Signif" + "GE"
    else:
        name = saveName + "_Signif" + "LE"
    plots.drawPlot(p2, name, **kwargs) 
    SavePlot(p2, name, os.path.join(opts.saveDir), [".png"])#, ".pdf"] )
    return
コード例 #5
0
 def createPlot(name, **kwargs):
     if mcOnly:
         plot = plots.MCPlot(datasets,
                             name,
                             normalizeToLumi=mcOnlyLumi,
                             **kwargs)
     else:
         plot = plots.DataMCPlot(datasets, name, **kwargs)
     plot.histoMgr.removeHisto("EWK")
     return plot
コード例 #6
0
def Plot2dHistograms(datasetsMgr, histoName):
    Verbose("Plotting Data-MC Histograms")

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]
    kwargs   = GetHistoKwargs(saveName, opts)

    # Create the 2d plot
    if opts.dataset == "Data":
        p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
    else:
        if opts.normalizeToLumi:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[])
        elif opts.normalizeByCrossSection:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeByCrossSection=True, saveFormats=[], **{})
        elif opts.normalizeToOne:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeToOne=True, saveFormats=[], **{})
        else:
            raise Exception("One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\").")
            
    # Customise z-axis
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle(kwargs["zlabel"]))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3))
    if kwargs.get("zmin") != None:
        zMin = float(kwargs.get("zmin"))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(zMin))
    if kwargs.get("zmax") != None:
        zMax = float(kwargs.get("zmax"))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(zMax))

    # Drawing style    
    p.histoMgr.setHistoDrawStyleAll("COLZ")

    # Add dataset name on canvas
    p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset], bold=True, size=22))

    # Draw the plot
    plots.drawPlot(p, saveName, **kwargs) #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder, opts.dataset), [".png", ".pdf"] )
    return
コード例 #7
0
def PurityHistograms(datasetsMgr, qcdDatasetName):
    '''
    '''
    Verbose("Plotting Purity Histograms")

    # Definitions
    histoNames  = []
    saveFormats = [".png"] #[".C", ".png", ".eps"]
    dataPath    = "ForDataDrivenCtrlPlots"
    histoList   = datasetsMgr.getDataset(qcdDatasetName).getDirectoryContent(dataPath)
    histoList   = [h for h in histoList if "_Purity" in h]
    # histoList   = [h for h in histoList if "_MCEWK" in h]
    histoPaths  = [dataPath+"/"+h for h in histoList]
    histoKwargs = GetHistoKwargs(histoPaths, opts)

    # For-loop: All histograms in list
    for histoName in histoPaths:
        if "_Vs_" in histoName:
            continue

        if "subldg" in histoName.lower():
            continue

        kwargs_  = histoKwargs[histoName]
        saveName = histoName.replace("/", "_")

        # Create the plotting object
        p = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=True, saveFormats=[])
        p.setLuminosity(GetLumi(datasetsMgr))

        # Apply QCD data-driven style
        p.histoMgr.forHisto(qcdDatasetName, styles.getQCDLineStyle())
        p.histoMgr.setHistoDrawStyle(qcdDatasetName, "AP")
        p.histoMgr.setHistoLegendStyle(qcdDatasetName, "LP")
        p.histoMgr.setHistoLegendLabelMany({
                #qcdDatasetName: "QCD (Data)",
                qcdDatasetName: "QCD",
                })

        # Draw and save the plot
        plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary
        SavePlot(p, saveName, os.path.join(opts.saveDir, "", opts.optMode) )
    return
コード例 #8
0
def PlotSignalBackground(datasetsMgr, hG, hF, intLumi):
    kwargs = {}
    _kwargs = {}

    if opts.normaliseToOne:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 0, "ymaxfactor": 1.1}

    if "mass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units

    if "trijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 805  #1005
        _opts = {"xmin": 0.0, "xmax": 805}
    if "bjetmass" in hG.lower():
        _xlabel = "m_{b-tagged jet} (%s)" % _units
        _opts["xmax"] = 50
    if "bjetldgjet_mass" in hG.lower():
        _xlabel = "m_{b, ldg jet} (%s)" % _units
        _opts["xmax"] = 705
    if "bjetsubldgjet_mass" in hG.lower():
        _xlabel = "m_{b-tagged, subldg jet} (%s)" % _units
        _opts["xmax"] = 705
    if "jet_mass" in hG.lower():
        _opts["xmax"] = 750

    if "mult" in hG.lower():
        _format = "%0.0f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet mult"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet mult"
        if "avg" in hG.lower():
            _xlabel = "avg CvsL"

    if "cvsl" in hG.lower():
        _format = "%0.2f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet CvsL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CvsL"
        if "avg" in hG.lower():
            _xlabel = "avg CvsL"
    if "axis2" in hG.lower():
        _format = "%0.3f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet axis2"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet axis2"
        if "avg" in hG.lower():
            _xlabel = "avg axis2"

    if "dijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600
        _opts = {"xmin": 0.0, "xmax": 605, "ymin": 1e-3, "ymaxfactor": 1.0}

    if "trijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{t}"

    if "dijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{W}"

    if "dgjetptd" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet p_{T}D"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet p_{T}D"

    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        else:
            _xlabel = "b-tagged jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.35}

    if "over" in hG.lower():
        _format = "%0.2f "
        _xlabel = "m_{W}/m_{t}"
        _opts["xmax"] = 1
        _opts["xmin"] = 0
    if "likelihood" in hG.lower():
        _format = "%0.2f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet QGL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet QGL"
        if "avg" in hG.lower():
            _xlabel = "avg QGL"

    else:
        pass
    '''
    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
        else:
            _xlabel = "b-tagged jet CSV"
    '''

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    myList = []
    # Customise styling
    pG.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pF.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    #Dataset: ttbar
    dataset = datasetsMgr.getDataset(opts.dataset)  #soti
    #dataset = datasetsMgr.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_1000")

    #Get Genuine-top histogram
    h = dataset.getDatasetRootHisto(hG)
    h.normalizeToOne()
    HG = h.getHistogram()

    #Get Fake-top histogram
    h = dataset.getDatasetRootHisto(hF)
    h.normalizeToOne()
    HF = h.getHistogram()

    #Define Signal style
    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9)
    ])
    #Define Background style
    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kRed - 4, fillStyle=3001)
    ])

    signalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kTeal + 2,
                           markerSizes=None,
                           markerStyle=ROOT.kFullTriangleUp),
        styles.StyleLine(lineColor=ROOT.kTeal + 2,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kTeal + 2)
    ])  #, fillStyle=3001)])

    signalGrayStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kGray + 1,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kGray + 1,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kGray + 1)
    ])
    backgroundGrayStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kGray + 3,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kGray + 3,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kGray + 3, fillStyle=3001)
    ])

    #Comparison Plot
    p = plots.ComparisonPlot(
        histograms.Histo(HF, "Fake", "p", "P"),
        histograms.Histo(HG, "Genuine", "pl", "PL"),
    )

    #Set labels
    p.histoMgr.setHistoLegendLabelMany({
        "Fake": "Unmatched",
        "Genuine": "Truth-matched"
    })

    #Set Draw style
    p.histoMgr.forHisto("Fake", altBackgroundBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Fake", "LP")
    p.histoMgr.setHistoLegendStyle("Fake", "LP")  #F

    p.histoMgr.forHisto("Genuine", altSignalBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
    p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    if "avg" in hG.lower() or "likelihood" in hG.lower() or "over" in hG.lower(
    ):
        p.histoMgr.forHisto("Genuine", signalBDTGStyle)
        p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
        p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    if "Gray" in opts.mcrab:
        p.histoMgr.forHisto("Fake", backgroundGrayStyle)
        p.histoMgr.forHisto("Genuine", signalGrayStyle)
    histoG = histograms.Histo(HG, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)

    histoF = histograms.Histo(HF, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)

    styleG = styles.ttStyle
    styleF = styles.signalStyleHToTB1000

    styleG.apply(HG)
    styleF.apply(HF)

    myList.append(histoG)
    myList.append(histoF)

    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Arbitrary Units / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        #"opts"             : {"ymin": 0.0, "ymaxfactor": 1.1},
        "opts": _opts,
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": False,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
    }

    # Save plot in all formats
    saveName = hG.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    savePath = os.path.join(opts.saveDir + ANALYSISNAME, "HplusMasses",
                            hG.split("/")[0], opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p,
             saveName,
             os.path.join(opts.saveDir + opts.mcrab, opts.optMode),
             saveFormats=[".png"])

    return
コード例 #9
0
def main(hName, opts):

    # Setup the style
    style = tdrstyle.TDRStyle()
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(opts.batchMode)

    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)
    datasetsMgr.updateNAllEventsToPUWeighted()
    # datasetsMgr.PrintCrossSections()
    # datasetsMgr.PrintLuminosities()

    # Set/Overwrite cross-sections
    for d in datasetsMgr.getAllDatasets():
        if "ChargedHiggs" in d.getName():
            datasetsMgr.getDataset(d.getName()).setCrossSection(1.0)
    
    # Merge datasets: All JetHT to "Data", QCD_Pt to "QCD", QCD_bEnriched to "QCD_b",  single-top to "SingleTop", WW, WZ, ZZ to "Diboson"           
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets
    # datasetsMgr.remove("QCD-b") 
    
    # Print dataset information
    # datasetsMgr.PrintInfo()
    
    # Create  plot, with the default 
    s = {"normalizeToOne": True}
    p = plots.MCPlot(datasetsMgr, hName, **s)
    p.histoMgr.setHistoLegendStyleAll("LP")
    p.histoMgr.setHistoDrawStyleAll("EP")
    p.histoMgr.setHistoLegendStyle("ChargedHiggs_HplusTB_HplusToTB_M_500", "F")
    p.histoMgr.setHistoDrawStyle ("ChargedHiggs_HplusTB_HplusToTB_M_500", "HIST")

    # Create a comparison plot
    ratioOpts = {"ymin": 0.0, "ymax": 2.0}
    if kwargs.get("logY")==True:
        canvOpts = {"xmin": 0.0, "ymin": 1e-5, "ymaxfactor": 10}
    else:
        canvOpts = {"ymin": 0.0, "ymaxfactor": 1.2}

    # Draw a customised plot & Save it
    plots.drawPlot(p, 
                   os.path.join(kwargs.get("savePath"), hName.replace("/", "_").replace(" ", "_").replace("(", "_").replace(")", "") ),
                   xlabel=kwargs.get("xlabel"), 
                   ylabel=kwargs.get("ylabel"),
                   rebinX=kwargs.get("rebinX"), 
                   rebinY=kwargs.get("rebinY"),
                   xlabelsize=kwargs.get("xlabelsize"),
                   ratio=kwargs.get("ratio"), 
                   stackMCHistograms=kwargs.get("stackMCHistograms"), 
                   ratioYlabel=kwargs.get("ratioYlabel"),
                   ratioInvert=kwargs.get("ratioInvert"),
                   addMCUncertainty=kwargs.get("addMCUncertainty"), 
                   addLuminosityText=kwargs.get("addLuminosityText"),
                   addCmsText=kwargs.get("addCmsText"),
                   opts=canvOpts, opts2=ratioOpts, 
                   log=kwargs.get("logY"), 
                   errorBarsX=kwargs.get("errorBarsX"),
                   cmsExtraText=kwargs.get("cmsExtraText"),
                   moveLegend=kwargs.get("moveLegend"),
                   drawStyle="P",
                   legendStyle="LP",
                   #cutLine=kwargs.get("cutValue"),
                   cutBox={"cutValue": kwargs.get("cutValue"), "fillColor": kwargs.get("cutFillColour"), "box": kwargs.get("cutBox"), "line": kwargs.get("cutLine"), "lessThan": kwargs.get("cutLessthan")},
                   )
    
    # Remove legend?
    if kwargs.get("removeLegend"):
        p.removeLegend()

    # Additional text
    # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
    # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)
    
    if not opts.batchMode:
        raw_input("=== plotEventVars.py:\n\tPress any key to quit ROOT ...")

    return
コード例 #10
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None
    logY    = True
    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.0}
    
    if "dijetm" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {"cutValue": 80.399, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 400.0
    if "trijetm" in histo.lower():
        _rebinX = 1
        logY    = False
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 1000.0 #1500.0
    if "pt" in histo.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c"
    if "eta" in histo.lower():
        _format = "%0.2f"
        _cutBox = {"cutValue": 0., "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in histo.lower():
        _format = "%0.2f"
        _opts["xmin"] =  0.0
        _opts["xmax"] = 6.0
    if "bdisc" in histo.lower():
        _format = "%0.2f"
    if "tetrajetm" in histo.lower():
        _rebinX = 10
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjjb} (%s)" % (_units)
        _opts["xmax"] = 3500.0
    if "chisqr" in histo.lower():
        _rebinX = 10
        _units  = ""
        _format = "%0.0f " + _units
        _xlabel = "#chi^{2}"
        #_opts["xmax"] = 3500.0
        
    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise Dataset styling
    p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() )
    p.histoMgr.setHistoDrawStyle("QCD", "HIST")
    p.histoMgr.setHistoLegendStyle("QCD", "F")

    p.histoMgr.setHistoDrawStyle("TT", "AP")
    p.histoMgr.setHistoLegendStyle("TT", "LP")

    #p.histoMgr.setHistoDrawStyle("TTZToQQ", "AP")
    #p.histoMgr.setHistoLegendStyle("TTZToQQ", "LP")

    # Customise style                                                                                                                                                                                                          
    if 0:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_500", styles.getSignalStyleHToTB())

    plots.drawPlot(p, 
                   histo,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.62, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    # Save plot in all formats    
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, histo.split("/")[0], "", opts.optMode)
    SavePlot(p, saveName, savePath) 
    return
コード例 #11
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)
#    p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)
    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None

    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.0}

    if "ChiSqr" in histo:
        _rebinX = 1
#        logY    = True
        _units  = ""
        _format = "%0.1f " + _units
        _xlabel = "#chi^{2}"
        _cutBox = {"cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 100

    elif "trijetmass" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 505 #1005

    elif "ht" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV"
        _format = "%0.0f " + _units
        _xlabel = "H_{T} (%s)" % _units
        _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 2000

    elif "tetrajetmass" in histo.lower():
        _rebinX = 5 #5 #10 #4
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 1500 #3500.0

    elif "dijetmass" in histo.lower():
        _rebinX = 1 #5 #10 #4
#        logY    = False
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800 #3500.0
        _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 300

    elif "tetrajetbjetpt" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800
    elif "ldgtrijetpt" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "trijetbdt_mass" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 505 
#    elif "topcandmass" in histo.lower():
#        _rebinX = 2
#        _units  = "GeV/c^{2}"
#        _format = "%0.0f " + _units
#        _xlabel = "m_{jjb} (%s)" % _units
#        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
#        _opts["xmax"] = 505 

    elif "matched_mass" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 505 

    elif "bdtvalue" in histo.lower():
        _format = "%0.1f"

    elif "foxwolframmoment" in histo.lower():
        _format = "%0.1f"
        _cutBox = {"cutValue": 0.5, "fillColor": 16, "box": False, "line": True, "greaterThan": True}

    elif "absdeltamvamax_mctruth_sameobjfakes" in histo.lower():
        _format = "%0.1f"
        _xlabel = "|#Delta BDTG| response"

    elif "deltamvamin_mctruth_sameobjfakespassbdt" in histo.lower():
        _opts["xmax"] = 1
        _opts["xmin"] = -1
    elif "bdtmultiplicity" in histo.lower():
        _opts["xmax"] = 15


    else:
        pass


    if opts.normaliseToOne:
        logY    = False
        Ylabel  = "Arbitrary Units / %s" % (_format)
    else:
        logY    = True
        Ylabel  = "Events / %s" % (_format)

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise styling
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    if "QCD" in datasetsMgr.getAllDatasets():
        p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() )
        p.histoMgr.setHistoDrawStyle("QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("QCD", "F")

    if "TT" in datasetsMgr.getAllDatasets():
        p.histoMgr.setHistoDrawStyle("TT", "AP")
        p.histoMgr.setHistoLegendStyle("TT", "LP")

    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m))
        

    plots.drawPlot(p, 
                   histo,  
                   xlabel       = _xlabel,
                   ylabel       = Ylabel,#"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92},
#                   createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    # Save plot in all formats    
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode)

    if opts.normaliseToOne:
        save_path = savePath + opts.MVAcut
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
    else:
        save_path = savePath + opts.MVAcut + "/normToLumi/"
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"

#    SavePlot(p, saveName, savePath) 
    SavePlot(p, saveName, save_path) 

    return
コード例 #12
0
ファイル: plot_1d.py プロジェクト: mohsinwaseem/HiggsAnalysis
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToLumi=intLumi,
                         saveFormats=[],
                         **kwargs)

    # Get histogram<->kwargs dictionary
    kwargs = GetHistoKwargs(histo, opts)

    # Customise style
    for i, m in enumerate(signalMass):
        massNum = m.rsplit("M_")[-1]
        if i == len(signalMass) - 1:
            p.histoMgr.setHistoDrawStyle(m, "HIST")
            p.histoMgr.setHistoLegendStyle(m, "F")
            p.histoMgr.forHisto(m, styles.getSignalStyleHToTB())
            # p.histoMgr.forHisto(m, styles. getSignalfillStyleHToTB())
            # p.histoMgr.forHisto(m, datasetsMgr.getDataset(m).getRootHisto().SetMarkerStyle(6))
            # h = GetRootHisto(datasetsMgr, m, histo)
            # h.SetFillStyle(1001)
            # p.histoMgr.setHistoLegendStyle(dName, "LP")
            h = datasetsMgr.getDataset(m).getDatasetRootHisto(
                histo).getHistogram()
            styles.qcdFillStyle.apply(h)
        else:
            p.histoMgr.forHisto(m, styles.getSignalStyleHToTB_M(massNum))
            p.histoMgr.setHistoLegendStyle(m, "LP")

    # Plot customised histogram
    plots.drawPlot(
        p,
        histo,
        xlabel=kwargs.get("xlabel"),
        ylabel=kwargs.get("ylabel"),
        log=kwargs.get("log"),
        rebinX=kwargs.get("rebinX"),
        cmsExtraText="Preliminary",
        #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92},
        moveLegend=kwargs.get("moveLegend"),
        opts=kwargs.get("opts"),
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox=kwargs.get("cutBox"),
    )

    # Customise styling
    if 0:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6))
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    # Save plot in all formats
    saveName = histo.split("/")[-1]
    if opts.folder == "":
        savePath = os.path.join(opts.saveDir, opts.optMode)
    else:
        savePath = os.path.join(opts.saveDir,
                                histo.split("/")[0], opts.optMode)
    SavePlot(p, saveName, savePath, [".png", ".pdf"])
    return
コード例 #13
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None

    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.0}


    if "pt" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _opts["xmax"] = 805 #1005

    if "bdisc" in histo.lower():
        _rebinX = 2
        _units  = ""
        _format = "%0.2f " + _units
        _xlabel = "b-discriminator" #(%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _opts["xmax"] = 1.2

    if "ht" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "H_{T} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _opts["xmax"] = 1505 #1005

    if "met" in histo.lower():
        _rebinX = 1
        _units  = "GeV"
        _format = "%0.0f " + _units
        _xlabel = "E_{T,missing} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _opts["xmax"] = 205 #1005

    if "mult" in histo.lower():
        _units  = ""
        _format = "%0.0f " + _units
        _xlabel = "jet multiplicity"
        _opts["xmax"] = 10

    if "mass" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 350 #1005

    elif "tetrajetmass" in histo.lower():
        _rebinX = 5 #5 #10 #4
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 1500 #3500.0

    elif "dijetmass" in histo.lower():
        _rebinX = 1 #5 #10 #4
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800 #3500.0
        _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 300

    elif "tetrajetbjetpt" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "ldgtrijetpt" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "tau" in histo.lower():
        _format = "%0.2f "

    elif "deltar" in histo.lower():
        _format = "%0.2f "

    elif "bdtvalue" in histo.lower():
        _format = "%0.1f"

    else:
        pass


    if opts.normaliseToOne:
        logY    = False
        Ylabel  = "Arbitrary Units / %s" % (_format)
    else:
        logY    = True
        Ylabel  = "Events / %s" % (_format)

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise styling
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    if "QCD" in datasetsMgr.getAllDatasetNames():
        p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() )
        p.histoMgr.setHistoDrawStyle("QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("QCD", "F")

    if "TT" in datasetsMgr.getAllDatasetNames():
        TTStyle           = styles.StyleCompound([styles.StyleFill(fillColor=ROOT.kMagenta-2), styles.StyleLine(lineColor=ROOT.kMagenta-2, lineStyle=ROOT.kSolid, lineWidth=3),
                                                  styles.StyleMarker(markerSize=1.2, markerColor=ROOT.kMagenta-2, markerSizes=None, markerStyle=ROOT.kFullTriangleUp)])
        p.histoMgr.forHisto("TT", TTStyle)
        p.histoMgr.setHistoDrawStyle("TT", "HIST") #AP
        p.histoMgr.setHistoLegendStyle("TT", "F")  #LP
        
        
    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m))
        

    plots.drawPlot(p, 
                   histo,  
                   xlabel       = _xlabel,
                   ylabel       = Ylabel,
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.68, "y1": 0.82, "x2": 1.0, "y2": 0.92},
                   #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    # Save plot in all formats    
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode)

    '''
    if opts.normaliseToOne:
        save_path = savePath + opts.MVAcut
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
    else:
        save_path = savePath + opts.MVAcut + "/normToLumi/"
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
     '''
    
    SavePlot(p, saveName, savePath) 

    return
コード例 #14
0
def PlotHistograms(datasetsMgr):

    # Definitions
    kwargs = {}
    histos = []

    # For-loop: All histos in list
    dName = "ChargedHiggs_HplusTB_HplusToTB_M_%s" % (opts.signalMass)

    # Matched Leading Trijet
    p0 = plots.MCPlot(datasetsMgr,
                      "AnalysisTriplets/TetrajetMass_LdgTopIsHTop",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    hTopTrue = p0.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Matched-LdgTrijet")
    histos.append(hTopTrue)

    # Matched Bjet
    p1 = plots.MCPlot(datasetsMgr,
                      "AnalysisTripletsTrue/TetrajetMass",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    hBjetTrue = p1.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Matched-Bjet")
    histos.append(hBjetTrue)

    # Matched Leading Trijet + Bjet
    p2 = plots.MCPlot(datasetsMgr,
                      "AnalysisTripletsTrue/TetrajetMass_LdgTopIsHTop",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    hAllTrue = p2.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Matched-LdgTrijet-Bjet")
    histos.append(hAllTrue)

    # Inclusive
    p3 = plots.MCPlot(datasetsMgr,
                      "AnalysisTriplets/TetrajetMass",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    hInclusive = p3.histoMgr.getHisto(dName).getRootHisto().Clone("Inclusive")
    histos.append(hInclusive)

    # Unmatched
    hUnmatched = p3.histoMgr.getHisto(dName).getRootHisto().Clone("Unmatched")
    hUnmatched.Add(hAllTrue, +1)
    hUnmatched.Add(hBjetTrue, -1)
    hUnmatched.Add(hTopTrue, -1)
    histos.append(Unmatched)

    # Make comparison plot
    nTotal = hInclusive.Integral()
    align = "{:>25} {:>25}"
    title = align.format("Histogram", "Percentage (%)")
    hLine = 50 * "="
    table = []
    table.append(hLine)
    table.append(title)
    table.append(hLine)
    for h in histos:
        n = h.Integral()
        perc = (n / nTotal) * 100
        table.append(align.format(h.GetName(), " %.1f" % (perc)))

        if opts.normaliseToOne:
            h = h.Scale(1 / h.Integral())

    # Print table info
    table.append(hLine)
    for row in table:
        print row

    # Make comparison plot
    p = plots.ComparisonManyPlot(hInclusive,
                                 [hBjetTrue, hTopTrue, hAllTrue, hUnmatched],
                                 saveFormats=[])
    p.setLuminosity(opts.intLumi)

    # Overwite signal style?
    style = [200, 500, 800, 1000, 2000, 5000]
    lstyle = [
        ROOT.kSolid, ROOT.kDashed, ROOT.kDashDotted, ROOT.kDotted,
        ROOT.kDotted, ROOT.kSolid
    ]
    p.histoMgr.forHisto("Matched-LdgTrijet-Bjet",
                        styles.getFakeBLineStyle())  #styles.getFakeBStyle())
    p.histoMgr.forHisto("Matched-Bjet",
                        styles.mcStyle)  #getInvertedLineStyle())
    p.histoMgr.forHisto("Matched-LdgTrijet", styles.stylesCompound[-1])
    p.histoMgr.forHisto("Inclusive", styles.getGenuineBLineStyle())
    p.histoMgr.forHisto("Unmatched", styles.errorRatioStatStyle)

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Inclusive", "AP")
    p.histoMgr.setHistoDrawStyle("Matched-Bjet", "AP")
    p.histoMgr.setHistoDrawStyle("Matched-LdgTrijet", "HIST")
    p.histoMgr.setHistoDrawStyle("Matched-LdgTrijet-Bjet", "HIST")
    p.histoMgr.setHistoDrawStyle("Unmatched", "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("Inclusive", "LP")
    p.histoMgr.setHistoLegendStyle("Matched-Bjet", "LP")
    p.histoMgr.setHistoLegendStyle("Matched-LdgTrijet", "F")
    p.histoMgr.setHistoLegendStyle("Matched-LdgTrijet-Bjet", "L")
    p.histoMgr.setHistoLegendStyle("Unmatched", "F")

    p.histoMgr.setHistoLegendLabelMany({
        "Inclusive": "Inclusive",
        "Matched-Bjet": "b-jet match",
        "Matched-LdgTrijet": "top match",
        "Matched-LdgTrijet-Bjet": "full match",  #"top + b-jet match",
        "Unmatched": "Combinatoric",
    })

    # Draw customised plot
    saveName = "TetrajetMass"
    _units = "GeV/c^{2}"
    if opts.signalMass > 500:
        _leg = {"x1": 0.20, "y1": 0.65, "x2": 0.45, "y2": 0.87}
    else:
        _leg = {"x1": 0.60, "y1": 0.65, "x2": 0.85, "y2": 0.87}

    if opts.normaliseToOne:
        yLabel = "Arbitrary Units / %0.0f " + _units
    else:
        yLabel = "Events / %0.0f " + _units

    if opts.logY:
        ymin = 1e-3
        ymaxf = 5
    else:
        ymin = 0.0
        ymaxf = 1.2

    ROOT.gStyle.SetNdivisions(6 + 100 * 5 + 10000 * 2, "X")

    plots.drawPlot(
        p,
        saveName,
        xlabel="m_{jjbb} (%s)" % (_units),
        ylabel=yLabel,
        log=opts.logY,
        rebinX=2,  #2, 5
        cmsExtraText="Preliminary",
        createLegend=_leg,
        opts={
            "xmin": 0.0,
            "xmax": 1400.0,
            "ymin": ymin,
            "ymaxfactor": ymaxf
        },
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox={
            "cutValue": opts.signalMass,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        })

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, "%s_M%s" % (saveName, opts.signalMass), savePath)

    return
コード例 #15
0
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    rootHistos = []
    regionsList = ["SR", "VR", "CRone", "CRtwo"]
    hRegion = histoName.split("_")[-1]
    saveName = histoName.rsplit("/")[-1]
    saveName = saveName.replace("_" + hRegion, "")
    kwargs = GetHistoKwargs(saveName, opts)
    myRegions = []

    # For-loop: All histograms in all regions
    for region in regionsList:
        hName = histoName.replace(hRegion, region)
        if "Data" in datasetsMgr.getAllDatasetNames():
            p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])
        else:
            p = plots.MCPlot(datasetsMgr,
                             hName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])

        # Append (non-empty) dataset ROOT histos to a list for plotting
        h = p.histoMgr.getHisto(opts.dataset).getRootHisto()
        if h.GetEntries() > 0:
            h.SetName(region)
            rootHistos.append(h)
            myRegions.append(region)

    # Create a comparison plot for a given dataset in all CRs
    if len(rootHistos) == 0:
        return
    else:
        p = plots.ComparisonManyPlot(rootHistos[0],
                                     rootHistos[1:],
                                     saveFormats=[])
        p.setLuminosity(opts.intLumi)

    if opts.normalizeToOne:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(
            1.0 / h.getRootHisto().Integral()))

    # Drawing style
    p.histoMgr.setHistoDrawStyleAll("AP")
    p.histoMgr.setHistoLegendStyleAll("LP")

    # Apply styles
    for h in rootHistos:
        region = h.GetName()
        if region == "SR":
            styles.fakeBLineStyle1.apply(
                p.histoMgr.getHisto(region).getRootHisto())
            p.histoMgr.setHistoDrawStyle(region, "HIST")
            p.histoMgr.setHistoLegendStyle(region, "L")
        else:
            styles.getABCDStyle(region).apply(
                p.histoMgr.getHisto(region).getRootHisto())

    # Add dataset name on canvas
    p.appendPlotObject(
        histograms.PlotText(0.18,
                            0.88,
                            plots._legendLabels[opts.dataset],
                            bold=True,
                            size=22))

    # Set legend labels
    if "CRone" in myRegions:
        p.histoMgr.setHistoLegendLabelMany({
            "CRone": "CR1",
        })
    if "CRtwo" in myRegions:
        p.histoMgr.setHistoLegendLabelMany({
            "CRtwo": "CR2",
        })

    # Draw the plot
    plots.drawPlot(p, saveName,
                   **kwargs)  #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"])
    return
コード例 #16
0
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    rootHistos = []
    bdiscList  = ["Loose", "Medium"]
    saveName   = histoName.rsplit("/")[-1]
    kwargs     = GetHistoKwargs(saveName, opts)
    myBdiscs   = []
    histoName  = histoName.replace(opts.folder, "")
    stylesList = [styles.FakeBStyle1, styles.FakeBStyle3, styles.FakeBStyle2, styles.FakeBStyle4] 
    #stylesList = [styles.fakeBLineStyle1, styles.FakeBStyle2, styles.FakeBStyle3, styles.FakeBStyle4] 

    # For-loop: All histograms in all regions
    for bdisc in bdiscList:
        
        hName_ = histoName.replace(opts.refBdisc, bdisc)
        hName = opts.folder + "/" + hName_

        if "Data" in datasetsMgr.getAllDatasetNames():
            p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])
        else:
            p = plots.MCPlot(datasetsMgr, hName, normalizeToLumi=opts.intLumi, saveFormats=[])
            
        # Append (non-empty) dataset ROOT histos to a list for plotting
        h = p.histoMgr.getHisto(opts.dataset).getRootHisto()
        if h.GetEntries() > 0:
            h.SetName(bdisc)
            rootHistos.append(h)
            myBdiscs.append(bdisc)

    # Create a comparison plot for a given dataset in all CRs
    if len(rootHistos) < 2:
        Print("Cannot plot comparison due to too few non-empty histograms present (=%i)" % (len(rootHistos)), False)
        return

    # Move ref histo to top of rootHisto list
    for rh in rootHistos:
        if opts.refBdisc in rh.GetName():
            s = rootHistos.pop( rootHistos.index(rh) )
            #rootHistos.insert(0, s)
            rootHistos.insert(len(rootHistos), s)

    # Draw the comparison plot (first argument the reference histo for ratio purposes)
    p = plots.ComparisonManyPlot(rootHistos[-1], rootHistos[:-1], saveFormats=[])
    # p = plots.ComparisonManyPlot(rootHistos[0], rootHistos[1:], saveFormats=[])
    p.setLuminosity(opts.intLumi)

    if opts.normalizeToOne:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(1.0/h.getRootHisto().Integral()))

    # Apply drawing/legend styles
    for i, bdisc in enumerate(myBdiscs, 0):
        stylesList[i].apply(p.histoMgr.getHisto(bdisc).getRootHisto())
        if bdisc == opts.refBdisc:
            p.histoMgr.setHistoDrawStyle(bdisc, "AP")
            p.histoMgr.setHistoLegendStyle(bdisc,"LP")
        else:
            p.histoMgr.setHistoDrawStyle(bdisc, "AP")
            p.histoMgr.setHistoLegendStyle(bdisc, "LP")
            #p.histoMgr.setHistoDrawStyle(bdisc, "HIST")
            #p.histoMgr.setHistoLegendStyle(bdisc, "F")
            
    # Add dataset name on canvas
    p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset], bold=True, size=22))
    #p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset + " (%s)" % ], bold=True, size=22))

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            "Loose" : "Loose (%s)"  % (GetCRLabel(histoName)),
            "Medium": "Medium (%s)" % (GetCRLabel(histoName)),
            })
    
    # Draw the plot
    plots.drawPlot(p, saveName, **kwargs) #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"] )
    return
コード例 #17
0
def PlotHistogram(dsetMgr, histoName, opts):

    # Get kistogram argumetns
    kwargs   = GetHistoKwargs(histoName, opts)
    saveName = histoName.replace(opts.folder + "/", "")

    # Create the plotting object (Data, "FakeB")
    p1 = plots.DataMCPlot(dsetMgr, histoName, saveFormats=[])

    # Copy dataset manager before changing datasets. Keep only EWK (GenuineB) datasets
    datasetMgr = dsetMgr.deepCopy()
    datasetMgr.selectAndReorder(aux.GetListOfEwkDatasets())
        
    # Create the MCPlot for the EWKGenuineB histograms
    if opts.useMC:
        p2 = plots.MCPlot(datasetMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[])
    else:
        histoNameGenuineB = histoName.replace(opts.folder, opts.folder + "EWKGenuineB")
        p2 = plots.MCPlot(datasetMgr, histoNameGenuineB, normalizeToLumi=opts.intLumi, saveFormats=[])

    # Add the datasets to be included in the plot
    myStackList = []

    # Data-driven FakeB background
    if not opts.useMC:
        hFakeB  = p1.histoMgr.getHisto("FakeB").getRootHisto()
        hhFakeB = histograms.Histo(hFakeB, "FakeB", legendLabel="Fake-b")
        hhFakeB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhFakeB)
    else:
        hQCD  = p1.histoMgr.getHisto("QCD").getRootHisto()
        hhQCD = histograms.Histo(hQCD, "QCD", legendLabel="QCD")
        hhQCD.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhQCD)

    # EWK GenuineB background (Replace all EWK histos with GenuineB histos)
    ewkHistoList = []
    # For-loop: All EWK datasets 
    for dataset in aux.GetListOfEwkDatasets():
        h = p2.histoMgr.getHisto(dataset).getRootHisto()
        hh = histograms.Histo(h, dataset,  plots._legendLabels[dataset])
        hh.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hh)

    # Collision data
    hData  = p1.histoMgr.getHisto("Data").getRootHisto()
    hhData = histograms.Histo(hData, "Data")
    hhData.setIsDataMC(isData=True, isMC=False)
    myStackList.insert(0, hhData)

    # Signal
    hSignal  = p1.histoMgr.getHisto(opts.signal).getRootHisto()
    hhSignal = histograms.Histo(hSignal, opts.signal, plots._legendLabels[opts.signal])
    hhSignal.setIsDataMC(isData=False, isMC=True)
    myStackList.insert(1, hhSignal)

    # Create the final plot by passing the histogram list
    p3 = plots.DataMCPlot2(myStackList, saveFormats=[])
    p3.setLuminosity(opts.intLumi)
    p3.setDefaultStyles()

    # Apply blinding of data in Signal Region (After creating the plot)
    if "blindingRangeString" in kwargs:
        startBlind = float(kwargs["blindingRangeString"].split("-")[1])
        endBlind   = float(kwargs["blindingRangeString"].split("-")[0])
        plots.partiallyBlind(p3, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs["moveBlindedText"])

    # Draw and save the plot
    plots.drawPlot(p3, saveName, **kwargs)
    SavePlot(p3, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"])
    return
コード例 #18
0
def PurityTripletPlots(datasetsMgr, analysisType=""):
    '''
    Create data-MC comparison plot, with the default:
    - legend labels (defined in plots._legendLabels)
    - plot styles (defined in plots._plotStyles, and in styles)
    - drawing styles ('HIST' for MC, 'EP' for data)
    - legend styles ('L' for MC, 'P' for data)
    '''
    Verbose("Plotting the Purity-Triplets for %s" % analysisType)

    analysisTypes = ["", "EWKFakeB", "EWKGenuineB"]
    if analysisType not in analysisTypes:
        raise Exception(
            "Invalid analysis type \"%s\". Please select one of the following: %s"
            % (analysisType, "\"" + "\", \"".join(analysisTypes) + "\""))
    else:
        folder = "FakeBPurity" + analysisType

    # Definitions
    histoNames = []
    histoKwargs = {}

    # General Settings
    if opts.mergeEWK:
        _moveLegend = {"dx": -0.05, "dy": 0.0, "dh": -0.15}
    else:
        _moveLegend = {"dx": -0.05, "dy": 0.0, "dh": 0.1}

    _kwargs = {
        "xlabel": "",
        "ylabel": "",
        "rebinX": 1,
        "rebinY": None,
        "ratioYlabel": "Data/MC",
        "ratio": False,
        "stackMCHistograms": True,
        "ratioInvert": False,
        "addMCUncertainty": False,
        "addLuminosityText": True,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 2e-1,
            "ymaxfactor": 10
        },
        "opts2": {
            "ymin": 0.0,
            "ymax": 2.0
        },
        "log": True,
        "errorBarsX": True,
        "moveLegend": _moveLegend,
        "cutBox": {
            "cutValue": 0.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        }
    }

    # Create/Draw the plots
    histoNames.append("%s/Inverted_FailedBJetPt_AfterAllSelections" % folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet p_{T} (GeV/c)"
    kwargs["ylabel"] = "Events / %.0f GeV/c"
    kwargs["cutBox"] = {
        "cutValue": 40.0,
        "fillColor": 16,
        "box": True,
        "line": True,
        "greaterThan": True
    }
    histoKwargs["%s/Inverted_FailedBJetPt_AfterAllSelections" %
                folder] = kwargs

    histoNames.append("%s/Inverted_FailedBJetEta_AfterAllSelections" % folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet #eta"
    kwargs["ylabel"] = "Events / %.2f"
    histoKwargs["%s/Inverted_FailedBJetEta_AfterAllSelections" %
                folder] = kwargs

    histoNames.append("%s/Inverted_FailedBJetBDisc_AfterAllSelections" %
                      folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet b-tag discriminator"
    kwargs["ylabel"] = "Events / %.2f"
    kwargs["cutBox"] = {
        "cutValue": 0.8484,
        "fillColor": 16,
        "box": True,
        "line": True,
        "greaterThan": False
    }
    histoKwargs["%s/Inverted_FailedBJetBDisc_AfterAllSelections" %
                folder] = kwargs

    histoNames.append("%s/Inverted_FailedBJetPdgId_AfterAllSelections" %
                      folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet pdgId"
    kwargs["ylabel"] = "Events / %.0f"
    histoKwargs["%s/Inverted_FailedBJetPdgId_AfterAllSelections" %
                folder] = kwargs

    histoNames.append(
        "%s/Inverted_FailedBJetPartonFlavour_AfterAllSelections" % folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet parton flavour"
    kwargs["ylabel"] = "Events / %.0f"
    histoKwargs["%s/Inverted_FailedBJetPartonFlavour_AfterAllSelections" %
                folder] = kwargs

    histoNames.append(
        "%s/Inverted_FailedBJetHadronFlavour_AfterAllSelections" % folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "jet hadron flavour"
    kwargs["ylabel"] = "Events / %.0f"
    histoKwargs["%s/Inverted_FailedBJetHadronFlavour_AfterAllSelections" %
                folder] = kwargs

    histoNames.append("%s/Inverted_FailedBJetAncestry_AfterAllSelections" %
                      folder)
    kwargs = copy.deepcopy(_kwargs)
    kwargs["xlabel"] = "ancestor bit"
    kwargs["ylabel"] = "Events / %.0f"
    histoKwargs["%s/Inverted_FailedBJetAncestry_AfterAllSelections" %
                folder] = kwargs

    # For-loop: All histograms in list
    for histoName in histoNames:
        kwargs_ = histoKwargs[histoName]
        saveName = histoName.replace(folder + "/", "")
        if opts.mcOnly:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])
            kwargs_.pop("ratio", None)
            kwargs_.pop("ratioYlabel", None)
            kwargs_.pop("ratioInvert", None)
            kwargs_.pop("opts2", None)
            plots.drawPlot(p, histoName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary
        else:
            p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
            plots.drawPlot(p, histoName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary

        # Save plot in all formats
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, folder),
                 saveFormats=[".png"])

    return
コード例 #19
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToLumi=intLumi,
                         saveFormats=[],
                         **kwargs)

    # Get histogram<->kwargs dictionary
    kwargs = GetHistoKwargs(histo, opts)

    # Customise styling
    if 0:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6))

        # Customise signal
        for d in datasetsMgr.getAllDatasetNames():
            if "Charged" not in d:
                continue
            else:
                #p.histoMgr.setHistoDrawStyle(d, "HIST")
                p.histoMgr.setHistoLegendStyle(d, "L")
                p.histoMgr.setHistoLegendStyle(d, "L")

    #  Customise QCD style
    p.histoMgr.setHistoDrawStyle("QCD", "P")
    p.histoMgr.setHistoLegendStyle("QCD", "P")
    p.histoMgr.setHistoLegendLabelMany({
        "QCD": "QCD (MC)",
    })

    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        dName = "ChargedHiggs_HplusTB_HplusToTB_M_%s" % m
        if dName in datasetsMgr.getAllDatasetNames():
            p.histoMgr.forHisto(dName, styles.getSignalStyleHToTB_M(m))
            p.histoMgr.setHistoLegendStyle(dName, "LP")

    # Plot customised histogram
    plots.drawPlot(
        p,
        histo,
        xlabel=kwargs.get("xlabel"),
        ylabel=kwargs.get("ylabel"),
        log=kwargs.get("log"),
        rebinX=kwargs.get("rebinX"),
        cmsExtraText="Preliminary",
        #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92},
        moveLegend=kwargs.get("moveLegend"),
        opts=kwargs.get("opts"),
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox=kwargs.get("cutBox"),
    )

    # Save plot in all formats
    saveName = histo.split("/")[-1]
    if opts.folder == "":
        savePath = os.path.join(opts.saveDir, opts.optMode)
    else:
        savePath = os.path.join(opts.saveDir,
                                histo.split("/")[0], opts.optMode)
    SavePlot(p, saveName, savePath, [".png", ".pdf"])
    return
コード例 #20
0
def PlotHistograms(datasetsMgr_Mcrab644_TopPtRew,
                   datasetsMgr_Mcrab644_noTopPtRew,
                   datasetsMgr_Mcrab905_TopPtRew,
                   datasetsMgr_Mcrab905_noTopPtRew):

    # Definitions
    kwargs = {}
    histos = []

    # For-loop: All histos in list
    dName = "TT"

    # Multicrab *644, top pt reweighting:
    p0 = plots.MCPlot(datasetsMgr_Mcrab644_TopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab644_TopPtRew = p0.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab644-ptRew")
    histos.append(h_Mcrab644_TopPtRew)

    # Multicrab *644, no top pt reweighting:
    p1 = plots.MCPlot(datasetsMgr_Mcrab644_noTopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab644_noTopPtRew = p1.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab644-noptRew")
    histos.append(h_Mcrab644_noTopPtRew)

    # Multicrab *905, top pt reweighting:
    p2 = plots.MCPlot(datasetsMgr_Mcrab905_TopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab905_TopPtRew = p2.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab905-ptRew")
    histos.append(h_Mcrab905_TopPtRew)

    # Multicrab *905, no top pt reweighting:
    p3 = plots.MCPlot(datasetsMgr_Mcrab905_noTopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab905_noTopPtRew = p3.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab905-noptRew")
    histos.append(h_Mcrab905_noTopPtRew)

    # Normalise histos
    for h in histos:
        if opts.normaliseToOne:
            h = h.Scale(1 / h.Integral())

    # Make comparison plot
    if opts.eight:
        # p = plots.ComparisonManyPlot(h_Mcrab905_TopPtRew, [ h_Mcrab905_noTopPtRew], saveFormats=[])
        p = plots.ComparisonManyPlot(h_Mcrab905_noTopPtRew,
                                     [h_Mcrab905_TopPtRew],
                                     saveFormats=[])
    else:
        # p = plots.ComparisonManyPlot(h_Mcrab644_TopPtRew, [h_Mcrab644_noTopPtRew], saveFormats=[])
        # p = plots.ComparisonManyPlot(h_Mcrab644_noTopPtRew, [h_Mcrab644_TopPtRew], saveFormats=[])
        p = plots.ComparisonManyPlot(
            h_Mcrab644_noTopPtRew, [h_Mcrab644_TopPtRew, h_Mcrab905_TopPtRew],
            saveFormats=[])
    p.setLuminosity(opts.intLumi)

    # Overwite signal style?
    if opts.eight:
        p.histoMgr.forHisto("Mcrab905-ptRew", styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Mcrab905-noptRew", styles.getFakeBLineStyle())
    else:
        p.histoMgr.forHisto("Mcrab644-ptRew", styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Mcrab644-noptRew", styles.getFakeBLineStyle())

    # Set draw style
    if opts.eight:
        p.histoMgr.setHistoDrawStyle("Mcrab905-noptRew", "HIST")
        p.histoMgr.setHistoDrawStyle("Mcrab905-ptRew", "AP")
    else:
        p.histoMgr.setHistoDrawStyle("Mcrab644-noptRew", "HIST")
        p.histoMgr.setHistoDrawStyle("Mcrab644-ptRew", "AP")

    # Set legend style
    if opts.eight:
        p.histoMgr.setHistoLegendStyle("Mcrab905-noptRew", "L")  #"F"
        p.histoMgr.setHistoLegendStyle("Mcrab905-ptRew", "LP")
    else:
        p.histoMgr.setHistoLegendStyle("Mcrab644-noptRew", "L")  #"F"
        p.histoMgr.setHistoLegendStyle("Mcrab644-ptRew", "LP")

    if opts.eight:
        p.histoMgr.setHistoLegendLabelMany({
            "Mcrab905-ptRew": "p_{T} reweight (8 TeV)",
            "Mcrab905-noptRew": "Default",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            "Mcrab644-ptRew": "p_{T} reweight (13 TeV)",
            "Mcrab644-noptRew": "Default",
        })

    # Draw customised plot
    if opts.eight:
        saveName = "TopQuarkPt_PtReweight_8TeV"
    else:
        saveName = "TopQuarkPt_PtReweight_13TeV"
    _units = "GeV/c"
    _leg = {"x1": 0.55, "y1": 0.75, "x2": 0.85, "y2": 0.87}

    if opts.normaliseToOne:
        yLabel = "Arbitrary Units / %0.0f " + _units
    else:
        yLabel = "Events / %0.0f " + _units

    plots.drawPlot(
        p,
        saveName,
        xlabel="generated top p_{T} (%s)" % (_units),
        ylabel=yLabel,
        log=False,
        rebinX=2,
        cmsExtraText="Simulation",  #"Preliminary",
        ratio=True,
        ratioType="errorPropagation",  #"errorScale", "binomial"
        divideByBinWidth=False,
        ratioErrorOptions={
            "numeratorStatSyst": False,
            "denominatorStatSyst": True
        },
        ratioMoveLegend={
            "dx": +0.21,
            "dy": 0.03,
            "dh": -0.08
        },
        ratioYlabel="Ratio ",
        createLegend=_leg,
        opts={
            "xmin": 0.0,
            "xmax": 800.0,
            "ymin": 0.0,
            "ymaxfactor": 1.2
        },
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox={
            "cutValue": 0.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        })

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath)
    return
コード例 #21
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None

    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.0}
    #_opts   = {"ymin": 1e-3, "ymax": 60}


    if "pt" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        #_opts["xmax"] = 505 #1005

    if "ht" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "H_{T} (%s)" % _units
        _opts["xmax"] = 2000
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        #_opts["xmax"] = 505 #1005
        
    if "eta" in histo.lower():
        _units  = ""
        _format = "%0.1f " + _units
        _xlabel = "#eta %s" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _opts["xmax"] = 2.5
        _opts["xmin"] = -2.5

    if "trijetmass" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 505 #1005
        if "ldg" in histo.lower():
            _xlabel = "m_{jjb}^{ldg} (%s)" % _units
    elif "tetrajetmass" in histo.lower():
        _rebinX = 10 #5 #10 #4
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 2500 #3500.0

    elif "tetrajetpt" in histo.lower():
        _rebinX = 2 #5 #10 #4
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T,jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 1000 #3500.0

    elif "dijetmass" in histo.lower():
        _rebinX = 2 #5 #10 #4
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800 #3500.0
        _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 300
        if "ldg" in histo.lower():
            _xlabel = "m_{jj}^{ldg} (%s)" % (_units)
    elif "tetrajetbjetpt" in histo.lower():
        _rebinX = 2
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T,bjet}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "ldgtrijetpt" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T,jjb}^{ldg}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "ldgtrijetdijetpt" in histo.lower():
        _rebinX = 2
#        logY    = False
        _units  = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T,jj}^{ldg}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800


    elif "topbdt_" in histo.lower():
        _format = "%0.1f"
        _cutBox = {"cutValue": +0.40, "fillColor": 16, "box": False, "line": False, "greaterThan": True}
        _xlabel = "BDTG discriminant"
            
    if "gentop_pt" in histo.lower():
        _rebinX = 1
    if "genquark_pt" in histo.lower():
        _rebinX = 1
        _opts["xmax"] = 500
    else:
        pass

    if "delta" in histo.lower():
        _format = "%0.1f "
        if "phi" in histo.lower():
            _xlabel = "#Delta #phi"
        if "deltar" in histo.lower():
            _rebinX = 2

    if "DiBjetMaxMass_Mass" in histo:
        _units = "GeV"
        _rebinX = 4
        _xlabel = "m_{max}(bb) (%s)" % (_units)
        _format = "%0.0f " + _units
        
    if "DiJetDeltaRmin_Mass" in histo:
        _units = "GeV"
        _format = "%0.0f " + _units
        _xlabel = "m_{#DeltaR_{min}(jj)}(jj) (%s)" % (_units)
        _opts["xmax"] = 200

    if "DiBjetDeltaRmin_Mass" in histo:
        _units = "GeV"
        _format = "%0.0f " + _units
        _rebinX= 2
        _xlabel = "m_{#DeltaR_{min}(bb)}(bb) (%s)" % (_units)
        _opts["xmax"] = 600

    if "LdgBjet_SubldgBjet_Mass" in histo:
        _units = "GeV"
        _format = "%0.0f " + _units
        _rebinX= 4
        _xlabel = "m(b_{ldg}b_{sldg}) (%s)" % (_units)
        
    if "DeltaR_LdgTop_DiBjetDeltaRmin" in histo:
        _rebinX= 2        
        _format = "%0.1f "
        _xlabel = "#DeltaR (top_{ldg}, bb_{#Delta Rmin})"

    if "DeltaR_SubldgTop_DiBjetDeltaRmin" in histo:
        _rebinX= 2        
        _format = "%0.1f "
        _xlabel = "#DeltaR (top_{sldg}, bb_{#Delta Rmin})"

    if "over" in histo.lower():        
        _opts["xmax"] = 15
        _opts["xmax"] = +0.8
        _opts["xmin"] = -0.8
        _xlabel = "#Delta p_{T}(j-q)/p_{T,q}"
        _cutBox = {"cutValue": +0.32, "fillColor": 16, "box": False, "line": True, "greaterThan": True}

    if "within" in histo.lower():
        _opts["xmax"] = +0.8
        _opts["xmin"] = -0.8
        _xlabel = "#Delta p_{T}(j-q)/p_{T,q}"
        _cutBox = {"cutValue": +0.32, "fillColor": 16, "box": False, "line": True, "greaterThan": True}

    if "axis2" in histo.lower():
        _opts["xmax"] = +0.2
        _opts["xmin"] = 0.0
        _xlabel = "axis2"
        _units = ""
        _format = "%0.1f "+_units

    if "axis2" in histo.lower():
        _opts["xmax"] = +0.2
        _opts["xmin"] = 0.0
        _xlabel = "axis2"
        _units  = ""
        _format = "%0.2f "+_units

    if "mass" in histo.lower():
        _xlabel = "M (GeV/c^{2})"
        _units  = "GeV/c^{2}"
        _format = "%0.0f "+_units

    if "mult" in histo.lower():
        _xlabel = "mult"
        _units  = ""
        _format = "%0.0f "+_units

    if "BQuarkFromH_Pt" in histo:
        _opts["xmax"] = 200
        _rebinX= 1

    if "order" in histo.lower():
        _opts["xmax"] = 15
        _rebinX= 1
        if "pt" in histo.lower():
            _xlabel = "indx_{p_{T}}"
        if "csv" in histo.lower():
            _xlabel = "indx_{csv}"

    if "phi_alpha" in histo.lower() or "phi_beta" in histo.lower() or "r_alpha" in histo.lower() or "r_beta" in histo.lower():
        _format = "%0.1f "
        _opts["xmin"] = 0.0
        if "phi" in histo.lower():
            _xlabel = "#phi"
            _opts["xmax"] = 5.5
        else:
            _xlabel = "r"
            _opts["xmax"] = 6.5
        if "alpha" in histo.lower():
            _xlabel = _xlabel+"_{#alpha}"
        else:
            _xlabel = _xlabel+"_{#beta}"
    if opts.normaliseToOne:
        logY    = False
        Ylabel  = "Arbitrary Units / %s" % (_format)
    else:
        logY    = True
        Ylabel  = "Events / %s" % (_format)

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        if "order" in histo.lower():
            _opts["ymin"] = 1e-3
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise styling
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    if "QCD" in datasetsMgr.getAllDatasetNames():
        p.histoMgr.forHisto("QCD", styles.getQCDLineStyle()) #getQCDFillStyle() )
        p.histoMgr.setHistoDrawStyle("QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("QCD", "F")

    if "TT" in datasetsMgr.getAllDatasetNames():
        TTStyle           = styles.StyleCompound([styles.StyleFill(fillColor=ROOT.kMagenta-2), styles.StyleLine(lineColor=ROOT.kMagenta-2, lineStyle=ROOT.kSolid, lineWidth=3),
                                                  styles.StyleMarker(markerSize=1.2, markerColor=ROOT.kMagenta-2, markerSizes=None, markerStyle=ROOT.kFullTriangleUp)])
        p.histoMgr.forHisto("TT", TTStyle)
        p.histoMgr.setHistoDrawStyle("TT", "HIST") #AP
        p.histoMgr.setHistoLegendStyle("TT", "F")  #LP
        
        
    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m))
        

    plots.drawPlot(p, 
                   histo,  
                   xlabel       = _xlabel,
                   ylabel       = Ylabel,
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   #createLegend = {"x1": 0.59, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   createLegend = {"x1": 0.59, "y1": 0.70, "x2": 0.92, "y2": 0.92},
                   #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    # Save plot in all formats    
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode)

    '''
    if opts.normaliseToOne:
        save_path = savePath + opts.MVAcut
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
    else:
        save_path = savePath + opts.MVAcut + "/normToLumi/"
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
     '''
    
    SavePlot(p, saveName, savePath) 

    return
コード例 #22
0
def Fit_Gaus(datasetsMgr, signalMass):

    # Definitions
    kwargs = {}
    histos = []

    dName = "ChargedHiggs_HplusTB_HplusToTB_M_%s" % (signalMass)
    hName = "AnalysisTripletsTrue/TetrajetMass_LdgTopIsHTop"
    dataset = datasetsMgr.getDataset(dName)
    dx = signalMass / 2 + 50
    xmin = signalMass - dx
    xmax = signalMass + dx
    _rebin = 2

    # Get histograms
    pp = plots.MCPlot(datasetsMgr,
                      hName,
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)

    myhist = pp.histoMgr.getHisto(dName).getRootHisto().Clone(
        "TetrajetMass_LdgTopIsHTop0")
    if (opts.normaliseToOne):
        myhist.Scale(1. / myhist.Integral())
    myhist.Rebin(_rebin)

    #Initialize parameters
    #===Gaus
    g_const = myhist.Integral()  #myhist.GetMaximum()
    g_mean = signalMass
    g_sigma = signalMass * 0.1
    xminR = signalMass - g_sigma
    xmaxR = signalMass + g_sigma
    par = array.array('f', [g_const, g_mean, g_sigma])

    xminR, xmaxR = GetFitRange(signalMass)
    G1 = ROOT.TF1("G1", "gaus", xminR, xmaxR)

    #Set parameters
    G1.SetParameters(par[0], par[1], par[2])

    # Fit my function to the histo (https://root.cern.ch/root/htmldoc/guides/users-guide/FittingHistograms.html)
    r = myhist.Fit("G1", "WL Q R S")
    print "=" * 50
    print "***Fitting Results:***"
    print "Signal Mass = %.0f GeV" % (signalMass)
    if 0:
        print "chi2   = %.1f " % (r.Chi2())
        print "ndf    = %.0f " % (r.Ndf())
    print "chi2-N = %.1f " % (r.Chi2() / r.Ndf())
    print "const  = %.2f " % (r.Parameter(0))
    print "constE = %.2f " % (r.ParError(0))
    print "mean   = %.1f  +/- %.1f GeV" % (r.Parameter(1), r.ParError(1))
    print "sigma  = %.1f +/- %.1f GeV" % (r.Parameter(2), r.ParError(2))
    FWHM = 2 * math.sqrt(2 * math.log(2)) * r.Parameter(2)
    FWHM_E = 2 * math.sqrt(2 * math.log(2)) * r.ParError(2)
    print "FWHM   = %.1f +/- %.1f GeV" % (FWHM, FWHM_E)
    print "=" * 50

    par = G1.GetParameters()
    myhist.GetFunction("G1").SetLineWidth(3)
    myhist.Draw()

    #Update parameters
    width = myhist.GetXaxis().GetBinWidth(0)  #bin width
    ibinmn = myhist.GetXaxis().FindBin(xmin)  #first bin
    ibinmx = myhist.GetXaxis().FindBin(xmax)  #last bin
    g1_integral = G1.Integral(xmin, xmax) / width
    g1_mean = G1.GetParameter(1)
    g1_sigma = G1.GetParameter(2)

    myhist.SetMarkerStyle(20)
    myhist.SetMarkerSize(0.4)
    myhist.GetXaxis().SetRangeUser(xmin - 50, xmax + 50)

    G1.SetLineColor(kRed)
    G1.SetLineWidth(3)
    G1.Draw("same")

    ROOT.gStyle.SetOptFit(1)
    sb1 = ROOT.TPaveStats()
    ROOT.gPad.Update()
    sb1 = myhist.FindObject("stats")
    sb1.SetX1NDC(0.65)
    sb1.SetX2NDC(0.92)
    sb1.SetY1NDC(0.65)
    sb1.SetY2NDC(0.8)
    sb1.SetLineColor(2)

    p = plots.MCPlot(datasetsMgr,
                     "AnalysisTripletsTrue/TetrajetMass_LdgTopIsHTop",
                     normalizeToLumi=opts.intLumi,
                     saveFormats=[],
                     **kwargs)
    hTopTrue = p.histoMgr.getHisto(dName).getRootHisto().Clone("Matched")
    histos.append(hTopTrue)

    p0 = plots.PlotBase(datasetRootHistos=[hTopTrue], saveFormats=[])
    p0.histoMgr.forHisto("Matched", styles.getGenuineBLineStyle())
    p0.histoMgr.setHistoDrawStyle("Matched", "AP")
    p0.histoMgr.setHistoLegendLabelMany(
        {"Matched": "m_{H^{+}} = %s GeV" % (signalMass)})

    p0.appendPlotObject(G1)
    saveName = "TetrajetMass_G1"
    _units = "GeV/c^{2}"

    if opts.normaliseToOne:
        yLabel = "Arbitrary Units / %0.0f " + _units
    else:
        yLabel = "Events / %0.0f " + _units

    #if signalMass > 500:
    if 0:
        _leg = {"x1": 0.20, "y1": 0.65, "x2": 0.45, "y2": 0.87}
    else:
        _leg = {"x1": 0.60, "y1": 0.65, "x2": 0.85, "y2": 0.87}

    if opts.logY:
        ymin = 1e-3
        ymaxf = 5
    else:
        ymin = 0.0
        ymaxf = 1.3

    ROOT.gStyle.SetNdivisions(6 + 100 * 5 + 10000 * 2, "X")

    plots.drawPlot(
        p0,
        saveName,
        xlabel="m_{jjbb} (%s)" % (_units),
        ylabel=yLabel,
        log=opts.logY,
        rebinX=_rebin,  #2, 5
        cmsExtraText="Preliminary",
        createLegend=_leg,
        opts={
            "xmin": signalMass - 5 * g_sigma,
            "xmax": signalMass + 5 * g_sigma,
            "ymin": ymin,
            "ymaxfactor": ymaxf
        },  #xmin - 50, xmax + 50
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox={
            "cutValue": signalMass,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        })

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p0, "%s_M%s" % (saveName, signalMass), savePath)

    return r
コード例 #23
0
def PlotSignalBackground(datasetsMgr, hG, hF, intLumi):
    kwargs = {}
    _kwargs = {}
    #kwargs = GetHistoKwargs(hG, opts)

    if opts.normaliseToOne:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    if "mass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units

    if "trijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 805  #1005

    if "bjetmass" in hG.lower():
        _xlabel = "m_{b-tagged jet} (%s)" % _units
        _opts["xmax"] = 50
    if "bjetldgjet_mass" in hG.lower():
        _xlabel = "m_{b, ldg jet} (%s)" % _units
    if "bjetsubldgjet_mass" in hG.lower():
        _xlabel = "m_{b-tagged, subldg jet} (%s)" % _units

    if "jet_mass" in hG.lower():
        _opts["xmax"] = 750

    if "mult" in hG.lower():
        _format = "%0.0f"
        _xlabel = "Leading jet mult"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet mult"

    if "cvsl" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet CvsL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CvsL"

    if "axis2" in hG.lower():
        _format = "%0.3f"
        _xlabel = "Leading jet axis2"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet axis2"

    if "dijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600

    if "trijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{t}"

    if "dijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{W}"

    if "dgjetptd" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet p_{T}D"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet p_{T}D"

    else:
        pass
    '''
    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
        else:
            _xlabel = "b-tagged jet CSV"
    '''

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        else:
            _xlabel = "b-tagged jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.35}

    myList = []
    # Customise styling
    pG.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pF.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    '''
    plots.drawPlot(pG, 
                   hG,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    plots.drawPlot(pF, 
                   hF,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    '''

    dataset = datasetsMgr.getDataset("TT")

    h = dataset.getDatasetRootHisto(hG)
    h.normalizeToOne()
    HG = h.getHistogram()

    h = dataset.getDatasetRootHisto(hF)
    h.normalizeToOne()
    HF = h.getHistogram()

    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9)
    ])
    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kRed - 4, fillStyle=3001)
    ])

    p = plots.ComparisonPlot(
        histograms.Histo(HF, "Fake", "p", "P"),
        histograms.Histo(HG, "Genuine", "pl", "PL"),
    )
    p.histoMgr.setHistoLegendLabelMany({
        "Fake": "Unmatched",
        "Genuine": "Truth-matched"
    })
    p.histoMgr.forHisto("Fake", altBackgroundBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Fake", "LP")
    p.histoMgr.setHistoLegendStyle("Fake", "LP")  #F

    p.histoMgr.forHisto("Genuine", altSignalBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
    p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    #HF = dataset.getDatasetRootHisto(hF).getHistogram()
    #HG = dataset.getDatasetRootHisto(hG).getHistogram()

    histoG = histograms.Histo(HG, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)

    histoF = histograms.Histo(HF, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)

    styleG = styles.ttStyle
    styleF = styles.signalStyleHToTB1000

    #hG = histograms.Histo(histoBkg3, legNameBkg3, "F", "HIST9" )
    #background3_histo = histograms.Histo(histoBkg3, legNameBkg3, "F", "HIST9" )

    styleG.apply(HG)
    styleF.apply(HF)

    myList.append(histoG)
    myList.append(histoF)

    #myList.append(HF)
    #myList.append(HG)

    #    p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[])

    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Arbitrary Units / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 0.0,
            "ymaxfactor": 1.1
        },
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": False,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
    }
    '''
    plots.drawPlot(p, 
                   hG,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.82},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymaxfactor": 1.1},
                   cutBox       = _cutBox,
                   )


    '''
    # Save plot in all formats
    saveName = hG.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    savePath = os.path.join(opts.saveDir, "HplusMasses",
                            hG.split("/")[0], opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p,
             saveName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf", ".C"])

    #SavePlot(p, saveName, savePath)

    #p = plots.DataMCPlot2( myList, saveFormats=[])
    #p.setLuminosity(opts.intLumi)
    #p.setDefaultStyles()

    # Draw the plot and save it
    #hName = hG
    #plots.drawPlot(p, hName, **_kwargs)
    #SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])

    return
コード例 #24
0
def TopSelectionHistograms(opts, datasetsMgr, analysisType):
    '''
    Create data-MC comparison plot, with the default:
    - legend labels (defined in plots._legendLabels)
    - plot styles (defined in plots._plotStyles, and in styles)
    - drawing styles ('HIST' for MC, 'EP' for data)
    - legend styles ('L' for MC, 'P' for data)
    '''
    Verbose("Plotting all topSelection histograms for %s" % analysisType)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    # Definitions
    histoNames = getTopSelectionHistos(opts.histoLevel, analysisType)
    histoKwargs = {}
    saveFormats = [".png", ".pdf"]  #[".C", ".png", ".pdf"]

    # General Settings
    if opts.mergeEWK:
        _moveLegend = {"dx": -0.1, "dy": 0.0, "dh": -0.15}
    else:
        _moveLegend = {"dx": -0.1, "dy": 0.0, "dh": 0.1}
    logY = True
    if logY:
        _opts1 = {"ymin": 1.0, "ymaxfactor": 10}
    else:
        _opts1 = {"ymin": 0.0, "ymaxfactor": 1.2}
    _opts2 = {"ymin": 0.0, "ymax": 2.0},

    _kwargs = {
        "rebinX": 10,
        "rebinY": None,
        "ratioYlabel": "Data/MC",
        "ratio": False,
        "stackMCHistograms": True,
        "ratioInvert": False,
        "addMCUncertainty": False,
        "addLuminosityText": True,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": _opts1,
        "opts2": _opts2,
        "log": logY,
        "errorBarsX": True,
        "moveLegend": _moveLegend,
        "cutBox": {
            "cutValue": 0.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        },
        "ylabel": "Events / %.0f",
    }

    # Create/Draw the plots
    for histoName in histoNames:
        histoKwargs[histoName] = _kwargs

    # For-loop: All histograms in list
    folder = "topSelection_"
    for histoName in histoNames:
        kwargs_ = histoKwargs[histoName]
        saveName = histoName.replace(folder + analysisType + "/", "")

        if opts.mcOnly:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])
            kwargs_.pop("ratio", None)
            kwargs_.pop("ratioYlabel", None)
            kwargs_.pop("ratioInvert", None)
            kwargs_.pop("opts2", None)
            plots.drawPlot(p, saveName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary
        else:
            p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
            plots.drawPlot(p, saveName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary

        # Save plot in all formats
        SavePlot(p, histoName, os.path.join(opts.saveDir, "DataEwkSignal"))
        #SavePlot(p, histoName, os.path.join(opts.saveDir, analysisType) )
    return
コード例 #25
0
def Plot_Comparisons(datasetsMgr, datasetsMgrRef, hT, hR, intLumi):
    #kwargs = {}
    _kwargs = {}
    #kwargs = GetHistoKwargs(hG, opts)

    print
    if opts.normaliseToOne:
        pT = plots.MCPlot(datasetsMgr,
                          hT,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pR = plots.MCPlot(datasetsMgrRef,
                          hR,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pT = plots.MCPlot(datasetsMgr,
                          hT,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pR = plots.MCPlot(datasetsMgrRef,
                          hR,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    print "HT", hT

    xMax = 200
    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Events / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        #"opts"             : {"ymin": 0.1, "ymaxfactor": 1.2},
        "opts": {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": xMax
        },
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": True,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
        "rebinX": 1,
    }

    if "counters" in hT.lower():
        print "HERE"
        ROOT.gStyle.SetLabelSize(16.0, "X")
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 6
        }
        _kwargs["createLegend"] = {
            "x1": 0.65,
            "y1": 0.6,
            "x2": 0.90,
            "y2": 0.77
        },

    if "pt" in hT.lower():
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T} (%s)" % _units
        _kwargs["xmax"] = 800
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 800
        }

    if "mass" in hT.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units
        _kwargs["xmax"] = 800
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 800
        }
        if "tetrajet" in hT.lower():
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 2000
            }
            _kwargs["rebinX"] = 8
    if "trijetmass" in hT.lower():
        print "mass"
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _kwargs["xmax"] = 400  #1005
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 400
        }

    if "eta" in hT.lower():
        _units = ""
        _format = "%0.1f " + _units
        _xlabel = "#eta (%s)" % _units
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": -5.0,
            "xmax": +5.0
        }

    if "mult" in hT.lower():
        _format = "%0.0f"
        if "cleaned" in hT.lower():
            _kwargs["xmax"] = 10
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 10
            }
        else:
            _kwargs["xmax"] = 60
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 60
            }

    if "bdisc" in hT.lower():
        _format = "%0.2f"
        _kwargs["xmax"] = 1
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 1
        }

    if "topbdt" in hT.lower():
        _format = "%0.2f"
        _kwargs["xmax"] = 1
        _kwargs["xmin"] = 0.3
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0.3,
            "xmax": 1.0
        }

    if "dijetmass" in hT.lower():
        print "dijet-mass"
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 300
        }

    else:
        pass

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.5

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    myList = []
    # Customise styling
    pT.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pR.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    datasetTarg = datasetsMgr.getDataset(
        "QCD")  #ChargedHiggs_HplusTB_HplusToTB_M_500
    datasetRef = datasetsMgrRef.getDataset(
        "QCD")  #ChargedHiggs_HplusTB_HplusToTB_M_500

    h = datasetTarg.getDatasetRootHisto(hT)
    #h.normalizeToOne()
    h.normalizeToLuminosity(intLumi)
    HT = h.getHistogram()

    h = datasetRef.getDatasetRootHisto(hR)
    #h.normalizeToOne()
    h.normalizeToLuminosity(intLumi)
    HR = h.getHistogram()

    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9, fillStyle=3001)
    ])

    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        #styles.StyleFill(fillColor=ROOT.kRed-4)
    ])

    signalStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kTeal + 2,
                           markerSizes=None,
                           markerStyle=ROOT.kFullTriangleUp),
        styles.StyleLine(lineColor=ROOT.kTeal + 2,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kTeal + 2, fillStyle=3001)
    ])

    p = plots.ComparisonPlot(
        histograms.Histo(HT, "Target", "pl", "PL"),
        histograms.Histo(HR, "Reference", "pl", "PL"),
    )
    p.histoMgr.setHistoLegendLabelMany({
        "Target": "bug fixed",
        "Reference": "bug"
    })

    if ("TT" in datasetTarg.getName()):
        p.histoMgr.forHisto("Target", altBackgroundBDTGStyle)
        p.histoMgr.forHisto("Reference", altSignalBDTGStyle)
    elif ("QCD" in datasetTarg.getName()):
        p.histoMgr.forHisto(
            "Target", altBackgroundBDTGStyle)  #styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Reference", styles.qcdFillStyle)
    elif ("Charged" in datasetTarg.getName()):
        p.histoMgr.forHisto("Target", altBackgroundBDTGStyle)
        p.histoMgr.forHisto("Reference", signalStyle)

    p.histoMgr.setHistoDrawStyle("Target", "HIST")
    p.histoMgr.setHistoLegendStyle("Target", "LP")  #F

    p.histoMgr.setHistoDrawStyle("Reference", "HIST")
    p.histoMgr.setHistoLegendStyle("Reference", "F")  #LP
    '''
    histoG = histograms.Histo(HT, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)
    
    histoF = histograms.Histo(HR, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)
    '''
    #styleT = styles.ttStyle
    #styleR = styles.signalStyleHToTB1000

    #styleT.apply(HT)
    #styleR.apply(HR)
    '''
    myList.append(histoT)
    myList.append(histoR)
    '''

    # Save plot in all formats
    #saveName = hT.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    #savePath = os.path.join(opts.saveDir, "HplusMasses", hT.split("/")[0], opts.optMode)
    #plots.drawPlot(p, savePath, **_kwargs)
    #SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    dName = datasetTarg.getName()
    dName = dName.replace("ChargedHiggs_HplusTB_HplusToTB_", "")

    saveName = hT.split("/")[-1] + "_" + dName
    #print saveName, hT, opts.saveDir
    savePath = os.path.join(opts.saveDir, hT.split("/")[0], opts.optMode)
    print "TYPE", type(hT), type(savePath), type(p)
    plots.drawPlot(p, savePath, **_kwargs)

    #leg = ROOT.TLegend(0.2, 0.8, 0.81, 0.87)
    leg = ROOT.TLegend(0.2, 0.8, 0.51, 0.87)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    #{"dx": -0.55, "dy": -0.55, "dh": -0.08}
    datasetName = datasetTarg.getName()
    datasetName = datasetName.replace("TT", "t#bar{t}")
    if "ChargedHiggs" in datasetName:
        datasetName = datasetName.replace("ChargedHiggs_HplusTB_HplusToTB_M_",
                                          "m_{H+} = ")
        datasetName = datasetName + "GeV"
    #leg.SetHeader("t#bar{t}")

    leg.SetHeader(datasetName)
    leg.Draw()

    #print savePath
    #savePath = os.path.join(opts.saveDir,  opts.optMode)

    SavePlot(p, saveName, savePath)

    return
コード例 #26
0
def DataMCHistograms(datasetsMgr, analysisType=""):
    '''
    Create data-MC comparison plot, with the default:
    - legend labels (defined in plots._legendLabels)
    - plot styles (defined in plots._plotStyles, and in styles)
    - drawing styles ('HIST' for MC, 'EP' for data)
    - legend styles ('L' for MC, 'P' for data)
    '''
    Verbose("Plotting all histograms for %s" % analysisType)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    # Definitions
    histoNames = []
    histoKwargs = {}
    saveFormats = [".png", ".pdf"]  #[".C", ".png", ".pdf"]

    # General Settings
    if opts.mergeEWK:
        _moveLegend = {"dx": -0.05, "dy": 0.0, "dh": -0.15}
    else:
        _moveLegend = {"dx": -0.05, "dy": 0.0, "dh": 0.1}

    _kwargs = {
        "rebinX": 1,
        "rebinY": None,
        "ratioYlabel": "Data/MC",
        "ratio": False,
        "stackMCHistograms": True,
        "ratioInvert": False,
        "addMCUncertainty": False,
        "addLuminosityText": True,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 2e-1,
            "ymaxfactor": 10
        },  #1.2
        "opts2": {
            "ymin": 0.0,
            "ymax": 2.0
        },
        "log": True,
        "errorBarsX": True,
        "moveLegend": _moveLegend,
        "cutBox": {
            "cutValue": 0.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        },
    }

    # Create/Draw the plots
    histoName = "%s_TopMassReco_LdgTrijetPt_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f"
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_LdgTrijetM_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c^{2}"
    kwargs["log"] = False
    kwargs["opts"] = {"xmax": 700, "ymin": 2e-1, "ymaxfactor": 1.2}
    kwargs["cutBox"] = {
        "cutValue": 173.21,
        "fillColor": 16,
        "box": False,
        "line": True,
        "greaterThan": True
    }
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_SubLdgTrijetPt_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c"
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_SubLdgTrijetM_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c^{2}"
    kwargs["log"] = False
    kwargs["opts"] = {"xmax": 700, "ymin": 2e-1, "ymaxfactor": 1.2}
    kwargs["cutBox"] = {
        "cutValue": 173.21,
        "fillColor": 16,
        "box": False,
        "line": True,
        "greaterThan": True
    }
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_LdgDijetPt_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c"
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_LdgDijetM_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c^{2}"
    kwargs["cutBox"] = {
        "cutValue": 80.399,
        "fillColor": 16,
        "box": False,
        "line": True,
        "greaterThan": True
    }
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_SubLdgDijetPt_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c"
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    histoName = "%s_TopMassReco_SubLdgDijetM_AfterAllSelections" % analysisType
    kwargs = copy.deepcopy(_kwargs)
    kwargs["ylabel"] = "Events / %.0f GeV/c^{2}"
    kwargs["cutBox"] = {
        "cutValue": 80.399,
        "fillColor": 16,
        "box": False,
        "line": True,
        "greaterThan": True
    }
    histoNames.append(histoName)
    histoKwargs[histoName] = kwargs

    # For-loop: All histograms in list
    for histoName in histoNames:
        kwargs_ = histoKwargs[histoName]
        #saveName = os.path.join(opts.saveDir, histoName.replace("/", "_"))
        saveName = histoName.replace("/", "_")

        if opts.mcOnly:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])
            kwargs_.pop("ratio", None)
            kwargs_.pop("ratioYlabel", None)
            kwargs_.pop("ratioInvert", None)
            kwargs_.pop("opts2", None)
            plots.drawPlot(p, saveName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary
        else:
            p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
            plots.drawPlot(p, saveName,
                           **kwargs_)  #the "**" unpacks the kwargs_ dictionary

        # Save plot in all formats
        SavePlot(p, saveName, os.path.join(opts.saveDir, "Signal",
                                           opts.optMode))
    return
コード例 #27
0
def PlotMC(datasetsMgr, histo, intLumi):
    
    kwargs = {}
    p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.01f"
    _xlabel = None
    logY    = False
    _opts   = {"ymin": 1e-3, "ymaxfactor": 1.2}

    if "Pt" in histo:
        if "Gluon" in histo:
            _xlabel = "Gluon Jets p_{T} (GeV)"
        elif "Light" in histo:
            _xlabel = "Light Jets p_{T} (GeV)"

    if "JetsN" in histo:
        if "Gluon" in histo:
            _xlabel = "Gluon Jets Multiplicity"
        elif "Light" in histo:
            _xlabel = "Light Jets Multiplicity"


    if "QGL" in histo:
        _opts["xmin"] = 0.0
        _opts["xmax"] = 1.0
        _units  = ""
        _format = "%0.01f " + _units
        if "Gluon" in histo:
            _xlabel = "Gluon Jets QGL"
        elif "Light" in histo:
            _xlabel = "Light Jets QGL"

    # Customise styling
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m))

    plots.drawPlot(p, 
                   histo,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units",# / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.70, "y1": 0.65, "x2": 0.98, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    # Save plot in all formats    
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, "", "", opts.optMode)
    SavePlot(p, saveName, savePath) 
    return
コード例 #28
0
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]  # histoName.replace("/", "_")
    kwargs_ = GetHistoKwargs(saveName, opts)

    # Create the plotting object
    if "Data" in datasetsMgr.getAllDatasetNames():
        p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
    else:
        if opts.normalizeToLumi:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])
        elif opts.normalizeByCrossSection:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeByCrossSection=True,
                             saveFormats=[],
                             **{})
        elif opts.normalizeToOne:
            p = plots.MCPlot(datasetsMgr,
                             histoName,
                             normalizeToOne=True,
                             saveFormats=[],
                             **{})
        else:
            raise Exception(
                "One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\")."
            )

    # Overwite signal style?
    style = [200, 500, 800, 1000, 2000, 3000, 5000]
    lstyle = [
        ROOT.kSolid, ROOT.kDashed, ROOT.kDashDotted, ROOT.kDotted,
        ROOT.kDotted, ROOT.kSolid
    ]
    for i, d in enumerate(datasetsMgr.getAllDatasets(), 0):
        p.histoMgr.forHisto(d.getName(),
                            styles.getSignalStyleHToTB_M(style[i]))
    if 1:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    p.histoMgr.setHistoLegendLabelMany({
        #"ChargedHiggs_HplusTB_HplusToTB_M_500_MVA0p30": "H^{+} m_{H^{+}} = 500 GeV (BDT #geq 0.3)",
        "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p30" % (opts.signalMass):
        "m_{H^{+}}=%s GeV (BDT #geq 0.3)" % (opts.signalMass),
        "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p40" % (opts.signalMass):
        "m_{H^{+}}=%s GeV (BDT #geq 0.4)" % (opts.signalMass),
        "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p50" % (opts.signalMass):
        "m_{H^{+}}=%s GeV (BDT #geq 0.5)" % (opts.signalMass),
        "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p60" % (opts.signalMass):
        "m_{H^{+}}=%s GeV (BDT #geq 0.6)" % (opts.signalMass),
        "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p70" % (opts.signalMass):
        "m_{H^{+}}=%s GeV (BDT #geq 0.7)" % (opts.signalMass),
    })

    # Apply blinding of signal region
    if "blindingRangeString" in kwargs_:
        startBlind = float(kwargs_["blindingRangeString"].split("-")[1])
        endBlind = float(kwargs_["blindingRangeString"].split("-")[0])
        plots.partiallyBlind(p,
                             maxShownValue=startBlind,
                             minShownValue=endBlind,
                             invert=True,
                             moveBlindedText=kwargs_["moveBlindedText"])

    # Draw and save the plot
    saveName += "_M%s" % (opts.signalMass)
    plots.drawPlot(p, saveName,
                   **kwargs_)  #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode,
                                       opts.folder), [".png", ".pdf"])
    return
コード例 #29
0
ファイル: plotMC_HPlusMass.py プロジェクト: mlotti/HplusHW
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToLumi=intLumi,
                         saveFormats=[],
                         **kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.0f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    if "ChiSqr" in histo:
        _rebinX = 1
        logY = True
        _units = ""
        _format = "%0.1f " + _units
        _xlabel = "#chi^{2}"
        _cutBox = {
            "cutValue": 10.0,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 100
    elif "trijetmass" in histo.lower():
        _rebinX = 4
        logY = False
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 805  #1005
    elif "ht" in histo.lower():
        _rebinX = 2
        logY = False
        _units = "GeV"
        _format = "%0.0f " + _units
        _xlabel = "H_{T} (%s)" % _units
        _cutBox = {
            "cutValue": 500,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        #_opts["xmin"] = 500
        _opts["xmax"] = 2000
    elif "tetrajetmass" in histo.lower():
        _rebinX = 5  #5 #10 #4
        logY = False
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _cutBox = {
            "cutValue": 500.0,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 1500  #3500.0
        #_rebinX = 10
        #_opts["xmax"] = 3500
    elif "tetrajetbjetpt" in histo.lower():
        _rebinX = 2
        logY = False
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T}  (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 600
    elif "foxwolframmoment" in histo.lower():
        _format = "%0.1f"
        _cutBox = {
            "cutValue": 0.5,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
    else:
        pass

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise styling
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    if "QCD" in datasetsMgr.getAllDatasets():
        p.histoMgr.forHisto("QCD", styles.getQCDFillStyle())
        p.histoMgr.setHistoDrawStyle("QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("QCD", "F")

    if "TT" in datasetsMgr.getAllDatasets():
        p.histoMgr.setHistoDrawStyle("TT", "AP")
        p.histoMgr.setHistoLegendStyle("TT", "LP")

    # Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m,
                            styles.getSignalStyleHToTB_M(m))

    plots.drawPlot(
        p,
        histo,
        xlabel=_xlabel,
        ylabel="Arbitrary Units / %s" % (_format),
        log=logY,
        rebinX=_rebinX,
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox=_cutBox,
    )

    # Save plot in all formats
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, "HplusMasses",
                            histo.split("/")[0], opts.optMode)
    SavePlot(p, saveName, savePath)
    return
コード例 #30
0
def PlotMC(datasetsMgr, histo, intLumi):

    kwargs = {}
    if opts.normaliseToOne:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)
    else:
        p = plots.MCPlot(datasetsMgr,
                         histo,
                         normalizeToLumi=intLumi,
                         saveFormats=[],
                         **kwargs)
#    p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs)
# Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.1f"
    _xlabel = None

    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    if "ChiSqr" in histo:
        _rebinX = 1
        #logY    = True
        _units = ""
        _format = "%0.1f " + _units
        _xlabel = "#chi^{2}"
        _cutBox = {
            "cutValue": 10.0,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 100

    elif "trijetjets_deltarmin" in histo.lower():
        _xlabel = "#Delta R_{min}"
        _rebinX = 2
        _opts["xmax"] = 3
        _units = ""
        _format = "%0.1f "
        _cutBox = {
            "cutValue": 0.8,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }

    elif "trijetjets_deltarmax" in histo.lower():
        _xlabel = "#Delta R_{max}"
        _rebinX = 2
        _opts["xmax"] = 3.5
        _units = ""
        _format = "%0.1f "
        _cutBox = {
            "cutValue": 0.8,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }

    elif "trijetdijetdr" in histo.lower():
        _rebinX = 1
        units = ""
        _format = "%0.1f "
        _opts["xmax"] = 3.5
        _cutBox = {
            "cutValue": 0.8,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }

    elif "trijetdijetpt" in histo.lower():
        _rebinX = 2
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "trijetdijetmass" in histo.lower():
        _rebinX = 1
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _opts["xmax"] = 200
        _xlabel = "m_{w} (%s)" % _units
        _cutBox = {
            "cutValue": 80.39,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }

    if "cevts_ldgtrijetmatchedtofatjet_fatjetpt" in histo.lower():
        _rebin = 1
        _opts["xmax"] = 3

    elif "pt" in histo.lower():
        _rebinX = 2
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    elif "trijetmass" in histo.lower():
        _rebinX = 1
        #        logY    = False
        _units = "GeV/c^{2}"
        #        _format = "%0.0f " + _units
        _format = "%0.0f" + (_units)
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 305  #1005
        _opts["xmin"] = 55  #1005

    elif "topcandmass" in histo.lower():
        _rebinX = 1
        #        logY    = False
        _units = "GeV/c^{2}"
        #        _format = "%0.0f " + _units
        _format = "%0.0f" + (_units)
        _xlabel = "m_{jjb}^{BDTG} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 505  #1005
        _opts["xmin"] = 0  #1005

#    elif "ht" in histo.lower():
#        _rebinX = 2
##        logY    = False
#        _units  = "GeV"
#        _format = "%0.0f " + _units
#        _xlabel = "H_{T} (%s)" % _units
#        _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
#        _opts["xmax"] = 2000

    elif "tetrajetptd" in histo.lower():
        _rebinX = 2  #5 #10 #4
        _units = "GeV/c^{2}"
        #        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 2000  #3500.0
        _cutBox = {
            "cutValue": 400,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }

    elif "tetrajetmass" in histo.lower() or "tetrajetmass_" in histo.lower():
        #ROOT.gStyle.SetNdivisions(10, "X")
        #        h = dataset.getDatasetRootHisto(histo).getHistogram()
        #        h.SetTickLength(100, "X")
        _rebinX = 5  #5 #10 #4
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 1500  #3500.0
        _cutBox = {
            "cutValue": 500,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        }

    elif "dijetmass" in histo.lower():
        _rebinX = 1  #5 #10 #4
        #        logY    = False
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % (_units)
        _format = "%0.0f " + _units
        _opts["xmax"] = 800  #3500.0
        _cutBox = {
            "cutValue": 80.4,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 205

    elif "trijetmultiplicitypassbdt" in histo.lower():
        _rebinX = 1
        _opts["xmax"] = 5
        _format = "%0.0f "

    elif "bdtg" or "bdtvalue" in histo.lower():
        _rebinX = 1
        _format = "%0.2f "

    elif "trijetbdt_mass" in histo.lower():
        _rebinX = 2
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _opts["xmax"] = 800

#    if "eta" or "phi" or "delta" in histo.lower():
#_rebinX = 1 #5 #10 #4
#        _units  = ""
#        _format = "%0.1f "

#    if "eta" in histo.lower():
#        _xlabel = "#eta"
#    if "phi" in histo.lower():
#        _xlabel = "#phi"
#    if "pt" in histo.lower():
#        _opts["xmax"] = 800
    elif "boosted" in histo.lower():
        _xlabel = "Trijet Counter"
    elif "matched_dijetpt" in histo.lower():
        _units = "(GeV/c)"
        _xlabel = "p_{T}" + _units

    elif "deltar_bdttrijets_tetrajetbjet" in histo.lower():
        _xlabel = "#Delta R(Trijet,b_{free})"

    elif "tetrajetbjetbdisc" in histo.lower():
        _rebinX = 2
        _opts["xmax"] = 1.05

#    if "matched_dijetmass" in histo.lower():
#        _rebinX = 2
#    if "higgstop_dijetmass" in histo.lower():
#        _rebinX = 2

    elif "trijet_deltaeta_trijet_tetrajetbjet" in histo.lower():
        _rebinX = 2
        _xlabel = "#Delta #eta (Trijet, b_{free})"

    elif "trijet_deltaphi_trijet_tetrajetbjet" in histo.lower():
        _xlabel = "#Delta #phi (Trijet, b_{free})"
    elif "cevts_closejettotetrajetbjet_isbtagged" in histo.lower():
        _units = ""
        _format = "%0.0f " + _units
#    if "higgstop_" in histo.lower():
#        _rebinX = 2
    if "eventtrijetpt2t" in histo.lower():
        _rebinX = 2

    if "ldgfatjetpt" in histo.lower():
        _opts["xmax"] = 1000

    if "deltar_w" in histo.lower():
        _rebinX = 2
        _xlabel = "#Delta R"
        _format = "%0.1f "
        _opts["xmax"] = 5
        logY = True

    if "ldgtrijet_deltar" in histo.lower():
        _rebinX = 2
        _xlabel = "#Delta R"
        _format = "%0.1f "
        _opts["xmax"] = 5
        logY = True

    if "higgstop_deltar" in histo.lower():
        _rebinX = 2
        _xlabel = "#Delta R"
        _format = "%0.1f "
        _opts["xmax"] = 5
        logY = True

    if "allfatjet" in histo.lower():
        _rebinX = 2
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _opts["xmax"] = 800

    else:
        pass

    if opts.normaliseToOne:
        logY = True
        Ylabel = "Arbitrary Units / %s" % (_format)
    else:
        logY = True
        Ylabel = "Events / %s" % (_format)

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
        #_opts   = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None}
    else:
        _opts["ymin"] = 1e0
        #_opts["ymaxfactor"] = yMaxFactor
        #_opts   = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None}

    # Customise styling
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    if "QCD" in datasetsMgr.getAllDatasets():
        p.histoMgr.forHisto("QCD", styles.getQCDFillStyle())
        p.histoMgr.setHistoDrawStyle("QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("QCD", "F")

    if "TT" in datasetsMgr.getAllDatasets():
        p.histoMgr.setHistoDrawStyle("TT", "HIST")
        p.histoMgr.setHistoLegendStyle("TT", "LP")

#    if "M_200" in datasetsMgr.getAllDatasets() or "M_300" in datasetsMgr.getAllDatasets():
#        p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() )
#        p.histoMgr.setHistoDrawStyle("QCD", "P")
#        p.histoMgr.setHistoLegendStyle("QCD", "F")

#    elif d.getName() == "TT" or d.getName() == "QCD" or d.getName() == "Data":
#            otherHisto = histograms.Histo(histo, legName, "LP", "P")
#            otherHistos.append(otherHisto)

# Customise style
    signalM = []
    for m in signalMass:
        signalM.append(m.rsplit("M_")[-1])
    for m in signalM:
        p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m,
                            styles.getSignalStyleHToTB_M(m))
#soti
#        p.histoMgr.setHistoDrawStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "LP")
#        p.histoMgr.setHistoLegendStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "P")

    plots.drawPlot(
        p,
        histo,
        xlabel=_xlabel,
        ylabel=
        Ylabel,  #"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format),
        #                   ylabel       = "Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format),
        log=logY,
        rebinX=_rebinX,
        cmsExtraText="Preliminary",  #_rebinX
        #createLegend = {"x1": 0.48, "y1": 0.45, "x2": 0.92, "y2": 0.92}, #All datasets
        #                   createLegend = {"x1": 0.58, "y1": 0.7, "x2": 0.92, "y2": 0.92},
        createLegend={
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.87
        },
        #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77},   #One dataset
        opts=_opts,
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox=_cutBox,
    )

    # Save plot in all formats
    saveName = histo.split("/")[-1]
    savePath = os.path.join(opts.saveDir, "HplusMasses",
                            histo.split("/")[0], opts.optMode)

    if opts.normaliseToOne:
        save_path = savePath + opts.MVAcut
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"
    else:
        save_path = savePath + opts.MVAcut + "/normToLumi/TT/"
        if opts.noQCD:
            save_path = savePath + opts.MVAcut + "/noQCD/"


#    SavePlot(p, saveName, savePath)
    SavePlot(p, saveName, save_path)

    return