def plotgraph(histolist,lumi,j,name=""): name = os.path.basename(name) p = plots.DataMCPlot2(histolist) opts = {} if "opts" in j: opts = j["opts"] opts2 = {} if "opts2" in j: opts2 = j["opts2"] p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) if "xlabel" in j: p.getFrame().GetXaxis().SetTitle(j["xlabel"]) if "ylabel" in j: p.getFrame().GetYaxis().SetTitle(j["ylabel"]) # p.setDrawOptions("COLZ") if "drawStyle" in j: p.histoMgr.setHistoDrawStyleAll(j["drawStyle"]) if "rebinx" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"])) if "rebiny" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"])) p.draw() histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) print "Saved plot",os.path.join(plotDir, name)
def plotgraph(histolist, lumi, j, name=""): name = os.path.basename(name) p = plots.DataMCPlot2(histolist) opts = {} if "opts" in j: opts = j["opts"] opts2 = {} if "opts2" in j: opts2 = j["opts2"] opts = str2bool(opts) opts2 = str2bool(opts2) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) if "xlabel" in j: p.getFrame().GetXaxis().SetTitle(j["xlabel"]) if "ylabel" in j: p.getFrame().GetYaxis().SetTitle(j["ylabel"]) if "drawStyle" in j: p.histoMgr.setHistoDrawStyleAll(j["drawStyle"]) if "rebinx" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"])) if "rebiny" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"])) if "markerStyle" in j: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerStyle(j["markerStyle"])) if "markerColor" in j: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerColor(j["markerColor"])) if "markerSize" in j: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerSize(j["markerSize"])) if "useBeachPalette" in j and j["useBeachPalette"]: ROOT.gStyle.SetPalette(69) ROOT.TColor.InvertPalette() # invert color palette if asked p.draw() histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) print "Saved plot", os.path.join(plotDir, name) if "useBeachPalette" in j and j["useBeachPalette"]: ROOT.TColor.InvertPalette( ) # re-invert back to nominal, because the above line will invert for the next histogram again
def plotgraph(histolist,lumi,j,name=""): name = os.path.basename(name) p = plots.DataMCPlot2(histolist) opts = {} if "opts" in j: opts = j["opts"] opts2 = {} if "opts2" in j: opts2 = j["opts2"] opts = str2bool(opts) opts2 = str2bool(opts2) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) if "xlabel" in j: p.getFrame().GetXaxis().SetTitle(j["xlabel"]) if "ylabel" in j: p.getFrame().GetYaxis().SetTitle(j["ylabel"]) if "drawStyle" in j: p.histoMgr.setHistoDrawStyleAll(j["drawStyle"]) if "rebinx" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"])) if "rebiny" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"])) if "markerStyle" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(j["markerStyle"])) if "markerColor" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerColor(j["markerColor"])) if "markerSize" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(j["markerSize"])) if "useBeachPalette" in j and j["useBeachPalette"]: ROOT.gStyle.SetPalette(69) ROOT.TColor.InvertPalette() # invert color palette if asked p.draw() histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) print "Saved plot",os.path.join(plotDir, name) if "useBeachPalette" in j and j["useBeachPalette"]: ROOT.TColor.InvertPalette() # re-invert back to nominal, because the above line will invert for the next histogram again
def plotClosure(mt_nom, mts_var, name, optMode): #for mt_var in mts_var: # printSummedDifference(mt_nom, mt_var) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot(mt_nom, mts_var) plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True) moveLegend={"dx": -0.325,"dy": 0.02,"dw":-0.14,"dh":-0.12} plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText(0.65, 0.3, optMode.replace("OptQCDTailKiller","R_{BB} ").replace("Plus",""), 25) histograms.addStandardTexts() plot.draw() plot.save()
def plotClosure(mt_nom, mts_var, name, optMode): #for mt_var in mts_var: # printSummedDifference(mt_nom, mt_var) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot(mt_nom, mts_var) plot.createFrame(optMode.replace("Opt", "mT_Closure_" + name + "_"), createRatio=True) moveLegend = {"dx": -0.325, "dy": 0.02, "dw": -0.14, "dh": -0.12} plot.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText( 0.65, 0.3, optMode.replace("OptQCDTailKiller", "R_{BB} ").replace("Plus", ""), 25) histograms.addStandardTexts() plot.draw() plot.save()
def plotgraph(histolist,lumi,j,name=""): name = os.path.basename(name) p = plots.DataMCPlot2(histolist) opts = {} if "opts" in j: opts = j["opts"] opts2 = {} if "opts2" in j: opts2 = j["opts2"] opts = str2bool(opts) opts2 = str2bool(opts2) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) if "xlabel" in j: p.getFrame().GetXaxis().SetTitle(j["xlabel"]) if "ylabel" in j: p.getFrame().GetYaxis().SetTitle(j["ylabel"]) if "drawStyle" in j: p.histoMgr.setHistoDrawStyleAll(j["drawStyle"]) if "rebinx" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"])) if "rebiny" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"])) if "markerStyle" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(j["markerStyle"])) if "markerColor" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerColor(j["markerColor"])) if "markerSize" in j: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(j["markerSize"])) p.draw() histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) print "Saved plot",os.path.join(plotDir, name)
def doPlots(i, opts): Print("Processing %s%s%s algorithm" % (ShellStyles.NoteStyle(), opts.algorithm, ShellStyles.NormalStyle(), ), True) # Settings if opts.h2tb: analysis = "H^{+}#rightarrow tb fully hadronic" else: analysis = "H^{+}#rightarrow#tau_{h}#nu fully hadronic" # Hadd ROOT files #rootFiles = glob.glob1(filePath, "higgsCombinetoys*.root") rootFiles = glob.glob1(opts.inputDir, "higgsCombinetoys*.root") Verbose("Attempting to merge all toy ROOT files", True) if len(rootFiles) > 0: if os.path.isfile(opts.outputfile): os.remove(opts.outputfile) Print("Merging \"%s\" ROOT files into \"%s\"" % (opts.inputfile, opts.inputfile), True) call("hadd %s %s" % (opts.outputfile, opts.inputfile), shell=True) else: msg = "%sFound %d toy ROOT files to merge%s" % (ShellStyles.NoteStyle(), len(rootFiles), ShellStyles.NormalStyle() ) Print(msg, True) sys.exit() # Clean auxiliary jobs files? CleanFiles(opts) # Perform GoF calculations if not os.path.isfile(opts.outputfile): raise Exception("The output ROOT file \"%s\" does not exist!" % (opts.outputfile) ) else: Print("Opening merged ROOT file \"%s\" to read results" % (opts.outputfile), False) fToys = ROOT.TFile(opts.outputfile) fData = ROOT.TFile(opts.outputfile) tToys = fToys.Get("limit") tData = fData.Get("limit") nToys = tToys.GetEntries() if 1:#opts.verbose: aux.PrintTH1Info(tData) if opts.verbose: tData.Print() # Store the goodness-of-fit value observed in data Verbose("NData = %.1f, NToys = %.1f" % (tData.GetEntries(), tToys.GetEntries()), False) tData.GetEntry(0) GoF_DATA = tData.limit Verbose(GoF_DATA, True) # Setting (Toys) GoF_TOYS_TOT = 0 pval_cum = 0 toys = [] minToy = +99999999 maxToy = -99999999 # For-loop: All toys for i in range(0, tToys.GetEntries()): tToys.GetEntry(i) # Toys counter GoF_TOYS_TOT += tToys.limit toys.append(tToys.limit) # Accumulate p-Value if GoF_toy > GoF_data if tToys.limit > GoF_DATA: Verbose("GoF (toy) = %.3f, GoF (data) = %.3f, p-Value += %d (%d)" % (tToys.limit, GoF_DATA, tToys.limit, pval_cum), i==1) pval_cum += tToys.limit # Finalise p-value calculation by dividing by number of toys total pval = pval_cum / GoF_TOYS_TOT Print("p-Value = %d/%d = %.3f" % (pval_cum, GoF_TOYS_TOT, pval), False) # Create GoF histo & fill it hist = ROOT.TH1D("GoF", "", 50, round(min(toys)), round(max(toys))) # For-loop: Toys for k in toys: hist.Fill(k) # Customise canvas & histogram c = ROOT.TCanvas("canvas", "canvas") hist.GetYaxis().SetTitle("Entries") hist.GetXaxis().SetTitle("#chi^{2}_{%s}" % (opts.algorithm) ) hist.SetLineColor(ROOT.kRed) hist.SetLineWidth(3) hist.Draw() # Customise arrow indicating data-observed arr = ROOT.TArrow(GoF_DATA, 0.0001, GoF_DATA, hist.GetMaximum()/8, 0.02, "<|") arr.SetLineColor(ROOT.kBlue) arr.SetFillColor(ROOT.kBlue) arr.SetFillStyle(1001) arr.SetLineWidth(3) arr.SetLineStyle(1) arr.SetAngle(60) arr.Draw("<|same") # Add data observed value left = ROOT.TLatex() #left.SetNDC() left.SetTextFont(43) left.SetTextSize(22) left.SetTextAlign(11) #left.DrawLatex(GoF_DATA*0.9, (hist.GetMaximum()/8.0)*1.05, "#color[4]{data_{obs}}") left.DrawLatex(GoF_DATA*0.9, (hist.GetMaximum()/8.0)*1.05, "#color[4]{data}") # Analysis text anaText = ROOT.TLatex() anaText.SetNDC() anaText.SetTextFont(43) anaText.SetTextSize(22) anaText.SetTextAlign(31) anaText.DrawLatex(0.92, 0.86, analysis) # p-value pvalText = ROOT.TLatex() pvalText.SetNDC() pvalText.SetTextFont(43) pvalText.SetTextSize(22) pvalText.SetTextAlign(31) #11 pvalText.DrawLatex(0.92, 0.80, "# toys: %d" % nToys) pvalText.DrawLatex(0.92, 0.74, "p-value: %.2f" % pval) pvalText.DrawLatex(0.92, 0.68, "H^{+} m_{H^{+}}= %s GeV" % opts.mass) # pvalText.DrawLatex(0.92, 0.74, " #alpha=#int^{#infty}_{#chi^{2}_{obs}} f(#chi^{2}) d#chi^{2}=%.2f" % pval) # pvalText.DrawLatex(0.92, 0.58, "1-#alpha=#int^{#chi^{2}_{obs}}_{0} f(#chi^{2}) d#chi^{2}=%.2f" % (1.0-pval)) # Print some info Verbose("Toys = %.0f" % (nToys), True) Verbose("GoF_TOYS_TOT = %.0f" % (GoF_TOYS_TOT), True) Verbose("p-value = %.2f" % (pval), False) # Add default texts histograms.addStandardTexts(lumi=opts.lumi, sqrts="13 TeV", addCmsText=True, cmsTextPosition=None, cmsExtraTextPosition=None, cmsText="CMS", cmsExtraText="Internal ") #histograms.addStandardTexts(lumi=opts.lumi, sqrts="13 TeV", addCmsText=True, cmsTextPosition=None, cmsExtraTextPosition=None, cmsText="CMS", cmsExtraText="Preliminary") # Save the plot (not needed - drawPlot saves the canvas already) saveName = "GoF_m%s_%s" % (opts.mass, opts.algorithm) SavePlot(c, saveName, opts.saveDir, saveFormats = [".C", ".png", ".pdf"]) 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 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 _generateDQMPlot(self): ''' Create a Data Quality Monitor (DQM) style plot to easily check the error for each transfer factor and whether it is within an acceptable relative error ''' # Define error warning/tolerance on relative errors okay = 1.0/(len(self._BinLabelMap.keys())) warn = 0.5*okay NEvts = [] # Check the uncertainties on the normalization factors for k in self._BinLabelMap: relErrorUp = abs(self._TF_Up[k])/(self._TF[k]) relErrorDown = abs(self._TF_Down[k])/(self._TF[k]) relError = self._TF_Error[k]/self._TF[k] if 0: print "bin = %s , relErrorUp = %s, relErrorDown = %s " % (k, relErrorUp, relErrorDown) # Add DQM entries NCR1 = 0 NCR2 = 0 NCR3 = 0 NCR4 = 0 for j in self._NEvtsCR1: NCR1 += self._NEvtsCR1[j] NEvts.append(self._NEvtsCR1[j]) for j in self._NEvtsCR2: NCR2 += self._NEvtsCR2[j] NEvts.append(self._NEvtsCR2[j]) for j in self._NEvtsCR3: NCR3 += self._NEvtsCR3[j] NEvts.append(self._NEvtsCR3[j]) for j in self._NEvtsCR4: NCR4 += self._NEvtsCR4[j] NEvts.append(self._NEvtsCR4[j]) if 0: print "NCR1[%s] = %0.1f, NCR2[%s] = %0.1f, k = %s" % (k, self._NEvtsCR1[k], k, self._NEvtsCR2[k], k) print "NCR1 = %s, NCR2 = %s, k = %s" % (NCR1, NCR2, k) print "error/NCR1[%s] = %0.2f, error/NCR2[%s] = %0.2f" % (k, self._NEvtsCR1_Error[k]/self._NEvtsCR1[k], k, self._NEvtsCR2_Error[k]/self._NEvtsCR2[k]) # Add DQM plot entries self._addDqmEntry(self._BinLabelMap[k], "N_{CR1}", self._NEvtsCR1[k], NCR1*okay, NCR1*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR2}", self._NEvtsCR2[k], NCR2*okay, NCR2*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR3}", self._NEvtsCR3[k], NCR3*okay, NCR3*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR4}", self._NEvtsCR4[k], NCR4*okay, NCR4*warn) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR1}}{N_{CR1}}", self._NEvtsCR1_Error[k]/NCR1, 0.05, 0.15) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR2}}{N_{CR2}}", self._NEvtsCR2_Error[k]/NCR2, 0.05, 0.15) # Construct the DQM histogram nBinsX = len(self._dqmKeys[self._dqmKeys.keys()[0]].keys()) nBinsY = len(self._dqmKeys.keys()) h = ROOT.TH2F("FakeB DQM", "FakeB DQM", nBinsX, 0, nBinsX, nBinsY, 0, nBinsY) # Customise axes h.GetXaxis().SetLabelSize(15) h.GetYaxis().SetLabelSize(10) # Set Min and Max of z-axis if 0: # red, yellow, green for DQM h.SetMinimum(0) h.SetMaximum(3) else: # pure entries instead of red, yellow, green h.SetMinimum(min(NEvts)*0.25) h.SetMaximum(round(max(NCR1, NCR2, NCR3, NCR4))) h.SetContour(10) #h.SetContour(3) if 0: h.GetXaxis().LabelsOption("v") h.GetYaxis().LabelsOption("v") nWarnings = 0 nErrors = 0 # For-loop: All x-axis bins for i in range(h.GetNbinsX()): # For-loop: All y-axis bins for j in range(h.GetNbinsY()): ykey = self._dqmKeys.keys()[j] xkey = self._dqmKeys[ykey].keys()[i] # Set the bin content h.SetBinContent(i+1, j+1, self._dqmKeys[ykey][xkey]) h.GetXaxis().SetBinLabel(i+1, xkey) h.GetYaxis().SetBinLabel(j+1, ykey) if self._dqmKeys[ykey][xkey] > 2: nErrors += 1 elif self._dqmKeys[ykey][xkey] > 1: nWarnings += 1 # Apply TDR style style = tdrstyle.TDRStyle() style.setOptStat(False) style.setGridX(False) style.setGridY(False) style.setWide(True, 0.15) # Set the colour styling (red, yellow, green) if 0: palette = array.array("i", [ROOT.kGreen+1, ROOT.kYellow, ROOT.kRed]) ROOT.gStyle.SetPalette(3, palette) else: # https://root.cern.ch/doc/master/classTColor.html ROOT.gStyle.SetPalette(ROOT.kLightTemperature) # ROOT.gStyle.SetPalette(ROOT.kColorPrintableOnGrey) #tdrstyle.setRainBowPalette() #tdrstyle.setDeepSeaPalette() # Create canvas c = ROOT.TCanvas() c.SetLogx(False) c.SetLogy(False) c.SetLogz(True) c.SetGridx() c.SetGridy() h.Draw("COLZ") #"COLZ TEXT" # Add CMS text and text with colour keys histograms.addStandardTexts(cmsTextPosition="outframe") if 0: histograms.addText(0.55, 0.80, "green < %.0f %%" % (okay*100), size=20) histograms.addText(0.55, 0.84, "yellow < %.0f %%" % (warn*100), size=20) histograms.addText(0.55, 0.88, "red > %.0f %%" % (warn*100), size=20) # Save the canvas to a file backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kWarning plotName = os.path.join(self._plotDirName, "FakeBNormalisationDQM") # For-loop: Save formats for ext in ["png", "C", "pdf"]: saveName ="%s.%s" % (plotName, ext) c.Print(saveName) ROOT.gErrorIgnoreLevel = backup ROOT.gStyle.SetPalette(1) msg = "Obtained %d warnings and %d errors for the normalisation" % (nWarnings, nErrors) self.Verbose(msg) if nWarnings > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % (nWarnings, nErrors, os.path.basename(plotName)) self.Verbose(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) #if nWarnings > 0 or nErrors > 0: if nErrors > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % (nWarnings, nErrors, os.path.basename(plotName)) self.Verbose(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) return
def doPlot(name, graphs, limits, xlabel, scenario,progversion): 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.SetPoint(excluded.GetN(), -1, 1) # excluded.SetPoint(excluded.GetN(), -1, 100) # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], 100) # if not obs.GetY()[0] == 100: # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], obs.GetY()[0]) """ excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetPoint(excluded.GetN(), 0, tanbMax) excluded.SetPoint(excluded.GetN(), 0, 1) excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN()-1], 1) """ # excluded.SetFillColor(ROOT.kGray) # excluded.SetFillStyle(3354) # excluded.SetLineWidth(0) # excluded.SetLineColor(ROOT.kWhite) expected = graphs["exp"] expected.SetLineStyle(2) expected1 = graphs["exp1"] expected1.SetLineStyle(2) expected2 = graphs["exp2"] expected2.SetLineStyle(2) 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(graphs["excluded"], "Excluded", drawStyle="F", legendStyle="f"), histograms.HistoGraph(expected, "Expected", drawStyle="L"), #histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), #### histograms.HistoGraph(graphs["Allowed"], "Allowed by \nm_{H} = 125.9#pm3.0 "+GeVUnit, drawStyle="F", legendStyle="f"), #### histograms.HistoGraph(graphs["Allowed"], "AllowedCopy", drawStyle="L", legendStyle="f"), # histograms.HistoGraph(graphs["mintanb"], "MinTanb", drawStyle="L"), #histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), #histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected1, "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected2, "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Expected": None, # "MinTanb": None, #### "AllowedCopy": 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.setLegend(histograms.createLegend(0.19, 0.60, 0.57, 0.80)) plot.legend.SetFillColor(0) plot.legend.SetFillStyle(1001) plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax, "xmin": 180, "xmax": 600}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() histograms.addStandardTexts(lumi="2.3-4.9", addCmsText=False) size = 20 x = 0.2 histograms.addText(x, 0.9, limit.processHeavy, 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.815,scenario, size=size) # histograms.addText(x, 0.775, limit.BRassumption, size=size) # histograms.addText(x, 0.735, "#mu=%d %s"%(mu, limit.massUnit()), size=size) # histograms.addText(0.7, 0.23, "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) histograms.addText(x, 0.55, progversion, size=size) histograms.addText(x, 0.48, "Derived from", size=size) histograms.addText(x, 0.43, "CMS HIG-13-XXX", size=size) # histograms.addText(x, 0.38, "JHEP07(2012)143", size=size) plot.save()
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 doPlot(name, graphs, limits, xlabel, scenario, progversion): 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.SetPoint(excluded.GetN(), -1, 1) # excluded.SetPoint(excluded.GetN(), -1, 100) # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], 100) # if not obs.GetY()[0] == 100: # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], obs.GetY()[0]) """ excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetPoint(excluded.GetN(), 0, tanbMax) excluded.SetPoint(excluded.GetN(), 0, 1) excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN()-1], 1) """ # excluded.SetFillColor(ROOT.kGray) # excluded.SetFillStyle(3354) # excluded.SetLineWidth(0) # excluded.SetLineColor(ROOT.kWhite) expected = graphs["exp"] expected.SetLineStyle(2) expected1 = graphs["exp1"] expected1.SetLineStyle(2) expected2 = graphs["exp2"] expected2.SetLineStyle(2) 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(graphs["excluded"], "Excluded", drawStyle="F", legendStyle="f"), histograms.HistoGraph(expected, "Expected", drawStyle="L"), #histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), #### histograms.HistoGraph(graphs["Allowed"], "Allowed by \nm_{H} = 125.9#pm3.0 "+GeVUnit, drawStyle="F", legendStyle="f"), #### histograms.HistoGraph(graphs["Allowed"], "AllowedCopy", drawStyle="L", legendStyle="f"), # histograms.HistoGraph(graphs["mintanb"], "MinTanb", drawStyle="L"), #histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), #histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected1, "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected2, "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Expected": None, # "MinTanb": None, #### "AllowedCopy": 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.setLegend(histograms.createLegend(0.19, 0.60, 0.57, 0.80)) plot.legend.SetFillColor(0) plot.legend.SetFillStyle(1001) plot.createFrame(name, opts={ "ymin": 0, "ymax": tanbMax, "xmin": 180, "xmax": 600 }) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() histograms.addStandardTexts(lumi="2.3-4.9", addCmsText=False) size = 20 x = 0.2 histograms.addText(x, 0.9, limit.processHeavy, 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.815, scenario, size=size) # histograms.addText(x, 0.775, limit.BRassumption, size=size) # histograms.addText(x, 0.735, "#mu=%d %s"%(mu, limit.massUnit()), size=size) # histograms.addText(0.7, 0.23, "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) histograms.addText(x, 0.55, progversion, size=size) histograms.addText(x, 0.48, "Derived from", size=size) histograms.addText(x, 0.43, "CMS HIG-13-XXX", size=size) # histograms.addText(x, 0.38, "JHEP07(2012)143", size=size) plot.save()
def PlotProb(datasets, numPath, denPath): EfficiencyList = [] index = 0 for dataset in datasets: datasetName = dataset.getName() print "Dataset = ", datasetName statOption = ROOT.TEfficiency.kFNormal ## n = dataset.getDatasetRootHisto(numPath).getHistogram() # n.normalizeToOne() ## d = dataset.getDatasetRootHisto(denPath).getHistogram() nn = dataset.getDatasetRootHisto(numPath) nn.normalizeToLuminosity(35.8 * (10**3)) n = nn.getHistogram() dd = dataset.getDatasetRootHisto(denPath) # dd.normalizeToOne() # dd.normalizeToLuminosity(36.3*(10**3)) dd.normalizeToLuminosity(35.8 * (10**3)) # dd.normalizeByCrossSection() d = dd.getHistogram() # if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # continue # elif "M_" in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # continue if "Event" in numPath: n.Rebin(10) d.Rebin(10) else: n.Rebin(5) d.Rebin(5) if d.GetEntries() == 0 or n.GetEntries() == 0: continue if n.GetEntries() > d.GetEntries(): continue # Check Negatives CheckNegatives(n, d, True) # Remove Negatives RemoveNegatives(n) nBins = d.GetNbinsX() xMin = d.GetXaxis().GetXmin() xMax = d.GetXaxis().GetXmax() binwidth = int(n.GetBinWidth(0)) # ----------------------------------------------------------------------------------------- # # Ugly hack to ignore EMPTY (in the wanted range) histograms with overflows/underflows # ----------------------------------------------------------------------------------------- # if (0): print "\n" print "=========== getEfficiency:" print "Dataset = ", dataset.getName() print "Numerator: entries=", n.GetEntries( ), " Bins=", n.GetNbinsX(), " Low edge=", n.GetBinLowEdge(1) print "Denominator: entries=", d.GetEntries( ), " Bins=", d.GetNbinsX(), " Low edge=", d.GetBinLowEdge(1) print "\n" print ">>>>>> Sanity Check: <<<<<<" print "Numerator Mean = ", n.GetMean() print "Numerator RMS = ", n.GetRMS() print "Numerator Integral = ", n.Integral(1, nBins) print "Denominator Mean = ", d.GetMean() print "Denominator RMS = ", d.GetRMS() print "Denominator Integral = ", d.Integral(1, nBins) if (n.GetMean() == 0 or d.GetMean() == 0): continue if (n.GetRMS() == 0 or d.GetRMS() == 0): continue if (n.Integral(1, nBins) == 0 or d.Integral(1, nBins) == 0): continue # if not (ROOT.TEfficiency.CheckConsistency(n,d)): continue; effic = ROOT.TEfficiency(n, d) effic.SetStatisticOption(statOption) weight = 1 if dataset.isMC(): weight = dataset.getCrossSection() effic.SetWeight(weight) eff = convert2TGraph(effic) # Apply Styles if "TT" in datasetName: if index == 0: styles.signalStyleHToTB500.apply(eff) # styles.ttStyle.apply(eff) eff.SetLineStyle(1) eff.SetLineWidth(3) eff.SetLineColor(619) legend = "Default: t#bar{t}" index = 1 else: styles.signalStyleHToTB500.apply(eff) # styles.ttStyle.apply(eff) eff.SetLineStyle(1) eff.SetLineWidth(3) eff.SetLineColor(417) legend = "#Delta R(q,q')>0.8: t#bar{t}" elif "M_500" in datasetName: styles.signalStyleHToTB500.apply(eff) legend = "H^{+} m_{H^{+}} = 500 GeV" elif "M_300" in datasetName: styles.signalStyleHToTB300.apply(eff) legend = "H^{+} m_{H^{+}} = 300 GeV" elif "M_1000" in datasetName: styles.signalStyleHToTB1000.apply(eff) legend = "H^{+} m_{H^{+}} = 1000 GeV" elif "M_800" in datasetName: styles.signalStyleHToTB800.apply(eff) legend = "H^{+} m_{H^{+}} = 800 GeV" elif "M_200" in datasetName: styles.signalStyleHToTB200.apply(eff) legend = "H^{+} m_{H^{+}} = 200 GeV" else: styles.ttStyle.apply(eff) legend = "other" EfficiencyList.append(histograms.HistoGraph(eff, legend, "lp", "P")) saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split( "/")[-1] if "Pt" in numPath: xMin = 0.0 # rebinX = 2 xMax = 805.0 # xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Efficiency / " + str(binwidth) + " " + units yMin = 0.0 yMax = 1.1 elif "_Eta" in numPath: xMin = -3.0 xMax = +3.0 xTitle = "#eta" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 elif "_Mass" in numPath: xMin = 50.0 xMax = 300 xTitle = "M (GeV/c^{2})" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 elif "_Phi" in numPath: xMin = -3 xMax = +3 xTitle = "#phi" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 else: xMin = 0.0 xMax = 250.0 xTitle = "xTitle" yTitle = "yTitle" yMin = 0.0 yMax = 1.1 if "Fake" in numPath: # xMin = 95.0 # rebinX = 4 xMax = 805.0 xTitle = "candidate p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Misid rate / " + str(binwidth) + " " + units yMin = 0.0 yMax = 0.11 if "Event" in numPath: rebinX = 2 # xMin = 95.0 xMax = 805.0 xTitle = "candidate p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Efficiency / " + str(binwidth) + " " + units yMin = 0.0 yMax = 1.1 if "NonMatched" in numPath: xMin = 90.0 rebinX = 4 xMax = 700.0 xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV)" yTitle = "Efficiency" yMin = 0.0 yMax = 0.15 if "AllTopQuarkPt_MatchedBDT" in numPath and "TopQuarkPt" in denPath: xMin = 0.0 # rebinX = 4 xMax = 805.0 #705 units = "GeV/c" xTitle = "generated top p_{T} (GeV/c)" yTitle = "Efficiency / " + str(binwidth) + " " + units yMin = 0.0 yMax = 1.1 if "SameFake" in numPath: xMin = 95.0 rebinX = 4 xMax = 705.0 xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} [GeV]" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 options = {"ymin": yMin, "ymax": yMax, "xmin": xMin, "xMax": xMax} # if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # return # if "M_" in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # return p = plots.PlotBase(datasetRootHistos=EfficiencyList, saveFormats=kwargs.get("saveFormats")) #p = plots.ComparisonManyPlot(refEff, EfficiencyList, saveFormats=[]) p.createFrame(saveName, opts=options) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) # Set Titles # p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel")) #"ylabel" p.getFrame().GetXaxis().SetTitle(xTitle) p.getFrame().GetYaxis().SetTitle(yTitle) # Set range p.getFrame().GetXaxis().SetRangeUser(xMin, xMax) moveLegend = {"dx": -0.55, "dy": -0.02, "dh": -0.2} # 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", numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CRone", "CRtwo"] rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= manager = FakeBNormalization.FakeBNormalizationManager(binLabels, opts.mcrab, opts.optMode, verbose=False) if opts.inclusiveOnly: #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"]) binLabel = "Inclusive" manager.CalculateTransferFactor("Inclusive", rhDict["FakeB-CRone-Inclusive"], rhDict["FakeB-CRtwo-Inclusive"]) else: for bin in binLabels: manager.CalculateTransferFactor(bin, rhDict["FakeB-CRone-%s" % bin], rhDict["FakeB-CRtwo-%s" % bin]) # Get unique a style for each region for k in rhDict: dataset = k.split("-")[0] region = k.split("-")[1] styles.getABCDStyle(region).apply(rhDict[k]) if "FakeB" in k: styles.getFakeBStyle().apply(rhDict[k]) # sr.apply(rhDict[k]) # ========================================================================================= # Create the final plot object # ========================================================================================= rData_SR = rhDict["Data-SR-Inclusive"] rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"] rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive") rBkgSum_SR.Reset() if opts.inclusiveOnly: bin = "Inclusive" # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) else: # For-loop: All bins for i, bin in enumerate(binLabels, 1): if bin == "Inclusive": continue # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), i==1) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) #Print("Got Verification Region (VR) shape %s%s%s" % (ShellStyles.NoteStyle(), rFakeB_VR.GetName(), ShellStyles.NormalStyle()), True) # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) #VRtoSR_TF = manager.GetTransferFactor("Inclusive") #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) #rBkgSum_SR.Scale(VRtoSR_TF) # Plot histograms if opts.altPlot: # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] ) rBkgSum_SR.Add(rEWKGenuineB_SR, +1) # Change style styles.getGenuineBStyle().apply(rBkgSum_SR) # Remove unsupported settings of kwargs _kwargs["stackMCHistograms"] = False _kwargs["addLuminosityText"] = False # Create the plot p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[]) # Set draw / legend style p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P") p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive" , "LP") p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST") p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive" , "F") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Data-SR" : "Data", "BkgSum-SR" : "Fake-b + Gen-b", }) else: # Create empty histogram stack list myStackList = [] # Signal p2 = plots.DataMCPlot(datasetsMgr, "ForTestQGLR/QGLR_SR/QGLR_SRInclusive", saveFormats=[]) hSignal_800 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto() hhSignal_800= histograms.Histo(hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800', "H^{+} m_{H^+}=800 GeV") hhSignal_800.setIsDataMC(isData=False, isMC=True) myStackList.append(hhSignal_800) hSignal_250 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto() hhSignal_250= histograms.Histo(hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250', "H^{+} m_{H^+}=250 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250']) hhSignal_250.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_250) hSignal_500 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto() hhSignal_500= histograms.Histo(hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500', "H^{+} m_{H^+}=500 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_500.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_500) hSignal_1000 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto() hhSignal_1000= histograms.Histo(hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000', "H^{+} m_{H^+}=1000 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_1000.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_1000) # Add the FakeB data-driven background to the histogram list hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b") hFakeB.setIsDataMC(isData=False, isMC=True) myStackList.append(hFakeB) # Add the EWKGenuineB MC background to the histogram list hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB", "EWK Genuine-b") hGenuineB.setIsDataMC(isData=False, isMC=True) myStackList.append(hGenuineB) # Add the collision datato the histogram list hData = histograms.Histo(rData_SR, "Data", "Data") hData.setIsDataMC(isData=True, isMC=False) myStackList.insert(0, hData) p = plots.DataMCPlot2( myStackList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setDefaultStyles() # Draw the plot and save it hName = "test" plots.drawPlot(p, hName, **_kwargs) SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"]) #========================================================================================== # Calculate Cut-Flow Efficiency #========================================================================================== kwargs = { "rebinX" : 1, "xlabel" : "QGLR", "ylabel" : "Significance / %.02f ", "opts" : {"ymin": 0.0, "ymaxfactor": 1.3}, "createLegend": {"x1": 0.55, "y1": 0.70, "x2": 0.92, "y2": 0.92}, # "cutBox" : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True}, } efficiencyList = [] xValues = [] yValues_250 = [] yValues_500 = [] yValues_800 = [] yValues_1000 = [] yValues_Bkg = [] nBins = hSignal_250.GetNbinsX()+1 hBkg = p.histoMgr.getHisto("ChargedHiggs_HplusTB_HplusToTB_M_800").getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) for i in range (0, nBins): # Cut value cut = hSignal_250.GetBinCenter(i) passed_250 = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins()) passed_500 = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins()) passed_800 = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins()) passed_1000 = hSignal_1000.Integral(i, hSignal_1000.GetXaxis().GetNbins()) passed_Bkg = hBkg.Integral(i, hBkg.GetXaxis().GetNbins()) total_250 = hSignal_250.Integral() total_500 = hSignal_500.Integral() total_800 = hSignal_800.Integral() total_1000 = hSignal_1000.Integral() total_Bkg = hBkg.Integral() eff_250 = float(passed_250)/total_250 eff_500 = float(passed_500)/total_500 eff_800 = float(passed_800)/total_800 eff_1000 = float(passed_1000)/total_1000 eff_Bkg = float(passed_Bkg)/total_Bkg xValues.append(cut) yValues_250.append(eff_250) yValues_500.append(eff_500) yValues_800.append(eff_800) yValues_1000.append(eff_1000) yValues_Bkg.append(eff_Bkg) # Create the Efficiency Plot tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_250)) tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_500)) tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_800)) tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_1000)) tGraph_Bkg = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_Bkg)) styles.getSignalStyleHToTB_M("200").apply(tGraph_250) styles.getSignalStyleHToTB_M("500").apply(tGraph_500) styles.getSignalStyleHToTB_M("800").apply(tGraph_800) styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000) styles.getQCDLineStyle().apply(tGraph_Bkg) drawStyle = "CPE" effGraph_250 = histograms.HistoGraph(tGraph_250, "H^{+} m_{H^{+}} = 250 GeV", "lp", drawStyle) effGraph_500 = histograms.HistoGraph(tGraph_500, "H^{+} m_{H^{+}} = 500 GeV", "lp", drawStyle) effGraph_800 = histograms.HistoGraph(tGraph_800, "H^{+} m_{H^{+}} = 800 GeV", "lp", drawStyle) effGraph_1000 = histograms.HistoGraph(tGraph_1000, "H^{+} m_{H^{+}} = 1000 GeV", "lp", drawStyle) effGraph_Bkg = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle) efficiencyList.append(effGraph_250) efficiencyList.append(effGraph_500) efficiencyList.append(effGraph_800) efficiencyList.append(effGraph_1000) efficiencyList.append(effGraph_Bkg) # Efficiency plot pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) pE.createFrame("QGLR_Efficiency") pE.setEnergy("13") pE.getFrame().GetYaxis().SetLabelSize(18) pE.getFrame().GetXaxis().SetLabelSize(20) pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") pE.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} pE.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pE.draw() # plots.drawPlot(pE, "QGLR_Efficiency", **kwargs) SavePlot(pE, "QGLR_Efficiency", os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] ) #========================================================================================== # Calculate Significance #========================================================================================== SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800" hSignif_250 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_500 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_800 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_250.Reset() hSignif_500.Reset() hSignif_800.Reset() hSignif_1000.Reset() hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) nBins = hSignif_250.GetNbinsX()+1 # For-loop: All histo bins for i in range (1, nBins+1): sigmaB = ROOT.Double(0) b = hBkg.IntegralAndError(i, nBins, sigmaB) s_250 = hSignal_250.Integral(i, nBins) s_500 = hSignal_500.Integral(i, nBins) s_800 = hSignal_800.Integral(i, nBins) s_1000 = hSignal_1000.Integral(i, nBins) # Calculate significance signif_250 = stat.significance(s_250, b, sigmaB, option="Simple")#Asimov") signif_500 = stat.significance(s_500, b, sigmaB, option="Simple")#Asimov") signif_800 = stat.significance(s_800, b, sigmaB, option="Simple")#Asimov") signif_1000 = stat.significance(s_1000, b, sigmaB, option="Simple")#"Asimov") # Set signif for this bin hSignif_250.SetBinContent(i, signif_250) hSignif_500.SetBinContent(i, signif_500) hSignif_800.SetBinContent(i, signif_800) hSignif_1000.SetBinContent(i, signif_1000) # Apply style s_250 = styles.getSignalStyleHToTB_M("200") s_250.apply(hSignif_250) s_500 = styles.getSignalStyleHToTB_M("500") s_500.apply(hSignif_500) s_800 = styles.getSignalStyleHToTB_M("800") s_800.apply(hSignif_800) s_1000 = styles.getSignalStyleHToTB_M("1000") s_1000.apply(hSignif_1000) hList = [] hList.append(hSignif_250) hList.append(hSignif_500) hList.append(hSignif_800) hList.append(hSignif_1000) hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV") hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV") hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV") hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV") pS = plots.PlotBase(hList, saveFormats=["png", "pdf"]) pS.setLuminosity(opts.intLumi) # Drawing style pS.histoMgr.setHistoDrawStyleAll("HIST") pS.histoMgr.setHistoLegendStyleAll("L") pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0)) pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle)) # Draw the plot name = "QGLR_Signif" + "GE" plots.drawPlot(pS, name, **kwargs) SavePlot(pS, name, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] ) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= Verbose("Write the normalisation factors to a python file", True) fileName = os.path.join(opts.mcrab, "FakeBTransferFactors%s.py"% ( getModuleInfoString(opts) ) ) manager.writeNormFactorFile(fileName, opts) return
def _generateDQMPlot(self): ''' Create a Data Quality Monitor (DQM) style plot to easily check the error for each transfer factor and whether it is within an acceptable relative error ''' # Define error warning/tolerance on relative errors okay = 1.0 / (len(self._BinLabelMap.keys())) warn = 0.5 * okay NEvts = [] # Check the uncertainties on the normalization factors for k in self._BinLabelMap: relErrorUp = abs(self._TF_Up[k]) / (self._TF[k]) relErrorDown = abs(self._TF_Down[k]) / (self._TF[k]) relError = self._TF_Error[k] / self._TF[k] if 0: print "bin = %s , relErrorUp = %s, relErrorDown = %s " % ( k, relErrorUp, relErrorDown) # Add DQM entries NCR1 = 0 NCR2 = 0 NCR3 = 0 NCR4 = 0 for j in self._NEvtsCR1: NCR1 += self._NEvtsCR1[j] NEvts.append(self._NEvtsCR1[j]) for j in self._NEvtsCR2: NCR2 += self._NEvtsCR2[j] NEvts.append(self._NEvtsCR2[j]) for j in self._NEvtsCR3: NCR3 += self._NEvtsCR3[j] NEvts.append(self._NEvtsCR3[j]) for j in self._NEvtsCR4: NCR4 += self._NEvtsCR4[j] NEvts.append(self._NEvtsCR4[j]) if 0: print "NCR1[%s] = %0.1f, NCR2[%s] = %0.1f, k = %s" % ( k, self._NEvtsCR1[k], k, self._NEvtsCR2[k], k) print "NCR1 = %s, NCR2 = %s, k = %s" % (NCR1, NCR2, k) print "error/NCR1[%s] = %0.2f, error/NCR2[%s] = %0.2f" % ( k, self._NEvtsCR1_Error[k] / self._NEvtsCR1[k], k, self._NEvtsCR2_Error[k] / self._NEvtsCR2[k]) # Add DQM plot entries self._addDqmEntry(self._BinLabelMap[k], "N_{CR1}", self._NEvtsCR1[k], NCR1 * okay, NCR1 * warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR2}", self._NEvtsCR2[k], NCR2 * okay, NCR2 * warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR3}", self._NEvtsCR3[k], NCR3 * okay, NCR3 * warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR4}", self._NEvtsCR4[k], NCR4 * okay, NCR4 * warn) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR1}}{N_{CR1}}", self._NEvtsCR1_Error[k]/NCR1, 0.05, 0.15) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR2}}{N_{CR2}}", self._NEvtsCR2_Error[k]/NCR2, 0.05, 0.15) # Construct the DQM histogram nBinsX = len(self._dqmKeys[self._dqmKeys.keys()[0]].keys()) nBinsY = len(self._dqmKeys.keys()) h = ROOT.TH2F("FakeB DQM", "FakeB DQM", nBinsX, 0, nBinsX, nBinsY, 0, nBinsY) # Customise axes h.GetXaxis().SetLabelSize(15) h.GetYaxis().SetLabelSize(10) # Set Min and Max of z-axis if 0: # red, yellow, green for DQM h.SetMinimum(0) h.SetMaximum(3) else: # pure entries instead of red, yellow, green h.SetMinimum(min(NEvts) * 0.25) h.SetMaximum(round(max(NCR1, NCR2, NCR3, NCR4))) h.SetContour(10) #h.SetContour(3) if 0: h.GetXaxis().LabelsOption("v") h.GetYaxis().LabelsOption("v") nWarnings = 0 nErrors = 0 # For-loop: All x-axis bins for i in range(h.GetNbinsX()): # For-loop: All y-axis bins for j in range(h.GetNbinsY()): ykey = self._dqmKeys.keys()[j] xkey = self._dqmKeys[ykey].keys()[i] # Set the bin content h.SetBinContent(i + 1, j + 1, self._dqmKeys[ykey][xkey]) h.GetXaxis().SetBinLabel(i + 1, xkey) h.GetYaxis().SetBinLabel(j + 1, ykey) if self._dqmKeys[ykey][xkey] > 2: nErrors += 1 elif self._dqmKeys[ykey][xkey] > 1: nWarnings += 1 # Apply TDR style style = tdrstyle.TDRStyle() style.setOptStat(False) style.setGridX(False) style.setGridY(False) style.setWide(True, 0.15) # Set the colour styling (red, yellow, green) if 0: palette = array.array("i", [ROOT.kGreen + 1, ROOT.kYellow, ROOT.kRed]) ROOT.gStyle.SetPalette(3, palette) else: # https://root.cern.ch/doc/master/classTColor.html ROOT.gStyle.SetPalette(ROOT.kLightTemperature) # ROOT.gStyle.SetPalette(ROOT.kColorPrintableOnGrey) #tdrstyle.setRainBowPalette() #tdrstyle.setDeepSeaPalette() # Create canvas c = ROOT.TCanvas() c.SetLogx(False) c.SetLogy(False) c.SetLogz(True) c.SetGridx() c.SetGridy() h.Draw("COLZ") #"COLZ TEXT" # Add CMS text and text with colour keys histograms.addStandardTexts(cmsTextPosition="outframe") if 0: histograms.addText(0.55, 0.80, "green < %.0f %%" % (okay * 100), size=20) histograms.addText(0.55, 0.84, "yellow < %.0f %%" % (warn * 100), size=20) histograms.addText(0.55, 0.88, "red > %.0f %%" % (warn * 100), size=20) # Save the canvas to a file backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kWarning plotName = os.path.join(self._plotDirName, "FakeBNormalisationDQM") # For-loop: Save formats for ext in ["png", "C", "pdf"]: saveName = "%s.%s" % (plotName, ext) c.Print(saveName) ROOT.gErrorIgnoreLevel = backup ROOT.gStyle.SetPalette(1) msg = "Obtained %d warnings and %d errors for the normalisation" % ( nWarnings, nErrors) self.Verbose(msg) if nWarnings > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % ( nWarnings, nErrors, os.path.basename(plotName)) self.Verbose( ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) #if nWarnings > 0 or nErrors > 0: if nErrors > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % ( nWarnings, nErrors, os.path.basename(plotName)) self.Verbose( ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) return
def main(): style = tdrstyle.TDRStyle() hNames = getHistoNames(kinVar) # hName = hNames[0] # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_") # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_") # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # Inform user of datasets retrieved Print("Got following datasets from multicrab dir \"%s\"" % parseOpts.mcrab) for d in datasets.getAllDatasets(): print "\t", d.getName() # Determine Integrated Luminosity (If Data datasets present) intLumi = 0.0 if len(datasets.getDataDatasets()) != 0: # Load Luminosity JSON file datasets.loadLuminosities(fname="lumi.json") # Load RUN range # runRange = datasets.loadRunRange(fname="runrange.json") # Calculate Integrated Luminosity intLumi = GetLumi(datasets) # For-loop: All Histogram names for counter, hName in enumerate(hNames): plotName = hName #analysis + "_" + hName saveName = os.path.join(savePath, plotName) # Get Data or MC datasets # dataDatasets = datasets.getDataDatasets() # mcDatasets = datasets.getMCDatasets() # Build ROOT histos from individual datasets dataset1 = datasets.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_400").getDatasetRootHisto(hName) dataset2 = datasets.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_300").getDatasetRootHisto(hName) # dataset2 = datasets.getDataset("TT_ext3").getDatasetRootHisto(hName) # datasets.getDataset("TT_ext3").setCrossSection(831.76) # Normalise datasets if normalizeTo == "One": dataset1.normalizeToOne() dataset2.normalizeToOne() elif normalizeTo == "XSection": dataset1.normalizeByCrossSection() dataset2.normalizeByCrossSection() elif normalizeTo == "Luminosity": dataset1.normalizeToLumi(intLumi) dataset2.normalizeToLumi(intLumi) else: isValidNorm(normalizeTo) # Customise histos histo1 = dataset1.getHistogram() styles.signal200Style.apply(histo1) # histo1.SetMarkerStyle(ROOT.kFullCircle) # histo1.SetFillStyle(3001) # histo1.SetFillColor(histo2.GetMarkerColor()) # removeNegatives(histo1) # removeErrorBars(histo1) histo1.Rebin(rebinFactor) # Customise histos histo2 = dataset2.getHistogram() styles.ttStyle.apply(histo2) # histo2.SetMarkerStyle(ROOT.kFullCross) histo2.SetFillStyle(3001) histo2.SetFillColor(styles.ttStyle.color) # removeNegatives(histo2) # removeErrorBars(histo2) histo2.Rebin(rebinFactor) # Create a comparison plot p = plots.ComparisonPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 400 GeV/c^{2}", "p", "P"), histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST,E,9")) # histograms.Histo(histo2, "t#bar{t}", "F", "HIST,E,9")) # Create a comparison plot (One histogram is treated as a reference histogram, and all other histograms are compared with respect to that) # p = plots.ComparisonManyPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 200 GeV/c^{2}", "p", "P"), # [histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST9"), # histograms.Histo(histo3, "t#bar{t}", "F", "HIST9")]) # Customise plots opts = {"ymin": 0.0, "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar)} ratioOpts = {"ymin": 0.0, "ymax": 2.0 , "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar)} p.createFrame(os.path.join(savePath, plotName), createRatio=ratio, opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.2} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Customise text if intLumi > 0.0: histograms.addStandardTexts(lumi=intLumi) else: histograms.addStandardTexts() # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasets.loadRunRange(), 17) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetTitle( getTitleY(normalizeTo, kinVar, opts) ) p.getFrame().GetXaxis().SetTitle( getTitleX(kinVar, opts) ) if ratio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Draw plots p.draw() # Save canvas under custom dir if counter == 0: Print("Saving plots in %s format(s)" % (len(saveFormats)) ) SavePlotterCanvas(p, savePath, saveName, saveFormats) return
def PlotProb(datasets, numPath, denPath): EfficiencyList = [] index = 0 for dataset in datasets: datasetName = dataset.getName() print "Dataset = ", datasetName statOption = ROOT.TEfficiency.kFNormal ## n = dataset.getDatasetRootHisto(numPath).getHistogram() # n.normalizeToOne() ## d = dataset.getDatasetRootHisto(denPath).getHistogram() nn = dataset.getDatasetRootHisto(numPath) nn.normalizeToLuminosity(35.8*(10**3)) n = nn.getHistogram() dd = dataset.getDatasetRootHisto(denPath) # dd.normalizeToOne() # dd.normalizeToLuminosity(36.3*(10**3)) dd.normalizeToLuminosity(35.8*(10**3)) # dd.normalizeByCrossSection() d = dd.getHistogram() # if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # continue # elif "M_" in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # continue if "Event" in numPath: n.Rebin(10) d.Rebin(10) else: n.Rebin(5) d.Rebin(5) if d.GetEntries() == 0 or n.GetEntries() == 0: continue if n.GetEntries() > d.GetEntries(): continue # Check Negatives CheckNegatives(n, d, True) # Remove Negatives RemoveNegatives(n) nBins = d.GetNbinsX() xMin = d.GetXaxis().GetXmin() xMax = d.GetXaxis().GetXmax() binwidth = int(n.GetBinWidth(0)) # ----------------------------------------------------------------------------------------- # # Ugly hack to ignore EMPTY (in the wanted range) histograms with overflows/underflows # ----------------------------------------------------------------------------------------- # if (0): print "\n" print "=========== getEfficiency:" print "Dataset = ", dataset.getName() print "Numerator: entries=", n.GetEntries(), " Bins=", n.GetNbinsX(), " Low edge=", n.GetBinLowEdge(1) print "Denominator: entries=", d.GetEntries(), " Bins=", d.GetNbinsX(), " Low edge=", d.GetBinLowEdge(1) print "\n" print ">>>>>> Sanity Check: <<<<<<" print "Numerator Mean = ", n.GetMean() print "Numerator RMS = ", n.GetRMS() print "Numerator Integral = ", n.Integral(1, nBins) print "Denominator Mean = ", d.GetMean() print "Denominator RMS = ", d.GetRMS() print "Denominator Integral = ", d.Integral(1, nBins) if (n.GetMean() == 0 or d.GetMean() == 0): continue if (n.GetRMS() == 0 or d.GetRMS() == 0): continue if (n.Integral(1,nBins) == 0 or d.Integral(1,nBins) == 0): continue # if not (ROOT.TEfficiency.CheckConsistency(n,d)): continue; effic = ROOT.TEfficiency(n,d) effic.SetStatisticOption(statOption) weight = 1 if dataset.isMC(): weight = dataset.getCrossSection() effic.SetWeight(weight) eff = convert2TGraph(effic) # Apply Styles if "TT" in datasetName: if index == 0: styles.signalStyleHToTB500.apply(eff) # styles.ttStyle.apply(eff) eff.SetLineStyle(1) eff.SetLineWidth(3) eff.SetLineColor(619) legend = "Default: t#bar{t}" index = 1 else: styles.signalStyleHToTB500.apply(eff) # styles.ttStyle.apply(eff) eff.SetLineStyle(1) eff.SetLineWidth(3) eff.SetLineColor(417) legend = "#Delta R(q,q')>0.8: t#bar{t}" elif "M_500" in datasetName: styles.signalStyleHToTB500.apply(eff) legend = "H^{+} m_{H^{+}} = 500 GeV" elif "M_300" in datasetName: styles.signalStyleHToTB300.apply(eff) legend = "H^{+} m_{H^{+}} = 300 GeV" elif "M_1000" in datasetName: styles.signalStyleHToTB1000.apply(eff) legend = "H^{+} m_{H^{+}} = 1000 GeV" elif "M_800" in datasetName: styles.signalStyleHToTB800.apply(eff) legend = "H^{+} m_{H^{+}} = 800 GeV" elif "M_200" in datasetName: styles.signalStyleHToTB200.apply(eff) legend = "H^{+} m_{H^{+}} = 200 GeV" else: styles.ttStyle.apply(eff) legend = "other" EfficiencyList.append(histograms.HistoGraph(eff, legend, "lp", "P")) saveName = "Eff_"+numPath.split("/")[-1]+"Over"+denPath.split("/")[-1] if "Pt" in numPath: xMin = 0.0 # rebinX = 2 xMax = 805.0 # xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Efficiency / " + str(binwidth) + " "+units yMin = 0.0 yMax = 1.1 elif "_Eta" in numPath: xMin = -3.0 xMax = +3.0 xTitle = "#eta" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 elif "_Mass" in numPath: xMin = 50.0 xMax = 300 xTitle = "M (GeV/c^{2})" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 elif "_Phi" in numPath: xMin = -3 xMax = +3 xTitle = "#phi" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 else: xMin = 0.0 xMax = 250.0 xTitle = "xTitle" yTitle = "yTitle" yMin = 0.0 yMax = 1.1 if "Fake" in numPath: # xMin = 95.0 # rebinX = 4 xMax = 805.0 xTitle = "candidate p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Misid rate / " + str(binwidth) + " " +units yMin = 0.0 yMax = 0.11 if "Event" in numPath: rebinX = 2 # xMin = 95.0 xMax = 805.0 xTitle = "candidate p_{T} (GeV/c)" units = "GeV/c" _format = "%0.1f" + units yTitle = "Efficiency / " + str(binwidth) + " "+ units yMin = 0.0 yMax = 1.1 if "NonMatched" in numPath: xMin = 90.0 rebinX = 4 xMax = 700.0 xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV)" yTitle = "Efficiency" yMin = 0.0 yMax = 0.15 if "AllTopQuarkPt_MatchedBDT" in numPath and "TopQuarkPt" in denPath: xMin = 0.0 # rebinX = 4 xMax = 805.0 #705 units = "GeV/c" xTitle = "generated top p_{T} (GeV/c)" yTitle = "Efficiency / " + str(binwidth) + " " + units yMin = 0.0 yMax = 1.1 if "SameFake" in numPath: xMin = 95.0 rebinX = 4 xMax = 705.0 xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} [GeV]" yTitle = "Efficiency" yMin = 0.0 yMax = 1.1 options = {"ymin": yMin , "ymax": yMax, "xmin":xMin, "xMax":xMax} # if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # return # if "M_" in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath): # return p = plots.PlotBase(datasetRootHistos=EfficiencyList, saveFormats=kwargs.get("saveFormats")) #p = plots.ComparisonManyPlot(refEff, EfficiencyList, saveFormats=[]) p.createFrame(saveName, opts=options) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) # Set Titles # p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel")) #"ylabel" p.getFrame().GetXaxis().SetTitle(xTitle) p.getFrame().GetYaxis().SetTitle(yTitle) # Set range p.getFrame().GetXaxis().SetRangeUser(xMin, xMax) moveLegend = {"dx": -0.55, "dy": -0.02, "dh": -0.2} # 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", numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def main(): if len(sys.argv) < 2: usage() paths = [sys.argv[1]] analysis = "METLeg_2015D_MET80" # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") datasets = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) styles.mcStyle.apply(eff2_MET80) eff1_MET80.SetMarkerSize(1) eff2_MET80.SetMarkerSize(1.5) p = plots.ComparisonPlot( histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_" + analysis + "_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({ "eff1_MET80": legend1, "eff2_MET80": legend2 }) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend( histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) label = analysis.split("_")[1] histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 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_MET80) pythonWriter.addMCParameters(label, eff2_MET80) pythonWriter.writeJSON( os.path.join(plotDir, "metLegTriggerEfficiency2015.json")) """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET #### MET80 analysisc = "METLeg_2015D_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths, analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysisc, excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot( histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_" + analysis + "_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({ "eff2_MET80": legend1c, "eff2c_MET80": legend2c }) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend( histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) 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) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.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) pPU = plots.ComparisonManyPlot( histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) opts = {"ymin": 0.001, "ymax": 0.1} pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) pPU.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) pPU.getPad1().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.25, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) histograms.addText(0.4, 0.18, analysis.split("_")[len(analysis.split("_")) - 1], 17) histograms.addText(0.4, 0.11, "Runs " + datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in", plotDir
def PlotCutFlowEfficiency(h, datasetsMgr, intLumi): Verbose("Plotting Cut Flow Efficiency") efficiencyList = [] signalMass.append("QCD") for mass in signalMass: xValues = [] yValues = [] hSignal = getHisto(datasetsMgr, h, mass, intLumi) for i in range (0, hSignal.GetXaxis().GetNbins()): # Cut value cut = hSignal.GetBinCenter(i) passed = hSignal.Integral(i, hSignal.GetXaxis().GetNbins()) total = hSignal.Integral() eff = float(passed)/total xValues.append(cut) yValues.append(eff) # Create the Significance Plot tGraph = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues)) if "M_" in mass: styles.getSignalStyleHToTB_M(mass.split("_")[-1]).apply(tGraph) else: styles.getQCDStyle().apply(tGraph) drawStyle = "CPE" legName = plots._legendLabels[mass] effGraph = histograms.HistoGraph(tGraph, legName, "lp", drawStyle) efficiencyList.append(effGraph) saveName = "QGLREfficiency" # Create the plot with all the significance plots p = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) p.createFrame(saveName) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetLabelSize(18) p.getFrame().GetXaxis().SetLabelSize(20) p.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") p.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.draw() savePath = opts.saveDir if opts.url: savePath = opts.saveDir.replace("/publicweb/m/mkolosov/", "http://home.fnal.gov/~mkolosov/") savePath = os.path.join(opts.saveDir, opts.folder, saveName, opts.optMode) SavePlot(p, saveName, savePath) return
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 main(opts): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # 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(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) 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.0015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0045)) # 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() # Draw plots p.draw() # Customise text 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 main(): style = tdrstyle.TDRStyle() hNames = getHistoNames(kinVar) # hName = hNames[0] # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_") # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_") # datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # Inform user of datasets retrieved Print("Got following datasets from multicrab dir \"%s\"" % parseOpts.mcrab) for d in datasets.getAllDatasets(): print "\t", d.getName() # Determine Integrated Luminosity (If Data datasets present) intLumi = 0.0 if len(datasets.getDataDatasets()) != 0: # Load Luminosity JSON file datasets.loadLuminosities(fname="lumi.json") # Load RUN range # runRange = datasets.loadRunRange(fname="runrange.json") # Calculate Integrated Luminosity intLumi = GetLumi(datasets) # For-loop: All Histogram names for counter, hName in enumerate(hNames): plotName = hName #analysis + "_" + hName saveName = os.path.join(savePath, plotName) # Get Data or MC datasets # dataDatasets = datasets.getDataDatasets() # mcDatasets = datasets.getMCDatasets() # Build ROOT histos from individual datasets dataset1 = datasets.getDataset( "ChargedHiggs_HplusTB_HplusToTB_M_400").getDatasetRootHisto(hName) dataset2 = datasets.getDataset( "ChargedHiggs_HplusTB_HplusToTB_M_300").getDatasetRootHisto(hName) # dataset2 = datasets.getDataset("TT_ext3").getDatasetRootHisto(hName) # datasets.getDataset("TT_ext3").setCrossSection(831.76) # Normalise datasets if normalizeTo == "One": dataset1.normalizeToOne() dataset2.normalizeToOne() elif normalizeTo == "XSection": dataset1.normalizeByCrossSection() dataset2.normalizeByCrossSection() elif normalizeTo == "Luminosity": dataset1.normalizeToLumi(intLumi) dataset2.normalizeToLumi(intLumi) else: isValidNorm(normalizeTo) # Customise histos histo1 = dataset1.getHistogram() styles.signal200Style.apply(histo1) # histo1.SetMarkerStyle(ROOT.kFullCircle) # histo1.SetFillStyle(3001) # histo1.SetFillColor(histo2.GetMarkerColor()) # removeNegatives(histo1) # removeErrorBars(histo1) histo1.Rebin(rebinFactor) # Customise histos histo2 = dataset2.getHistogram() styles.ttStyle.apply(histo2) # histo2.SetMarkerStyle(ROOT.kFullCross) histo2.SetFillStyle(3001) histo2.SetFillColor(styles.ttStyle.color) # removeNegatives(histo2) # removeErrorBars(histo2) histo2.Rebin(rebinFactor) # Create a comparison plot p = plots.ComparisonPlot( histograms.Histo(histo1, "m_{H^{#pm}} = 400 GeV/c^{2}", "p", "P"), histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST,E,9")) # histograms.Histo(histo2, "t#bar{t}", "F", "HIST,E,9")) # Create a comparison plot (One histogram is treated as a reference histogram, and all other histograms are compared with respect to that) # p = plots.ComparisonManyPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 200 GeV/c^{2}", "p", "P"), # [histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST9"), # histograms.Histo(histo3, "t#bar{t}", "F", "HIST9")]) # Customise plots opts = { "ymin": 0.0, "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar) } ratioOpts = { "ymin": 0.0, "ymax": 2.0, "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar) } p.createFrame(os.path.join(savePath, plotName), createRatio=ratio, opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.2} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Customise text if intLumi > 0.0: histograms.addStandardTexts(lumi=intLumi) else: histograms.addStandardTexts() # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasets.loadRunRange(), 17) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetTitle(getTitleY(normalizeTo, kinVar, opts)) p.getFrame().GetXaxis().SetTitle(getTitleX(kinVar, opts)) if ratio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Draw plots p.draw() # Save canvas under custom dir if counter == 0: Print("Saving plots in %s format(s)" % (len(saveFormats))) SavePlotterCanvas(p, savePath, saveName, saveFormats) return
def main(): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC( datasetsMgr ) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.2} ratioOpts = {"ymin": 0.0, "ymax": 2.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs)) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder( filter( lambda n: plots._legendLabels[kwargs.get("refDataset")] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def PlotSignificance(h, datasetsMgr, intLumi): Verbose("Plotting Significance") significanceList = [] for mass in signalMass: xValues = [] yValues = [] maxSignificance = 0.0 hSignal = getHisto(datasetsMgr, h, mass, intLumi) hBackground = getHisto(datasetsMgr, h, "QCD", intLumi) for i in range(0, hSignal.GetXaxis().GetNbins()): # Cut value cut = hSignal.GetBinCenter(i) s = hSignal.Integral(i, hSignal.GetXaxis().GetNbins()) b = hBackground.Integral(i, hSignal.GetXaxis().GetNbins()) significance = float(s) / math.sqrt(float(b + s)) if (significance > maxSignificance): maxSignificance = significance maxSignificanceCut = cut xValues.append(cut) yValues.append(significance) # Create the Significance Plot tGraph = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues)) styles.getSignalStyleHToTB_M(mass.split("_")[-1]).apply(tGraph) drawStyle = "CPE" legName = plots._legendLabels[mass] significanceGraph = histograms.HistoGraph(tGraph, legName, "lp", drawStyle) significanceList.append(significanceGraph) saveName = "QGLRSignificance" # Create the plot with all the significance plots p = plots.PlotBase(significanceList, saveFormats=["pdf"]) p.createFrame(saveName) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetLabelSize(18) p.getFrame().GetXaxis().SetLabelSize(20) p.getFrame().GetYaxis().SetTitle("S/#sqrt{S+B} / 0.01") p.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.15, "dy": -0.5, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.draw() savePath = opts.saveDir if opts.url: savePath = opts.saveDir.replace("/publicweb/m/mkolosov/", "http://home.fnal.gov/~mkolosov/") savePath = os.path.join(opts.saveDir, opts.folder, saveName, opts.optMode) SavePlot(p, saveName, savePath) return
def analyze(analysis=None): paths = [sys.argv[1]] if not analysis == None: # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis, includeOnlyTasks="Tau|TT") datasets = dataset.getDatasetsFromMulticrabDirs(paths, analysisName=analysis) else: datasets = dataset.getDatasetsFromMulticrabDirs(paths) analysis = datasets.getAllDatasets()[0].getAnalysisName() analysisList = [] # analysisList.append("METLeg_2016MET80_MET80") # analysisList.append("METLeg_2016ICHEP_MET90") # analysisList.append("METLeg_2016_MET90") met_re = re.compile("_(?P<met>MET\d+)$") if True: #for analysis in analysisList: met = "METX" met_match = met_re.search(analysis) if met_match: met = met_match.group("met") print "Analysis", analysis datasets = dataset.getDatasetsFromMulticrabDirs(paths, analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") # datasetsMC = None datasetsMC = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, excludeTasks="Tau_") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 createRatio = False if isinstance(datasetsMC, dataset.DatasetManager): dataset2 = datasetsMC.getMCDatasets() createRatio = True eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) eff1_MET80.SetMarkerSize(1) if createRatio: styles.mcStyle.apply(eff2_MET80) eff2_MET80.SetMarkerSize(1.5) if createRatio: p = plots.ComparisonPlot( histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) else: p = plots.PlotBase( [histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P")]) #from plotTauLegEfficiency import fit #fit("Data",p,eff1_MET80,20,300) #fit("MC",p,eff2_MET80,20,300) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_" + analysis + "_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" #legend2 = "MC" legend2 = "Simulation" if createRatio: p.histoMgr.setHistoLegendLabelMany({ "eff1_MET80": legend1, "eff2_MET80": legend2 }) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) else: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1}) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend( histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) histograms.addText(0.4, 0.87, "LooseIsoPFTau50_Trk30_eta2p1_" + met, 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) # label = analysis.split("_")[1] # label = "2016" label = string.replace(analysis, "METLeg_", "") histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 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_MET80) pythonWriter.addMCParameters(label, eff2_MET80) pythonWriter.writeJSON( os.path.join(plotDir, "metLegTriggerEfficiency_" + label + ".json")) ######################################################################### eff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi") eff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi") styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsMC, 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(datasetsMC, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2 }) opts = {"ymin": 0, "ymax": 0.3} name = "TauMET_" + analysis + "_DataVsMC_PFMETPhi" 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.6, "dh": -0.1} moveLegendPhi = {"dx": -0.55, "dy": -0.15, "dh": -0.1} p_phi.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p_phi.getFrame().GetXaxis().SetTitle("MET Type 1 #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.86, "LooseIsoPFTau50_Trk30_eta2p1_" + met, 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET """ #### MET80 analysisc = "METLeg_2016B_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) 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) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.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(datasetsMC, 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}) opts = {"ymin": 0.001, "ymax": 1.0} moveLegend = {"dx": -0.33, "dy": -0.25, "dh": -0.1} createRatio = False 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)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET 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.4, 0.85, "LooseIsoPFTau50_Trk30_eta2p1_MET90", 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in", plotDir
def _generateTransferFactorsPlot(self): ''' The resulting plot will contain the transfer factors (y-axis) for a given measurement bin (x-axis) This is needed in the case the Fake-b measurement is done in bins of a correlated quantity (e.g. eta of leading b-jet in Fake-b for HToTB, and tau-pT in the case of inverted tau isolatio for HToTau) ''' def makeGraph(markerStyle, color, binList, valueDict, upDict, downDict): g = ROOT.TGraphAsymmErrors(len(binList)) for i in range(len(binList)): g.SetPoint(i, i+0.5, valueDict[binList[i]]) g.SetPointEYhigh(i, upDict[binList[i]]) g.SetPointEYlow(i, downDict[binList[i]]) g.SetMarkerSize(1.2) g.SetMarkerStyle(markerStyle) g.SetLineColor(color) g.SetLineWidth(3) g.SetMarkerColor(color) return g # Obtain bin list in right order keyList = [] keys = self._TF.keys() keys.sort() # for k in keys: # if "lt" in k: # keyList.append(k) # for k in keys: # if "eq" in k: # keyList.append(k) # for k in keys: # if "gt" in k: # keyList.append(k) # For-loop: All Fake-b measurement bins for k in keys: keyList.append(k) #if "Inclusive" in keys: # keyList.append("Inclusive") # Apply TDR style style = tdrstyle.TDRStyle() style.setGridX(False) style.setGridY(False) style.setOptStat(False) # Create graphs gFakeB = makeGraph(ROOT.kFullCircle, ROOT.kAzure, keyList, self._TF, self._TF_Error, self._TF_Error) # Make plot hFrame = ROOT.TH1F("frame","frame", len(keyList), 0, len(keyList)) # Change bin labels to text for i, binLabel in enumerate(keyList, 1): binLabelText = self.getFormattedBinLabelString(binLabel) hFrame.GetXaxis().SetBinLabel(i, binLabelText) # Set axes names hFrame.GetYaxis().SetTitle("transfer factor") #R_{i} # hFrame.GetXaxis().SetTitle("Fake-b bin") # Customise axes logy = False if logy: hFrame.SetMinimum(0.6e-1) hFrame.SetMaximum(2e0) else: hFrame.SetMinimum(0.0) hFrame.SetMaximum(1.0) if len(self._BinLabelMap) > 12: lSize = 8 elif len(self._BinLabelMap) > 8: lSize = 12 else: lSize = 16 hFrame.GetXaxis().SetLabelSize(lSize) # 20 hFrame.GetXaxis().LabelsOption("d") # Label Style options # "a" sort by alphabetic order # ">" sort by decreasing values # "<" sort by increasing values # "h" draw labels horizonthal # "v" draw labels vertical # "u" draw labels up (end of label right adjusted) # "d" draw labels down (start of label left adjusted) # Create canvas c = ROOT.TCanvas() c.SetLogy(logy) c.SetGridx(False) c.SetGridy(False) hFrame.Draw() gFakeB.Draw("p same") histograms.addStandardTexts(cmsTextPosition="outframe") # Create the legend & draw it l = ROOT.TLegend(0.65, 0.80, 0.90, 0.90) l.SetFillStyle(-1) l.SetBorderSize(0) l.AddEntry(gFakeB, "Value #pm stat.", "LP") # "Fake-#it{b} #pm Stat.", "LP" l.SetTextSize(0.035) if 0: l.Draw() # Store ROOT ignore level to normal before changing it backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kWarning # Save the plot for item in ["png", "C", "pdf"]: c.Print(self._plotDirName + "/FakeBNormalisationCoefficients.%s" % item) # Reset the ROOT ignore level to normal ROOT.gErrorIgnoreLevel = backup # Inform user msg = "Plot saved under %s" % (ShellStyles.SuccessStyle() + self._plotDirName + "/" + ShellStyles.NormalStyle()) self.Print(msg, True) return
def analyze(analysis): paths = [sys.argv[1]] datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Silver|GluGluHToTauTau_M125") 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 = datasets.getMCDatasets() 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")]) else: p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"), histograms.HistoGraph(eff2, "eff2", "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)" legend3 = "MC (H125)" p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) if isinstance(datasetsH125,dataset.DatasetManager): p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2, "eff3": legend3}) p.createFrame(os.path.join(plotDir, name), createRatio=True, 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.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] 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,"tauLegTriggerEfficiency2015.json")) ######################################################################### 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")]) else: p_eta = plots.ComparisonPlot(histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), histograms.HistoGraph(eff2eta, "eff2eta", "p", "P")) 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" p_eta.createFrame(os.path.join(plotDir, name), createRatio=True, 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") 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, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.2, 0.31, "Runs "+datasets.loadRunRange(), 17) p_eta.draw() histograms.addStandardTexts(lumi=lumi) p_eta.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) pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) optsPU = {"ymin": 0.001, "ymax": 0.1} pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=optsPU, opts2=opts2) pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pPU.getPad1().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("HLT tau efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.5, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.5, 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", ["TTJets","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 PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CRone", "CRtwo"] rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= manager = FakeBNormalization.FakeBNormalizationManager(binLabels, opts.mcrab, opts.optMode, verbose=False) if opts.inclusiveOnly: #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"]) binLabel = "Inclusive" manager.CalculateTransferFactor("Inclusive", rhDict["FakeB-CRone-Inclusive"], rhDict["FakeB-CRtwo-Inclusive"]) else: for bin in binLabels: manager.CalculateTransferFactor(bin, rhDict["FakeB-CRone-%s" % bin], rhDict["FakeB-CRtwo-%s" % bin]) # Get unique a style for each region for k in rhDict: dataset = k.split("-")[0] region = k.split("-")[1] styles.getABCDStyle(region).apply(rhDict[k]) if "FakeB" in k: styles.getFakeBStyle().apply(rhDict[k]) # sr.apply(rhDict[k]) # ========================================================================================= # Create the final plot object # ========================================================================================= rData_SR = rhDict["Data-SR-Inclusive"] rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"] rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive") rBkgSum_SR.Reset() if opts.inclusiveOnly: bin = "Inclusive" # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print( "Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) else: # For-loop: All bins for i, bin in enumerate(binLabels, 1): if bin == "Inclusive": continue # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print( "Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), i == 1) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) #Print("Got Verification Region (VR) shape %s%s%s" % (ShellStyles.NoteStyle(), rFakeB_VR.GetName(), ShellStyles.NormalStyle()), True) # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) #VRtoSR_TF = manager.GetTransferFactor("Inclusive") #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) #rBkgSum_SR.Scale(VRtoSR_TF) # Plot histograms if opts.altPlot: # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] ) rBkgSum_SR.Add(rEWKGenuineB_SR, +1) # Change style styles.getGenuineBStyle().apply(rBkgSum_SR) # Remove unsupported settings of kwargs _kwargs["stackMCHistograms"] = False _kwargs["addLuminosityText"] = False # Create the plot p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[]) # Set draw / legend style p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P") p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive", "LP") p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST") p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive", "F") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Data-SR": "Data", "BkgSum-SR": "Fake-b + Gen-b", }) else: # Create empty histogram stack list myStackList = [] # Signal p2 = plots.DataMCPlot(datasetsMgr, "ForTestQGLR/QGLR_SR/QGLR_SRInclusive", saveFormats=[]) hSignal_800 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto() hhSignal_800 = histograms.Histo( hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800', "H^{+} m_{H^+}=800 GeV") hhSignal_800.setIsDataMC(isData=False, isMC=True) myStackList.append(hhSignal_800) hSignal_250 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto() hhSignal_250 = histograms.Histo( hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250', "H^{+} m_{H^+}=250 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250']) hhSignal_250.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_250) hSignal_500 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto() hhSignal_500 = histograms.Histo( hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500', "H^{+} m_{H^+}=500 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_500.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_500) hSignal_1000 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto() hhSignal_1000 = histograms.Histo( hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000', "H^{+} m_{H^+}=1000 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_1000.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_1000) # Add the FakeB data-driven background to the histogram list hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b") hFakeB.setIsDataMC(isData=False, isMC=True) myStackList.append(hFakeB) # Add the EWKGenuineB MC background to the histogram list hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB", "EWK Genuine-b") hGenuineB.setIsDataMC(isData=False, isMC=True) myStackList.append(hGenuineB) # Add the collision datato the histogram list hData = histograms.Histo(rData_SR, "Data", "Data") hData.setIsDataMC(isData=True, isMC=False) myStackList.insert(0, hData) p = plots.DataMCPlot2(myStackList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setDefaultStyles() # Draw the plot and save it hName = "test" plots.drawPlot(p, hName, **_kwargs) SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================== # Calculate Cut-Flow Efficiency #========================================================================================== kwargs = { "rebinX": 1, "xlabel": "QGLR", "ylabel": "Significance / %.02f ", "opts": { "ymin": 0.0, "ymaxfactor": 1.3 }, "createLegend": { "x1": 0.55, "y1": 0.70, "x2": 0.92, "y2": 0.92 }, # "cutBox" : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True}, } efficiencyList = [] xValues = [] yValues_250 = [] yValues_500 = [] yValues_800 = [] yValues_1000 = [] yValues_Bkg = [] nBins = hSignal_250.GetNbinsX() + 1 hBkg = p.histoMgr.getHisto( "ChargedHiggs_HplusTB_HplusToTB_M_800").getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) for i in range(0, nBins): # Cut value cut = hSignal_250.GetBinCenter(i) passed_250 = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins()) passed_500 = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins()) passed_800 = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins()) passed_1000 = hSignal_1000.Integral(i, hSignal_1000.GetXaxis().GetNbins()) passed_Bkg = hBkg.Integral(i, hBkg.GetXaxis().GetNbins()) total_250 = hSignal_250.Integral() total_500 = hSignal_500.Integral() total_800 = hSignal_800.Integral() total_1000 = hSignal_1000.Integral() total_Bkg = hBkg.Integral() eff_250 = float(passed_250) / total_250 eff_500 = float(passed_500) / total_500 eff_800 = float(passed_800) / total_800 eff_1000 = float(passed_1000) / total_1000 eff_Bkg = float(passed_Bkg) / total_Bkg xValues.append(cut) yValues_250.append(eff_250) yValues_500.append(eff_500) yValues_800.append(eff_800) yValues_1000.append(eff_1000) yValues_Bkg.append(eff_Bkg) # Create the Efficiency Plot tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_250)) tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_500)) tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_800)) tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_1000)) tGraph_Bkg = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_Bkg)) styles.getSignalStyleHToTB_M("200").apply(tGraph_250) styles.getSignalStyleHToTB_M("500").apply(tGraph_500) styles.getSignalStyleHToTB_M("800").apply(tGraph_800) styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000) styles.getQCDLineStyle().apply(tGraph_Bkg) drawStyle = "CPE" effGraph_250 = histograms.HistoGraph(tGraph_250, "H^{+} m_{H^{+}} = 250 GeV", "lp", drawStyle) effGraph_500 = histograms.HistoGraph(tGraph_500, "H^{+} m_{H^{+}} = 500 GeV", "lp", drawStyle) effGraph_800 = histograms.HistoGraph(tGraph_800, "H^{+} m_{H^{+}} = 800 GeV", "lp", drawStyle) effGraph_1000 = histograms.HistoGraph(tGraph_1000, "H^{+} m_{H^{+}} = 1000 GeV", "lp", drawStyle) effGraph_Bkg = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle) efficiencyList.append(effGraph_250) efficiencyList.append(effGraph_500) efficiencyList.append(effGraph_800) efficiencyList.append(effGraph_1000) efficiencyList.append(effGraph_Bkg) # Efficiency plot pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) pE.createFrame("QGLR_Efficiency") pE.setEnergy("13") pE.getFrame().GetYaxis().SetLabelSize(18) pE.getFrame().GetXaxis().SetLabelSize(20) pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") pE.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} pE.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pE.draw() # plots.drawPlot(pE, "QGLR_Efficiency", **kwargs) SavePlot(pE, "QGLR_Efficiency", os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================== # Calculate Significance #========================================================================================== SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800" hSignif_250 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_500 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_800 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_250.Reset() hSignif_500.Reset() hSignif_800.Reset() hSignif_1000.Reset() hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) nBins = hSignif_250.GetNbinsX() + 1 # For-loop: All histo bins for i in range(1, nBins + 1): sigmaB = ROOT.Double(0) b = hBkg.IntegralAndError(i, nBins, sigmaB) s_250 = hSignal_250.Integral(i, nBins) s_500 = hSignal_500.Integral(i, nBins) s_800 = hSignal_800.Integral(i, nBins) s_1000 = hSignal_1000.Integral(i, nBins) # Calculate significance signif_250 = stat.significance(s_250, b, sigmaB, option="Simple") #Asimov") signif_500 = stat.significance(s_500, b, sigmaB, option="Simple") #Asimov") signif_800 = stat.significance(s_800, b, sigmaB, option="Simple") #Asimov") signif_1000 = stat.significance(s_1000, b, sigmaB, option="Simple") #"Asimov") # Set signif for this bin hSignif_250.SetBinContent(i, signif_250) hSignif_500.SetBinContent(i, signif_500) hSignif_800.SetBinContent(i, signif_800) hSignif_1000.SetBinContent(i, signif_1000) # Apply style s_250 = styles.getSignalStyleHToTB_M("200") s_250.apply(hSignif_250) s_500 = styles.getSignalStyleHToTB_M("500") s_500.apply(hSignif_500) s_800 = styles.getSignalStyleHToTB_M("800") s_800.apply(hSignif_800) s_1000 = styles.getSignalStyleHToTB_M("1000") s_1000.apply(hSignif_1000) hList = [] hList.append(hSignif_250) hList.append(hSignif_500) hList.append(hSignif_800) hList.append(hSignif_1000) hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV") hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV") hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV") hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV") pS = plots.PlotBase(hList, saveFormats=["png", "pdf"]) pS.setLuminosity(opts.intLumi) # Drawing style pS.histoMgr.setHistoDrawStyleAll("HIST") pS.histoMgr.setHistoLegendStyleAll("L") pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0)) pS.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) pS.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle)) # Draw the plot name = "QGLR_Signif" + "GE" plots.drawPlot(pS, name, **kwargs) SavePlot(pS, name, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= Verbose("Write the normalisation factors to a python file", True) fileName = os.path.join( opts.mcrab, "FakeBTransferFactors%s.py" % (getModuleInfoString(opts))) manager.writeNormFactorFile(fileName, opts) return
def main(): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir #datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets #datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr.remove( filter(lambda name: not kwargs.get("refDataset") in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC( datasetsMgr ) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) # datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for hName in 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(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)) # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work # 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() # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.20, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def analyze(analysis=None): paths = [sys.argv[1]] if not analysis == None: # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis, includeOnlyTasks="Tau|TT") datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) else: datasets = dataset.getDatasetsFromMulticrabDirs(paths) analysis = datasets.getAllDatasets()[0].getAnalysisName() analysisList = [] # analysisList.append("METLeg_2016MET80_MET80") # analysisList.append("METLeg_2016ICHEP_MET90") # analysisList.append("METLeg_2016_MET90") met_re = re.compile("_(?P<met>MET\d+)$") if True: #for analysis in analysisList: met = "METX" met_match = met_re.search(analysis) if met_match: met = met_match.group("met") print "Analysis",analysis datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") # datasetsMC = None datasetsMC = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 createRatio = False if isinstance(datasetsMC,dataset.DatasetManager): dataset2 = datasetsMC.getMCDatasets() createRatio = True eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) eff1_MET80.SetMarkerSize(1) if createRatio: styles.mcStyle.apply(eff2_MET80) eff2_MET80.SetMarkerSize(1.5) if createRatio: p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) else: p = plots.PlotBase([histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P")]) #from plotTauLegEfficiency import fit #fit("Data",p,eff1_MET80,20,300) #fit("MC",p,eff2_MET80,20,300) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_"+analysis+"_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" #legend2 = "MC" legend2 = "Simulation" if createRatio: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1, "eff2_MET80": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) else: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1}) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) histograms.addText(0.4, 0.87, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) # label = analysis.split("_")[1] # label = "2016" label = string.replace(analysis,"METLeg_","") histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 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_MET80) pythonWriter.addMCParameters(label,eff2_MET80) pythonWriter.writeJSON(os.path.join(plotDir,"metLegTriggerEfficiency_"+label+".json")) ######################################################################### eff1phi = getEfficiency(dataset1,"NumeratorPhi","DenominatorPhi") eff2phi = getEfficiency(dataset2,"NumeratorPhi","DenominatorPhi") styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsMC,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(datasetsMC,dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1, "eff2phi": legend2}) opts = {"ymin": 0, "ymax": 0.3} name = "TauMET_"+analysis+"_DataVsMC_PFMETPhi" 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.6, "dh": -0.1} moveLegendPhi = {"dx": -0.55, "dy": -0.15, "dh": -0.1} p_phi.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p_phi.getFrame().GetXaxis().SetTitle("MET Type 1 #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.86, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs "+datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET """ #### MET80 analysisc = "METLeg_2016B_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) 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) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.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(datasetsMC,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}) opts = {"ymin": 0.001, "ymax": 1.0} moveLegend = {"dx": -0.33, "dy": -0.25, "dh": -0.1} createRatio = False 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)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET 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.4, 0.85, "LooseIsoPFTau50_Trk30_eta2p1_MET90", 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs "+datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in",plotDir
def main(): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir #datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets #datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr.remove(filter(lambda name: not kwargs.get("refDataset") in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) # datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for hName in 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(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) ) # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work # 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() # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.20, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) ROOT.gErrorIgnoreLevel = 3000 # Get all datasets from the mcrab dir datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) # datasetsMgr = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_200") # datasetsMgr = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), excludeTasks="M_200") # Determine Integrated Luminosity intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # datasetsMgr.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC( datasetsMgr ) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # For-loop: All Histogram names for hName in hNames: savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get efficiency histos refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFCP", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFFC", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kBJeffrey", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFNormal", **kwargs) # Plot the efficiencies p = plots.ComparisonManyPlot(refEff, otherEff) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.2} #"ymax": 5e-1} ratioOpts = {"ymin": 0.0, "ymaxfactor": 1.2} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame # p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder( filter( lambda n: plots._legendLabels[kwargs.get("refDataset")] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(opts): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # Get all datasets from the mcrab dir # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) #kwargs.get("analysis")) datasetsMgr_fixed = GetDatasetsFromDir(opts.mcrab, opts, **kwargs_fixed) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr_fixed.remove(kwargs_fixed.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) plots.mergeRenameReorderForDataMC(datasetsMgr_fixed) # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr_fixed.remove(kwargs_fixed.get("rmDataset")) # Print the cross datasetsMgr.PrintCrossSections() for h_prefix in ["reco", "gen"]: # Get ref histo (?) here and the fixed histos (TT, QCD, QCD-b inclusiveHisto, fixedHistos = GetHistosForPlotter( datasetsMgr_fixed, h_prefix + "MHT", **kwargs_fixed) inclusiveHisto.setName(inclusiveHisto.getName() + " (inclusive)") #for hi in fixedHistos: # print(type(hi), hi.getName()) #return # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(h_prefix + hName, **kwargs) # Get Histos for Plotter refHisto_, otherHistos_ = GetHistosForPlotter( datasetsMgr, h_prefix + hName, **kwargs) refHisto = refHisto_ otherHistos = otherHistos_ + fixedHistos #for hi in otherHistos: # print hi.getName() #return # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame if kwargs.get("logY") == True: opts = {"ymin": 8e-5, "ymax": 2} #opts = {"ymin": 1e-3, "ymax": 1} else: opts = {"ymin": 8.e-5, "ymax": 2} ratioOpts = {"ymin": 0.0, "ymax": 2.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs)) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder( filter( lambda n: plots._legendLabels[kwargs.get("refDataset")] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(opts): global RunEra mcrabName = opts.mcrab print("mcrabNAME ISSSSSS ", mcrabName) RunEra = mcrabName.split("_")[1] print " Run Era is: ", RunEra print " Plotting efficiency for trigger:", kwargs.get("trigger") # Setup the style style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # Setup & configure the dataset manager #datasetsMgr = GetSpecificDatasetsFromDir(opts.mcrab, opts, RunEra, reHLT_samples, **kwargs) datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) minRunRange = None maxRunRange = None Counter = 0 nDataDatasets = len(datasetsMgr.getDataDatasets()) for d in datasetsMgr.getDataDatasets(): Counter = Counter + 1 if Counter == 1: minRunRange = d.getName().split("_")[-2] if Counter == nDataDatasets: maxRunRange = d.getName().split("_")[-1] print "Data Name==> ", d.getName() print "RunRange ==> ", d.getName().split( "_")[-2], " - ", d.getName().split("_")[-1] print "Run Range = ", minRunRange, " - ", maxRunRange runRange = minRunRange + " - " + maxRunRange intLumi = GetLumi(datasetsMgr) print "intLumi=", intLumi # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Load Luminosities datasetsMgr.loadLuminosities() datasetsMgr.PrintLuminosities() # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" #plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something! #dataset_MC.normalizeMCByLuminosity() datasetsMgr.PrintCrossSections() datasetsMgr.PrintLuminosities() plots.mergeRenameReorderForDataMC(datasetsMgr) datasetsMgr.PrintCrossSections() datasetsMgr.PrintLuminosities() dataset_Data = datasetsMgr.getDataDatasets() datasetsMgr.mergeMC() #ATHER dataset_MC = None dataset_MC = datasetsMgr.getMCDatasets() #datasetsMgr.normalizeMCByLuminosity() #datasetsMgr.mergeMC() datasetsMgr.PrintCrossSections() datasetsMgr.PrintLuminosities() lumi = 0.0 for d in datasetsMgr.getDataDatasets(): lumi += d.getLuminosity() SigSel = ["1BTag", "2BTag", "OR", "OR_PFJet450"] for s in SigSel: for xVar in xVariables: print s, xVar #if xVar == "pt6thJet": # cutValue = 40 # cutLine = True #for den,num num_name = "hNum_" + xVar + "_RefTrg_OfflineSel_Signal" + s den_name = "hDen_" + xVar + "_RefTrg_OfflineSel" # Get the save path and name plotName = "Eff" + "_" + xVar + "_" + s savePath, saveName = GetSavePathAndName(plotName, **kwargs) # Get Efficiency Plots eff_Data = getEfficiency(datasetsMgr, dataset_Data, num_name, den_name, **kwargs) eff_MC = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name, **kwargs) if xVar == "pt6thJet": xMin = 29.0 xMax = 125.0 elif xVar == "eta6thJet": xMin = -2.5 xMax = 2.5 elif xVar == "phi6thJet": xMin = -3.2 xMax = 3.2 elif xVar == "Ht": xMin = 350 xMax = 2000 elif xVar == "nBTagJets": xMin = 0 xMax = 10 elif xVar == "pu": xMin = 0 xMax = 50 elif xVar == "CSV": xMin = 0 xMax = 1 elif xVar == "JetMulti": xMin = 4 xMax = 15 elif xVar == "BJetMulti": xMin = 0 xMax = 8 # Apply Styles styles.dataStyle.apply(eff_Data) styles.mcStyle.apply(eff_MC) # Marker Style eff_Data.SetMarkerSize(1) # Create Comparison Plot p = plots.ComparisonPlot( histograms.HistoGraph(eff_Data, "eff_Data", "p", "P"), histograms.HistoGraph(eff_MC, "eff_MC", "p", "P")) opts = {"ymin": 0, "ymax": 1.1, "xmin": xMin, "xmax": xMax} opts2 = {"ymin": 0.8, "ymax": 1.05} if xVar == "pu": moveLegend = {"dx": -0.44, "dy": -0.62, "dh": -0.2} else: moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2} p.histoMgr.setHistoLegendLabelMany({ "eff_Data": "Data", "eff_MC": "Simulation" }) createRatio = True #kwargs.get("ratio") p.createFrame(saveName, createRatio=createRatio, opts=opts, opts2=opts2) # Set Legend p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Set Log & Grid SetLogAndGrid(p, **kwargs) # Set Titles p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel")) if xVar == "pt6thJet": p.getFrame().GetXaxis().SetTitle("p_{T,6thJet} (Gev/c)") elif xVar == "eta6thJet": p.getFrame().GetXaxis().SetTitle("#eta_{6thJet}") elif xVar == "phi6thJet": p.getFrame().GetXaxis().SetTitle("#phi_{6thJet}") elif xVar == "Ht": p.getFrame().GetXaxis().SetTitle("H_{T} (Gev/c)") elif xVar == "nBTagJets": p.getFrame().GetXaxis().SetTitle("nB-Jet") elif xVar == "pu": p.getFrame().GetXaxis().SetTitle("nPU") elif xVar == "CSV": p.getFrame().GetXaxis().SetTitle("CSV") elif xVar == "JetMulti": p.getFrame().GetXaxis().SetTitle("Jet Multiplicity") elif xVar == "BJetMulti": p.getFrame().GetXaxis().SetTitle("B-Jet Multiplicity") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) #if xVar == "pt6thJet" and s == "OR": # plist = [0.7, 0.99, 1000, 0.16, 28.0] # Fit_Richards(30.0, 120.0, p, eff_Data, plist) # plist = [0.72, 0.91, 0.212, 0.15, 50.0] # Fit_Richards(30.0, 120.0, p, eff_MC, plist) #elif xVar == "Ht" and s == "OR": # plist = [0.00005, 0.988, 0.000000109, 0.15, 29.0] # Fit_Richards(350.0, 2000.0, p, eff_Data, plist) #plist = [0.0003, 0.97, 0.45, 0.24, 43.0] #Fit_Richards(500.0, 2000.0, p, eff_MC, plist) #elif xVar == "nBTagJets": #plist = [0.07, 0.984, 0.45, 0.24, 43.0] #Fit_Richards(30.0, 120.0, p, eff_Data, plist) #elif xVar == "pu": #plist = [0.07, 0.984, 0.45, 0.24, 43.0] #Fit_Richards(30.0, 120.0, p, eff_Data, plist) # Draw histograms.addText(0.30, 0.10, "Runs " + runRange, 17) histograms.addText(0.30, 0.15, "2016", 17) histograms.addStandardTexts(lumi=lumi) p.draw() # Save the canvas to a file SaveAs(p, kwargs.get("savePath"), saveName, kwargs.get("saveFormats"), True) ''' # IN SLICES OF HT HTSlices = ["450ht600","600ht800","800ht1000", "1000ht1250", "1250ht1500", "1500ht2000"] for s in SigSel: for hsl in HTSlices: num_name = "Num_pt6thJet_Vs_"+hsl+"_RefTrg_OfflineSel_"+s den_name = "Den_pt6thJet_Vs_"+hsl+"_RefTrg_OfflineSel" # Get the save path and name plotName = "Eff_pt6thJet_Vs_"+hsl+"_"+s savePath, saveName = GetSavePathAndName(plotName, **kwargs) # Get Efficiency Plots eff_Data = getEfficiency(datasetsMgr, dataset_Data, num_name, den_name , **kwargs) eff_MC = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name, **kwargs) xMin = 29.0 xMax = 125.0 # Apply Styles styles.dataStyle.apply(eff_Data) styles.mcStyle.apply(eff_MC) # Marker Style eff_Data.SetMarkerSize(1) # Create Comparison Plot p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data","p","P"), histograms.HistoGraph(eff_MC, "eff_MC", "p", "P")) opts = {"ymin": 0 , "ymax": 1.1, "xmin":xMin, "xMax":xMax} opts2 = {"ymin": 0.7, "ymax": 1.3} moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2 } p.histoMgr.setHistoLegendLabelMany({"eff_Data": "Data", "eff_MC": "Simulation"}) createRatio = True #kwargs.get("ratio") p.createFrame(saveName, createRatio=createRatio, opts=opts, opts2=opts2) # Set Legend p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Set Log & Grid SetLogAndGrid(p, **kwargs) # Set Titles p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel")) p.getFrame().GetXaxis().SetTitle("p_{T} (Gev/c)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Draw histograms.addText(0.30, 0.10, "Runs "+runRange, 17) histograms.addText(0.30, 0.15, "2016", 17) histograms.addStandardTexts(lumi=lumi) p.draw() # Save the canvas to a file SaveAs(p, kwargs.get("savePath"), saveName, kwargs.get("saveFormats"), True) PTSlices = ["40pt50","50pt60", "60pt70", "70pt90", "90pt120"] for s in SigSel: for psl in PTSlices: num_name = "Num_ht_Vs_"+psl+"_HLT_PFHT350_"+s den_name = "Den_ht_Vs_"+psl+"_HLT_PFHT350" # Get the save path and name plotName = "Eff_ht_Vs_"+psl+"_"+s savePath, saveName = GetSavePathAndName(plotName, **kwargs) # Get Efficiency Plots eff_Data = getEfficiency(datasetsMgr, dataset_Data, num_name, den_name , **kwargs) eff_MC = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name, **kwargs) xMin = 450 xMax = 2000 # Apply Styles styles.dataStyle.apply(eff_Data) styles.mcStyle.apply(eff_MC) # Marker Style eff_Data.SetMarkerSize(1) # Create Comparison Plot p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data","p","P"), histograms.HistoGraph(eff_MC, "eff_MC", "p", "P")) opts = {"ymin": 0 , "ymax": 1.1, "xmin":xMin, "xMax":xMax} opts2 = {"ymin": 0.7, "ymax": 1.3} moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2 } p.histoMgr.setHistoLegendLabelMany({"eff_Data": "Data", "eff_MC": "Simulation"}) createRatio = True #kwargs.get("ratio") #if eff_Data != None and eff_MC != None: p.createFrame(saveName, createRatio=createRatio, opts=opts, opts2=opts2) # Set Legend p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Set Log & Grid SetLogAndGrid(p, **kwargs) # Set Titles p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel")) p.getFrame().GetXaxis().SetTitle("H_{T} (Gev/c)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Draw histograms.addText(0.30, 0.10, "Runs "+runRange, 17) histograms.addText(0.30, 0.15, "2016", 17) histograms.addStandardTexts(lumi=lumi) p.draw() # Save the canvas to a file SaveAs(p, kwargs.get("savePath"), saveName, kwargs.get("saveFormats"), True) ''' return
def main(opts): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # Get all datasets from the mcrab dir # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) #kwargs.get("analysis")) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # Print the cross datasetsMgr.PrintCrossSections() for h_prefix in ["reco"]: # Get ref histo here and the fixed histos (TT, QCD, QCD-b inclusiveHisto, fixedHistos = GetHistosForPlotter(datasetsMgr, h_prefix + "MET_Et", **kwargs) inclusiveHisto.setName("Inclusive") inclusiveHisto.setLegendLabel("Inclusive") #for hi in fixedHistos: # print(type(hi), hi.getName()) #return # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(h_prefix + hName[0], **kwargs) saveName = savePath + h_prefix + hSaveNames[counter] # Get Histos for Plotter refHisto_, otherHistos_ = GetHistosForPlotter(datasetsMgr, h_prefix + hName[0], **kwargs) refHisto1, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[1], **kwargs) refHisto2, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[2], **kwargs) refHisto3, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[3], **kwargs) refHisto4, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[4], **kwargs) refHisto5, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[5], **kwargs) refHisto = inclusiveHisto # customize histos refHisto_.setName(hLegends[counter][0]) refHisto_.setLegendLabel(hLegends[counter][0]) refHisto_.setDrawStyle("P") refHisto_.setLegendStyle("P") styleDict[hStyles[0]].apply(refHisto_.getRootHisto()) refHisto1.setName(hLegends[counter][1]) refHisto1.setLegendLabel(hLegends[counter][1]) refHisto1.setDrawStyle("P") refHisto1.setLegendStyle("P") styleDict[hStyles[1]].apply(refHisto1.getRootHisto()) refHisto2.setName(hLegends[counter][2]) refHisto2.setLegendLabel(hLegends[counter][2]) refHisto2.setDrawStyle("P") refHisto2.setLegendStyle("P") styleDict[hStyles[2]].apply(refHisto2.getRootHisto()) refHisto3.setName(hLegends[counter][3]) refHisto3.setLegendLabel(hLegends[counter][3]) refHisto3.setDrawStyle("P") refHisto3.setLegendStyle("P") styleDict[hStyles[3]].apply(refHisto3.getRootHisto()) refHisto4.setName(hLegends[counter][4]) refHisto4.setLegendLabel(hLegends[counter][4]) refHisto4.setDrawStyle("P") refHisto4.setLegendStyle("P") styleDict[hStyles[4]].apply(refHisto4.getRootHisto()) refHisto5.setName(hLegends[counter][5]) refHisto5.setLegendLabel(hLegends[counter][5]) refHisto5.setDrawStyle("P") refHisto5.setLegendStyle("P") styleDict[hStyles[5]].apply(refHisto5.getRootHisto()) otherHistos = [refHisto_, refHisto1, refHisto2, refHisto3, refHisto4, refHisto5] #for hi in otherHistos: # print hi.getName() #return # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame if kwargs.get("logY")==True: opts = {"ymin": 8e-5, "ymax": 2} #opts = {"ymin": 1e-3, "ymax": 1} else: opts = {"ymin": 8.e-5, "ymax": 2} ratioOpts = {"ymin": 0.1, "ymax": 10.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.7) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) histograms.addText(0.2, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(opts): # Setup the style style = tdrstyle.TDRStyle() # 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 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 if 0: datasetsMgr.remove("TTJets") datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # Print dataset information datasetsMgr.PrintInfo() # ======================================== # Histograms # ======================================== for counter, hName in enumerate(hNames): # Get the save path and name, Get Histos for Plotter savePath, saveName = GetSavePathAndName(hName, **kwargs) refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a comparison plot #p = plots.ComparisonManyPlot(refHisto, otherHistos) p = plots.DataMCPlot(datasetsMgr, hName) # Remove negative contributions if 0: RemoveNegativeBins(datasetsMgr, hName, p) # Y-axis ratioOpts = {"ymin": 0.0, "ymax": 2.0} if kwargs.get("logY")==True: opts = {"ymin": 1e-2, "ymaxfactor": 100} else: opts = {"ymin": 0.0, "ymaxfactor": 1.2} # ======================================== # Frame # ======================================== p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Legend moveLegend = {"dx": -0.11, "dy": +0.0, "dh": +0.2} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames)) if 0: p.removeLegend() # Axes #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) #p.getFrame().GetYaxis().SetTitle( getTitleY(p.histoMgr.getHistos()[0], **kwargs) ) if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Set Log and Grid SetLogAndGrid(p, **kwargs) # Cut line / Cut 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) # Draw the final plot p.draw() # ======================================== # Add Text # ======================================== histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save the canvas to a file SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter==0) return
def main(opts): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # 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(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) 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.0015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0045)) # 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() # Draw plots p.draw() # Customise text 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 main(): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame if kwargs.get("logY"): opts = {"ymin": 1e-5, "ymaxfactor": 10} else: opts = {"ymin": 0.0, "ymaxfactor": 1.2} ratioOpts = {"ymin": 0.0, "ymax": 2.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(opts): # Setup the style style = tdrstyle.TDRStyle() # 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 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 if 0: datasetsMgr.remove("TTJets") datasetsMgr.remove( filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # Print dataset information datasetsMgr.PrintInfo() # ======================================== # Histograms # ======================================== for counter, hName in enumerate(hNames): # Get the save path and name, Get Histos for Plotter savePath, saveName = GetSavePathAndName(hName, **kwargs) refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a comparison plot #p = plots.ComparisonManyPlot(refHisto, otherHistos) p = plots.DataMCPlot(datasetsMgr, hName) # Remove negative contributions if 0: RemoveNegativeBins(datasetsMgr, hName, p) # Y-axis ratioOpts = {"ymin": 0.0, "ymax": 2.0} if kwargs.get("logY") == True: opts = {"ymin": 1e-2, "ymaxfactor": 100} else: opts = {"ymin": 0.0, "ymaxfactor": 1.2} # ======================================== # Frame # ======================================== p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Legend moveLegend = {"dx": -0.11, "dy": +0.0, "dh": +0.2} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder( filter( lambda n: plots._legendLabels[kwargs.get("refDataset")] not in n, histoNames)) if 0: p.removeLegend() # Axes #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) #p.getFrame().GetYaxis().SetTitle( getTitleY(p.histoMgr.getHistos()[0], **kwargs) ) if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # Set Log and Grid SetLogAndGrid(p, **kwargs) # Cut line / Cut 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) # Draw the final plot p.draw() # ======================================== # Add Text # ======================================== histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save the canvas to a file SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter == 0) return
def drawAllInOne(self, myAllShapeNuisances, luminosity): myMaxSize = len(myAllShapeNuisances) # Create pads canvasHeight = _cHeaderHeight + _cBodyHeight * myMaxSize + _cFooterHeight c = ROOT.TCanvas("","",600,canvasHeight) c.Divide(1,myMaxSize) myHeightBefore = canvasHeight myHeightAfter = canvasHeight for i in range(0,myMaxSize): myHeightBefore = myHeightAfter p = c.cd(i+1) myTopMargin = 0.0 myBottomMargin = 0.0 if i == 0: # Top histogram with header myHeightAfter -= _cHeaderHeight + _cBodyHeight myTopMargin = float(_cHeaderHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: # Bottom histogram with x axis label and title myHeightAfter -= _cFooterHeight + _cBodyHeight myBottomMargin = float(_cFooterHeight) / float(_cFooterHeight+_cBodyHeight) else: # Middle histogram, only body myHeightAfter -= _cBodyHeight (xlow, ylow, xup, yup) = [ROOT.Double(x) for x in [0.0]*4] p.GetPadPar(xlow, ylow, xup, yup) p.SetPad(xlow, float(myHeightAfter)/float(canvasHeight), xup, float(myHeightBefore)/float(canvasHeight)) p.SetBorderMode(0) p.SetFillStyle(4000) p.SetTopMargin(myTopMargin) p.SetBottomMargin(myBottomMargin) # Draw plots if len(self._ratioPlotList) == 0: print "No ratioplots in list! Cannot draw all-in-one plot!" return o = self._ratioPlotList[0].getFrame2() myEmptyPlot = aux.Clone(o) # Keep the clone if it is needed to draw the x axis for i in range(0,myMaxSize): p = c.cd(i+1) # Find plot myPlotIndex = None for j in range(0,len(self._systNameList)): if myAllShapeNuisances[i] == self._systNameList[j]: myPlotIndex = j plot = None if myPlotIndex != None: plot = self._ratioPlotList[myPlotIndex].getFrame2() else: if i == myMaxSize-1: plot = myEmptyPlot # Use this to draw the x axis else: plot = self._ratioPlotList[0].getFrame2() # Only the empty frame matters # Draw plot if i == myMaxSize-1: # Bottom histogram plot.GetXaxis().SetTitleOffset(0.6*myMaxSize+0.6) # 6.6/10, 3.6/5 else: plot.GetXaxis().SetTitleSize(0) plot.GetXaxis().SetLabelSize(0) plot.GetYaxis().SetLabelSize(26) plot.GetYaxis().SetTitleOffset(0.34*myMaxSize+0.1) # 3.5/10, 1.8/5 # plot.SetMinimum(0.001) # plot.SetMaximum(1.999) plot.SetMinimum(0.601) plot.SetMaximum(1.399) plot.Draw() # Plot frame for every nuisance if myPlotIndex != None: self._ratioPlotList[myPlotIndex].ratioHistoMgr.draw() # Plot content only if affected self._ratioPlotList[0].ratioLine.Draw("L") p.RedrawAxis() # Labels for shape nuisance and dataset myHeight = 0.82 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.18, y=myHeight, text=myAllShapeNuisances[i], size=30) myHeight = 0.08 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.93, y=myHeight, text=self._dsetName, size=30, align="right") # Header labels if i == 0: histograms.addStandardTexts(lumi=luminosity, cmsTextPosition="outframe") # Labels for non-existing nuisances if myPlotIndex == None: myHeight = 0.44 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.555, y=myHeight, text="Not affected", size=30, align="center") # Save plot myPlotName = "shapeSystRatioOnlyAll_%s"%(self._dsetName) backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError for suffix in [".png",".C",".eps"]: c.Print("%s/%s%s"%(_dirname,myPlotName,suffix)) ROOT.gErrorIgnoreLevel = backup
def analyze(analysis=None): paths = [sys.argv[1]] if (len(sys.argv) == 3): howAnalyse = sys.argv[2] else: howAnalyse = "--fit" # howAnalyse = "--bin" 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") datasetsDY = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="DYJetsToLL|Zprime") # 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() histeff1 = getEfficiency(dataset1) histeff2 = getEfficiency(dataset2) eff1 = convert2TGraph(histeff1) eff2 = convert2TGraph(histeff2) if isinstance(datasetsH125,dataset.DatasetManager): histeff3 = getEfficiency(datasetsH125.getMCDatasets()) eff3 = convert2TGraph(histeff3) 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 FUNCTIONS: "Sigmoid", "Error", "Gompertz", "Richard","Crystal" ## ## FIT TYPES: binned max likelihood: "ML" , Chi2-fit: "Chi" ## if (howAnalyse == "--fit" ): datafit = fitType("Data",p,histeff1,eff1,20,500,"Crystal","ML") mcfit = fitType("MC",p,histeff2,eff2,20,500,"Crystal","ML") 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) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau120_Trk50_eta2p1", 17) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau140_Trk50_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() ## does the ratio of the fits if (howAnalyse=="--fit"): funcRatio = ROOT.TH1F("","",480,20,500) for i in range(0,480): ratio = datafit.Eval(i+20-1)/mcfit.Eval(i+20-1) funcRatio.SetBinContent(i,ratio) p.getPad().GetCanvas().cd(2) funcRatio.Draw("SAME") p.getPad().GetCanvas().cd(1) ## lumi = 0.0 for d in datasets.getDataDatasets(): if(d.getName() != "SingleMuon_Run2016F_03Feb2017_v1_277932_278800" and d.getName() != "SingleMuon_Run2016C_03Feb2017_v1_275656_276283"): 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) if (howAnalyse == "--fit"): pythonWriter.addParameters(plotDir,label,runRange,lumi,datafit) pythonWriter.addMCParameters(label,mcfit) pythonWriter.writeJSON(os.path.join(plotDir,"tauLegTriggerEfficiency_"+label+"_fit.json")) pythonWriter.__init__() #need to clear the Json arrays # if (howAnalyse == "--bin"): pythonWriter.addParameters(plotDir,label,runRange,lumi,eff1) pythonWriter.addMCParameters(label,eff2) pythonWriter.writeJSON(os.path.join(plotDir,"tauLegTriggerEfficiency_"+label+"_bin.json")) # if not createRatio: # sys.exit() ######################################################################### histeff1eta = getEfficiency(dataset1,"NumeratorEta","DenominatorEta") histeff2eta = getEfficiency(dataset2,"NumeratorEta","DenominatorEta") eff1eta = convert2TGraph(histeff1eta) eff2eta = convert2TGraph(histeff2eta) if isinstance(datasetsH125,dataset.DatasetManager): histeff3eta = getEfficiency(datasetsH125.getMCDatasets(),"NumeratorEta","DenominatorEta") eff3eta = convert2TGraph(histeff3eta) 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) ######################################################################### histeff1phi = getEfficiency(dataset1,"NumeratorPhi","DenominatorPhi") histeff2phi = getEfficiency(dataset2,"NumeratorPhi","DenominatorPhi") eff1phi = convert2TGraph(histeff1phi) eff2phi = convert2TGraph(histeff2phi) if isinstance(datasetsH125,dataset.DatasetManager): histeff3phi = getEfficiency(datasetsH125.getMCDatasets(),"NumeratorPhi","DenominatorPhi") eff3phi = convert2TGraph(histeff3phi) 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" histeff1PU = getEfficiency(dataset1,"NumeratorPU","DenominatorPU") histeff2PU = getEfficiency(dataset2,"NumeratorPU","DenominatorPU") eff1PU = convert2TGraph(histeff1PU) eff2PU = convert2TGraph(histeff2PU) 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 _generateCoefficientPlot(self): ''' This probably is needed in the case the measurement is done in bins of a correlated quantity (e.g. pT in the case of inverted tau isolation ''' def makeGraph(markerStyle, color, binList, valueDict, upDict, downDict): g = ROOT.TGraphAsymmErrors(len(binList)) for i in range(len(binList)): g.SetPoint(i, i + 0.5, valueDict[binList[i]]) g.SetPointEYhigh(i, upDict[binList[i]]) g.SetPointEYlow(i, downDict[binList[i]]) g.SetMarkerSize(1.2) g.SetMarkerStyle(markerStyle) g.SetLineColor(color) g.SetLineWidth(3) g.SetMarkerColor(color) return g # Obtain bin list in right order keyList = [] keys = self._TF.keys() keys.sort() # for k in keys: # if "lt" in k: # keyList.append(k) # for k in keys: # if "eq" in k: # keyList.append(k) # for k in keys: # if "gt" in k: # keyList.append(k) # For-loop: All Fake-b measurement bins for k in keys: keyList.append(k) #if "Inclusive" in keys: # keyList.append("Inclusive") # Apply TDR style style = tdrstyle.TDRStyle() style.setOptStat(False) style.setGridX(True) style.setGridY(True) # Create graphs gFakeB = makeGraph(ROOT.kFullCircle, ROOT.kRed, keyList, self._TF, self._TF_Error, self._TF_Error) # Make plot hFrame = ROOT.TH1F("frame", "frame", len(keyList), 0, len(keyList)) # Change bin labels to text for i, binLabel in enumerate(keyList, 1): # for i in range(len(keyList)): binLabelText = self.getFormattedBinLabelString(binLabel) #hFrame.GetXaxis().SetBinLabel(i+1, binLabelText) hFrame.GetXaxis().SetBinLabel(i, binLabelText) # Set axes names hFrame.GetYaxis().SetTitle("transfer factor ") # hFrame.GetYaxis().SetTitle("transfer factors (R_{i})") # hFrame.GetXaxis().SetTitle("Fake-b bin") # Customise axes hFrame.SetMinimum(0.6e-1) hFrame.SetMaximum(2e0) if len(self._BinLabelMap) > 12: lSize = 8 elif len(self._BinLabelMap) > 8: lSize = 12 else: lSize = 16 hFrame.GetXaxis().SetLabelSize(lSize) # 20 hFrame.GetXaxis().LabelsOption("d") # Label Style options # "a" sort by alphabetic order # ">" sort by decreasing values # "<" sort by increasing values # "h" draw labels horizonthal # "v" draw labels vertical # "u" draw labels up (end of label right adjusted) # "d" draw labels down (start of label left adjusted) # Create canvas c = ROOT.TCanvas() c.SetLogy(True) c.SetGridx() c.SetGridy() hFrame.Draw() gFakeB.Draw("p same") histograms.addStandardTexts(cmsTextPosition="outframe") # Create the legend & draw it l = ROOT.TLegend(0.65, 0.80, 0.90, 0.90) l.SetFillStyle(-1) l.SetBorderSize(0) # l.AddEntry(gFakeB, "Fake-#it{b} #pm Stat.", "LP") l.AddEntry(gFakeB, "Value #pm Stat.", "LP") l.SetTextSize(0.035) l.Draw() # Store ROOT ignore level to normal before changing it backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kWarning # Save the plot for item in ["png", "C", "pdf"]: c.Print(self._plotDirName + "/QCDNormalisationCoefficients.%s" % item) # Reset the ROOT ignore level to normal ROOT.gErrorIgnoreLevel = backup # Inform user msg = "Transfer-factors written in %s " % (ShellStyles.SuccessStyle() + self._plotDirName + ShellStyles.NormalStyle()) self.Print(msg, False) return
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 main(): if len(sys.argv) < 2: usage() paths = [sys.argv[1]] analysis = "METLeg_2015D_MET80" # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) styles.mcStyle.apply(eff2_MET80) eff1_MET80.SetMarkerSize(1) eff2_MET80.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_"+analysis+"_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1, "eff2_MET80": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) label = analysis.split("_")[1] histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 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_MET80) pythonWriter.addMCParameters(label,eff2_MET80) pythonWriter.writeJSON(os.path.join(plotDir,"metLegTriggerEfficiency2015.json")) """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET #### MET80 analysisc = "METLeg_2015D_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) 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) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.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) pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) opts = {"ymin": 0.001, "ymax": 0.1} pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pPU.getPad1().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.25, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) histograms.addText(0.4, 0.18, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.11, "Runs "+datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in",plotDir
def main(): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) ROOT.gErrorIgnoreLevel = 3000 # Get all datasets from the mcrab dir datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) # datasetsMgr = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_200") # datasetsMgr = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), excludeTasks="M_200") # Determine Integrated Luminosity intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # datasetsMgr.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # For-loop: All Histogram names for hName in hNames: savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get efficiency histos refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFCP", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFFC", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kBJeffrey", **kwargs) # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFNormal", **kwargs) # Plot the efficiencies p = plots.ComparisonManyPlot(refEff, otherEff) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.2} #"ymax": 5e-1} ratioOpts = {"ymin": 0.0, "ymaxfactor": 1.2} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.1 , "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame # p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # 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) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def analyze(analysis=None): paths = [sys.argv[1]] if (len(sys.argv) == 3): howAnalyse = sys.argv[2] else: howAnalyse = "--fit" # howAnalyse = "--bin" 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") datasetsDY = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL|Zprime") # 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() histeff1 = getEfficiency(dataset1) histeff2 = getEfficiency(dataset2) eff1 = convert2TGraph(histeff1) eff2 = convert2TGraph(histeff2) if isinstance(datasetsH125, dataset.DatasetManager): histeff3 = getEfficiency(datasetsH125.getMCDatasets()) eff3 = convert2TGraph(histeff3) 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 FUNCTIONS: "Sigmoid", "Error", "Gompertz", "Richard","Crystal" ## ## FIT TYPES: binned max likelihood: "ML" , Chi2-fit: "Chi" ## if (howAnalyse == "--fit"): datafit = fitType("Data", p, histeff1, eff1, 20, 500, "Crystal", "ML") mcfit = fitType("MC", p, histeff2, eff2, 20, 500, "Crystal", "ML") 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) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau120_Trk50_eta2p1", 17) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau140_Trk50_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() ## does the ratio of the fits if (howAnalyse == "--fit"): funcRatio = ROOT.TH1F("", "", 480, 20, 500) for i in range(0, 480): ratio = datafit.Eval(i + 20 - 1) / mcfit.Eval(i + 20 - 1) funcRatio.SetBinContent(i, ratio) p.getPad().GetCanvas().cd(2) funcRatio.Draw("SAME") p.getPad().GetCanvas().cd(1) ## lumi = 0.0 for d in datasets.getDataDatasets(): if (d.getName() != "SingleMuon_Run2016F_03Feb2017_v1_277932_278800" and d.getName() != "SingleMuon_Run2016C_03Feb2017_v1_275656_276283"): 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) if (howAnalyse == "--fit"): pythonWriter.addParameters(plotDir, label, runRange, lumi, datafit) pythonWriter.addMCParameters(label, mcfit) pythonWriter.writeJSON( os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + "_fit.json")) pythonWriter.__init__() #need to clear the Json arrays # if (howAnalyse == "--bin"): pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1) pythonWriter.addMCParameters(label, eff2) pythonWriter.writeJSON( os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + "_bin.json")) # if not createRatio: # sys.exit() ######################################################################### histeff1eta = getEfficiency(dataset1, "NumeratorEta", "DenominatorEta") histeff2eta = getEfficiency(dataset2, "NumeratorEta", "DenominatorEta") eff1eta = convert2TGraph(histeff1eta) eff2eta = convert2TGraph(histeff2eta) if isinstance(datasetsH125, dataset.DatasetManager): histeff3eta = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorEta", "DenominatorEta") eff3eta = convert2TGraph(histeff3eta) 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) ######################################################################### histeff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi") histeff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi") eff1phi = convert2TGraph(histeff1phi) eff2phi = convert2TGraph(histeff2phi) if isinstance(datasetsH125, dataset.DatasetManager): histeff3phi = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorPhi", "DenominatorPhi") eff3phi = convert2TGraph(histeff3phi) 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" histeff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU") histeff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU") eff1PU = convert2TGraph(histeff1PU) eff2PU = convert2TGraph(histeff2PU) 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 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 doPlots(i, opts): Print( "Processing %s%s%s algorithm" % ( ShellStyles.NoteStyle(), opts.algorithm, ShellStyles.NormalStyle(), ), True) # Settings if opts.h2tb: analysis = "H^{+}#rightarrow tb fully hadronic" else: analysis = "H^{+}#rightarrow#tau_{h}#nu fully hadronic" # Hadd ROOT files #rootFiles = glob.glob1(filePath, "higgsCombinetoys*.root") rootFiles = glob.glob1(opts.inputDir, "higgsCombinetoys*.root") Verbose("Attempting to merge all toy ROOT files", True) if len(rootFiles) > 0: if os.path.isfile(opts.outputfile): os.remove(opts.outputfile) Print( "Merging \"%s\" ROOT files into \"%s\"" % (opts.inputfile, opts.inputfile), True) call("hadd %s %s" % (opts.outputfile, opts.inputfile), shell=True) else: msg = "%sFound %d toy ROOT files to merge%s" % ( ShellStyles.NoteStyle(), len(rootFiles), ShellStyles.NormalStyle()) Print(msg, True) sys.exit() # Clean auxiliary jobs files? CleanFiles(opts) # Perform GoF calculations if not os.path.isfile(opts.outputfile): raise Exception("The output ROOT file \"%s\" does not exist!" % (opts.outputfile)) else: Print( "Opening merged ROOT file \"%s\" to read results" % (opts.outputfile), False) fToys = ROOT.TFile(opts.outputfile) fData = ROOT.TFile(opts.outputfile) tToys = fToys.Get("limit") tData = fData.Get("limit") nToys = tToys.GetEntries() if 1: #opts.verbose: aux.PrintTH1Info(tData) if opts.verbose: tData.Print() # Store the goodness-of-fit value observed in data Verbose( "NData = %.1f, NToys = %.1f" % (tData.GetEntries(), tToys.GetEntries()), False) tData.GetEntry(0) GoF_DATA = tData.limit Verbose(GoF_DATA, True) # Setting (Toys) GoF_TOYS_TOT = 0 pval_cum = 0 toys = [] minToy = +99999999 maxToy = -99999999 # For-loop: All toys for i in range(0, tToys.GetEntries()): tToys.GetEntry(i) # Toys counter GoF_TOYS_TOT += tToys.limit toys.append(tToys.limit) # Accumulate p-Value if GoF_toy > GoF_data if tToys.limit > GoF_DATA: Verbose( "GoF (toy) = %.3f, GoF (data) = %.3f, p-Value += %d (%d)" % (tToys.limit, GoF_DATA, tToys.limit, pval_cum), i == 1) pval_cum += tToys.limit # Finalise p-value calculation by dividing by number of toys total pval = pval_cum / GoF_TOYS_TOT Print("p-Value = %d/%d = %.3f" % (pval_cum, GoF_TOYS_TOT, pval), False) # Create GoF histo & fill it hist = ROOT.TH1D("GoF", "", 50, round(min(toys)), round(max(toys))) # For-loop: Toys for k in toys: hist.Fill(k) # Customise canvas & histogram c = ROOT.TCanvas("canvas", "canvas") hist.GetYaxis().SetTitle("Entries") hist.GetXaxis().SetTitle("#chi^{2}_{%s}" % (opts.algorithm)) hist.SetLineColor(ROOT.kRed) hist.SetLineWidth(3) hist.Draw() # Customise arrow indicating data-observed arr = ROOT.TArrow(GoF_DATA, 0.0001, GoF_DATA, hist.GetMaximum() / 8, 0.02, "<|") arr.SetLineColor(ROOT.kBlue) arr.SetFillColor(ROOT.kBlue) arr.SetFillStyle(1001) arr.SetLineWidth(3) arr.SetLineStyle(1) arr.SetAngle(60) arr.Draw("<|same") # Add data observed value left = ROOT.TLatex() #left.SetNDC() left.SetTextFont(43) left.SetTextSize(22) left.SetTextAlign(11) #left.DrawLatex(GoF_DATA*0.9, (hist.GetMaximum()/8.0)*1.05, "#color[4]{data_{obs}}") left.DrawLatex(GoF_DATA * 0.9, (hist.GetMaximum() / 8.0) * 1.05, "#color[4]{data}") # Analysis text anaText = ROOT.TLatex() anaText.SetNDC() anaText.SetTextFont(43) anaText.SetTextSize(22) anaText.SetTextAlign(31) anaText.DrawLatex(0.92, 0.86, analysis) # p-value pvalText = ROOT.TLatex() pvalText.SetNDC() pvalText.SetTextFont(43) pvalText.SetTextSize(22) pvalText.SetTextAlign(31) #11 pvalText.DrawLatex(0.92, 0.80, "# toys: %d" % nToys) pvalText.DrawLatex(0.92, 0.74, "p-value: %.2f" % pval) pvalText.DrawLatex(0.92, 0.68, "H^{+} m_{H^{+}}= %s GeV" % opts.mass) # pvalText.DrawLatex(0.92, 0.74, " #alpha=#int^{#infty}_{#chi^{2}_{obs}} f(#chi^{2}) d#chi^{2}=%.2f" % pval) # pvalText.DrawLatex(0.92, 0.58, "1-#alpha=#int^{#chi^{2}_{obs}}_{0} f(#chi^{2}) d#chi^{2}=%.2f" % (1.0-pval)) # Print some info Verbose("Toys = %.0f" % (nToys), True) Verbose("GoF_TOYS_TOT = %.0f" % (GoF_TOYS_TOT), True) Verbose("p-value = %.2f" % (pval), False) # Add default texts histograms.addStandardTexts(lumi=opts.lumi, sqrts="13 TeV", addCmsText=True, cmsTextPosition=None, cmsExtraTextPosition=None, cmsText="CMS", cmsExtraText="Internal ") #histograms.addStandardTexts(lumi=opts.lumi, sqrts="13 TeV", addCmsText=True, cmsTextPosition=None, cmsExtraTextPosition=None, cmsText="CMS", cmsExtraText="Preliminary") # Save the plot (not needed - drawPlot saves the canvas already) saveName = "GoF_m%s_%s" % (opts.mass, opts.algorithm) SavePlot(c, saveName, opts.saveDir, saveFormats=[".C", ".png", ".pdf"]) return