Beispiel #1
0
def MCPlot(datasetsMgr, json):
    Verbose("Creating MC plot")
        
    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    ylabel_ = json["ylabel"]
    if json["normalization"]=="normalizeToLumi":
        kwargs = {}
        p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=opts.intLumi, **kwargs)
    elif json["normalization"]=="normalizeToOne":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0], "Arbitrary Units")
        kwargs  = {json["normalization"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" % (json["normalization"]) )
    
    # 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            = ylabel_,
                   rebinX            = json["rebinX"],
                   rebinY            = json["rebinY"], 
                   stackMCHistograms = json["stackMCHistograms"]=="True", 
                   addMCUncertainty  = json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne",
                   addLuminosityText = json["addLuminosityText"]=="True",
                   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
Beispiel #2
0
def PlotHisto(dsetsMgr, h, histoType):
    kwargs = {}
    hList = getHistoList(dsetsMgr, h)

    if 1:
        p = plots.PlotSameBase(dsetsMgr,
                               h,
                               normalizeToOne=False,
                               saveFormats=[],
                               **kwargs)
    else:
        p = plots.MCPlot(dsetsMgr,
                         h,
                         normalizeToLumi=opts.intLumi,
                         saveFormats=[],
                         **kwargs)
        p = plots.PlotSameBase(dsetsMgr, h, saveFormats=[], **kwargs)
        p = plots.MCPlot(dsetsMgr,
                         h,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)

    # Set default styles (Called by default in MCPlot)
    p._setLegendStyles()
    p._setLegendLabels()
    p._setPlotStyles()

    # Customise legend
    for d in dsetsMgr.getAllDatasetNames():
        if "TH2" not in histoType:
            if "pCalo" in h:
                p.histoMgr.setHistoLegendStyle(d, "LP")
                p.histoMgr.setHistoDrawStyle(d, "AP")

    # Draw a customised plot
    kwargs = GetHistoKwargs(h, opts)
    plots.drawPlot(p, h, **kwargs)

    # Add text
    ptSlice = h.rsplit("_")[-1].replace("GE",
                                        "#geq ").replace("to", " to ").replace(
                                            "Pt", "p_{T} = ")
    ptSlice += " GeV"
    histograms.addText(0.20, 0.865, ptSlice, 18)

    # Remove legend?
    if kwargs["removeLegend"]:
        p.removeLegend()

    # Save in all formats chosen by user
    aux.SavePlot(p, opts.saveDir, h, opts.saveFormats, opts.url)
    return
Beispiel #3
0
def MCPlot(datasetsMgr, json):
    Verbose("Creating MC plot")

    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    ylabel_ = json["ylabel"]

    if json["normalization"] == "normalizeToLumi":
        kwargs = {}
        p = plots.MCPlot(datasetsMgr,
                         json["histogram"],
                         normalizeToLumi=opts.intLumi,
                         **kwargs)
    elif json["normalization"] == "normalizeToOne":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0],
                                  "Arbitrary Units")
        kwargs = {json["normalization"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" %
                        (json["normalization"]))
    '''

    if json["normalizationToOne"]=="True":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0], "Arbitrary Units")
        kwargs  = {json["normalizationToOne"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" % (json["normalization"]) )
    '''
    # 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"]

    # Set universal histo styles
    if ("drawStyle" in json):
        p.histoMgr.setHistoDrawStyleAll(json["drawStyle"])
    if ("legendStyle" in json):
        p.histoMgr.setHistoLegendStyleAll(json["legendStyle"])

    # For-loop: All histos
    for index, h in enumerate(p.histoMgr.getHistos()):
        if index == 0:
            continue
        else:
            p.histoMgr.setHistoDrawStyle(h.getName(), "AP")
            p.histoMgr.setHistoLegendStyle(h.getName(), "AP")

    # Set default dataset style to all histos
    for index, h in enumerate(p.histoMgr.getHistos()):
        plots._plotStyles[p.histoMgr.getHistos()
                          [index].getDataset().getName()].apply(
                              p.histoMgr.getHistos()[index].getRootHisto())

    # Draw a customised plot
    saveDir = "/afs/cern.ch/user/m/mtoumazo/public/html/hltaus/TkCalo/"
    saveName = os.path.join(saveDir, json["saveName"])
    plots.drawPlot(
        p,
        saveName,
        xlabel=json["xlabel"],
        ylabel=ylabel_,
        rebinX=json["rebinX"],
        rebinY=json["rebinY"],
        stackMCHistograms=json["stackMCHistograms"] == "True",
        addMCUncertainty=json["addMCUncertainty"] == "True"
        and json["normalization"] != "normalizeToOne",
        addLuminosityText=json["addLuminosityText"] == "True",
        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 = [".pdf"]
    for i, ext in enumerate(saveFormats):
        saveNameURL = saveName + ext
        saveNameURL = saveNameURL.replace(
            "/afs/cern.ch/user/m/mtoumazo/public/html/hltaus/",
            "https://cmsdoc.cern.ch/~mtoumazo/hltaus/")
        if opts.url:
            Print(saveNameURL, 1)
        else:
            Print(saveName + ext, 1)
        p.saveAs(saveName, formats=saveFormats)

    return
Beispiel #4
0
def Plot2dHistograms(datasetsMgr, dsetName, histoName, index):

    msg = "%s%s (%s)%s" % (ShellStyles.SuccessStyle(), histoName, dsetName, ShellStyles.NormalStyle() )
    aux.PrintFlushed(msg, index==1)

    # Custom Filtering of datasets 
    dsetsMgr = datasetsMgr.deepCopy()
    if opts.verbose:
        dsetsMgr.PrintInfo()

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

    for i, d in enumerate(dsetsMgr.getAllDatasetNames(), 0):
        if d == dsetName:
            continue
        else:
            # Remove dataset from manager but do NOT close the file!
            dsetsMgr.remove(d, close=False)

    # Sanity check
    nDatasets = len(dsetsMgr.getAllDatasets())
    if nDatasets > 1:
        raise Exception("More than 1 datasets detected in the dataset manager! Can only support 1 dataset. Please use the -i option to choose exactly 1 dataset'")

    # Get the reference histo and the list of histos to compare
    datasets0 = dsetsMgr.getAllDatasets()[0].getName()
    histoList = [getHisto(dsetsMgr, datasets0, histoName)]

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

    Verbose("Setting universal histo styles", True)
    p.histoMgr.setHistoDrawStyleAll("COLZ")
    #p.histoMgr.setHistoLegendStyleAll("L")

    Verbose("Customising histograms", True)
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3)) #fixme

    Verbose("Setting plot styles to histograms", True)
    for index, h in enumerate(p.histoMgr.getHistos()):
        plots._plotStyles[p.histoMgr.getHistos()[index].getDataset().getName()].apply(p.histoMgr.getHistos()[index].getRootHisto())

    Verbose("Drawing the plot", True)
    plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary
    
    # Add fit line for shrinking cone?
    const= 0.0
    coeff= 0.0
    step = 1    
    xmin = 0
    xmax = 0
    if "GenP_VisEt_Vs" in histoName:
        const=   3.5
        coeff=   1.0        
        step =   100    
        xmin =   0
        xmax =  30
    if "GenP_PtLdg_Vs" in histoName:
        const=   2.5 #2.0
        coeff=   1.0
        step = 100
        xmin =   0
        xmax =  30
    if "VtxIso_Vs_RelIso" in histoName:
        const= -0.5
        coeff=  0.3 #0.4
        step =  100
        xmin =   0
        xmax =   0#3

    if "GenP_VisEt_Vs" in histoName or "GenP_PtLdg_Vs" in histoName:
        gr = getCustomTGraph(histoName, const, coeff, xmin, xmax, step)
        gr.SetLineWidth(3)
        gr.Draw("L same")

    Verbose("Removing the legend", True)
    p.removeLegend()

    Verbose("Adding text on canvas", True)
    histograms.addText(0.22, 0.89, plots._legendLabels[datasets0], 18)
    #histograms.addText(0.5, 0.89, plots._legendLabels[datasets0], 18)

    Verbose("Saving the canvas", True)
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, opts.url)

    return