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 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 makeIntegratedPlot(self, histoName, outName, histoSpecs, plotOptions, optionPrintPurityByBins=False): h = self.getIntegratedHistogram(histoName, histoSpecs, optionPrintPurityByBins) plot = plots.PlotBase([histograms.Histo(h, "shape", drawStyle="E")]) plot.createFrame("%s/%s_%s"%(self._myDir,outName,self._moduleInfoString), opts=plotOptions) plot.frame.GetXaxis().SetTitle(histoSpecs["xtitle"]) plot.frame.GetYaxis().SetTitle(histoSpecs["ytitle"]) styles.dataStyle(plot.histoMgr.getHisto("shape")) self._drawPlot(plot)
def makeFinalPlot(self, histoName, outName, histoSpecs, plotOptions, optionPrintPurityByBins=False): # Check if plot exists if not self._dsetMgr.getDataset("Data").hasRootHisto(histoName): print "Could not find histogram or directory '%s' in the multicrab root files (perhaps you did not run on Informative level), skipping it ..."%histoName return h = self.getFinalHistogram(histoName, histoSpecs, optionPrintPurityByBins) plot = plots.PlotBase([histograms.Histo(h,"shape", drawStyle="E")]) plot.createFrame("%s/%s_%s"%(self._myDir,outName,self._moduleInfoString), opts=plotOptions) plot.frame.GetXaxis().SetTitle(histoSpecs["xtitle"]) plot.frame.GetYaxis().SetTitle(histoSpecs["ytitle"]) styles.dataStyle(plot.histoMgr.getHisto("shape")) self._drawPlot(plot)
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 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 doPlot(opts, signif, lumi, pvalue=False): grObs = None histos = [] if opts.unblinded: grObs = signif.observedGraph(pvalue) histos.append(histograms.HistoGraph(grObs, "Observed", drawStyle="LP")) grExp = signif.expectedGraph(pvalue) histos.append(histograms.HistoGraph(grExp, "Expected", drawStyle="L")) expData = "#it{B}#times#it{B}=%s %%" % signif.lightExpectedSignal() if signif.isHeavyStatus(): expData = "#sigma#times#it{B}=%s pb" % signif.heavyExpectedSignal() plot = plots.PlotBase(histos) plot.setLuminosity(lumi) if pvalue: plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected p-value", "Observed": "Observed p-value" }) plot.appendPlotObject(histograms.PlotText(0.6, 0.68, expData, size=18)) drawPlot(plot, "pvalue", ylabel="P-value", log=True, moveLegend={"dx": -0.2}, opts={ "ymin": 1e-10, "ymax": 1 }) else: plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected significance", "Observed": "Observed significance" }) plot.appendPlotObject(histograms.PlotText(0.2, 0.68, expData, size=18)) drawPlot(plot, "significance", ylabel="Significance", moveLegend={"dx": -0.55})
def doPlot(mass, name, nuisance, thetas): f = ROOT.TFile.Open("lands_histograms_hplushadronic_m%d.root" % mass) h = f.Get(name) hUp = f.Get("%s_%dUp" % (name, nuisance)) hDown = f.Get("%s_%dDown" % (name, nuisance)) shapes = [] ll = {} for i, theta in enumerate(thetas): morphed = doShape(h, hUp, hDown, theta) shapes.append( histograms.Histo(morphed, "Theta%d" % i, drawStyle="HIST", legendStyle="l")) ll["Theta%d" % i] = "#theta=%.2f (%.1f)" % (theta, _integral(morphed)) plot = plots.PlotBase(shapes) plot.histoMgr.forEachHisto(styles.generator()) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) plot.histoMgr.setHistoLegendLabelMany(ll) plot.setLegend(histograms.createLegend()) plot.createFrame("shape_theta_%s_syst%d_m%d" % (name, nuisance, mass)) plot.frame.GetXaxis().SetTitle("m_{T} (GeV)") plot.frame.GetYaxis().SetTitle("Rate") plot.draw() x = 0.6 size = 20 histograms.addText(x, 0.70, "Sample %s" % name, size=size) histograms.addText(x, 0.65, "Nuisance %d" % nuisance, size=size) histograms.addText(x, 0.60, "m_{H^{+}}=%d GeV" % mass, size=size) plot.save() f.Close()
def doPlotMu(name, graphs, styleList, limits, xlabel): objs = [] ll = {} for gr, mu in graphs: objs.append( histograms.HistoGraph(gr, "Obs%d" % mu, drawStyle="LP", legendStyle="lp")) ll["Obs%d" % mu] = "Observed, #mu=%d %s" % (mu, limit.massUnit()) plot = plots.PlotBase(objs) plot.histoMgr.forEachHisto(styles.Generator(styleList)) plot.histoMgr.setHistoLegendLabelMany(ll) plot.setLegend( histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355), dx=-0.1)) plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.9, limit.process, size=size) histograms.addText(x, 0.863, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size) histograms.addText(x, 0.775, limit.BRassumption, size=size) plot.save()
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 doPlot(name, graphs, limits, xlabel): if "obs" in graphs.keys(): obs = graphs["obs"] excluded = ROOT.TGraph(obs) excluded.SetName("ExcludedArea") excluded.SetFillColor(ROOT.kGray) excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN() - 1], tanbMax) excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetFillColor(ROOT.kGray) excluded.SetFillStyle(3354) excluded.SetLineWidth(0) excluded.SetLineColor(ROOT.kWhite) plot = None if "obs" in graphs.keys(): plot = plots.PlotBase([ histograms.HistoGraph(graphs["obs"], "Observed", drawStyle="PL", legendStyle="lp"), histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L"), histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="f"), histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) else: plot = plots.PlotBase([ histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) plot.setLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355)) plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.9, limit.process, size=size) histograms.addText(x, 0.863, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size) histograms.addText(x, 0.775, limit.BRassumption, size=size) histograms.addText(x, 0.735, "#mu=%d %s" % (mu, limit.massUnit()), size=size) plot.save()
def doPlot(rootfile): f = ROOT.TFile.Open(rootfile) basename = rootfile.replace(".root", "") match = name_re.search(rootfile) if not match: raise Exception("Assert: the file name regex did not match") mass = match.group("mass") name = match.group("name") canvas = f.Get("c1") primitives = canvas.GetListOfPrimitives() # Suppress the warning message of missing dictionary for some iterator backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError primiter = primitives.MakeIterator() ROOT.gErrorIgnoreLevel = backup graph = None expoFit = None lines = [] obj = primiter.Next() while obj: # print obj, obj.GetName() if isinstance(obj, ROOT.TGraph): if graph != None: raise Exception("Assert: graph was already found") graph = obj elif isinstance(obj, ROOT.TF1): if expoFit != None: raise Exception("Assert: expoFit was already found") expoFit = obj elif isinstance(obj, ROOT.TLine): lines.append(obj) obj = primiter.Next() if graph == None: raise Exception("Assert: did not find any TGraph") if expoFit == None: raise Exception("Assert: did not find any TF1") plot = plots.PlotBase( [histograms.HistoGraph(graph, "CLs", drawStyle="PE")]) plot.createFrame(basename, opts={ "xmin": 0, "ymin": 0, "ymaxfactor": 1.1, "xmaxlist": [0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.15, 0.2] }) plot.frame.GetXaxis().SetTitle("#mu") plot.frame.GetXaxis().SetNdivisions(1005) plot.frame.GetYaxis().SetTitle("CL_{s}") expoFit.SetLineColor(ROOT.kBlue - 9) # skip the vertical non-solid lines lines = filter(lambda l: l.GetLineStyle() == 1 or l.GetX1() != l.GetX2(), lines) plot.prependPlotObject(expoFit) for l in lines: plot.appendPlotObject(l) plot.draw() labelName = { "observed": "Observed", "median": "Expected median", "1sigma": "Expected +1#sigma", "2sigma": "Expected +2#sigma", "-1sigma": "Expected .1#sigma", "-2sigma": "Expected -2#sigma" }[name] size = 20 x = 0.62 histograms.addText(x, 0.85, "m_{H^{+}} = %s %s" % (mass, limit.massUnit()), size=size) histograms.addText(x, 0.81, labelName, size=size) plot.save() f.Close() f.Delete()
def main(opts): style = tdrstyle.TDRStyle() style.setOptStat(True) style.setWide(True, 0.15) ### style = tdrstyle.TDRStyle() ### #style.setWide(True) ### style.setPaletteMy() ### ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() style.setWide(True, 0.15) # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # ======================================== # Datasets # ======================================== # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) intLumi = GetLumi(datasetsMgr) 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 datasts (Note: Merged MC histograms must be normalized to something) plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets if 0: datasetsMgr.remove("TTJets") datasetsMgr.remove( filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # Print dataset information datasetsMgr.PrintInfo() # For-loop: All Histogram names for counter, hName in enumerate(hNames): savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a plot p = plots.PlotBase([refHisto], kwargs.get("saveFormats")) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Customize # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL" p.histoMgr.forEachHisto( lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.00001)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.05)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(2)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(2)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0009)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0041)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0012)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.00435)) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().GetZaxis().SetTitle("Arbitrary Units")) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(2.)) #ROOT.gPad.RedrawAxis() # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=opts) # Customise frame p.getFrame().GetXaxis().SetTitle(getTitleX(refHisto, **kwargs)) #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = {"lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.removeLegend() # Add MC Uncertainty (Invalid method for a 2-d histogram) #p.addMCUncertainty() # Customise histogram (after frame is created) # Draw plots p.draw() # Customise text #Soti lumitext histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.17, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.17, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter == 0) 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 doBRlimit(limits, unblindedStatus, opts, log=False): leptonicFS = False graphs = [] if unblindedStatus: gr = limits.observedGraph() if gr != None: gr.SetPoint(gr.GetN() - 1, gr.GetX()[gr.GetN() - 1] - 1e-10, gr.GetY()[gr.GetN() - 1]) if opts.excludedArea: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle=None)) excluded = gr.Clone() excluded.SetPoint(excluded.GetN(), excluded.GetX()[excluded.GetN() - 1], 0.05) excluded.SetPoint(excluded.GetN(), excluded.GetX()[0], 0.05) limit.setExcludedStyle(excluded) graphs.append( histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="lpf", legendLabel="Observed")) else: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle="lp")) graphs.extend([ histograms.HistoGraph(limits.expectedGraph(), "Expected", drawStyle="L"), histograms.HistoGraph(limits.expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(limits.expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"), ]) saveFormats = [".png", ".C", ".pdf"] if not opts.excludedArea: saveFormats.append(".eps") plot = plots.PlotBase(graphs, saveFormats=saveFormats) plot.setLuminosity(limits.getLuminosity()) plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) dy = -0.1 limit.BRassumption = "" #limit.BRassumption = "Assuming B(H^{+}#rightarrow#tau^{+}#nu_{#tau}) = 1" #limit.BRassumption = "Assuming B(H^{+}#rightarrowt#bar{b}) = 1" if limit.BRassumption != "": dy -= 0.05 #if len(limits.getFinalstates()) > 1: # dy -= 0.1 # Create legend x = 0.51 x = 0.45 legend = histograms.createLegend(x, 0.78 + dy, x + 0.4, 0.92 + dy) legend.SetMargin(0.17) # Make room for the final state text if opts.excludedArea: legend.SetFillStyle(1001) plot.setLegend(legend) name = "limitsBr" ymin = 0 ymax = limits.getFinalstateYmaxBR() #fixme: alexandros if opts.logx: name += "_logx" if log: name += "_log" if limits.isHeavyStatus: ymin = 1e-3 ymax = 10.0 if limit.BRassumption != "": ymax = 10.0 else: ymin = 1e-3 ymax = 4e-2 if leptonicFS: ymax = 10 if len(limits.mass) == 1: plot.createFrame(name, opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": ymin, "ymax": ymax }) else: plot.createFrame(name, opts={"ymin": ymin, "ymax": ymax}) # Set x-axis title plot.frame.GetXaxis().SetTitle(limit.mHplus()) if limits.isHeavyStatus: if limit.BRassumption != "": plot.frame.GetYaxis().SetTitle( "95% CL limit for #sigma_{H^{+}} (pb)") else: plot.frame.GetYaxis().SetTitle(limit.sigmaBRlimit) else: plot.frame.GetYaxis().SetTitle(limit.BRlimit) # Enable/Disable logscale for axes if log: plot.getPad().SetLogy(log) if opts.logx: plot.getPad().SetLogx(log) # Draw the plot with standard texts plot.draw() plot.addStandardTexts() # Add physics-process text size = 20 x = 0.51 x = 0.45 process = limit.process if limits.isHeavyStatus: process = limit.processHeavy histograms.addText(x, 0.88, process, size=size) # Add final-state text # histograms.addText(x, 0.84, limits.getFinalstateText(), size=size) #fixme: alexandros histograms.addText(x, 0.84, "fully hadronic final state", size=size) #fixme: alexandros # histograms.addText(x, 0.84, "#tau_{h}+jets and #mu#tau_{h} final states", size=size) # histograms.addText(x, 0.84, "#tau_{h}+jets final state", size=size) # histograms.addText(x, 0.84, "#tau_{h}+jets, #mu#tau_{h}, ee, e#mu, #mu#mu final states", size=size) if leptonicFS: histograms.addText(x, 0.84, "#mu#tau_{h}, ee, e#mu, #mu#mu final states", size=size) if limit.BRassumption != "": histograms.addText(x, 0.79, limit.BRassumption, size=size) plot.save() return
def doPlot(name, genuineBDataset, fakeBDataset, errorlevel, optimizationMode, lumi): btagWP = "CSVv2-" + name.split("_")[-1] Verbose("Generating efficiency for discriminator WP \"%s\"" % (btagWP), True) # Definitions s = optimizationMode.split("BjetDiscrWorkingPoint") discrName = s[0].replace("OptBjetDiscr", "") discrWP = s[1] myPartons = ["B", "C", "Light"] myPartonLabels = ["b#rightarrowb", "c#rightarrowb", "guds#rightarrowb"] histoObjects = [] results = [] # For-loop: All partons for i, parton in enumerate(myPartons, 0): counter = i+1 msg = "{:<9} {:>3} {:<1} {:<3} {:<50}".format("Histogram", "%d" % counter, "/", "%s:" % (len(myPartons)), "%s->b for %s" % (parton.lower(), btagWP)) Print(ShellStyles.SuccessStyle() + msg + ShellStyles.NormalStyle(), counter==1) n = "All%sjets" % parton if parton == "B": dsetHisto = genuineBDataset.getDatasetRootHisto(n) elif (parton == "C" or parton == "Light"): dsetHisto = fakeBDataset.getDatasetRootHisto(n) else: raise Exception("This should never be reached") dsetHisto.normalizeToLuminosity(lumi) hAll = dsetHisto.getHistogram() if hAll == None: raise Exception("Error: could not find histogram '%s'!"%n) treatNegativeBins(hAll) n = "Selected%sjets" % parton if parton == "B": dsetHisto = genuineBDataset.getDatasetRootHisto(n) if (parton == "C" or parton == "G" or parton == "Light"): dsetHisto = fakeBDataset.getDatasetRootHisto(n) # Normalise to luminosity dsetHisto.normalizeToLuminosity(lumi) # Get Numerator. Treate -ve bins hPassed = dsetHisto.getHistogram() if hPassed == None: raise Exception("Error: could not find histogram '%s'!"%n) treatNegativeBins(hPassed) # Find proper binning myBinEdges = [] for k in range(1, hPassed.GetNbinsX()+1): if len(myBinEdges) > 0 or hPassed.GetBinContent(k) > 0: myBinEdges.append(hPassed.GetXaxis().GetBinLowEdge(k)) myBinEdges.append(hPassed.GetXaxis().GetBinUpEdge(hPassed.GetNbinsX())) myArray = array.array("d", myBinEdges) hAllNew = hAll.Rebin(len(myArray)-1, "", myArray) hPassedNew = hPassed.Rebin(len(myArray)-1, "", myArray) (hPassed, hAll) = findProperBinning(hPassedNew, hAllNew, myBinEdges, errorlevel) # For-loop: All x-axis bins for k in range(hPassed.GetNbinsX()+2): # Treat fluctuations if hPassed.GetBinContent(k) > hAll.GetBinContent(k): hPassed.SetBinContent(k, hAll.GetBinContent(k)) # Construct efficiency plot eff = ROOT.TEfficiency(hPassed, hAll) eff.SetStatisticOption(ROOT.TEfficiency.kFNormal) # For-loop: All x-axis bins for k in range(hPassed.GetNbinsX()): resultObject = {} resultObject["flavor"] = parton resultObject["ptMin"] = hPassed.GetXaxis().GetBinLowEdge(k+1) resultObject["ptMax"] = hPassed.GetXaxis().GetBinUpEdge(k+1) resultObject["eff"] = eff.GetEfficiency(k+1) resultObject["effUp"] = eff.GetEfficiencyErrorUp(k+1) resultObject["effDown"] = eff.GetEfficiencyErrorLow(k+1) resultObject["discr"] = discrName resultObject["workingPoint"] = discrWP results.append(resultObject) # Apply style styles.styles[i].apply(eff) hobj = histograms.HistoEfficiency(eff, myPartonLabels[i], legendStyle="P", drawStyle="P") hobj.setIsDataMC(False, True) histoObjects.append(hobj) # Create the plot myPlot = plots.PlotBase(histoObjects, saveFormats=[]) myPlot.setLuminosity(lumi) myPlot.setEnergy("13") #myPlot.setDefaultStyles() # Add btag WP to canvas myPlot.appendPlotObject(histograms.PlotText(0.70, 0.48-0.16, btagWP, bold=True, size=20)) # Create the plotting object drawPlot = plots.PlotDrawer(ratio=False, addLuminosityText=False, cmsTextPosition="outframe") # Create the plotting object drawPlot(myPlot, "%s_%s" % ("Hybrid", name), **GetKwargs(name, btagWP, opts)) # Save the plot in custom formats SavePlot(myPlot, name, opts.saveDir, saveFormats = [".C", ".png", ".pdf"]) return results
def analyze(analysis=None): paths = [sys.argv[1]] datasets = dataset.getDatasetsFromMulticrabDirs(paths) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="SingleNeutrino") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="QCD") # analysis = datasets.getAllDatasets()[0].getAnalysisName() #datasetsMC = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="ZeroBias") createRatio = False # for d in datasets.getAllDatasets(): # print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() #### dataset1 = datasets.getMCDatasets() rateETM120 = 5521.35 # Hz #effETM120 = 0.000611208781402 #8.75017364672e-05 #effETM120 = 0.000619219298648 effETM120 = 0.000203698623826 #### effETM120 = 0.186701136914 # QCD scale = rateETM120 / effETM120 * 0.001 #(Hz->kHz) # for d in dataset1: # d.scale(scale) dataset2 = dataset1 createRatio = False #if isinstance(datasetsMC,dataset.DatasetManager): # dataset2 = datasetsMC.getMCDatasets() # createRatio = True eff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU") scaleGraph(eff1PU, scale) namePU = "TauMET_" + analysis + "_nVtx" legend1 = "Data" legend2 = "Simulation" styles.dataStyle.apply(eff1PU) eff1PU.SetMarkerSize(1) #eff2PU.SetMarkerSize(1.5) pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) # Fit # yval = fit("Data",pPU,eff1PU,30,59) yval = fit("Data", pPU, eff1PU, 5, 59) #### opts = {"ymin": 0, "ymax": 6, "xmax": 60} opts = {"ymin": 0, "ymax": 20, "xmax": 60} #### opts = {"ymin": 0, "ymax": 300, "xmax": 60} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.5, "dy": -0.1, "dh": -0.1} if createRatio: pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) else: pPU.createFrame(os.path.join(plotDir, namePU), opts=opts, opts2=opts2) pPU.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) pPU.getFrame().GetYaxis().SetTitle("L1 rate (kHz)") pPU.getFrame().GetXaxis().SetTitle("n vertices") if createRatio: pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) pPU.draw() print "check frame min,max", pPU.getFrame().GetYaxis().GetXmin( ), pPU.getFrame().GetYaxis().GetXmax() x = array.array('d', [55, 55, 0]) y = array.array('d', [0, yval, yval]) n = 3 vert = ROOT.TGraph(n, x, y) vert.SetLineStyle(2) vert.SetLineColor(2) vert.SetLineWidth(2) vert.Draw("L") lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity", d.getName(), d.getLuminosity() lumi += d.getLuminosity() histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) pPU.save(formats) print "Output written in", plotDir
def doLimitError(limits, unblindedStatus): expRelErrors = [] expLabels = {} obsRelErrors = [] obsLabels = {} order = [0, 1, -1, 2, -2] expErrors = [limits.expectedErrorGraph(sigma=s) for s in order] if expErrors[0] != None: exps = [limits.expectedGraph(sigma=s) for s in order] expRelErrors = [(limit.divideGraph(expErrors[i], exps[i]), "ExpRelErr%d" % i) for i in xrange(len(exps))] expLabels = { "ExpRelErr0": "Expected median", "ExpRelErr1": "Expected +1#sigma", "ExpRelErr2": "Expected -1#sigma", "ExpRelErr3": "Expected +2#sigma", "ExpRelErr4": "Expected -2#sigma", } if unblindedStatus: obsErr = limits.observedErrorGraph() if obsErr != None: obs = limits.observedGraph() if obs != None: obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")] obsLabels = {"ObsRelErr": "Observed"} if len(expRelErrors) == 0 and len(obsRelErrors) == 0: return # Create the plot plot = plots.PlotBase() if len(expRelErrors) > 0: plot.histoMgr.extendHistos([ histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp") for x in expRelErrors ]) plot.histoMgr.forEachHisto(styles.generator()) def sty(h): r = h.getRootHisto() r.SetLineStyle(1) r.SetLineWidth(3) r.SetMarkerSize(1.4) plot.histoMgr.forEachHisto(sty) plot.histoMgr.setHistoLegendLabelMany(expLabels) if unblindedStatus: if len(obsRelErrors) > 0: obsRelErrors[0][0].SetMarkerSize(1.4) obsRelErrors[0][0].SetMarkerStyle(25) plot.histoMgr.insertHisto( 0, histograms.HistoGraph(obsRelErrors[0][0], obsRelErrors[0][1], drawStyle="PL", legendStyle="lp")) plot.histoMgr.setHistoLegendLabelMany(obsLabels) plot.setLegend( histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=0.1, dy=-0.1)) if len(limits.mass) == 1: plot.createFrame("limitsBrRelativeUncertainty", opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": 0, "ymaxfactor": 1.5 }) else: plot.createFrame("limitsBrRelativeUncertainty", opts={ "ymin": 0, "ymaxfactor": 1.5 }) plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle("Uncertainty/limit") plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.88, limit.process, size=size) histograms.addText(x, 0.84, limits.getFinalstateText(), size=size) histograms.addText(x, 0.79, limit.BRassumption, size=size) size = 22 x = 0.55 histograms.addText(x, 0.88, "Toy MC relative", size=size) histograms.addText(x, 0.84, "statistical uncertainty", size=size) plot.save()
def main(): if len(sys.argv) < 2: usage() dirs = [] dirs.append(sys.argv[1]) #datasets = dataset.getDatasetsFromMulticrabDirs(dirs) datasets = dataset.getDatasetsFromMulticrabDirs(dirs,dataEra=dataEra, searchMode=searchMode, analysisName=analysis) # consistencyCheck.checkConsistencyStandalone(dirs[0],datasets,name="QCD inverted") datasets.loadLuminosities() datasets.updateNAllEventsToPUWeighted() # erik # datasets.remove(filter(lambda name: "TTJets_SemiLept" in name, datasets.getAllDatasetNames())) # datasets.remove(filter(lambda name: "TTJets_FullLept" in name, datasets.getAllDatasetNames())) # datasets.remove(filter(lambda name: "TTJets_Hadronic" in name, datasets.getAllDatasetNames())) datasets.remove(filter(lambda name: "WJetsToLNu" in name and not "WJetsToLNu_HT" in name, datasets.getAllDatasetNames())) plots.mergeRenameReorderForDataMC(datasets) datasets.merge("EWK", [ "TT", "WJetsHT", "DYJetsToLLHT", "SingleTop", # "Diboson" ]) style = tdrstyle.TDRStyle() plot = plots.PlotBase() legends = {} name_re = re.compile("SelectedTau_pT_(?P<name>\S+)") for i,histo in enumerate(HISTONAMES): plot.histoMgr.appendHisto(purityGraph(i,datasets,histo)) name = histo match = name_re.search(histo) if match: name = match.group("name") legends["Purity%s"%i] = name # if "AfterMetCut" in name: # legends["Purity%s"%i] = "MET > 60 GeV" if "SelectedTau_pT_CollinearCuts" in name: legends["Purity%s"%i] = "Collinear cuts" if "AfterBtagging" in name: legends["Purity%s"%i] = "B tagging" if "AfterBveto" in name: legends["Purity%s"%i] = "B-jet veto" if "AfterBvetoPhiCuts" in name: legends["Purity%s"%i] = "B-jet veto, TailKiller" if "SelectedTau_pT_BackToBackCuts" in name: legends["Purity%s"%i] = "BackToBack cuts" # plot.createFrame("purity_QCD_only", opts={"xmin": 40, "xmax": 160, "ymin": 0., "ymax": 1.05}) plot.createFrame("purity_QCD_only", opts={"xmin": 40, "xmax": 400, "ymin": 0., "ymax":1}) plot.frame.GetXaxis().SetTitle("p_{T}^{#tau jet} (GeV/c)") plot.frame.GetYaxis().SetTitle("QCD purity") # plot.setEnergy(datasets.getEnergies()) # plot.histoMgr.appendHisto(histograms.Histo(histo,"InvertedTauPtAfterAllSelections")) plot.histoMgr.setHistoLegendLabelMany(legends) ### plot.setLegend(histograms.createLegend(0.2, 0.35, 0.6, 0.5)) # histograms.addText(0.2, 0.3, "TailKiller: MediumPlus", 18) # histograms.addText(0.35, 0.28, "BackToBack cuts: TightPlus", 20) # histograms.addText(0.35, 0.22, "2011B", 20) histograms.addText(0.3, 0.35, "QCD only", 20) histograms.addText(0.3, 0.3, "After all selection cuts", 20) # histograms.addText(0.2, 0.3, "QCD only", 18) histograms.addCmsPreliminaryText() histograms.addEnergyText(s="%s TeV"%(datasets.getEnergies()[0])) histograms.addLuminosityText(x=None, y=None, lumi=datasets.getDataset("Data").getLuminosity()) plot.draw() plot.save()
def doPlot(name, dset, errorlevel, optimizationMode, lumi): print shellStyles.HighlightStyle()+"Generating plots for dataset '%s'"%name+shellStyles.NormalStyle() s = optimizationMode.split("BjetDiscrWorkingPoint") discrName = s[0].replace("OptBjetDiscr","") discrWP = s[1] myPartons = ["B", "C", "G", "Light"] myPartonLabels = ["b#rightarrowb", "c#rightarrowb", "g#rightarrowb", "uds#rightarrowb"] histoObjects = [] results = [] for i in range(len(myPartons)): n = "All%sjets"%myPartons[i] dsetHisto = dset.getDatasetRootHisto(n) dsetHisto.normalizeToLuminosity(lumi) hAll = dsetHisto.getHistogram() #(hAll, hAllName) = dset.getRootHisto(n) if hAll == None: raise Exception("Error: could not find histogram '%s'!"%n) treatNegativeBins(hAll) n = "Selected%sjets"%myPartons[i] dsetHisto = dset.getDatasetRootHisto(n) dsetHisto.normalizeToLuminosity(lumi) hPassed = dsetHisto.getHistogram() #(hPassed, hPassedName) = dset.getRootHisto(n) if hPassed == None: raise Exception("Error: could not find histogram '%s'!"%n) treatNegativeBins(hPassed) # Find proper binning myBinEdges = [] for k in range(1, hPassed.GetNbinsX()+1): if len(myBinEdges) > 0 or hPassed.GetBinContent(k) > 0: myBinEdges.append(hPassed.GetXaxis().GetBinLowEdge(k)) myBinEdges.append(hPassed.GetXaxis().GetBinUpEdge(hPassed.GetNbinsX())) myArray = array.array("d", myBinEdges) hAllNew = hAll.Rebin(len(myArray)-1, "", myArray) hPassedNew = hPassed.Rebin(len(myArray)-1, "", myArray) (hPassed, hAll) = findProperBinning(hPassedNew, hAllNew, myBinEdges, errorlevel) #print myBinEdges # Treat fluctuations for k in range(hPassed.GetNbinsX()+2): if hPassed.GetBinContent(k) > hAll.GetBinContent(k): hPassed.SetBinContent(k, hAll.GetBinContent(k)) # Construct efficiency plot eff = ROOT.TEfficiency(hPassed, hAll) eff.SetStatisticOption(ROOT.TEfficiency.kFNormal) for k in range(hPassed.GetNbinsX()): resultObject = {} resultObject["flavor"] = myPartons[i] resultObject["ptMin"] = hPassed.GetXaxis().GetBinLowEdge(k+1) resultObject["ptMax"] = hPassed.GetXaxis().GetBinUpEdge(k+1) resultObject["eff"] = eff.GetEfficiency(k+1) resultObject["effUp"] = eff.GetEfficiencyErrorUp(k+1) resultObject["effDown"] = eff.GetEfficiencyErrorLow(k+1) resultObject["discr"] = discrName resultObject["workingPoint"] = discrWP results.append(resultObject) #gEff = eff.CreateGraph() styles.styles[i].apply(eff) hobj = histograms.HistoEfficiency(eff, myPartonLabels[i], legendStyle="P", drawStyle="") #hobj = histograms.HistoGraph(gEff, myPartonLabels[i], legendStyle="P", drawStyle="") hobj.setIsDataMC(False, True) histoObjects.append(hobj) myPlot = plots.PlotBase(histoObjects) #myPlot.setLuminosity(-1) # Do not set myPlot.setEnergy("13") #myPlot.setDefaultStyles() myParams = {} myParams["xlabel"] = "Jet p_{T}, GeV" myParams["ylabel"] = "Probability for passing b tagging" myParams["log"] = True myParams["cmsExtraText"] = "Simulation" myParams["cmsTextPosition"] = "outframe" # options: left, right, outframe myParams["opts"] = {"ymin": 1e-3, "ymax": 1.0} #myParams["opts2"] = {"ymin": 0.5, "ymax":1.5} #myParams["moveLegend"] = {"dx": -0.08, "dy": -0.12, "dh": 0.1} # for MC EWK+tt #myParams["moveLegend"] = {"dx": -0.15, "dy": -0.12, "dh":0.05} # for data-driven myParams["moveLegend"] = {"dx": 0.0, "dy": -0.46} # for data-driven drawPlot = plots.PlotDrawer(ratio=False, #stackMCHistograms=False, addMCUncertainty=True, addLuminosityText=False, cmsTextPosition="outframe") drawPlot(myPlot, "%s_%s"%(dset.name, name), **myParams) return results
def analyze(analysis=None): paths = [sys.argv[1]] if not analysis == None: datasets = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, excludeTasks="Silver|GluGluHToTauTau_M125") else: datasets = dataset.getDatasetsFromMulticrabDirs( paths, excludeTasks="Silver|GluGluHToTauTau_M125") analysis = datasets.getAllDatasets()[0].getAnalysisName() # datasetsDY = None datasetsDY = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="GluGluHToTauTau_M125|TTJets") datasetsH125 = None # datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125",emptyDatasetsAsNone=True) # datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125") datasets.loadLuminosities() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 # dataset2 = datasets.getMCDatasets() if not datasetsDY == None: dataset2 = datasetsDY.getMCDatasets() eff1 = getEfficiency(dataset1) eff2 = getEfficiency(dataset2) if isinstance(datasetsH125, dataset.DatasetManager): eff3 = getEfficiency(datasetsH125.getMCDatasets()) styles.dataStyle.apply(eff1) styles.mcStyle.apply(eff2) eff1.SetMarkerSize(1) # eff2.SetMarkerSize(1.5) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3) eff3.SetMarkerSize(1.5) eff3.SetMarkerColor(4) eff3.SetLineColor(4) # p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"), # histograms.HistoGraph(eff2, "eff2", "p", "P")) if isinstance(datasetsH125, dataset.DatasetManager): p = plots.ComparisonManyPlot( histograms.HistoGraph(eff1, "eff1", "p", "P"), [ histograms.HistoGraph(eff2, "eff2", "p", "P"), histograms.HistoGraph(eff3, "eff3", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"), histograms.HistoGraph(eff2, "eff2", "p", "P")) else: p = plots.PlotBase([histograms.HistoGraph(eff1, "eff1", "p", "P")]) fit("Data", p, eff1, 20, 200) fit("MC", p, eff2, 20, 200) if isinstance(datasetsH125, dataset.DatasetManager): fit("H125", p, eff3, 20, 200) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} # moveLegend = {"dx": -0.55, "dy": -0.15, "dh": -0.1} moveLegend = {"dx": -0.2, "dy": -0.5, "dh": -0.1} name = "TauMET_" + analysis + "_DataVsMC_PFTauPt" legend1 = "Data" # legend2 = "MC (DY)" legend2 = "Simulation" legend3 = "MC (H125)" createRatio = False p.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) createRatio = True if isinstance(datasetsH125, dataset.DatasetManager): p.histoMgr.setHistoLegendLabelMany({ "eff1": legend1, "eff2": legend2, "eff3": legend3 }) if createRatio: p.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.getFrame().GetYaxis().SetTitle("HLT tau efficiency") # p.getFrame().GetXaxis().SetTitle("#tau-jet p_{T} (GeV/c)") p.getFrame().GetXaxis().SetTitle("#tau_{h} p_{T} (GeV/c)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17) # label = analysis.split("_")[len(analysis.split("_")) -1] label = "2016" histograms.addText(0.5, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.5, 0.46, "Runs " + runRange, 17) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity", d.getName(), d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum", lumi histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1) pythonWriter.addMCParameters(label, eff2) pythonWriter.writeJSON( os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + ".json")) # if not createRatio: # sys.exit() ######################################################################### eff1eta = getEfficiency(dataset1, "NumeratorEta", "DenominatorEta") eff2eta = getEfficiency(dataset2, "NumeratorEta", "DenominatorEta") if isinstance(datasetsH125, dataset.DatasetManager): eff3eta = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorEta", "DenominatorEta") styles.dataStyle.apply(eff1eta) styles.mcStyle.apply(eff2eta) eff1eta.SetMarkerSize(1) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3eta) eff3eta.SetMarkerSize(1.5) eff3eta.SetMarkerColor(4) eff3eta.SetLineColor(4) if isinstance(datasetsH125, dataset.DatasetManager): p_eta = plots.ComparisonManyPlot( histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), [ histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"), histograms.HistoGraph(eff3eta, "eff3eta", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p_eta = plots.ComparisonPlot( histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), histograms.HistoGraph(eff2eta, "eff2eta", "p", "P")) else: p_eta = plots.PlotBase( [histograms.HistoGraph(eff1eta, "eff1eta", "p", "P")]) p_eta.histoMgr.setHistoLegendLabelMany({"eff1eta": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p_eta.histoMgr.setHistoLegendLabelMany({ "eff1eta": legend1, "eff2eta": legend2 }) if isinstance(datasetsH125, dataset.DatasetManager): p_eta.histoMgr.setHistoLegendLabelMany({ "eff1eta": legend1, "eff2eta": legend2, "eff3eta": legend3 }) name = "TauMET_" + analysis + "_DataVsMC_PFTauEta" if createRatio: p_eta.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_eta.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) moveLegendEta = {"dx": -0.5, "dy": -0.65, "dh": -0.1} p_eta.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendEta)) p_eta.getFrame().GetYaxis().SetTitle("HLT tau efficiency") p_eta.getFrame().GetXaxis().SetTitle("#tau-jet #eta") if createRatio: p_eta.getFrame2().GetYaxis().SetTitle("Ratio") p_eta.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.38, label, 17) histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17) p_eta.draw() histograms.addStandardTexts(lumi=lumi) p_eta.save(formats) ######################################################################### eff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi") eff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi") if isinstance(datasetsH125, dataset.DatasetManager): eff3phi = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorPhi", "DenominatorPhi") styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3phi) eff3phi.SetMarkerSize(1.5) eff3phi.SetMarkerColor(4) eff3phi.SetLineColor(4) if isinstance(datasetsH125, dataset.DatasetManager): p_phi = plots.ComparisonManyPlot( histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), [ histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"), histograms.HistoGraph(eff3phi, "eff3phi", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p_phi = plots.ComparisonPlot( histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), histograms.HistoGraph(eff2phi, "eff2phi", "p", "P")) else: p_phi = plots.PlotBase( [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")]) p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2 }) if isinstance(datasetsH125, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2, "eff3phi": legend3 }) name = "TauMET_" + analysis + "_DataVsMC_PFTauPhi" if createRatio: p_phi.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) moveLegendPhi = {"dx": -0.5, "dy": -0.65, "dh": -0.1} p_phi.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("HLT tau efficiency") p_phi.getFrame().GetXaxis().SetTitle("#tau-jet #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.38, label, 17) histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### namePU = "TauMET_" + analysis + "_DataVsMC_nVtx" eff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU") eff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU") styles.dataStyle.apply(eff1PU) styles.mcStyle.apply(eff2PU) eff1PU.SetMarkerSize(1) eff2PU.SetMarkerSize(1.5) if isinstance(datasetsDY, dataset.DatasetManager): pPU = plots.ComparisonManyPlot( histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({ "eff1": legend1, "eff2": legend2 }) else: pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) optsPU = {"ymin": 0.01, "ymax": 1.0} createRatio = False if createRatio: pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=optsPU, opts2=opts2) else: pPU.createFrame(os.path.join(plotDir, namePU), opts=optsPU, opts2=opts2) moveLegend = {"dx": -0.5, "dy": -0.5, "dh": -0.1} pPU.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("HLT tau efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") if createRatio: pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.53, label, 17) histograms.addText(0.2, 0.46, "Runs " + datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) ######################################################################### """ hName = "Pull" # hName = "Sub" namePull = "TauMET_"+analysis+"_DataVsMC_"+hName+"s" plots.mergeRenameReorderForDataMC(datasets) datasets.merge("MC", ["TT","WJets","DYJetsToLL","SingleTop","QCD"], keepSources=True) drh1 = datasets.getDataset("Data").getDatasetRootHisto(hName) drh2 = datasets.getDataset("MC").getDatasetRootHisto(hName) drh1.normalizeToOne() drh2.normalizeToOne() pull1 = drh1.getHistogram() pull2 = drh2.getHistogram() if isinstance(datasetsH125,dataset.DatasetManager): plots.mergeRenameReorderForDataMC(datasetsH125) drh3 = datasetsH125.getMCDatasets()[0].getDatasetRootHisto(hName) drh3.normalizeToOne() pull3 = drh3.getHistogram() styles.dataStyle.apply(pull1) styles.mcStyle.apply(pull2) pull1.SetMarkerSize(1) if isinstance(datasetsH125,dataset.DatasetManager): styles.mcStyle.apply(pull3) pull3.SetMarkerSize(1.5) pull3.SetMarkerColor(4) pull3.SetLineColor(4) if isinstance(datasetsH125,dataset.DatasetManager): p_pull = plots.ComparisonManyPlot(histograms.Histo(pull1, "pull1", "p", "P"), [histograms.Histo(pull2, "pull2", "p", "P"), histograms.Histo(pull3, "pull3", "p", "P")]) else: p_pull = plots.ComparisonPlot(histograms.Histo(pull1, "pull1", "p", "P"), histograms.Histo(pull2, "pull2", "p", "P")) p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2}) if isinstance(datasetsH125,dataset.DatasetManager): p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2, "pull3": legend3}) p_pull.createFrame(os.path.join(plotDir, namePull), createRatio=True, opts=opts, opts2=opts2) moveLegendPull = {"dx": -0.5, "dy": -0.35, "dh": -0.1} p_pull.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPull)) p_pull.getFrame().GetYaxis().SetTitle("Arbitrary units") # p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T} - #tau-jet p_{T} (GeV/c)") p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T}/ #tau-jet p_{T} - 1") p_pull.getFrame2().GetYaxis().SetTitle("Ratio") p_pull.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.75, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.68, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.2, 0.61, "Runs "+runRange, 17) p_pull.draw() histograms.addStandardTexts(lumi=lumi) p_pull.save(formats) """ ######################################################################### print "Output written in", plotDir
def createDrawPlot(gr, labels, fname): plot = plots.PlotBase( [histograms.HistoGraph(gr, "Fitted", drawStyle="P")]) plot.setLuminosity(lumi) canvasOpts = {} if len(labels) > 15: canvasOpts["addHeight"] = 0.03 * (len(labels) - 15) canvasOpts["addWidth"] = 0.2 plot.createFrame(fname, opts={ "ymin": 0, "xmin": -4.2, "xmax": 2.5 }, canvasOpts=canvasOpts) plot.getFrame().GetXaxis().SetTitle("Fitted value") scale = 1 if "addHeight" in canvasOpts: scale = 1 / (1 + canvasOpts["addHeight"]) plot.getFrame().GetXaxis().SetTickLength( plot.getFrame().GetXaxis().GetTickLength() * scale) plot.getPad().SetBottomMargin(plot.getPad().GetBottomMargin() * scale) plot.getPad().SetTopMargin(plot.getPad().GetTopMargin() * scale) if "addWidth" in canvasOpts: scale = 1 / (1 + canvasOpts["addWidth"]) #plot.getFrame().GetXaxis().SetTickLength(plot.getFrame().GetXaxis().GetTickLength()*scale) plot.getPad().SetRightMargin(0.04) plot.getPad().SetLeftMargin(0.04) plot.getPad().SetLeftMargin(plot.getPad().GetRightMargin()) plot.getPad().Update() ymin = plot.cf.frame.GetYaxis().GetXmin() ymax = plot.cf.frame.GetYaxis().GetXmax() for xval, color in [(0, ROOT.kRed), (-1, ROOT.kBlue), (1, ROOT.kBlue)]: l = ROOT.TLine(xval, ymin, xval, ymax) l.SetLineColor(color) l.SetLineStyle(ROOT.kDotted) l.SetLineWidth(2) plot.prependPlotObject(l) plot.cf.frame.GetYaxis().SetLabelSize(0) plot.draw() plot.addStandardTexts(cmsTextPosition="outframe") # Intentionally not NDC l = ROOT.TLatex() l.SetTextFont(l.GetTextFont() - 20) # bold->normal l.SetTextSize(17) x_nuis = -4.0 x_value = 1.5 l.DrawLatex(x_nuis, ymax * 0.93, "Nuisance parameter") l.DrawLatex(x_value, ymax * 0.93, "Fitted value") for i, label in enumerate(labels): y = gr.GetY()[i] - 0.3 l.DrawLatex(x_nuis, y, label[:40]) l.DrawLatex(x_value, y, "%.2f #pm %.2f" % (gr.GetX()[i], gr.GetErrorX(i))) plot.save()
def Plot2d(datasetsMgr, dataset, histoName, kwargs, opts): ''' ''' # Definitions saveName = histoName.replace("/", "_") # Get Histos for the plotter object refHisto = GetHisto(datasetsMgr, dataset, histoName) # Create the plotting object p = plots.PlotBase(datasetRootHistos=[refHisto], saveFormats=kwargs.get("saveFormats")) if 0: p.histoMgr.normalizeMCToLuminosity(opts.intLumi) # Customise axes (before drawing histo) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) if 0: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle(kwargs.get("xlabel"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetTitle(kwargs.get("ylabel"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle( h.getRootHisto().GetXaxis().GetTitle() + "%0.1f" )) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(kwargs.get("xmin"), kwargs.get("xmax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(kwargs.get("zmin"), kwargs.get("zmax"))) # Create a frame fOpts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=fOpts) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box if 1: _kwargs = { "lessThan": True} p.addCutBoxAndLine(cutValue=400.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs) p.addCutBoxAndLineY(cutValue=200.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **kwargs.get("moveLegend"))) p.removeLegend() # Customise histogram (after frame is created) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle("Events")) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.4)) #ROOT.gPad.RedrawAxis() p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zmin"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zmax"))) # Drawing style p.histoMgr.setHistoDrawStyle(dataset, "COLZ") p.histoMgr.setHistoDrawStyleAll("COLZ") # The lines below do nothing since the Legend is disabled if 0: p.histoMgr.setHistoLegendStyle(dataset, "F") if "FakeB" in dataset: p.histoMgr.setHistoLegendLabelMany({ dataset: "QCD (Data)", }) if dataset == "QCD": p.histoMgr.setHistoLegendLabelMany({ dataset: "QCD (MC)", }) # Draw the plot p.draw() # Add canvas text if kwargs.get("addLuminosityText"): histograms.addStandardTexts(lumi=opts.intLumi) else: histograms.addStandardTexts() # Add dataset name on the canvas if dataset == "QCD": histograms.addText(0.17, 0.88, "QCD (H_{T} binned)", 27) else: histograms.addText(0.17, 0.88, plots._legendLabels[dataset], 27) # Save the plots SavePlot(p, saveName, os.path.join(opts.saveDir, opts.analysisName, opts.folder, dataset, 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 doBRlimit(limits, unblindedStatus, opts, logy=False): graphs = [] if unblindedStatus: gr = limits.observedGraph() if gr != None: gr.SetPoint(gr.GetN() - 1, gr.GetX()[gr.GetN() - 1] - 1e-10, gr.GetY()[gr.GetN() - 1]) if opts.excludedArea: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle=None)) excluded = gr.Clone() excluded.SetPoint(excluded.GetN(), excluded.GetX()[excluded.GetN() - 1], 0.05) excluded.SetPoint(excluded.GetN(), excluded.GetX()[0], 0.05) limit.setExcludedStyle(excluded) graphs.append( histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="lpf", legendLabel="Observed")) else: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle="lp")) # Add the expected lines graphs.extend([ histograms.HistoGraph(limits.expectedGraph(), "Expected", drawStyle="L"), histograms.HistoGraph(limits.expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(limits.expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"), ]) # Plot the TGraphs saveFormats = [".png", ".C", ".pdf"] if not opts.excludedArea: saveFormats.append(".eps") plot = plots.PlotBase(graphs, saveFormats=saveFormats) plot.setLuminosity(limits.getLuminosity()) # Customise legend entries plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) # Branching Ratio Assumption if 0: limit.BRassumption = "Assuming B(H^{+}#rightarrowt#bar{b}) = 1" # Create legend xPos = 0.53 legend = getLegend(limit, opts, xPos) plot.setLegend(legend) # Get y-min, y-max, and histogram name to be saved as ymin, ymax, saveName = getYMinMaxAndName(limits, "limitsBr", logy, opts) if opts.yMin != -1: ymin = opts.yMin if opts.yMax != -1: ymax = opts.yMax if len(limits.mass) == 1: plot.createFrame(saveName, opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": ymin, "ymax": ymax }) else: plot.createFrame(saveName, opts={"ymin": ymin, "ymax": ymax}) # Add cut box? if opts.cutLine > 0: kwargs = {"greaterThan": True} plot.addCutBoxAndLine(cutValue=opts.cutLine, fillColor=ROOT.kRed, box=False, line=True, **kwargs) # Set x-axis title plot.frame.GetXaxis().SetTitle(limit.mHplus()) if limit.BRassumption != "": plot.frame.GetYaxis().SetTitle("95% CL limit for #sigma_{H^{+}} (pb)") else: plot.frame.GetYaxis().SetTitle(limit.sigmaBRlimit) # plot.frame.GetYaxis().SetTitle(limit.BRlimit) # Enable/Disable logscale for axes if logy: plot.getPad().SetLogy(logy) plot.getPad().SetLogx(opts.logx) # Enable grids in x and y? plot.getPad().SetGridx(opts.gridX) plot.getPad().SetGridy(opts.gridY) # Draw the plot with standard texts plot.draw() plot.addStandardTexts() # Add physics-related text on canvas addPhysicsText(histograms, limit, x=xPos) # Save the canvas plot.save() # Save the plots SavePlot(plot, saveName, os.path.join(opts.saveDir, opts.settings)) return
def Fit(datasets, histo, function): FitList = [] for dataset in datasets: datasetName = dataset.getName() print "Dataset = ", datasetName hh = dataset.getDatasetRootHisto(histo) hh.normalizeToOne() h = hh.getHistogram() #h = dataset.getDatasetRootHisto(histo).getHistogram() xMin = h.GetXaxis().GetXmin() xMax = h.GetXaxis().GetXmax() yMin = 0 yMax = 1.2 #statOption = ROOT.TEfficiency.kFNormal if "TT" in datasetName: if function == "gaus": fitGauss = ROOT.TF1("fitGauss", "gaus", -2.5, 2.5) # TF1 *fitBoFreq = new TF1("fitBoFreq","[0]*x+[1]",0,20); # h.Fit("gaus") #fitTest = ROOT.TF1("fitTest", "0.01", -2.5, 2.5) h.Fit("fitGauss", "SRBM") #h.GetListOfFunctions().Add(fitTest) legend = "TT" legend = "a legend" print "Legend", legend saveName = histo.split("/")[-1] + "_Fit" print saveName xTitle = "fixXTitle" yTitle = "fixYTitle" yMin = 0. yMax = 0.03 xMin = -2.3 xMax = 2.3 kwargs = {} options = {"ymin": yMin, "ymax": yMax, "xmin": xMin, "xMax": xMax} FitList.append(h) #p = plots.MCPlot(dataset, h, normalizeToLumi=0, saveFormats=[], **kwargs) p = plots.PlotBase(datasetRootHistos=FitList, saveFormats=kwargs.get("saveFormats")) p.createFrame(saveName, opts=options) p.getFrame().GetXaxis().SetTitle(xTitle) p.getFrame().GetYaxis().SetTitle(yTitle) #p.histoMgr.setHistoDrawStyle(datasetName, "AP") # Set range p.getFrame().GetXaxis().SetRangeUser(xMin, xMax) moveLegend = {"dx": -0.55, "dy": -0.01, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Add Standard Texts to plot histograms.addStandardTexts() p.draw() # Save plot in all formats savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) save_path = savePath SavePlot(p, saveName, save_path) return
def doPlot(name, graphs, limits, xlabel, scenario, mass): higgs = "h" if "lowMH" in scenario: higgs = "H" excluded = graphs["muexcluded"] limit.setExcludedStyle(excluded) excluded.SetFillStyle(1001) excluded.SetLineWidth(0) excluded.SetLineStyle(0) excluded.SetLineColor(ROOT.kWhite) excludedCopy = excluded.Clone() if not mass in [90]: excludedCopy.SetFillColorAlpha( ROOT.kWhite, 0.0) # actual color doesn't matter, want fully transparent # else: # excluded.SetLineColor(ROOT.kBlack) # Uncomment when we have allowed for n in ["Allowed", "Allowed2"]: a = graphs[n] if a is None: continue a.SetFillStyle(3005) a.SetFillColor(ROOT.kRed) a.SetLineWidth(-302) a.SetLineColor(ROOT.kRed) a.SetLineStyle(1) legend_dh = 0 grs = [] if "observed" in graphs: grs.extend([ histograms.HistoGraph(graphs["observed"], "Observed", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L", legendStyle=None), ]) legend_dh = 0.1 grs.extend([ histograms.HistoGraph(excluded, "Excluded", drawStyle="F"), histograms.HistoGraph(excludedCopy, "ExcludedCopy", drawStyle=None, legendStyle="f"), histograms.HistoGraph(graphs["Allowed"], "Allowed", drawStyle="L", legendStyle="lf"), ]) if graphs["Allowed2"] is not None: grs.append( histograms.HistoGraph(graphs["Allowed2"], "Allowed2", drawStyle="L", legendStyle=None)) plot = plots.PlotBase(grs, saveFormats=[".png", ".pdf", ".C"]) plot.histoMgr.setHistoLegendLabelMany({ "ExcludedCopy": "Excluded", "Allowed": "m_{" + higgs + "}^{MSSM} #neq 125#pm3 GeV", "Excluded": None, }) if "observed" in graphs: plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", }) textPos = "left" dx = 0 dy = -0.15 if mass in [90, 150]: textPos = "right" dx = 0.35 if mass in [155, 160]: textPos = "right" dy = -0.02 plot.setLegend( histograms.createLegend(0.19 + dx, 0.75 + dy - legend_dh, 0.57 + dx, 0.80 + dy)) histograms.moveLegend(plot.legend, dh=0.05, dy=-0.05) #plot.legend.SetFillColor(0) #plot.legend.SetFillStyle(1001) name = name.replace("-", "_") plot.createFrame(name, opts={ "ymin": 0, "ymax": tanbMax, "xmin": 200, "xmax": 3300 }) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts(cmsTextPosition=textPos) size = 20 x = 0.2 + dx histograms.addText(x, 0.9 + dy, limit.process, size=size) histograms.addText(x, 0.863 + dy, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815 + dy, limit.getTypesetScenarioName(scenario.replace( "_mu", "")), size=size) histograms.addText(x, 0.767 + dy, "m_{H^{+}}=%d GeV" % mass, size=size) # histograms.addText(0.2, 0.231, "Min "+limit.BR+"(t#rightarrowH^{+}b)#times"+limit.BR+"(H^{+}#rightarrow#tau#nu)", size=0.5*size) #Adding a LHC label: # ROOT.LHCHIGGS_LABEL(0.97,0.72,1) # FH_version = db.getVersion("FeynHiggs") # histograms.addText(x, 0.55, FH_version) # HD_version = db.getVersion("HDECAY") # histograms.addText(x, 0.55, FH_version+" and "+HD_version, size=size) # histograms.addText(x, 0.48, "Derived from", size=size) # histograms.addText(x, 0.43, "CMS HIG-12-052", size=size) plot.save() print "Created", name