def PlotHistograms(datasetsMgr, histoName): # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object dataset = "FakeB" p = plots.PlotBase( [getHisto(datasetsMgr, dataset, histoName)], saveFormats=[]) p.setLuminosity(opts.intLumi) # Apply histogram style p.histoMgr.forHisto("histo_" + dataset, styles.getFakeBStyle()) # Set drawing/legend style p.histoMgr.setHistoDrawStyle("histo_" + dataset, "AP") p.histoMgr.setHistoLegendStyle("histo_" + dataset, "LP") # Customise legend labels p.histoMgr.setHistoLegendLabelMany({ "histo_" + dataset: "Fake b (VR)", }) # 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), [".png"])#, ".pdf"] ) return
def MtComparisonBaseline(datasets): mt = plots.PlotBase(getHistos(datasets,"ForQCDNormalization/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive", "ForQCDNormalizationEWKFakeTaus/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive", "ForQCDNormalizationEWKGenuineTaus/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive")) # mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity()) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st3 = styles.StyleCompound([styles.styles[3]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) st2.append(styles.StyleLine(lineStyle=3, lineWidth=3)) mt.histoMgr.forHisto("transverseMass", st1) mt.histoMgr.forHisto("transverseMassTriangleCut", st2) mt.histoMgr.forHisto("transverseMass3JetCut", st3) mt.histoMgr.setHistoLegendLabelMany({ "transverseMass": "All baseline Taus", "transverseMassTriangleCut": "Baseline Fake Taus", "transverseMass3JetCut": "Baseline Genuine Taus" }) # mt.histoMgr.setHistoDrawStyleAll("P") mt.appendPlotObject(histograms.PlotText(50, 1, "3-prong Taus", size=20)) xlabel = "E_{T}^{miss} (GeV)" ylabel = "Events / %.2f" plots.drawPlot(mt, "MtComparisonBaseline", xlabel=xlabel, ylabel=ylabel, rebinX=1, log=True, createLegend={"x1": 0.4, "y1": 0.75, "x2": 0.8, "y2": 0.9}, ratio=False, opts2={"ymin": 0.5, "ymax": 1.5})
def MtComparison(datasets): mt = plots.PlotBase(getHistos(datasets,"transverseMass", "transverseMassTriangleCut", "transverseMass3JetCut")) # mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity()) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st3 = styles.StyleCompound([styles.styles[3]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) st2.append(styles.StyleLine(lineStyle=3, lineWidth=3)) mt.histoMgr.forHisto("transverseMass", st1) mt.histoMgr.forHisto("transverseMassTriangleCut", st2) mt.histoMgr.forHisto("transverseMass3JetCut", st3) mt.histoMgr.setHistoLegendLabelMany({ "transverseMass": "m_{T}(#tau jet, E_{T}^{miss})", "transverseMassTriangleCut": "m_{T}(#tau jet, E_{T}^{miss}) with Triangle Cut", "transverseMass3JetCut": "m_{T}(#tau jet, E_{T}^{miss}) with 3-jet Cut" }) # mt.histoMgr.setHistoDrawStyleAll("P") mt.appendPlotObject(histograms.PlotText(300, 50, "p_{T}^{jet} > 50 GeV/c", size=20)) xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})" ylabel = "Events / %.2f" plots.drawPlot(mt, "MtComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=False, createLegend={"x1": 0.4, "y1": 0.75, "x2": 0.8, "y2": 0.9}, ratio=False, opts2={"ymin": 0.5, "ymax": 1.5})
def PlotSignal(datasetsMgr, dataPath, opts): Verbose("Plotting Ctrl Plots with Signal") # Definitions histoList = datasetsMgr.getDataset("Data").getDirectoryContent(dataPath) histoPaths = [dataPath + "/" + h for h in histoList] histoKwargs = GetHistoKwargs(histoPaths, opts) saveFormats = [".C", ".png", ".pdf"] # Create/Draw the plots for histoName in histoPaths: if "_afterstandardselections" not in histoName.lower(): continue # Skip TH2 plots if "JetEtaPhi_" in histoName: continue kwargs_ = histoKwargs[histoName] saveName = histoName.replace("/", "") # Create the plot p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Customise style p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_500", styles.getSignalStyleHToTB()) # Draw the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Save plot in all formats SavePlot(p, histoName, os.path.join(opts.saveDir, "Signal", opts.optMode)) return
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
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
def doPlot(tree): # tree.Draw("BRT:BRH >>htemp(100,0,1, 100,0,1)", "deltaNLL * (deltaNLL < 0.5", "colz goff") # sigma1 = ROOT.gDirectory.Get("htemp").Clone("sigma1") tree.Draw("BRT:BRH >>htemp(100,0,1, 100,0,1)", "deltaNLL * (deltaNLL <= 2)", "colz") sigma2 = ROOT.gDirectory.Get("htemp").Clone("sigma2") bfBRT = None bfBRH = None for entry in tree: if entry.quantileExpected == 1: bfBRT = entry.BRT bfBRH = entry.BRH break print "Best fit B(t->H+) %.8f, B(H+->tau) %.8f" % (bfBRT, bfBRH) bestFit = ROOT.TGraph(1, array.array("d", [bfBRH]), array.array("d", [bfBRT])) bestFit.SetMarkerStyle(34) bestFit.SetMarkerSize(2) histos = [ histograms.HistoGraph(bestFit, "bestFit", drawStyle="P", legendLabel="Best fit", legendStyle="P"), histograms.Histo(sigma2, "sigma2", drawStyle="COLZ", legendLabel=None), ] brt = "#it{B}_{t#rightarrow bH^{+}}" brh = "#it{B}_{H^{+}#rightarrow#tau#nu}" legend_h = 0.1 if opts.bxblimit is not None: limit_tf = ROOT.TF1("bxblimit", "%s/x"%opts.bxblimit) limit_tf.SetLineWidth(2) limit_tf.SetLineStyle(2) limit_tf.SetLineColor(ROOT.kBlack) histos.insert(1, histograms.Histo(limit_tf, "bxblimit", legendLabel="Exp. limit on {brt}#times{brh}\n={limit:.2f}%".format(brt=brt, brh=brh, limit=float(opts.bxblimit)*100))) legend_h += 0.03 plot = plots.PlotBase(histos) x = 0.4 y = 0.87 dy = 0.05 plot.appendPlotObject(histograms.PlotText(x, y, "HH: {brt}^{{2}} #times {brh}^{{2}}".format(brt=brt, brh=brh), bold=False, size=20)) y -= dy #plot.appendPlotObject(histograms.PlotText(x, y, "HW: 2(1-{brt}){brt} #times {brh}".format(brt=brt, brh=brh), bold=False, size=20)) plot.appendPlotObject(histograms.PlotText(x, y, "HW: 2(1-{brt}{brh}){brt}{brh}".format(brt=brt, brh=brh), bold=False, size=20)) # mod1 y -= dy #plot.appendPlotObject(histograms.PlotText(x, y, "WW: (1-{brt})^{{2}}".format(brt=brt), bold=False, size=20)) plot.appendPlotObject(histograms.PlotText(x, y, "WW: (1-{brt}{brh})^{{2}}".format(brt=brt, brh=brh), bold=False, size=20)) # mod2 y -= dy*2 if opts.mass is not None: plot.appendPlotObject(histograms.PlotText(x, y, "m_{H^{+}} = %s GeV" % opts.mass, bold=False, size=20)) y -= dy plot.appendPlotObject(histograms.PlotText(x, y, "Fit to bkg-only Asimov dataset", bold=False, size=20)) y -= 0.01 plots.drawPlot(plot, opts.name, xlabel=brh, ylabel=brt, zlabel="#DeltaLL", zhisto="sigma2", opts={"ymax": 1.0}, createLegend={"x1":x, "y2":y, "x2":x+0.2, "y1":y-legend_h})
def PlotHistos(datasetName, hPath): _kwargs = GetHistoKwargs(hPath, opts) datasetsMgr_list = [] j = 0 histoList = [] # For-loop: All pseudo-multicrabs while j < len(opts.mcrabs): textweight = opts.mcrabs[j].split("_")[-1] dMgr = GetDatasetsFromDir(opts, j) dMgr.updateNAllEventsToPUWeighted() dMgr.loadLuminosities() # from lumi.json # Set/Overwrite cross-sections if "ChargedHiggs" in datasetName: dMgr.getDataset(datasetName).setCrossSection(1.0) # Get dataset dataset = dMgr.getDataset(datasetName) # Get Histogram from dataset histo = dataset.getDatasetRootHisto(hPath).getHistogram() # Set style styles.styles[j].apply(histo) if (j == 0): # refHisto = histograms.Histo(histo, "Nominal", legendStyle = "F", drawStyle="HIST") # refHisto.getRootHisto().SetFillStyle(1001) # refHisto.getRootHisto().SetFillColor(ROOT.kBlue) refHisto = histograms.Histo(histo, "Nominal", legendStyle = "L", drawStyle="HIST") refHisto.getRootHisto().SetLineStyle(ROOT.kSolid) refHisto.getRootHisto().SetLineWidth(3) else: text = str(j) histoList.append(histograms.Histo(histo, "Weight " + textweight, legendStyle = "LP", drawStyle="AP")) j = j + 1 # Create the plotter object p = plots.ComparisonManyPlot(refHisto, histoList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setLegendHeader(plots._legendLabels[datasetName]) # Draw the plots plots.drawPlot(p, opts.saveDir, **_kwargs) # Add text if 0: histograms.addText(0.65, 0.1, "#\pm %.1f %% band" % (opts.bandValue), 20) # Save plot in all formats saveName = hPath.split("/")[-1] + "_" + datasetName SavePlot(p, saveName, opts.saveDir, saveFormats = [".png", ".pdf", ".C"]) return
def doPlot(legList, graphList, saveName, **kwargs): # Definitions hgList = [] lList = {} # For-loop: All TGraphs for i, g in enumerate(graphList, 0): if opts.boldText: gName = legList[i] else: gName = "#font[42]{%s}" % legList[i] hg = histograms.HistoGraph(graphList[i], gName, drawStyle="L", legendStyle="l") hgList.append(hg) # Create a plot-base object Verbose("Creating the plot-base object", True) # plot = plots.PlotBase(hgList, saveFormats=[]) hgList.insert(0, hgList.pop(opts.refIndex)) plot = plots.ComparisonManyPlot(hgList[0], hgList[1:], saveFormats=[]) #plot = plots.ComparisonManyPlot(hgList[-1], hgList[:-1], saveFormats=[]) # Apply histo style Verbose("Applying the histogram styles (generator)", True) plot.histoMgr.forEachHisto(styles.generator()) # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.2)) # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) def sty(h): r = h.getRootHisto() r.SetLineWidth(3) r.SetMarkerSize(1.2) return # Apply style and set label Verbose("Applying the histogram styles (forEachHisto)", True) plot.histoMgr.forEachHisto(sty) if opts.plotType != "var": plot.setLegendHeader("Sequential Model (Keras)") # Draw the plot Verbose("Drawing the plot", True) plots.drawPlot(plot, saveName, **kwargs) if opts.removeLegend: plot.removeLegend() # Save plots and return Verbose("Saving the plot as %s" % (saveName), True) SavePlot(plot, opts.saveDir, saveName, opts.saveFormats) Verbose( "Plots saved under directory %s" % (sh_s + aux.convertToURL(opts.saveDir, opts.url) + sh_n), True) return
def MCPlot(datasetsMgr, json): Verbose("Creating MC plot") # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi") #if json["normalization"]=="normalizeToLumi": if 0: kwargs = {} p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=float(json["luminosity"]), **kwargs) else: #kwargs = {json["normalization"]: True} kwargs = {"normalizeToOne": 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 = False, #json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne", addLuminosityText = False, 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
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
def plot(self, plotDir): histolist = [] # self.h_data.SetMarkerStyle(21) # self.h_data.SetMarkerSize(2) styles.dataStyle.apply(self.h_data) hhd = histograms.Histo(self.h_data, "Data", legendStyle="PL", drawStyle="E1P") hhd.setIsDataMC(isData=True, isMC=False) histolist.append(hhd) for hname in self.histonames: hhp = histograms.Histo(self.histograms[hname], hname, legendStyle="F", drawStyle="HIST", legendLabel=self.labels[hname]) hhp.setIsDataMC(isData=False, isMC=True) histolist.append(hhp) name = "postFitMt_" + self.name # name = "preFitMt_"+self.name style = tdrstyle.TDRStyle() p = plots.DataMCPlot2(histolist) p.setDefaultStyles() p.stackMCHistograms() p.setLuminosity(lumi) p.addMCUncertainty(postfit=True) # p.addText(0.7, 0.84, "2016", size=20) #FIXME p.setLegendHeader("2016") myParams = {} myParams["xlabel"] = "m_{T} (GeV)" myParams["ylabel"] = "< Events / bin >" myParams["ratio"] = True myParams["ratioYlabel"] = "Data/Bkg. " myParams["logx"] = True myParams["ratioType"] = "errorScale" myParams["ratioErrorOptions"] = { "numeratorStatSyst": False, "denominatorStatSyst": True } myParams["opts"] = self.opts myParams["optsLogx"] = self.optsLogx myParams["opts2"] = self.opts2 myParams["errorBarsX"] = True myParams["xlabelsize"] = 25 myParams["ylabelsize"] = 25 myParams["addMCUncertainty"] = True myParams["addLuminosityText"] = True #FIXME myParams["moveLegend"] = self.moveLegend plots.drawPlot(p, os.path.join(plotDir, name), **myParams) print "Saved plot", os.path.join(plotDir, name)
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
def plot(self,plotDir): histolist = [] # self.h_data.SetMarkerStyle(21) # self.h_data.SetMarkerSize(2) styles.dataStyle.apply(self.h_data) hhd = histograms.Histo(self.h_data,"Data",legendStyle="PL", drawStyle="E1P") hhd.setIsDataMC(isData=True,isMC=False) histolist.append(hhd) for hsignal in self.h_signal: hhs = histograms.Histo(hsignal,hsignal.GetTitle(),legendStyle="L", drawStyle="HIST") hhs.setIsDataMC(isData=False,isMC=True) hhs.getRootHisto().SetLineWidth(2) histolist.append(hhs) for hname in self.histonames: hhp = histograms.Histo(self.histograms[hname],hname,legendStyle="F", drawStyle="HIST",legendLabel=self.labels[hname]) hhp.setIsDataMC(isData=False,isMC=True) histolist.append(hhp) name = "postFitMt_"+self.name # name = "preFitMt_"+self.name style = tdrstyle.TDRStyle() p = plots.DataMCPlot2(histolist) p.setDefaultStyles() p.stackMCHistograms() p.setLuminosity(lumi) p.addMCUncertainty(postfit=True) # p.addText(0.7, 0.84, "2016", size=20) #FIXME p.setLegendHeader(self.getCategoryName()) myParams = {} myParams["xlabel"] = "m_{T} (GeV)" myParams["ylabel"] = "< Events / GeV >" myParams["ratio"] = True myParams["ratioYlabel"] = "Data/Bkg. " myParams["logx"] = True myParams["ratioType"] ="errorScale" myParams["ratioErrorOptions"] = {"numeratorStatSyst": False, "denominatorStatSyst": True} myParams["opts"] = self.opts myParams["optsLogx"] = self.optsLogx myParams["opts2"] = self.opts2 myParams["errorBarsX"] = True myParams["xlabelsize"] = 25 myParams["ylabelsize"] = 25 myParams["addMCUncertainty"] = True myParams["addLuminosityText"] = True #FIXME myParams["moveLegend"] = self.moveLegend plots.drawPlot(p,os.path.join(plotDir, name),**myParams) print "Saved plot",os.path.join(plotDir, name)
def DataMCPlot(datasetsMgr, json): Verbose("Creating Data-MC plot") # Create the Data-MC Plot p = plots.DataMCPlot(datasetsMgr, json["histogram"]) # 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"], ratioYlabel = json["ratioYlabel"], ratio = json["ratio"]=="True", stackMCHistograms = json["stackMCHistograms"]=="True", ratioInvert = json["ratioInvert"]=="True", addMCUncertainty = json["addMCUncertainty"]=="True", addLuminosityText = json["addLuminosityText"]=="True", addCmsText = json["addCmsText"]=="True", cmsExtraText = json["cmsExtraText"], opts = json["opts"], opts2 = json["ratioOpts"], 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
def PlotMC_ForEffPlots(datasetsMgr, histoName, intLumi): index = 0 for dataset in datasetsMgr.getAllDatasets(): datasetName = dataset.getName() rootHisto = dataset.getDatasetRootHisto(histoName) rootHisto.normalizeToLuminosity(intLumi) histo = rootHisto.getHistogram() kwargs = {} if index == 0: # Apply Styles if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "LP") index = 1 else: # Apply Styles if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TTTT", "AP") p.histoMgr.setHistoLegendStyle("TTTT", "LP") _xlabel = "p_{T} (GeV/c)" logY = False _rebinX = 1 units = "GeV/c" _format = "%0.1f" + units _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} _cutBox = False # _cutBox = {"cutValue": 0.5, "fillColor": 16, "box": False, "line": False, "greaterThan": True} 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
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, 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
def PlotHistoGraph(histoGraph, _kwargs): histoName = _kwargs["histoName"] # Make the plots p = plots.PlotBase( [histoGraph], saveFormats=[]) # p = plots.ComparisonManyPlot(histoGraph, [histoGraph1, histoGraph2], saveFormats=[]) # Draw the plots plots.drawPlot(p, histoName, **_kwargs) # Save the plots histoName = histoName.replace("ForFakeBMeasurement/", "") histoName = GetSaveName(histoName) SavePlot(p, histoName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"] ) return
def MtComparison(datasets): mt = plots.PlotBase( getHistos(datasets, "transverseMass", "transverseMassTriangleCut", "transverseMass3JetCut")) # mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity()) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st3 = styles.StyleCompound([styles.styles[3]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) st2.append(styles.StyleLine(lineStyle=3, lineWidth=3)) mt.histoMgr.forHisto("transverseMass", st1) mt.histoMgr.forHisto("transverseMassTriangleCut", st2) mt.histoMgr.forHisto("transverseMass3JetCut", st3) mt.histoMgr.setHistoLegendLabelMany({ "transverseMass": "m_{T}(#tau jet, E_{T}^{miss})", "transverseMassTriangleCut": "m_{T}(#tau jet, E_{T}^{miss}) with Triangle Cut", "transverseMass3JetCut": "m_{T}(#tau jet, E_{T}^{miss}) with 3-jet Cut" }) # mt.histoMgr.setHistoDrawStyleAll("P") mt.appendPlotObject( histograms.PlotText(300, 50, "p_{T}^{jet} > 50 GeV/c", size=20)) xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})" ylabel = "Events / %.2f" plots.drawPlot(mt, "MtComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=False, createLegend={ "x1": 0.4, "y1": 0.75, "x2": 0.8, "y2": 0.9 }, ratio=False, opts2={ "ymin": 0.5, "ymax": 1.5 })
def PlotHistoGraphs(hGraphList, _kwargs): histoName = _kwargs["histoName"] histoName = histoName.replace("ForFakeBMeasurement/", "") histoName = histoName.split("_")[1] # Overwrite some canvas options _kwargs["opts"]["ymin"] = 0.0 _kwargs["opts"]["ymax"] = 1.02 # Create & draw the plot p = plots.PlotBase( hGraphList, saveFormats=[]) p.setLuminosity(opts.intLumi) plots.drawPlot(p, histoName, **_kwargs) # Save the plot SavePlot(p, histoName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"] ) return
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
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
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
def TauPtComparison(datasets): mt = plots.ComparisonPlot(*getHistos3(datasets, "tauPt", "tauPt")) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) mt.histoMgr.forHisto("Taupt_madgraph", st1) mt.histoMgr.forHisto("Taupt_pythia8", st2) mt.histoMgr.setHistoLegendLabelMany({ "Taupt_madgraph": "Tau pt from Madgraph", "Taupt_pythia8": "Tau pt from Pythia8" }) mt.histoMgr.setHistoDrawStyleAll("PE") mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20)) xlabel = "p_{T}^{#tau jet} (GeV)" ylabel = "Events / %.2f" plots.drawPlot(mt, "TauPtComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True, createLegend={ "x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9 }, ratio=False, opts2={ "ymin": 0.5, "ymax": 50 }, opts={ "xmax": 800, "ymin": 1, "ymax": 1000000 })
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
def TauPtComparison(datasets): mt = plots.ComparisonPlot(*getHistos3(datasets,"tauPt","tauPt")) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) mt.histoMgr.forHisto("Taupt_madgraph", st1) mt.histoMgr.forHisto("Taupt_pythia8", st2) mt.histoMgr.setHistoLegendLabelMany({ "Taupt_madgraph": "Tau pt from Madgraph", "Taupt_pythia8": "Tau pt from Pythia8" }) mt.histoMgr.setHistoDrawStyleAll("PE") mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20)) xlabel = "p_{T}^{#tau jet} (GeV)" ylabel = "Events / %.2f" plots.drawPlot(mt, "TauPtComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True, createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9}, ratio=False, opts2={"ymin": 0.5, "ymax": 50}, opts={"xmax": 800, "ymin":1, "ymax":1000000})
def MetComparison(datasets): mt = plots.ComparisonPlot(*getHistos2(datasets,"Met","Met")) # mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity()) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) mt.histoMgr.forHisto("Met_madgraph", st1) mt.histoMgr.forHisto("Met_pythia8", st2) mt.histoMgr.setHistoLegendLabelMany({ "Met_madgraph": "Met from Madgraph", "Met_pythia8": "Met from Pythia8" }) mt.histoMgr.setHistoDrawStyleAll("PE") mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20)) xlabel = "PF E_{T}^{miss} (GeV)" ylabel = "Events / %.2f" plots.drawPlot(mt, "MetComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True, createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9}, ratio=False, opts2={"ymin": 0.5, "ymax": 50}, opts={"xmax": 500})
def PlotHistoGraphs(datasetsMgr, histoName, hideZeros=False): # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] kwargs_ = GetHistoKwargs(saveName, opts) kwargs_["ylabel"] = "Purity" # Create the plotting object dataset = opts.dataset p1 = plots.PlotBase( [getHisto(datasetsMgr, dataset, histoName)], saveFormats=[]) p1.setLuminosity(opts.intLumi) # Convert to TGraph hPurity = p1.histoMgr.getHisto("histo_" + dataset).getRootHisto()#.Clone(dataset + "_clone") hgPurity = convertHisto2TGraph(hPurity, printValues=False, hideZeros=hideZeros) hgPurity.SetName(dataset) # Create & draw the plot p = plots.PlotBase( [hgPurity], saveFormats=[]) p.setLuminosity(opts.intLumi) # Apply histogram style p.histoMgr.forHisto(dataset, styles.getFakeBStyle()) # Set drawing/legend style p.histoMgr.setHistoDrawStyle(dataset, "P") #Do NOT use "AP"!!! p.histoMgr.setHistoLegendStyle(dataset, "LP") # Customise legend labels p.histoMgr.setHistoLegendLabelMany({ dataset: "Fake b (VR)", }) # Draw and save the plot plots.drawPlot(p, histoName.replace(opts.folder, ""), **kwargs_) SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), [".png"])#, ".pdf"] ) return
def main(argv): multicrabDir = sys.argv[1] if not os.path.exists(multicrabDir) or not os.path.isdir(multicrabDir): usage() # Apply TDR style style = tdrstyle.TDRStyle() # Construct datasets as stated in the multicrab.cfg of the execution # directory. The returned object is of type DatasetManager. datasets = dataset.getDatasetsFromMulticrabCfg(directory = multicrabDir) datasetlist = datasets.getMCDatasets() qlist_particle = ["Pt","Phi","Eta"] qlist_met = ["Et","Phi"] qlist_b = ["Pt","Eta"] if mass < 175: objects = { "Hplus/associatedB" : qlist_particle, "Hplus/hplus" : qlist_particle, "Hplus/associatedT" : qlist_particle, "Hplus/associatedSecondaryT" : qlist_particle, "Hplus/associatedTau" : qlist_particle, "Hplus/associatedOneProngTau" : qlist_particle, "met" : qlist_met } else: objects = { "Hplus/associatedB" : qlist_particle, "Hplus/associatedSecondaryB" : qlist_b, "Hplus/hplus" : qlist_particle, "Hplus/associatedT" : qlist_particle, "Hplus/associatedTau" : qlist_particle, "Hplus/associatedOneProngTau" : qlist_particle, "met" : qlist_met } colorlist = [1,2,4,5] print "These objects are considered: ", objects.keys() object_dict={ "met" : "Gen MET", "associatedB" : "associated b", "associatedT" : "associated t", "associatedSecondaryB" : "b (from associated t decay)", "associatedSecondaryT" : "t (from t#bar{t}, t#rightarrow bW)", "hplus" : "H^{#pm}", "associatedTau" : "associated #tau", "associatedOneProngTau" : "associated 1-prong #tau" } quantity_dict={ 'Et' : '(GeV)', "Pt" : "p_{T} (GeV)", "Phi" : "#phi", "Eta" : "#eta" } gen_dict = { 'PYTHIA6' : 'Pythia 6 (LO)', 'PYTHIA8' : 'Pythia 8', '2HDMII' : 'MG 2HDM type II', '2HDMtypeII' : 'MG 2HDM type II', 'MSSM' :'MG5_aMC@NLO MSSM', 'LowTanb' : 'Low tan#beta', '2HDMtypeII_LO' : 'MG5_aMC@NLO (LO)', '2HDMtypeII_NLO' : 'MG5_aMC@NLO (NLO)' } for obj in objects.keys(): for quantity in objects[obj]: HISTONAME = obj + quantity histos = [] for i in range(0,len(datasetlist)): name = datasetlist[i].getName() histotuple = datasetlist[i].getRootHisto(HISTONAME) histo = histotuple[0].Clone() if histo.Integral() == 0: print "Warning, histogram",histo.GetName(),"is empty" continue if len(datasetlist) > 1: histo.Scale(1/histo.Integral()) histo.SetLineColor(colorlist[i]) histo.SetName(gen_dict[name]) histos.append(histo) myParams = {} if len(obj.split("/")) > 1: obj_name = obj.split("/")[1] else: obj_name = obj xmin = None xmax = None if quantity == "Phi": myParams["moveLegend"] = {"dx": -0.25, "dy": -0.2, "dh": -0.1} ymin = 0 ymax = 0.012 elif quantity == "Eta": myParams["moveLegend"] = {"dx": -0.25, "dy": 0.0, "dh": -0.1} myParams["log"] = True xmin = -2.5 xmax = 2.5 ymin = 0.005 ymax = 0.05 if mass > 175: if "associatedB" in obj_name: xmin = -4.0 xmax = 4.0 ymax = 0.02 else: myParams["moveLegend"] = {"dx": -0.25, "dy": 0.0, "dh": -0.1} myParams["log"] = True ymin = 0.00005 ymax = 0.5 if obj_name == "associatedB": ymin = ymin/5 if mass > 175: ymin = ymin*10 if len(histos) > 1: myParams["ratio"] = True myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["ylabel"] = "#LT Events / bin #GT, normalized" if xmin and xmax: myParams["opts"] = {"xmin": xmin, "xmax": xmax, "ymin": ymin, "ymax": ymax} else: myParams["opts"] = {"ymin": ymin, "ymax": ymax} else: myParams["ylabel"] = "#LT Events / bin #GT" myParams["xlabel"] = object_dict[obj_name]+" "+quantity_dict[quantity] if len(histos) <= 1: plot = plots.PlotBase(histos) else: default = histos[0] compared = histos[1:] plot = plots.ComparisonManyPlot(default, compared) plot.saveFormats=formats tb = histograms.PlotTextBox(xmin=0.75, ymin=None, xmax=0.85, ymax=0.1, size=25, lineheight=0.035) tb.addText("m_{H^+} = %s GeV"%mass) plot.appendPlotObject(tb) histograms.createLegend.setDefaults(textSize = 0.045) def customYTitleOffset(p): if quantity != "Pt": scale = 1.2 else: scale = 1 yaxis = p.getFrame().GetYaxis() yaxis.SetTitleOffset(scale*yaxis.GetTitleOffset()) if len(histos) > 1: myParams["customise"] = customYTitleOffset if not os.path.exists(plotDir): os.mkdir(plotDir) plots.drawPlot(plot, os.path.join(plotDir,obj_name+quantity), **myParams)
def PlotEfficiency(datasetsMgr, numPath, denPath): # Definitions myList = [] _kwargs = GetHistoKwargs(numPath, opts) nx = 0 if len(_kwargs["binList"]) > 0: xBins = _kwargs["binList"] nx = len(xBins) - 1 counter = 0 # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): if dataset.isMC(): n = dataset.getDatasetRootHisto(numPath) d = dataset.getDatasetRootHisto(denPath) num = n.getHistogram() den = d.getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) else: num = dataset.getDatasetRootHisto(numPath).getHistogram() den = dataset.getDatasetRootHisto(denPath).getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) # Calculations total = den.Integral(0, den.GetXaxis().GetNbins() + 1) selected = num.Integral(0, num.GetXaxis().GetNbins() + 1) if 0: print "Numerical Efficiency", numPath, dataset.getName( ), ":", round(selected / total, 3) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) eff.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP datasetTT = datasetsMgr.getDataset("TT") # Get the histograms numTT = datasetTT.getDatasetRootHisto(numPath).getHistogram() denTT = datasetTT.getDatasetRootHisto(denPath).getHistogram() if nx > 0: numTT = numTT.Rebin(nx, "", xBins) #num.Rebin(nx, "", xBins) denTT = denTT.Rebin(nx, "", xBins) #den.Rebin(nx, "", xBins) ''' for i in range(1, num.GetNbinsX()+1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) nbinTT = numTT.GetBinContent(i) dbinTT = denTT.GetBinContent(i) eps = nbin/dbin epsTT = nbinTT/dbinTT ratioTT = eps/epsTT if ratioTT > 1: ratioTT = 1/ratioTT #print "bin: ", i, "eps: ", round(eps,5) , "epsTT: ", round(epsTT,5) #print "bin: ", i, "eps/epsTT: ", (1.0 - round(ratioTT, 3))*100 ''' eff_ref = ROOT.TEfficiency(numTT, denTT) eff_ref.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP # Convert to TGraph gEff = convert2TGraph(eff) gEffRef = convert2TGraph(eff_ref) # Style definitions stylesDef = styles.ttStyle styles0 = styles.signalStyleHToTB300 styles1 = styles.signalStyleHToTB500 styles2 = styles.signalStyleHToTB800 styles3 = styles.signalStyleHToTB500 styles4 = styles.signalStyleHToTB1000 styles5 = styles.signalStyleHToTB2000 styles6 = styles.signalStyleHToTB180 styles7 = styles.signalStyleHToTB3000 styles8 = styles.signalStyleHToTB200 if dataset.getName() == "TT": styles.ttStyle.apply(gEffRef) legend_ref = "t#bar{t}" if opts.type == "partonShower": legend_ref = "t#bar{t} (Pythia8)" elif opts.type == "evtGen": legend_ref = "t#bar{t} (Powheg)" refGraph = histograms.HistoGraph(gEffRef, legend_ref, "p", "P") else: styles.markerStyles[counter].apply(gEff) legend = dataset.getName().replace("TT_", "t#bar{t} (").replace( "isr", "ISR ").replace("fsr", "FSR ") legend = legend.replace("hdamp", "hdamp ").replace("DOWN", "down").replace( "UP", "up") legend = legend.replace("mtop1665", "m_{t} = 166.5 GeV") legend = legend.replace("mtop1695", "m_{t} = 169.5 GeV") legend = legend.replace("mtop1715", "m_{t} = 171.5 GeV") legend = legend.replace("mtop1735", "m_{t} = 173.5 GeV") legend = legend.replace("mtop1755", "m_{t} = 175.5 GeV") legend = legend.replace("mtop1785", "m_{t} = 178.5 GeV") legend = legend.replace("TuneEE5C", "Herwig++") legend += ")" counter += 1 #myList.append(histograms.HistoGraph(gEff, legend, "lp", "P")) myList.append(histograms.HistoGraph(gEff, legend, "p", "P")) # Define stuff numPath = numPath.replace("AfterAllSelections_", "") saveName = "Efficiency_%s_%s" % (opts.folder, opts.type) saveName = saveName.replace("__", "_Inclusive_") # Plot the efficiency p = plots.ComparisonManyPlot(refGraph, myList, saveFormats=[]) savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) # Save plot in all formats SavePlot(p, saveName, savePath, saveFormats=[".png", ".pdf", ".C"]) return
def DoPlots(datasetsMgr, histoName): analysisType = "Inverted" # Get the Inclusive (Data, EWK) p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, analysisType)) p1.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) # Get histos inverted_Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone( "Inverted-Data") inverted_EWK = p1.histoMgr.getHisto("EWK").getRootHisto().Clone( "Inverted-EWK") inverted_QCD = p1.histoMgr.getHisto("Data").getRootHisto().Clone( "Inverted-QCD") # Normalize histograms to unit area inverted_Data.Scale(1.0 / inverted_QCD.Integral()) inverted_QCD.Scale(1.0 / inverted_QCD.Integral()) inverted_EWK.Scale(1.0 / inverted_EWK.Integral()) # Create the final plot object (Cannot subtract EWK from Data since the trigger in the MC samples is NOT prescaled. In data it is) p = plots.ComparisonManyPlot(inverted_Data, [inverted_EWK], saveFormats=[]) #p = plots.PlotBase([inverted_Data], saveFormats=[]) # Apply styles p.histoMgr.forHisto("Inverted-Data", styles.getDataStyle()) #p.histoMgr.forHisto("Inverted-QCD" , styles.getInvertedLineStyle() ) p.histoMgr.forHisto("Inverted-EWK", styles.getAltEWKStyle()) # Set draw style p.histoMgr.setHistoDrawStyle("Inverted-Data", "AP") #p.histoMgr.setHistoDrawStyle("Inverted-QCD" , "HIST") p.histoMgr.setHistoDrawStyle("Inverted-EWK", "AP") # Set legend style p.histoMgr.setHistoLegendStyle("Inverted-Data", "P") #p.histoMgr.setHistoLegendStyle("Inverted-QCD" , "L") p.histoMgr.setHistoLegendStyle("Inverted-EWK", "P") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Inverted-Data": "Data", "Inverted-EWK": "EWK", #"Inverted-QCD" : "QCD=Data-EWK", }) # Draw the histograms _cutBox = None _rebinX = 1 #_opts = {"ymin": 1e-4, "ymaxfactor": 2.0} _opts = {"ymin": 1e-4, "ymax": 1e-1} _xlabel = None _units = "GeV/c^{2}" _xlabel = "m_{jjb} (%s)" % _units _ylabel = "Arbitrary Units / %0.0f %s " % (inverted_QCD.GetBinWidth(0), _units) _cutBox = { "cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 1500.0 # Complains (SysError in <TFile::TFile>: file ...) if 0: plots.drawPlot(p, histoName, xlabel=_xlabel, ylabel=_ylabel, log=True, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.62, "y1": 0.78, "x2": 0.92, "y2": 0.92 }, opts=_opts) if 1: plots.drawPlot( p, histoName, xlabel=_xlabel, ylabel=_ylabel, log=True, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.62, "y1": 0.78, "x2": 0.92, "y2": 0.92 }, opts=_opts, opts2={ "ymin": 0.0, "ymax": 2.0 }, ratio=True, ratioInvert=False, ratioYlabel="Ratio", cutBox=_cutBox, ) # Save to ROOT file inverted_QCD.SaveAs("Inverted_QCD.root") # Save plot in all formats SavePlot(p, histoName, os.path.join(opts.saveDir, "Test", opts.optMode)) return
def PurityPlots(datasetsMgr, histoName, analysisType="Inverted"): ''' Create plots with "FakeB=Data-EWKGenuineB" ''' Verbose( "Plotting histogram %s for Data, EWK, QCD for %s" % (histoName, analysisType), True) # Sanity check IsBaselineOrInverted(analysisType) defaultFolder = "FakeBPurity" genuineBFolder = defaultFolder + "EWKGenuineB" fakeBFolder = defaultFolder + "EWKFakeB" # Get histos (Data, EWK) for Inclusive p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, analysisType)) p1.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) # Get histos (Data, EWK) for GenuineB p2 = plots.ComparisonPlot( *getHistos(datasetsMgr, histoName.replace( defaultFolder, genuineBFolder), analysisType)) p2.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) # Clone histograms Data = p1.histoMgr.getHisto(analysisType + "-Data").getRootHisto().Clone(analysisType + "-Data") EWK = p1.histoMgr.getHisto(analysisType + "-EWK").getRootHisto().Clone(analysisType + "-EWK") EWKGenuineB = p2.histoMgr.getHisto( analysisType + "-EWK").getRootHisto().Clone(analysisType + "-EWK") FakeB = p1.histoMgr.getHisto(analysisType + "-Data").getRootHisto().Clone(analysisType + "-FakeB") # Subtract EWKGEnuineB from Data to get FakeB FakeB.Add(EWKGenuineB, -1) #FakeB.Add(EWK, -1) # Dos not work # p1.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2)) # p2.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2)) # Comparison plot. The first argument is the reference histo. All other histograms are compared with respect to that. FakeB_Purity, xMin, xMax = getPurityHisto(FakeB, Data, inclusiveBins=False, printValues=False) EWKGenuineB_Purity, xMin, xMax = getPurityHisto(EWKGenuineB, Data, inclusiveBins=False, printValues=False) p = plots.ComparisonManyPlot(FakeB_Purity, [EWKGenuineB_Purity], saveFormats=[]) # Apply histo styles p.histoMgr.forHisto( analysisType + "-FakeB", styles.getInvertedLineStyle()) #styles.getFakeBLineStyle() ) p.histoMgr.forHisto( analysisType + "-EWK", styles.getAltEWKLineStyle()) #styles.getAltEWKStyle() ) # Set draw style p.histoMgr.setHistoDrawStyle(analysisType + "-FakeB", "HIST") p.histoMgr.setHistoDrawStyle(analysisType + "-EWK", "HIST") # Set legend style p.histoMgr.setHistoLegendStyle(analysisType + "-FakeB", "L") p.histoMgr.setHistoLegendStyle(analysisType + "-EWK", "L") # p.histoMgr.setHistoLegendStyleAll("LP") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ analysisType + "-FakeB": "FakeB", analysisType + "-EWK": "GenuineB (EWK)", }) # Draw the histograms _cutBox = None _rebinX = 1 _opts = {"ymin": 1e-3, "ymaxfactor": 1.2} _format = "%0.0f" _opts["xmax"] = xMax _xlabel = None if "dijetm" in histoName.lower(): _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 } if "trijetm" in histoName.lower(): _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"] = 1500.0 if "pt" in histoName.lower(): _format = "%0.0f GeV/c" if "eta" in histoName.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 histoName.lower(): _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = 6.0 if "bdisc" in histoName.lower(): _format = "%0.2f" if "tetrajetm" in histoName.lower(): _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjjb} (%s)" % (_units) _opts["xmax"] = 3500.0 # Do the plot plots.drawPlot( p, histoName, xlabel=_xlabel, ylabel="Purity / {0}".format(_format), log=False, rebinX=_rebinX, # Can only Rebin BEFORE calculating purity cmsExtraText="Preliminary", createLegend={ "x1": 0.60, "y1": 0.80, "x2": 0.92, "y2": 0.92 }, opts=_opts, opts2={ "ymin": 1e-5, "ymax": 1e0 }, ratio=False, ratioInvert=False, ratioYlabel="Ratio", cutBox=_cutBox, ) # Save plot in all formats SavePlot(p, histoName, os.path.join(opts.saveDir, "Purity", opts.optMode)) #, saveFormats = [".png"] ) return
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
def PlotTemplates(datasetsMgr, histoName, analysisType="Inverted"): Verbose("Plotting EWK Vs QCD unity-normalised histograms") # Create comparison plot p1 = plots.ComparisonPlot( getHisto(datasetsMgr, "Data", histoName, "Baseline"), getHisto(datasetsMgr, "Data", histoName, "Inverted") ) p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity()) defaultFolder = "ForFakeBMeasurement" genuineBFolder = defaultFolder + "EWKGenuineB" fakeBFolder = defaultFolder + "EWKFakeB" histoNameNew = histoName.replace( defaultFolder, genuineBFolder) p2 = plots.ComparisonPlot( getHisto(datasetsMgr, "EWK", histoNameNew, "Baseline"), getHisto(datasetsMgr, "EWK", histoNameNew, "Inverted") ) p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity()) # Get EWKGenuineB histos EWKGenuineB_baseline = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline-EWKGenuineB") EWKGenuineB_inverted = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted-EWKGenuineB") # Get FakeB histos FakeB_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-FakeB") FakeB_baseline.Add(EWKGenuineB_baseline, -1) FakeB_inverted = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-FakeB") FakeB_inverted.Add(EWKGenuineB_inverted, -1) # Normalize histograms to unit area EWKGenuineB_baseline.Scale(1.0/EWKGenuineB_baseline.Integral()) EWKGenuineB_inverted.Scale(1.0/EWKGenuineB_inverted.Integral()) FakeB_baseline.Scale(1.0/FakeB_baseline.Integral()) FakeB_inverted.Scale(1.0/FakeB_inverted.Integral()) # Create the final plot object comparisonList = [EWKGenuineB_baseline] p = plots.ComparisonManyPlot(FakeB_inverted, comparisonList, saveFormats=[]) p.setLuminosity(GetLumi(datasetsMgr)) # Apply styles p.histoMgr.forHisto("Baseline-EWKGenuineB", styles.getBaselineStyle() ) p.histoMgr.forHisto("Inverted-FakeB" , styles.getInvertedStyle() ) # Set draw style p.histoMgr.setHistoDrawStyle("Baseline-EWKGenuineB", "AP") p.histoMgr.setHistoDrawStyle("Inverted-FakeB" , "HIST") # Set legend style p.histoMgr.setHistoLegendStyle("Baseline-EWKGenuineB", "LP") p.histoMgr.setHistoLegendStyle("Inverted-FakeB" , "LP") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Baseline-EWKGenuineB": "GenuineB (EWK)", # (Baseline) "Inverted-FakeB" : "FakeB", # (Inverted) }) # Append analysisType to histogram name saveName = histoName # Draw the histograms #alex plots.drawPlot(p, saveName, **GetHistoKwargs(histoName) ) #the "**" unpacks the kwargs_ # _kwargs = {"lessThan": True} # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs) # Add text text = opts.optMode.replace("OptChiSqrCutValue", "#chi^{2} #leq ") histograms.addText(0.21, 0.85, text) # Save plot in all formats saveDir = os.path.join(opts.saveDir, "Templates", opts.optMode) SavePlot(p, saveName, saveDir, saveFormats = [".C", ".png", ".pdf"]) return
def PlotPurity(datasetsMgr, histoName): ''' Create plots with "FakeB=Data-EWKGenuineB" ''' Verbose("Plotting histogram %s for Data, EWK, QCD " % (histoName), True) # Which folder to use (redundant) defaultFolder = "FakeBPurity" genuineBFolder = defaultFolder + "EWKGenuineB" fakeBFolder = defaultFolder + "EWKFakeB" # Customize the histograms (BEFORE calculating purity obviously otherwise numbers are nonsense) _cutBox = None _rebinX = 1 _opts = {"ymin": 1e-3, "ymax": 1.0} #"ymaxfactor": 1.2} _format = "%0.0f" #_opts["xmax"] = xMax _xlabel = None _ylabel = "Purity / " _format = "/ %.0f " h = histoName.split("/")[-1] if "dijetm" in h.lower(): _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 } if "trijetm" in h.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"] = 1000.0 if "pt" in h.lower(): _format = "%0.0f GeV/c" if "chisqr" in h.lower(): _opts["xmax"] = 100.0 if "allselections" in h.lower(): _opts["xmax"] = 10.0 #if histo.lower().endswith("met_et"): if h.lower().startswith("ht_"): _rebinX = 5 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = { "cutValue": 500.0, "fillColor": 16, "box": False, "line": False, "greaterThan": True } _opts["xmin"] = 500.0 _opts["xmax"] = 3500.0 if "eta" in h.lower(): _rebinX = 1 _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 h.lower(): _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = 6.0 if "bdisc" in h.lower(): _format = "%0.2f" if "tetrajetm" in h.lower(): _rebinX = 4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _opts["xmax"] = 2500.0 if "pt_" in h.lower(): _rebinX = 2 _ylabel += _format # Get histos (Data, EWK) for Inclusive p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName)) p1.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) # Clone histograms Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone("Data") EWK = p1.histoMgr.getHisto("EWK").getRootHisto().Clone("EWK") QCD = p1.histoMgr.getHisto("Data").getRootHisto().Clone("QCD") # Rebin histograms (Before calculating Purity) Data.Rebin(_rebinX) EWK.Rebin(_rebinX) QCD.Rebin(_rebinX) # Get QCD = Data-EWK QCD.Add(EWK, -1) # Comparison plot. The first argument is the reference histo. All other histograms are compared with respect to that. QCD_Purity, xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto( QCD, Data, inclusiveBins=False, printValues=False) EWK_Purity, xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto( EWK, Data, inclusiveBins=False, printValues=False) # Create TGraphs if 0: gQCD_Purity = MakeGraph(ROOT.kFullTriangleUp, ROOT.kOrange, binList, valueDict, upDict, downDict) gEWK_Purity = MakeGraph(ROOT.kFullTriangleDown, ROOT.kPurple, binList, valueDict, upDict, downDict) # Make the plots if opts.plotEWK: p = plots.ComparisonManyPlot(QCD_Purity, [EWK_Purity], saveFormats=[]) else: p = plots.PlotBase([QCD_Purity], saveFormats=[]) # Apply histo styles p.histoMgr.forHisto("QCD", styles.getQCDLineStyle()) if opts.plotEWK: p.histoMgr.forHisto("EWK", styles.getAltEWKLineStyle()) # Set draw style p.histoMgr.setHistoDrawStyle("QCD", "P") if opts.plotEWK: p.histoMgr.setHistoDrawStyle("EWK", "HIST") # Set legend style p.histoMgr.setHistoLegendStyle("QCD", "P") if opts.plotEWK: p.histoMgr.setHistoLegendStyle("EWK", "F") # Set legend labels if opts.plotEWK: p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD", "EWK": "EWK", }) else: p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD", }) # Do the plot plots.drawPlot( p, histoName, xlabel=_xlabel, ylabel=_ylabel, log=False, rebinX=1, # must be done BEFORE calculating purity cmsExtraText="Preliminary", createLegend={ "x1": 0.76, "y1": 0.80, "x2": 0.92, "y2": 0.92 }, opts=_opts, opts2={ "ymin": 1e-5, "ymax": 1e0 }, ratio=False, ratioInvert=False, ratioYlabel="Ratio", cutBox=_cutBox, ) # Save plot in all formats SavePlot(p, histoName, os.path.join(opts.saveDir, "Purity", opts.optMode)) #, saveFormats = [".png"] ) return
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
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
def plot(self): style = tdrstyle.TDRStyle() ROOT.gStyle.SetErrorX(0.5) #required for x-axis error bars! (must be called AFTER tdrstyle.TDRStyle()) histolist = [] #styles.dataStyle.apply(self.h_data) hhd = histograms.Histo(self.h_data,"Data", legendStyle="PL", drawStyle="E1P") hhd.setIsDataMC(isData=True, isMC=False) histolist.append(hhd) # For-loop: All signal histo for i, hsignal in enumerate(self.h_signal, 1): mass = hsignal.GetName().replace("Hp", "") Verbose( "Customing signal histogram for Mass = \"%s\"" % (mass), i==1) hhs = histograms.Histo(hsignal,hsignal.GetTitle(), legendStyle="L", drawStyle="HIST") hhs.setIsDataMC(isData=False, isMC=True) signalStyle = styles.getSignalStyleHToTB_M(mass) signalStyle.apply(hhs.getRootHisto()) histolist.append(hhs) # For-loop: All bkg histos for hname in self.histonames: hhp = histograms.Histo(self.histograms[hname],hname,legendStyle="F", drawStyle="HIST",legendLabel=self.labels[hname]) hhp.setIsDataMC(isData=False,isMC=True) histolist.append(hhp) # Sanity check for i, h in enumerate(histolist, 1): hName = h.getRootHisto().GetName() Verbose(hName, i==1) # Do the plot p = plots.DataMCPlot2(histolist) p.setDefaultStyles() p.stackMCHistograms() p.setLuminosity(opts.lumi) if opts.fitUncert: p.addMCUncertainty(postfit=not opts.prefit) # boolean changes only the legend if opts.prefit: p.setLegendHeader("Pre-Fit") else: p.setLegendHeader("Post-Fit") # Customise histogram units = "GeV" #(GeV/c^{2}) myParams = {} myParams["xlabel"] = "m_{jjbb} (%s)" % (units) myParams["ylabel"] = "< Events / " + units + " >" myParams["ratio"] = True myParams["ratioYlabel"] = "Data/Bkg. " myParams["logx"] = self.gOpts.logX myParams["log"] = self.gOpts.logY myParams["ratioType"] = "errorScale" myParams["ratioErrorOptions"] = {"numeratorStatSyst": False, "denominatorStatSyst": True} myParams["opts"] = self.opts myParams["optsLogx"] = self.optsLogx myParams["opts2"] = self.opts2 myParams["divideByBinWidth"] = True #not opts.fitUncert # Error when used for "TGraphAsymmErrors" (uncert.) myParams["errorBarsX"] = True myParams["xlabelsize"] = 25 myParams["ylabelsize"] = 25 myParams["addMCUncertainty"] = True myParams["addLuminosityText"] = True myParams["moveLegend"] = self.moveLegend #myParams["saveFormats"] = [] # Draw the plot if not os.path.exists(opts.saveDir): os.makedirs(opts.saveDir) plots.drawPlot(p, os.path.join(opts.saveDir, self.gOpts.saveName), **myParams) # Save the plot (not needed - drawPlot saves the canvas already) SavePlot(p, self.gOpts.saveName, opts.saveDir, saveFormats = [".png", ".pdf", ".C"]) return
def PlotHistos(noSF_datasetsMgr, withCR1SF_datasetsMgr, withCR2SF_datasetsMgr, num_histoList, den_histoList, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(num_histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CR1", "CR2"] labels = ["Genuine", "Fake", "Inclusive"] #========================================================================================== # Get Dictionaries #========================================================================================== rhDict_den_noSF = GetRootHistos(noSF_datasetsMgr, den_histoList, regions) rhDict_num_noSF = GetRootHistos(noSF_datasetsMgr, num_histoList, regions) rhDict_num_withCR1SF = GetRootHistos(withCR1SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR1 are only applied in the Numerator on Fake TT rhDict_num_withCR2SF = GetRootHistos(withCR2SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR2 are only applied in the Numerator on EWK+QCD+ST # ========================================================================================= # Normalization Factors (see: getNormalization.py) # ========================================================================================= f1=0.619886; f2=0.904877; # ========================================================================================= # (A) Apply Normalization Factors (see: getNormalizations.py) # ========================================================================================= # Normalize all histograms (QCD and TT) to normalization factors for re in regions: rhDict_den_noSF["NormQCD-"+re+"-Inclusive"] = rhDict_den_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1) rhDict_num_noSF["NormQCD-"+re+"-Inclusive"] =rhDict_num_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1) rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"] = rhDict_num_withCR2SF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Scale(f1) for la in labels: rhDict_den_noSF["NormTT-"+re+"-"+la] = rhDict_den_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_den_noSF["NormTT-"+re+"-"+la].Scale(f2) rhDict_num_noSF["NormTT-"+re+"-"+la] = rhDict_num_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_num_noSF["NormTT-"+re+"-"+la].Scale(f2) rhDict_num_withCR1SF["NormTT-"+re+"-"+la] = rhDict_num_withCR1SF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_num_withCR1SF["NormTT-"+re+"-"+la].Scale(f2) # ========================================================================================== # (B) Estimate Genuine TT in SR # ========================================================================================== # (B1) Genuine TT in Data - Denominator = Data - F1*QCD - F2*FakeTT - EWK - ST rhDict_den_noSF["TTinData-SR-Genuine"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormTT-SR-Fake"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["EWK-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1) # (B2) Genuine TT in Data - Numerator = Data - F1*QCD*SF_{CR2} - F2*FakeTT*SF_{CR1} - ST*SF_{CR2} - EWK*SF_{CR2} rhDict_num_noSF["TTinData-SR-Genuine"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["NormQCD-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR1SF["NormTT-SR-Fake"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["SingleTop-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["EWK-SR-Inclusive"], -1) # (B3) Genuine TT in MC - Denominator: rhDict_den_noSF["TT-SR-Genuine"] # (B4) Genuine TT in MC - Numerator: rhDict_num_noSF["TT-SR-Genuine"] # ======================================================================================== # (C) Plot Numerator and Denominator (Data Vs MC) # ======================================================================================== _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0} _kwargs["ratioYlabel"] = "Data/MC" _kwargs["ratio"] = True _kwargs["stackMCHistograms"] = False _kwargs["createLegend"] = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92} _kwargs["ratioInvert"] = True num_data = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)") den_data = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)") num_mc = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)") den_mc = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)") num_data.Rebin(2) num_mc.Rebin(2) den_data.Rebin(2) den_mc.Rebin(2) styles.getABCDStyle("CR4").apply(num_mc) styles.getABCDStyle("CR4").apply(den_mc) # Denominator hName = "GenuineTT_SR_Denominator_LeadingJet" hData_Den = histograms.Histo( den_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False) hMC_Den = histograms.Histo( den_mc, "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST"); hMC_Den.setIsDataMC(isData=False, isMC=True) pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[]) pDen.setLuminosity(opts.intLumi) pDen.setDefaultStyles() plots.drawPlot(pDen, hName, **_kwargs) SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"]) # Numerator hName = "GenuineTT_SR_Numerator_LeadingJet" hData_Num = histograms.Histo( num_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False) hMC_Num = histograms.Histo( num_mc, "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST"); hMC_Num.setIsDataMC(isData=False, isMC=True) pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[]) pNum.setLuminosity(opts.intLumi) pNum.setDefaultStyles() plots.drawPlot(pNum, hName, **_kwargs) SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"]) # ======================================================================================== # (D) Plot Genuine TT Efficiency # ======================================================================================== _kwargs = { "xlabel" : "p_{T} (GeV/c)", "ylabel" : "Efficiency", "ratioYlabel" : "Data/MC", "ratio" : True, "ratioInvert" : False, "ratioType" : "errorScale", "ratioCreateLegend": True, "ratioMoveLegend" : {"dx": -0.51, "dy": 0.03, "dh": -0.08}, "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False}, "errorBarsX" : True, "stackMCHistograms": False, "addMCUncertainty" : False, "addLuminosityText": False, "addCmsText" : True, "cmsExtraText" : "Preliminary", "opts" : {"ymin": 0.0, "ymaxfactor": 1.2, "xmax" : 600}, "opts2" : {"ymin": 0.6, "ymax": 1.5}, "log" : False, "createLegend" : {"x1": 0.54, "y1": 0.80, "x2": 0.95, "y2": 0.92}, } bins = [0, 100, 200, 300, 400, 500, 600] xBins = array.array('d', bins) nx = len(xBins)-1 # Data h0_data_den = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)") h0_data_num = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)") # MC h0_mc_den = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)") h0_mc_num = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)") h0_data_den = h0_data_den.Rebin(nx, "", xBins) h0_data_num = h0_data_num.Rebin(nx, "", xBins) h0_mc_den = h0_mc_den.Rebin(nx, "", xBins) h0_mc_num = h0_mc_num.Rebin(nx, "", xBins) hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den) hNumerator_MC, hDenominator_MC = GetHistosForEfficiency(h0_mc_num, h0_mc_den) eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data) eff_mc = ROOT.TEfficiency(hNumerator_MC, hDenominator_MC) eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP) eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP) geff_data = convert2TGraph(eff_data) geff_mc = convert2TGraph(eff_mc) styles.dataStyle.apply(geff_data) styles.ttStyle.apply(geff_mc) Graph_Data = histograms.HistoGraph(geff_data, "genuine t#bar{t}_{SR} (Data) ", "p", "P") Graph_MC = histograms.HistoGraph(geff_mc, "genuine t#bar{t}_{SR} (MC)", "p", "P") p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[]) saveName = "Efficiency_GenuineTT_SR_LeadingJet" savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"]) return
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
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
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
def PlotEfficiency(datasetsMgr, numPath, denPath, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): #if "Fake" in numPath and "TT" in dataset.getName(): # continue # Get the histograms #num = dataset.getDatasetRootHisto(numPath).getHistogram() #den = dataset.getDatasetRootHisto(denPath).getHistogram() n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Remove negative bins and ensure numerator bin <= denominator bin CheckNegatives(num, den, True) # RemoveNegatives(num) # RemoveNegatives(den) # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) # fixme: investigate warnings eff.SetStatisticOption(ROOT.TEfficiency.kFCP) # # Set the weights - Why is this needed? if 0: weight = 1 if dataset.isMC(): weight = dataset.getCrossSection() eff.SetWeight(weight) # Convert to TGraph eff = convert2TGraph(eff) # Apply default style (according to dataset name) plots._plotStyles[dataset.getName()].apply(eff) # Append in list myList.append( histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) # Define save name saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split( "/")[-1] # Plot the efficiency p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) # Save plot in all formats savePath = os.path.join(opts.saveDir, "HplusMasses", numPath.split("/")[0], opts.optMode) #savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut SavePlot(p, saveName, save_path, saveFormats=[".png", ".pdf", ".C"]) return
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
def PlotEfficiency_comparison(datasetsMgr, numPath, denPath, datasetsMgr_DR, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets #for dataset in datasetsMgr.getAllDatasets(): if 1: #if "Fake" in numPath: # return dataset = datasetsMgr.getDataset("TT") dataset_DR = datasetsMgr_DR.getDataset("TT") #if "Fake" in numPath: # dataset = datasetsMgr.getDataset("QCD") # dataset_DR = datasetsMgr_DR.getDataset("QCD") legend = "t#bar{t} (#Delta R < 0.30, #Delta p_{T} / p_{T} < 0.32)" legend_DR = "t#bar{t} (#Delta R < 0.30)" styleDef = styles.ttStyle style_DR = styles.signalStyleHToTB500 #800 n = dataset_DR.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num_DR = n.getHistogram() d = dataset_DR.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den_DR = d.getHistogram() #========================================= n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() #========================================= if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) num_DR = num_DR.Rebin(nx, "", xBins) den_DR = den_DR.Rebin(nx, "", xBins) for i in range(1, num.GetNbinsX() + 1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) nbin_DR = num_DR.GetBinContent(i) dbin_DR = den_DR.GetBinContent(i) eps = nbin / dbin eps_DR = nbin_DR / dbin_DR ratio_DR = eps / eps_DR if ratio_DR > 1: ratio_DR = 1 / ratio_DR print "bin: ", i, "eps: ", round(eps, 5), "eps_DR: ", round(eps_DR, 5) print "bin: ", i, "eps/eps_DR: ", (1.0 - round(ratio_DR, 3)) * 100 # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: # continue return if num.GetEntries() > den.GetEntries(): # continue return # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) eff.SetStatisticOption(ROOT.TEfficiency.kFCP) eff_DR = ROOT.TEfficiency(num_DR, den_DR) eff_DR.SetStatisticOption(ROOT.TEfficiency.kFCP) eff = convert2TGraph(eff) eff_DR = convert2TGraph(eff_DR) # Apply default style (according to dataset name) #plots._plotStyles[dataset.getName()].apply(eff) #styleDef.apply(eff) #style_DR.apply(eff_DR) styles.markerStyles[0].apply(eff) styles.markerStyles[1].apply(eff_DR) ''' eff_DR.SetLineStyle(ROOT.kSolid) eff.SetLineWidth(2) eff_DR.SetLineWidth(2) eff.SetLineStyle(ROOT.kSolid) eff_DR.SetLineStyle(ROOT.kSolid) eff.SetMarkerStyle(ROOT.kFullTriangleUp) eff_DR.SetMarkerStyle(ROOT.kFullTriangleUp) eff.SetMarkerSize(1.2) eff_DR.SetMarkerSize(1.2) ''' # Append in list myList.append(histograms.HistoGraph(eff, legend, "p", "P")) myList.append(histograms.HistoGraph(eff_DR, legend_DR, "p", "P")) # Save plot in all formats #savePath = os.path.join(opts.saveDir, opts.optMode) #plots.drawPlot(p, savePath, **_kwargs) #SavePlot(p, saveName, savePath, saveFormats = [".png", ".pdf"]) # Define stuff numPath = numPath.replace("AfterAllSelections_", "") numPath = numPath.replace("LeadingTrijet_Pt", "LdgTopPt") if "Genuine" in numPath: TTcateg = "_TTgenuine" elif "Fake" in numPath: TTcateg = "_TTfake" else: TTcateg = "_TTinclusive" if "SR" in numPath: region = "_SR" if "VR" in numPath: region = "_VR" if "CR1" in numPath: region = "_CR1" if "CR2" in numPath: region = "_CR2" saveName = "Eff_" + numPath.split("/")[-1] + TTcateg + "_BDTtraining" # Plot the efficiency p = plots.ComparisonManyPlot( histograms.HistoGraph(eff, legend, "p", "P"), [histograms.HistoGraph(eff_DR, legend_DR, "p", "P")], saveFormats=[".pdf", ".png", ".C"]) leg = ROOT.TLegend(0.2, 0.8, 0.81, 0.87) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetBorderSize(0) #{"dx": -0.55, "dy": -0.55, "dh": -0.08} leg.SetHeader("t#bar{t}") #if "Fake" in numPath: # leg.SetHeader("QCD") leg.Draw() #moveLegend = {"dx": -0.0, "dy": +0.0, "dh": +0.1} #moveLegend = {"dx": -0.1, "dy": +0.0, "dh": +0.1} #p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Save plot in all formats savePath = os.path.join(SAVEDIR, "HplusMasses", numPath.split("/")[0], opts.optMode) #savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) plots.drawPlot(p, SAVEDIR, **_kwargs) #leg.Draw() SavePlot(p, saveName, SAVEDIR, saveFormats=[".png", ".pdf", ".C"]) return
def main(opts): # Suppress warnings about weight being re-applied ROOT.gErrorIgnoreLevel = ROOT.kError # Obtain dsetMgrCreator and register it to module selector dsetMgrCreator = dataset.readFromMulticrabCfg(directory=opts.mcrab) # Get list of eras, modes, and optimisation modes erasList = dsetMgrCreator.getDataEras() modesList = dsetMgrCreator.getSearchModes() optList = dsetMgrCreator.getOptimizationModes() sysVarList = dsetMgrCreator.getSystematicVariations() sysVarSrcList = dsetMgrCreator.getSystematicVariationSources() # If user does not define optimisation mode do all of them if opts.optMode == None: if len(optList) < 1: optList.append("") else: pass optModes = optList else: optModes = [opts.optMode] opts.optMode = "" mcrabName = opts.mcrab RunEra = mcrabName.split("_")[1] # Setup ROOT and style ROOT.gROOT.SetBatch(opts.batchMode) style = tdrstyle.TDRStyle() style.setGridX(opts.gridX) style.setGridY(opts.gridY) if opts.paper: style.setGridX(False) style.setGridY(False) # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts) # Remove some QCD samples (the cross sections of these samples are not calculated) if 0: msg = "Removing following samples:" Print(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) for d in getDatasetsToExclude(): Print(d, False) datasetsMgr.remove(d) # Get run-range minRunRange, maxRunRange, runRange = GetRunRange(datasetsMgr) # Get int lumi intLumi = GetLumi(datasetsMgr) # Update to PU & load luminosities datasetsMgr.updateNAllEventsToPUWeighted() datasetsMgr.loadLuminosities() #datasetsMgr.normalizeMCByLuminosity() # Print luminisoties and cross-sections datasetsMgr.PrintLuminosities() datasetsMgr.PrintCrossSections() # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) # Get datasets datasetsMgr.mergeMC() dataset_Data = datasetsMgr.getDataDatasets() dataset_MC = datasetsMgr.getMCDatasets() # Define lists of Triggers to be plotted and Variables xVars = ["pt6thJet", "eta6thJet", "phi6thJet", "Ht", "nBTagJets", "pu", "JetMulti", "BJetMulti"] trgList = ["1BTag", "2BTag", "OR", "OR_PFJet450"] if opts.fast: trgList = ["OR_PFJet450"] xVars = ["pt6thJet", "Ht"] nPlots = len(trgList)*len(xVars) counter = 0 # For-loop: All signal triggers for i, trg in enumerate(trgList, 1): # For-loop: All x-variables for j, xVar in enumerate(xVars, 1): counter+=1 msg = "{:<9} {:>3} {:<1} {:<3} {:<50}".format("Histogram", "%i" % counter, "/", "%s:" % (nPlots), "%s Vs %s" % (trg, xVar)) Print(ShellStyles.SuccessStyle() + msg + ShellStyles.NormalStyle(), counter==1) # Define names hNumerator = "hNum_%s_RefTrg_OfflineSel_Signal%s" % (xVar, trg) hDenominator = "hDen_%s_RefTrg_OfflineSel" % (xVar) plotName = "Eff_%s_%s" % (xVar, trg) # Get Efficiency Plots _kwargs = GetHistoKwargs(xVar, opts) eff_Data = GetEfficiency(datasetsMgr, dataset_Data, hNumerator, hDenominator , **_kwargs) eff_MC = GetEfficiency(datasetsMgr, dataset_MC, hNumerator, hDenominator, **_kwargs) # Apply Styles styles.dataStyle.apply(eff_Data) styles.mcStyle.apply(eff_MC) # Create the plot p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data", "p", "P"), histograms.HistoGraph(eff_MC, "eff_MC" , "p", "P"), saveFormats=[]) # Define the legend entries p.histoMgr.setHistoLegendLabelMany( { "eff_Data": "Data", "eff_MC" : "Simulation" } ) # Draw and save the plot p.setLuminosity(intLumi) plots.drawPlot(p, plotName, **_kwargs) # Draw histograms.addText(0.65, 0.06, "Runs "+ runRange, 17) histograms.addText(0.65, 0.10, "2016", 17) # Save the canvas to a file SavePlot(p, plotName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".pdf", ".png", ".C"] ) Print("All plots saved under directory %s" % (ShellStyles.NoteStyle() + aux.convertToURL(opts.saveDir, opts.url) + ShellStyles.NormalStyle()), True) return
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
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") myArray = array.array("d", myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning) - 1, "", myArray) h.SetBinContent(1, h.GetBinContent(0) + h.GetBinContent(1)) h.SetBinError(1, math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2)) h.SetBinContent( h.GetNbinsX() + 1, h.GetBinContent(h.GetNbinsX() + 1) + h.GetBinContent(h.GetNbinsX() + 2)) h.SetBinError( h.GetNbinsX() + 1, math.sqrt( h.GetBinError(h.GetNbinsX() + 1)**2 + h.GetBinError(h.GetNbinsX() + 2)**2)) h.SetBinContent(0, 0.0) h.SetBinError(0, 0.0) h.SetBinContent(h.GetNbinsX() + 2, 0.0) h.SetBinError(h.GetNbinsX() + 2, 0.0) return h hbase.SetLineColor(ROOT.kBlack) hinv.SetLineColor(ROOT.kRed) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events" % (hbase.Integral(), hinv.Integral()) #hbase.Scale(1.0 / hbase.Integral()) #hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="l") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST", legendStyle="l") plot = plots.ComparisonPlot(baseHisto, invHisto) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) myPlotName = "%s/QCDInv_ClosureTest_%s" % (myDir, histoName) myParams = {} myParams["ylabel"] = "Events/#Deltam_{T}, normalized to 1" myParams["log"] = False myParams["opts2"] = {"ymin": 0.0, "ymax": 2.0} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Var./Nom." myParams["cmsText"] = myCMSText myParams["addLuminosityText"] = True myParams["divideByBinWidth"] = True plots.drawPlot(plot, myPlotName, **myParams)
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 "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 = 5 #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 "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 #_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
def PlotEfficiency(datasetsMgr, numPath, denPath): # Definitions myList = [] _kwargs = GetHistoKwargs(numPath, opts) nx = 0 if len(_kwargs["binList"]) > 0: xBins = _kwargs["binList"] nx = len(xBins)-1 counter = 0 # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): if dataset.isMC(): n = dataset.getDatasetRootHisto(numPath) d = dataset.getDatasetRootHisto(denPath) num = n.getHistogram() den = d.getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) else: num = dataset.getDatasetRootHisto(numPath).getHistogram() den = dataset.getDatasetRootHisto(denPath).getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) # Calculations total = den.Integral(0, den.GetXaxis().GetNbins()+1) selected = num.Integral(0, num.GetXaxis().GetNbins()+1) if 0: print "Numerical Efficiency", numPath, dataset.getName(), ":", round(selected/total, 3) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) eff.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP datasetTT = datasetsMgr.getDataset("TT") # Get the histograms numTT = datasetTT.getDatasetRootHisto(numPath).getHistogram() denTT = datasetTT.getDatasetRootHisto(denPath).getHistogram() if nx > 0: numTT = numTT.Rebin(nx, "", xBins) #num.Rebin(nx, "", xBins) denTT = denTT.Rebin(nx, "", xBins) #den.Rebin(nx, "", xBins) ''' for i in range(1, num.GetNbinsX()+1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) nbinTT = numTT.GetBinContent(i) dbinTT = denTT.GetBinContent(i) eps = nbin/dbin epsTT = nbinTT/dbinTT ratioTT = eps/epsTT if ratioTT > 1: ratioTT = 1/ratioTT #print "bin: ", i, "eps: ", round(eps,5) , "epsTT: ", round(epsTT,5) #print "bin: ", i, "eps/epsTT: ", (1.0 - round(ratioTT, 3))*100 ''' eff_ref = ROOT.TEfficiency(numTT, denTT) eff_ref.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP # Convert to TGraph gEff = convert2TGraph(eff) gEffRef = convert2TGraph(eff_ref) # Style definitions stylesDef = styles.ttStyle styles0 = styles.signalStyleHToTB300 styles1 = styles.signalStyleHToTB500 styles2 = styles.signalStyleHToTB800 styles3 = styles.signalStyleHToTB500 styles4 = styles.signalStyleHToTB1000 styles5 = styles.signalStyleHToTB2000 styles6 = styles.signalStyleHToTB180 styles7 = styles.signalStyleHToTB3000 styles8 = styles.signalStyleHToTB200 if dataset.getName() == "TT": styles.ttStyle.apply(gEffRef) legend_ref = "t#bar{t}" if opts.type == "partonShower": legend_ref = "t#bar{t} (Pythia8)" elif opts.type == "evtGen": legend_ref = "t#bar{t} (Powheg)" refGraph = histograms.HistoGraph(gEffRef, legend_ref, "p", "P") else: styles.markerStyles[counter].apply(gEff) legend = dataset.getName().replace("TT_", "t#bar{t} (").replace("isr", "ISR ").replace("fsr", "FSR ") legend = legend.replace("hdamp", "hdamp ").replace("DOWN", "down").replace("UP", "up") legend = legend.replace("mtop1665", "m_{t} = 166.5 GeV") legend = legend.replace("mtop1695", "m_{t} = 169.5 GeV") legend = legend.replace("mtop1715", "m_{t} = 171.5 GeV") legend = legend.replace("mtop1735", "m_{t} = 173.5 GeV") legend = legend.replace("mtop1755", "m_{t} = 175.5 GeV") legend = legend.replace("mtop1785", "m_{t} = 178.5 GeV") legend = legend.replace("TuneEE5C", "Herwig++") legend += ")" counter+=1 #myList.append(histograms.HistoGraph(gEff, legend, "lp", "P")) myList.append(histograms.HistoGraph(gEff, legend, "p", "P")) # Define stuff numPath = numPath.replace("AfterAllSelections_","") saveName = "Efficiency_%s_%s" % (opts.folder, opts.type) saveName = saveName.replace("__", "_Inclusive_") # Plot the efficiency p = plots.ComparisonManyPlot(refGraph, myList, saveFormats=[]) savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) # Save plot in all formats SavePlot(p, saveName, savePath, saveFormats = [".png", ".pdf", ".C"]) return
def PlotEfficiency(datasetsMgr, numPath, denPath, intLumi): # Definitions myList = [] myList_MC = [] myList_Data = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): if "Fake" in numPath and "TT" in dataset.getName(): continue if dataset.isMC(): n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() else: num = dataset.getDatasetRootHisto(numPath).getHistogram() den = dataset.getDatasetRootHisto(denPath).getHistogram() total = den.Integral(0, den.GetXaxis().GetNbins()+1) selected = num.Integral(0, num.GetXaxis().GetNbins()+1) print "Pass :"******" events" print "Numerical Efficiency", numPath, dataset.getName(), ":", round(selected/total, 3) if "binList" in _kwargs: #if len(_kwargs["binList"]) == 1: # continue xBins = _kwargs["binList"] nx = len(xBins)-1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) elif "Eta" in numPath or "Phi" in numPath: num = num.Rebin(2) den = den.Rebin(2) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) # fixme: investigate warnings eff.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP # Convert to TGraph eff = convert2TGraph(eff) # Apply default style (according to dataset name) plots._plotStyles[dataset.getName()].apply(eff) # Append in list myList.append(histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) if dataset.isMC(): eff_MC = eff if "QCD" in dataset.getName(): eff_QCD = eff elif "TT" in dataset.getName(): eff_TT= eff myList_MC.append(histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) else: eff_Data = eff plots._plotStyles[dataset.getName()].apply(eff_Data) #styles.dataStyle.apply(eff_Data) eff_Data.SetMarkerSize(1.2) myList_Data.append(histograms.HistoGraph(eff_Data, plots._legendLabels[dataset.getName()], "p", "P")) numPath = numPath.replace("AfterAllSelections_","") # Define save name saveName = "Eff_" + numPath.split("/")[-1] # Plot the efficiency p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) p1 = plots.ComparisonManyPlot(histograms.HistoGraph(eff_Data, "Data", drawStyle="P"), myList_MC, saveFormats=[]) # Save plot in all formats savePath = os.path.join(opts.saveDir, "HplusMasses", numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut print "save_path", save_path # Draw and save the plot p1.setLuminosity(intLumi) _kwargs["ratio"] = True _kwargs["ratioInvert"] = True _kwargs["cutBoxY"] = {"cutValue": 1.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True, "mainCanvas": True, "ratioCanvas": True} plots.drawPlot(p1, save_path1, **_kwargs) SavePlot(p1, saveName, save_path, saveFormats = [".png", ".pdf", ".C"]) return