def GetCutEfficiencyTGraphs(datasetsMgr, histoName, statOpt, **kwargs): ''' ''' HasKeys(["refDataset", "drawStyle", "legStyle", "cutDirection"], **kwargs) refGraph = None otherGraphs = [] refDataset = kwargs.get("refDataset") drawStyle = kwargs.get("drawStyle") legStyle = kwargs.get("legStyle") legLabel = plots._legendLabels[refDataset] refHisto, otherHistos = GetCutEfficiencyHistos(datasetsMgr, histoName, statOpt, **kwargs) refGraph = histograms.HistoGraph(refHisto, legLabel, legStyle, drawStyle) # For-loop: All efficiency histos for h in otherHistos: legLabel = plots._legendLabels[h.GetName()] otherGraphs.append( histograms.HistoGraph(h, legLabel, legStyle, drawStyle)) if refGraph == None: raise Exception("The \"reference\" graph is None!") elif len(otherGraphs) < 1: raise Exception("The \"other\" graph list empty!") else: return refGraph, otherGraphs
def doPlot(legList, graphList, saveName, **kwargs): # Definitions hgList = [] lList = {} # For-loop: All TGraphs for i, g in enumerate(graphList, 0): if opts.boldText: gName = legList[i] else: gName = "#font[42]{%s}" % legList[i] hg = histograms.HistoGraph(graphList[i], gName, drawStyle="L", legendStyle="l") hgList.append(hg) # Create a plot-base object Verbose("Creating the plot-base object", True) # plot = plots.PlotBase(hgList, saveFormats=[]) hgList.insert(0, hgList.pop(opts.refIndex)) plot = plots.ComparisonManyPlot(hgList[0], hgList[1:], saveFormats=[]) #plot = plots.ComparisonManyPlot(hgList[-1], hgList[:-1], saveFormats=[]) # Apply histo style Verbose("Applying the histogram styles (generator)", True) plot.histoMgr.forEachHisto(styles.generator()) # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.2)) # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) def sty(h): r = h.getRootHisto() r.SetLineWidth(3) r.SetMarkerSize(1.2) return # Apply style and set label Verbose("Applying the histogram styles (forEachHisto)", True) plot.histoMgr.forEachHisto(sty) if opts.plotType != "var": plot.setLegendHeader("Sequential Model (Keras)") # Draw the plot Verbose("Drawing the plot", True) plots.drawPlot(plot, saveName, **kwargs) if opts.removeLegend: plot.removeLegend() # Save plots and return Verbose("Saving the plot as %s" % (saveName), True) SavePlot(plot, opts.saveDir, saveName, opts.saveFormats) Verbose( "Plots saved under directory %s" % (sh_s + aux.convertToURL(opts.saveDir, opts.url) + sh_n), True) return
def doPlot(opts, signif, lumi, pvalue=False): grObs = None histos = [] if opts.unblinded: grObs = signif.observedGraph(pvalue) histos.append(histograms.HistoGraph(grObs, "Observed", drawStyle="LP")) grExp = signif.expectedGraph(pvalue) histos.append(histograms.HistoGraph(grExp, "Expected", drawStyle="L")) expData = "#it{B}#times#it{B}=%s %%" % signif.lightExpectedSignal() if signif.isHeavyStatus(): expData = "#sigma#times#it{B}=%s pb" % signif.heavyExpectedSignal() plot = plots.PlotBase(histos) plot.setLuminosity(lumi) if pvalue: plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected p-value", "Observed": "Observed p-value" }) plot.appendPlotObject(histograms.PlotText(0.6, 0.68, expData, size=18)) drawPlot(plot, "pvalue", ylabel="P-value", log=True, moveLegend={"dx": -0.2}, opts={ "ymin": 1e-10, "ymax": 1 }) else: plot.histoMgr.setHistoLegendLabelMany({ "Expected": "Expected significance", "Observed": "Observed significance" }) plot.appendPlotObject(histograms.PlotText(0.2, 0.68, expData, size=18)) drawPlot(plot, "significance", ylabel="Significance", moveLegend={"dx": -0.55})
def doPlotMu(name, graphs, styleList, limits, xlabel): objs = [] ll = {} for gr, mu in graphs: objs.append( histograms.HistoGraph(gr, "Obs%d" % mu, drawStyle="LP", legendStyle="lp")) ll["Obs%d" % mu] = "Observed, #mu=%d %s" % (mu, limit.massUnit()) plot = plots.PlotBase(objs) plot.histoMgr.forEachHisto(styles.Generator(styleList)) plot.histoMgr.setHistoLegendLabelMany(ll) plot.setLegend( histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355), dx=-0.1)) plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.9, limit.process, size=size) histograms.addText(x, 0.863, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size) histograms.addText(x, 0.775, limit.BRassumption, size=size) plot.save()
def 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 doPlot(limits, legendLabels, graphs, name, ylabel, _opts={}, yTitle=None): # Definitions hg = [] ll = {} nGraphs = len(graphs) # For-loop: All HistoGraphs for i in xrange(nGraphs): hg.append( histograms.HistoGraph(graphs[i], "Graph%d" % i, drawStyle="PL", legendStyle="lp")) ll["Graph%d" % (i)] = legendLabels[i] # Create a plot-base object plot = plots.PlotBase(hg) plot.histoMgr.forEachHisto(styles.Generator(styleList[0:len(limits)])) def sty(h): r = h.getRootHisto() r.SetLineWidth(3) r.SetLineStyle(ROOT.kSolid) return # Apply style and set label plot.histoMgr.forEachHisto(sty) plot.histoMgr.setHistoLegendLabelMany(ll) # Create & set legend nGraphs = len(graphs) # If sigma bands are drawn each legend entry is plotted twice. Correct this in the count if "Sigma1" in name or "Sigma2" in name: nGraphs = nGraphs / 2.0 legend = getLegend(nGraphs, limit, xPosLeg) plot.setLegend(legend) # Determine save name, minimum and maximum of y-axis ymin, ymax, saveName = getYMinMaxAndName(limits, name) if _opts.yMin == -1: _opts.yMin = ymin if _opts.yMax == -1: _opts.yMax = ymax # Create the frame and set axes titles plot.createFrame(saveName, opts={"ymin": _opts.yMin, "ymax": _opts.yMax}) # Add cut line? if opts.cutLine != 999.9: kwargs = {"greaterThan": True} plot.addCutBoxAndLine(cutValue=_opts.cutLine, fillColor=ROOT.kRed, box=False, line=True, **kwargs) if opts.cutLineY != 999.9: kwargs = { "greaterThan": True, "mainCanvas": True, "ratioCanvas": False } plot.addCutBoxAndLineY(cutValue=_opts.cutLineY, fillColor=ROOT.kRed, box=False, line=True, **kwargs) # Set axes titles plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle(ylabel) # Enable/Disable logscale for axes ROOT.gPad.SetLogy(_opts.logY) ROOT.gPad.SetLogx(_opts.logX) # Draw and add text plot.draw() plot.setLuminosity(limits[0].getLuminosity()) plot.addStandardTexts(cmsTextPosition="outframe") addPhysicsText(histograms, limit, x=xPosText) # Save plots and return SavePlot(plot, _opts.saveDir, saveName, [".png"]) #, ".pdf"]) return
def PlotEfficiency(datasetsMgr, numPath, denPath): # Definitions myList = [] _kwargs = GetHistoKwargs(numPath, opts) nx = 0 if len(_kwargs["binList"]) > 0: xBins = _kwargs["binList"] nx = len(xBins) - 1 counter = 0 # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): if dataset.isMC(): n = dataset.getDatasetRootHisto(numPath) d = dataset.getDatasetRootHisto(denPath) num = n.getHistogram() den = d.getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) else: num = dataset.getDatasetRootHisto(numPath).getHistogram() den = dataset.getDatasetRootHisto(denPath).getHistogram() if nx > 0: num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) # Calculations total = den.Integral(0, den.GetXaxis().GetNbins() + 1) selected = num.Integral(0, num.GetXaxis().GetNbins() + 1) if 0: print "Numerical Efficiency", numPath, dataset.getName( ), ":", round(selected / total, 3) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) eff.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP datasetTT = datasetsMgr.getDataset("TT") # Get the histograms numTT = datasetTT.getDatasetRootHisto(numPath).getHistogram() denTT = datasetTT.getDatasetRootHisto(denPath).getHistogram() if nx > 0: numTT = numTT.Rebin(nx, "", xBins) #num.Rebin(nx, "", xBins) denTT = denTT.Rebin(nx, "", xBins) #den.Rebin(nx, "", xBins) ''' for i in range(1, num.GetNbinsX()+1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) nbinTT = numTT.GetBinContent(i) dbinTT = denTT.GetBinContent(i) eps = nbin/dbin epsTT = nbinTT/dbinTT ratioTT = eps/epsTT if ratioTT > 1: ratioTT = 1/ratioTT #print "bin: ", i, "eps: ", round(eps,5) , "epsTT: ", round(epsTT,5) #print "bin: ", i, "eps/epsTT: ", (1.0 - round(ratioTT, 3))*100 ''' eff_ref = ROOT.TEfficiency(numTT, denTT) eff_ref.SetStatisticOption(ROOT.TEfficiency.kFCP) #FCP # Convert to TGraph gEff = convert2TGraph(eff) gEffRef = convert2TGraph(eff_ref) # Style definitions stylesDef = styles.ttStyle styles0 = styles.signalStyleHToTB300 styles1 = styles.signalStyleHToTB500 styles2 = styles.signalStyleHToTB800 styles3 = styles.signalStyleHToTB500 styles4 = styles.signalStyleHToTB1000 styles5 = styles.signalStyleHToTB2000 styles6 = styles.signalStyleHToTB180 styles7 = styles.signalStyleHToTB3000 styles8 = styles.signalStyleHToTB200 if dataset.getName() == "TT": styles.ttStyle.apply(gEffRef) legend_ref = "t#bar{t}" if opts.type == "partonShower": legend_ref = "t#bar{t} (Pythia8)" elif opts.type == "evtGen": legend_ref = "t#bar{t} (Powheg)" refGraph = histograms.HistoGraph(gEffRef, legend_ref, "p", "P") else: styles.markerStyles[counter].apply(gEff) legend = dataset.getName().replace("TT_", "t#bar{t} (").replace( "isr", "ISR ").replace("fsr", "FSR ") legend = legend.replace("hdamp", "hdamp ").replace("DOWN", "down").replace( "UP", "up") legend = legend.replace("mtop1665", "m_{t} = 166.5 GeV") legend = legend.replace("mtop1695", "m_{t} = 169.5 GeV") legend = legend.replace("mtop1715", "m_{t} = 171.5 GeV") legend = legend.replace("mtop1735", "m_{t} = 173.5 GeV") legend = legend.replace("mtop1755", "m_{t} = 175.5 GeV") legend = legend.replace("mtop1785", "m_{t} = 178.5 GeV") legend = legend.replace("TuneEE5C", "Herwig++") legend += ")" counter += 1 #myList.append(histograms.HistoGraph(gEff, legend, "lp", "P")) myList.append(histograms.HistoGraph(gEff, legend, "p", "P")) # Define stuff numPath = numPath.replace("AfterAllSelections_", "") saveName = "Efficiency_%s_%s" % (opts.folder, opts.type) saveName = saveName.replace("__", "_Inclusive_") # Plot the efficiency p = plots.ComparisonManyPlot(refGraph, myList, saveFormats=[]) savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) # Save plot in all formats SavePlot(p, saveName, savePath, saveFormats=[".png", ".pdf", ".C"]) return
def PlotEfficiency_comparison(datasetsMgr, numPath, denPath, datasetsMgr_DR, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets #for dataset in datasetsMgr.getAllDatasets(): if 1: #if "Fake" in numPath: # return dataset = datasetsMgr.getDataset("TT") dataset_DR = datasetsMgr_DR.getDataset("TT") #if "Fake" in numPath: # dataset = datasetsMgr.getDataset("QCD") # dataset_DR = datasetsMgr_DR.getDataset("QCD") legend = "t#bar{t} (#Delta R < 0.30, #Delta p_{T} / p_{T} < 0.32)" legend_DR = "t#bar{t} (#Delta R < 0.30)" styleDef = styles.ttStyle style_DR = styles.signalStyleHToTB500 #800 n = dataset_DR.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num_DR = n.getHistogram() d = dataset_DR.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den_DR = d.getHistogram() #========================================= n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() #========================================= if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) num_DR = num_DR.Rebin(nx, "", xBins) den_DR = den_DR.Rebin(nx, "", xBins) for i in range(1, num.GetNbinsX() + 1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) nbin_DR = num_DR.GetBinContent(i) dbin_DR = den_DR.GetBinContent(i) eps = nbin / dbin eps_DR = nbin_DR / dbin_DR ratio_DR = eps / eps_DR if ratio_DR > 1: ratio_DR = 1 / ratio_DR print "bin: ", i, "eps: ", round(eps, 5), "eps_DR: ", round(eps_DR, 5) print "bin: ", i, "eps/eps_DR: ", (1.0 - round(ratio_DR, 3)) * 100 # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: # continue return if num.GetEntries() > den.GetEntries(): # continue return # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) eff.SetStatisticOption(ROOT.TEfficiency.kFCP) eff_DR = ROOT.TEfficiency(num_DR, den_DR) eff_DR.SetStatisticOption(ROOT.TEfficiency.kFCP) eff = convert2TGraph(eff) eff_DR = convert2TGraph(eff_DR) # Apply default style (according to dataset name) #plots._plotStyles[dataset.getName()].apply(eff) #styleDef.apply(eff) #style_DR.apply(eff_DR) styles.markerStyles[0].apply(eff) styles.markerStyles[1].apply(eff_DR) ''' eff_DR.SetLineStyle(ROOT.kSolid) eff.SetLineWidth(2) eff_DR.SetLineWidth(2) eff.SetLineStyle(ROOT.kSolid) eff_DR.SetLineStyle(ROOT.kSolid) eff.SetMarkerStyle(ROOT.kFullTriangleUp) eff_DR.SetMarkerStyle(ROOT.kFullTriangleUp) eff.SetMarkerSize(1.2) eff_DR.SetMarkerSize(1.2) ''' # Append in list myList.append(histograms.HistoGraph(eff, legend, "p", "P")) myList.append(histograms.HistoGraph(eff_DR, legend_DR, "p", "P")) # Save plot in all formats #savePath = os.path.join(opts.saveDir, opts.optMode) #plots.drawPlot(p, savePath, **_kwargs) #SavePlot(p, saveName, savePath, saveFormats = [".png", ".pdf"]) # Define stuff numPath = numPath.replace("AfterAllSelections_", "") numPath = numPath.replace("LeadingTrijet_Pt", "LdgTopPt") if "Genuine" in numPath: TTcateg = "_TTgenuine" elif "Fake" in numPath: TTcateg = "_TTfake" else: TTcateg = "_TTinclusive" if "SR" in numPath: region = "_SR" if "VR" in numPath: region = "_VR" if "CR1" in numPath: region = "_CR1" if "CR2" in numPath: region = "_CR2" saveName = "Eff_" + numPath.split("/")[-1] + TTcateg + "_BDTtraining" # Plot the efficiency p = plots.ComparisonManyPlot( histograms.HistoGraph(eff, legend, "p", "P"), [histograms.HistoGraph(eff_DR, legend_DR, "p", "P")], saveFormats=[".pdf", ".png", ".C"]) leg = ROOT.TLegend(0.2, 0.8, 0.81, 0.87) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetBorderSize(0) #{"dx": -0.55, "dy": -0.55, "dh": -0.08} leg.SetHeader("t#bar{t}") #if "Fake" in numPath: # leg.SetHeader("QCD") leg.Draw() #moveLegend = {"dx": -0.0, "dy": +0.0, "dh": +0.1} #moveLegend = {"dx": -0.1, "dy": +0.0, "dh": +0.1} #p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Save plot in all formats savePath = os.path.join(SAVEDIR, "HplusMasses", numPath.split("/")[0], opts.optMode) #savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) plots.drawPlot(p, SAVEDIR, **_kwargs) #leg.Draw() SavePlot(p, saveName, SAVEDIR, saveFormats=[".png", ".pdf", ".C"]) return
def doPlot(name, graphs, limits, xlabel): if "obs" in graphs.keys(): obs = graphs["obs"] excluded = ROOT.TGraph(obs) excluded.SetName("ExcludedArea") excluded.SetFillColor(ROOT.kGray) excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN() - 1], tanbMax) excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetFillColor(ROOT.kGray) excluded.SetFillStyle(3354) excluded.SetLineWidth(0) excluded.SetLineColor(ROOT.kWhite) plot = None if "obs" in graphs.keys(): plot = plots.PlotBase([ histograms.HistoGraph(graphs["obs"], "Observed", drawStyle="PL", legendStyle="lp"), histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L"), histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="f"), histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) else: plot = plots.PlotBase([ histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) plot.setLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355)) plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.9, limit.process, size=size) histograms.addText(x, 0.863, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size) histograms.addText(x, 0.775, limit.BRassumption, size=size) histograms.addText(x, 0.735, "#mu=%d %s" % (mu, limit.massUnit()), size=size) plot.save()
def doPlot(rootfile): f = ROOT.TFile.Open(rootfile) basename = rootfile.replace(".root", "") match = name_re.search(rootfile) if not match: raise Exception("Assert: the file name regex did not match") mass = match.group("mass") name = match.group("name") canvas = f.Get("c1") primitives = canvas.GetListOfPrimitives() # Suppress the warning message of missing dictionary for some iterator backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError primiter = primitives.MakeIterator() ROOT.gErrorIgnoreLevel = backup graph = None expoFit = None lines = [] obj = primiter.Next() while obj: # print obj, obj.GetName() if isinstance(obj, ROOT.TGraph): if graph != None: raise Exception("Assert: graph was already found") graph = obj elif isinstance(obj, ROOT.TF1): if expoFit != None: raise Exception("Assert: expoFit was already found") expoFit = obj elif isinstance(obj, ROOT.TLine): lines.append(obj) obj = primiter.Next() if graph == None: raise Exception("Assert: did not find any TGraph") if expoFit == None: raise Exception("Assert: did not find any TF1") plot = plots.PlotBase( [histograms.HistoGraph(graph, "CLs", drawStyle="PE")]) plot.createFrame(basename, opts={ "xmin": 0, "ymin": 0, "ymaxfactor": 1.1, "xmaxlist": [0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.15, 0.2] }) plot.frame.GetXaxis().SetTitle("#mu") plot.frame.GetXaxis().SetNdivisions(1005) plot.frame.GetYaxis().SetTitle("CL_{s}") expoFit.SetLineColor(ROOT.kBlue - 9) # skip the vertical non-solid lines lines = filter(lambda l: l.GetLineStyle() == 1 or l.GetX1() != l.GetX2(), lines) plot.prependPlotObject(expoFit) for l in lines: plot.appendPlotObject(l) plot.draw() labelName = { "observed": "Observed", "median": "Expected median", "1sigma": "Expected +1#sigma", "2sigma": "Expected +2#sigma", "-1sigma": "Expected .1#sigma", "-2sigma": "Expected -2#sigma" }[name] size = 20 x = 0.62 histograms.addText(x, 0.85, "m_{H^{+}} = %s %s" % (mass, limit.massUnit()), size=size) histograms.addText(x, 0.81, labelName, size=size) plot.save() f.Close() f.Delete()
def PlotEfficiency(datasetsMgr, datasetsMgr40, intLumi): # Definitions myList = [] dataset_TT = datasetsMgr.getDataset("TT") dataset40_TT = datasetsMgr40.getDataset("TT") dataset_QCD = datasetsMgr.getDataset("QCD") dataset40_QCD = datasetsMgr40.getDataset("QCD") # Efficiency hNumerator = os.path.join(opts.folder, "AllTopQuarkPt_MatchedBDT") hDenominator = os.path.join(opts.folder, "TopQuarkPt") #AllTopQuarkPt_Matched n_TT = dataset40_TT.getDatasetRootHisto(hNumerator) n_TT.normalizeToLuminosity(intLumi) num40_TT = n_TT.getHistogram() d_TT = dataset40_TT.getDatasetRootHisto(hDenominator) d_TT.normalizeToLuminosity(intLumi) den40_TT = d_TT.getHistogram() # Misidentification rate hNumerator = os.path.join(opts.folder, "TrijetFakePt_BDT") hDenominator = os.path.join(opts.folder, "TrijetFakePt") n_QCD = dataset40_QCD.getDatasetRootHisto(hNumerator) n_QCD.normalizeToLuminosity(intLumi) num40_QCD = n_QCD.getHistogram() d_QCD = dataset40_QCD.getDatasetRootHisto(hDenominator) d_QCD.normalizeToLuminosity(intLumi) den40_QCD = d_QCD.getHistogram() # Customise binning _kwargs = GetHistoKwargs(opts) if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num40_TT = num40_TT.Rebin(nx, "", xBins) den40_TT = den40_TT.Rebin(nx, "", xBins) num40_QCD = num40_QCD.Rebin(nx, "", xBins) den40_QCD = den40_QCD.Rebin(nx, "", xBins) # Calculate efficiency eff40_TT = ROOT.TEfficiency(num40_TT, den40_TT) eff40_TT.SetStatisticOption(ROOT.TEfficiency.kFCP) eff40_QCD = ROOT.TEfficiency(num40_QCD, den40_QCD) eff40_QCD.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff40_TT = convert2TGraph(eff40_TT) eff40_QCD = convert2TGraph(eff40_QCD) styles.ttStyle.apply(eff40_TT) styles.qcdStyle.apply(eff40_QCD) # Append in list gEff40_TT = histograms.HistoGraph(eff40_TT, "t#bar{t}", "lp", "P") #gEff40_QCD = histograms.HistoGraph(eff40_QCD, "QCD multijet", "lp", "P") gEff40_QCD = histograms.HistoGraph(eff40_QCD, "QCD", "lp", "P") myList.append(gEff40_TT) myList.append(gEff40_QCD) # Define save name saveName = "TopTagEfficiency" # Plot the efficiency #p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) p = plots.ComparisonManyPlot(gEff40_TT, [gEff40_QCD], saveFormats=[]) #p = plots.ComparisonPlot(gEff40_TT, gEff40_QCD, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) # Save plot in all formats savePath = os.path.join(opts.saveDir, opts.optMode) save_path = os.path.join(savePath, "BDT0p40") SavePlot(p, saveName, save_path, saveFormats=[".png", ".C", ".pdf"]) return
def doPlot(): # Import the auto-generated file containing the transfer factors sys.path.append(opts.mcrab) import FakeBTransferFactors_Run2016_80to1000 as tf QCDNormalization = { "Inclusive": 0.441958, "1": 0.524575, "0": 0.600980, "3": 0.363374, "2": 0.457656, "5": 0.229395, "4": 0.315185, } xval = [] xerrl = [] xerrh = [] yval = [] yerrl = [] yerrh = [] # Fill TGraph arrays for i, k in enumerate(tf.QCDNormalization): xval.append(k) xerrl.append(0.001) xerrh.append(0.001) yval.append(QCDNormalization[k]) yerrl.append(0.01 * QCDNormalization[k]) yerrh.append(0.01 * QCDNormalization[k]) # Create TGraph object tgraph = ROOT.TGraphAsymmErrors(len(xval), array.array("d", xval), array.array("d", yval), array.array("d", xerrl), array.array("d", xerrh), array.array("d", yerrl), array.array("d", yerrh)) # Apply styles setNominalStyle(tgraph) # Convert the TGraphs to HistoGraphs and append to a list graphs = [] graphs.extend([ #histograms.HistoGraph(tgraph, "Nominal", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(tgraph, "Nominal", drawStyle="P", legendStyle="LP"), ]) # Plot the TGraphs saveFormats = [".png", ".C", ".pdf"] plot = plots.PlotBase(graphs, saveFormats=saveFormats) plot.setLuminosity(opts.intLumi) # Customise legend entries plot.histoMgr.setHistoLegendLabelMany({ #"Nominal" : "R_{i} #pm #sigma_{R_{i}}", "Nominal": "Nominal #pm Stat.", }) # Create legend xPos = 0.65 legend = getLegend(opts, xPos) plot.setLegend(legend) # Create a frame to be able to impose custom x- and y- range if opts.yMin != -1 and opts.yMax != -1: plot.createFrame("dumbie", opts={"ymin": opts.yMin, "ymax": opts.yMax}) elif opts.yMin != -1: plot.createFrame("dumbie", opts={"ymin": opts.yMin}) elif opts.yMax != -1: plot.createFrame("dumbie", opts={"ymax": opts.yMax}) else: plot.createFrame("dumbie", saveFormats=[]) # Add cut box? if opts.cutLine > 0: kwargs = {"greaterThan": True} plot.addCutBoxAndLine(cutValue=opts.cutLine, fillColor=ROOT.kRed, box=False, line=True, **kwargs) # Set x-axis title plot.frame.GetXaxis().SetTitle("bin") plot.frame.GetYaxis().SetTitle("transfer factor (R_{i})") # Enable/Disable logscale for axes plot.getPad().SetLogy(opts.logY) plot.getPad().SetLogx(opts.logX) # Enable grids in x and y? plot.getPad().SetGridx(opts.gridX) plot.getPad().SetGridy(opts.gridY) # Draw the plot with standard texts plot.draw() plot.addStandardTexts() # Add text on canvas if 0: histograms.addText(0.55, 0.84, "fully hadronic final state", size=20) # Save the canvas plot.save() # Save the plots SavePlot(plot, "transferFactors", os.path.join(opts.saveDir, "")) return
def main(opts): optModes = [""] if opts.optMode != None: optModes = [opts.optMode] # For-loop: All optimisation modes for opt in optModes: opts.optMode = opt # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts) datasetsMgr.updateNAllEventsToPUWeighted() datasetsMgr.loadLuminosities() # from lumi.json if opts.verbose: datasetsMgr.PrintCrossSections() datasetsMgr.PrintLuminosities() # Set/Overwrite cross-sections for d in datasetsMgr.getAllDatasets(): #if "ChargedHiggs_HplusTB_HplusToTB_M_%s" % (opts.signalMass) in d.getName(): if "ChargedHiggs_HplusTB_HplusToTB_M_" in d.getName(): datasetsMgr.getDataset(d.getName()).setCrossSection(1.0) else: datasetsMgr.remove(d.getName()) # Determine integrated Lumi before removing data if "Data" in datasetsMgr.getAllDatasetNames(): opts.intLumi = datasetsMgr.getDataset("Data").getLuminosity() else: opts.intLumi = 35920 # Merge histograms (see NtupleAnalysis/python/tools/plots.py) plots.mergeRenameReorderForDataMC(datasetsMgr) # Re-order datasets datasetOrder = [] for d in datasetsMgr.getAllDatasets(): if str(opts.signalMass) not in d.getName(): continue datasetOrder.append(d.getName()) # Print dataset information datasetsMgr.PrintInfo() # Apply TDR style style = tdrstyle.TDRStyle() style.setGridX(False) style.setGridY(False) # Do the histograms if opts.signalMass > -1: r = Fit_Gaus(datasetsMgr, opts.signalMass) else: align = "{:>25} {:>10} {:>10}" title = align.format("m_{H^{+}}", "FWHM", "Error") hLine = 50 * "=" table = [] table.append(hLine) table.append(title) table.append(hLine) const = 2 * math.sqrt(2 * math.log(2)) y = [] xerrl = [] xerrh = [] yerrl = [] yerrh = [] mass = [] for d in datasetsMgr.getAllDatasets(): if "Charged" in d.getName(): dName = d.getName() signalmass = dName.replace( "ChargedHiggs_HplusTB_HplusToTB_M_", "") signalmass = int(signalmass) if (signalmass == 180): continue r = Fit_Gaus(datasetsMgr, signalmass) mass.append(signalmass) sigma = r.Parameter(2) sigmaerror = r.ParError(2) y.append(const * sigma) xerrl.append(0.0) xerrh.append(0.0) yerrl.append(const * sigmaerror) yerrh.append(const * sigmaerror) table.append( align.format(" %.0f & " % (signalmass), " %.2f & " % (const * sigma), "+/- %.2f" % (const * sigmaerror))) table.append(hLine) # Print values for row in table: print row tgraph = ROOT.TGraphAsymmErrors(len(mass), array.array("d", mass), array.array("d", y), array.array("d", xerrl), array.array("d", xerrh), array.array("d", yerrl), array.array("d", yerrh)) testSigma = 0 if testSigma: tgraph_s = ROOT.TGraphAsymmErrors(len(mass), array.array("d", mass), array.array("d", sigma), array.array("d", xerrl), array.array("d", xerrh), array.array("d", sigmaerror), array.array("d", sigmaerror)) counter = 4 styles.markerStyles[counter].apply(tgraph) legend = " " hlist = [] saveName = "HPlusMass_vs_FWHM" ytitle = "Width (GeV/c^{2})" if testSigma: styles.markerStyles[2].apply(tgraph_s) styles.markerStyles[1].apply(tgraph_mu) hlist.append( histograms.HistoGraph(tgraph_s, "#sigma", "lp", "P")) hlist.append( histograms.HistoGraph(tgraph, "FWHM = 2*#sqrt{2ln2}#sigma", "lp", "P")) saveName = "HPlusMass_vs_Width" ytitle = "Width (GeV/c^{2})" else: hlist.append(histograms.HistoGraph(tgraph, legend, "", "P")) p = plots.PlotBase(datasetRootHistos=hlist, saveFormats=[]) _kwargs = { "xlabel": "m_{H^{+}} (GeV/c^{2})", "ylabel": ytitle, #"Width (GeV/c^{2})", #/ %.1f ", "ratioYlabel": "Ratio", "ratio": False, "ratioInvert": False, "stackMCHistograms": False, "addMCUncertainty": False, "addLuminosityText": False, "addCmsText": True, "cmsExtraText": "Preliminary", #"opts" : {"ymin": 0.0, "ymax": 1.09}, "opts": { "xmin": 150, "xmax": 950, "ymin": 0.0, "ymaxfactor": 1.2 }, "opts2": { "ymin": 0.6, "ymax": 1.4 }, "log": False, "moveLegend": { "dx": -0.25, "dy": -0.005, "dh": -0.2 }, "cutBoxY": { "cutValue": 1.0, "fillColor": 16, "box": False, "line": False, "greaterThan": True, "mainCanvas": True, "ratioCanvas": False } } plots.drawPlot(p, saveName, **_kwargs) SavePlot(p, saveName, opts.saveDir, saveFormats=[".png", ".pdf", ".C"]) return
def PlotEfficiency_comparison(datasetsMgr, datasetsMgr30, datasetsMgr40, datasetsMgr60, datasetsMgr80, datasetsMgr90, numPath, denPath, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets #for dataset in datasetsMgr.getAllDatasets(): if 1: #if "Fake" in numPath: # return dataset = datasetsMgr.getDataset("TT") dataset30 = datasetsMgr30.getDataset("TT") dataset40 = datasetsMgr40.getDataset("TT") #dataset50 = datasetsMgr50.getDataset("TT") dataset60 = datasetsMgr60.getDataset("TT") #dataset70 = datasetsMgr70.getDataset("TT") dataset80 = datasetsMgr80.getDataset("TT") dataset90 = datasetsMgr90.getDataset("TT") #dataset95 = datasetsMgr95.getDataset("TT") if "Fake" in numPath: dataset = datasetsMgr.getDataset("QCD") dataset30 = datasetsMgr30.getDataset("QCD") dataset40 = datasetsMgr40.getDataset("QCD") #dataset50 = datasetsMgr50.getDataset("QCD") dataset60 = datasetsMgr60.getDataset("QCD") #dataset70 = datasetsMgr70.getDataset("QCD") dataset80 = datasetsMgr80.getDataset("QCD") dataset90 = datasetsMgr90.getDataset("QCD") #dataset95 = datasetsMgr95.getDataset("QCD") legend = "BDTG > 0.85" legend30 = "BDTG > 0.30" legend40 = "BDTG > 0.40" legend50 = "BDTG > 0.50" legend60 = "BDTG > 0.60" legend70 = "BDTG > 0.70" legend80 = "BDTG > 0.80" legend90 = "BDTG > 0.90" legend95 = "BDTG > 0.95" #styleDef = styles.ttStyle style30 = styles.ttStyle #styles.signalStyleHToTB180 style40 = styles.signalStyleHToTB500 #800 style50 = styles.signalStyleHToTB500 style60 = styles.signalStyleHToTB1000 style70 = styles.signalStyleHToTB2000 style80 = styles.signalStyleHToTB300 style90 = styles.signalStyleHToTB3000 style95 = styles.signalStyleHToTB200 n = dataset30.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num30 = n.getHistogram() d = dataset30.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den30 = d.getHistogram() #========================================= n = dataset40.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num40 = n.getHistogram() d = dataset40.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den40 = d.getHistogram() #========================================= n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() #========================================= #n = dataset50.getDatasetRootHisto(numPath) #n.normalizeToLuminosity(intLumi) #num50 = n.getHistogram() #d = dataset50.getDatasetRootHisto(denPath) #d.normalizeToLuminosity(intLumi) #den50 = d.getHistogram() #========================================= n = dataset60.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num60 = n.getHistogram() d = dataset60.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den60 = d.getHistogram() #========================================= #n = dataset70.getDatasetRootHisto(numPath) #n.normalizeToLuminosity(intLumi) #num70 = n.getHistogram() #d = dataset70.getDatasetRootHisto(denPath) #d.normalizeToLuminosity(intLumi) #den70 = d.getHistogram() #========================================= n = dataset80.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num80 = n.getHistogram() d = dataset80.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den80 = d.getHistogram() #========================================= n = dataset90.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num90 = n.getHistogram() d = dataset90.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den90 = d.getHistogram() #========================================= #n = dataset95.getDatasetRootHisto(numPath) #n.normalizeToLuminosity(intLumi) #num95 = n.getHistogram() #d = dataset95.getDatasetRootHisto(denPath) #d.normalizeToLuminosity(intLumi) #den95 = d.getHistogram() #num = dataset.getDatasetRootHisto(numPath).getHistogram() #den = dataset.getDatasetRootHisto(denPath).getHistogram() #num50 = dataset50.getDatasetRootHisto(numPath).getHistogram() #den50 = dataset50.getDatasetRootHisto(denPath).getHistogram() #num60 = dataset60.getDatasetRootHisto(numPath).getHistogram() #den60 = dataset60.getDatasetRootHisto(denPath).getHistogram() #num70 = dataset70.getDatasetRootHisto(numPath).getHistogram() #den70 = dataset70.getDatasetRootHisto(denPath).getHistogram() #num80 = dataset80.getDatasetRootHisto(numPath).getHistogram() #den80 = dataset80.getDatasetRootHisto(denPath).getHistogram() #num90 = dataset90.getDatasetRootHisto(numPath).getHistogram() #den90 = dataset90.getDatasetRootHisto(denPath).getHistogram() #num95 = dataset95.getDatasetRootHisto(numPath).getHistogram() #den95 = dataset95.getDatasetRootHisto(denPath).getHistogram() if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) num30 = num30.Rebin(nx, "", xBins) den30 = den30.Rebin(nx, "", xBins) num40 = num40.Rebin(nx, "", xBins) den40 = den40.Rebin(nx, "", xBins) #num50 = num50.Rebin(nx, "", xBins) #den50 = den50.Rebin(nx, "", xBins) num60 = num60.Rebin(nx, "", xBins) den60 = den60.Rebin(nx, "", xBins) #num70 = num70.Rebin(nx, "", xBins) #den70 = den70.Rebin(nx, "", xBins) num80 = num80.Rebin(nx, "", xBins) den80 = den80.Rebin(nx, "", xBins) num90 = num90.Rebin(nx, "", xBins) den90 = den90.Rebin(nx, "", xBins) #num95 = num95.Rebin(nx, "", xBins) #den95 = den95.Rebin(nx, "", xBins) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: # continue return if num.GetEntries() > den.GetEntries(): # continue return # Remove negative bins and ensure numerator bin <= denominator bin #CheckNegatives(num, den, True) #CheckNegatives(num50, den50, True) #CheckNegatives(num60, den60, True) #CheckNegatives(num70, den70, True) #CheckNegatives(num80, den80, True) #CheckNegatives(num90, den90, True) #CheckNegatives(num95, den95, True) # RemoveNegatives(num) # RemoveNegatives(den) # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats #eff85 = ROOT.TEfficiency(num, den) # fixme: investigate warnings #eff85.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff30 = ROOT.TEfficiency(num30, den30) # fixme: investigate warnings eff30.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff40 = ROOT.TEfficiency(num40, den40) # fixme: investigate warnings eff40.SetStatisticOption(ROOT.TEfficiency.kFCP) # #eff50 = ROOT.TEfficiency(num50, den50) # fixme: investigate warnings #eff50.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff60 = ROOT.TEfficiency(num60, den60) # fixme: investigate warnings eff60.SetStatisticOption(ROOT.TEfficiency.kFCP) # #eff70 = ROOT.TEfficiency(num70, den70) # fixme: investigate warnings #eff70.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff80 = ROOT.TEfficiency(num80, den80) # fixme: investigate warnings eff80.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff90 = ROOT.TEfficiency(num90, den90) # fixme: investigate warnings eff90.SetStatisticOption(ROOT.TEfficiency.kFCP) # #eff95 = ROOT.TEfficiency(num95, den95) # fixme: investigate warnings #eff95.SetStatisticOption(ROOT.TEfficiency.kFCP) # eff30 = convert2TGraph(eff30) eff40 = convert2TGraph(eff40) #eff50 = convert2TGraph(eff50) eff60 = convert2TGraph(eff60) # eff70 = convert2TGraph(eff70) eff80 = convert2TGraph(eff80) #eff85 = convert2TGraph(eff85) eff90 = convert2TGraph(eff90) #eff95 = convert2TGraph(eff95) # Apply default style (according to dataset name) #plots._plotStyles[dataset.getName()].apply(eff) style40.apply(eff40) style30.apply(eff30) #style40.apply(eff40) #style50.apply(eff50) style60.apply(eff60) #style70.apply(eff70) style80.apply(eff80) style90.apply(eff90) #style95.apply(eff95) #eff50.SetLineStyle(ROOT.kSolid) #eff50.SetLineWidth(2) eff30.SetLineWidth(2) eff40.SetLineWidth(2) eff60.SetLineWidth(2) #eff70.SetLineWidth(2) eff80.SetLineWidth(2) #eff85.SetLineWidth(2) eff90.SetLineWidth(2) #eff95.SetLineWidth(2) #eff30.SetLineColor(1) #eff50.SetLineStyle(ROOT.kSolid) eff30.SetLineStyle(ROOT.kSolid) eff40.SetLineStyle(ROOT.kSolid) eff60.SetLineStyle(ROOT.kSolid) # eff70.SetLineStyle(ROOT.kSolid) eff80.SetLineStyle(ROOT.kSolid) #eff85.SetLineStyle(ROOT.kSolid) eff90.SetLineStyle(ROOT.kSolid) #eff95.SetLineStyle(ROOT.kSolid) eff30.SetMarkerStyle(ROOT.kFullTriangleUp) eff40.SetMarkerStyle(ROOT.kFullTriangleUp) #eff50.SetMarkerStyle(ROOT.kFullTriangleUp) eff60.SetMarkerStyle(ROOT.kFullTriangleUp) #eff70.SetMarkerStyle(ROOT.kFullTriangleUp) eff80.SetMarkerStyle(ROOT.kFullTriangleUp) #eff85.SetMarkerStyle(ROOT.kFullTriangleUp) eff90.SetMarkerStyle(ROOT.kFullTriangleUp) #eff95.SetMarkerStyle(ROOT.kFullTriangleUp) eff30.SetMarkerSize(1.2) eff40.SetMarkerSize(1.2) #eff50.SetMarkerSize(1.2) eff60.SetMarkerSize(1.2) # eff70.SetMarkerSize(1.2) eff80.SetMarkerSize(1.2) #eff85.SetMarkerSize(1.2) eff90.SetMarkerSize(1.2) #eff95.SetMarkerSize(1.2) # Append in list # myList.append(histograms.HistoGraph(eff, plots._legendLabels["Default"], "lp", "P")) myList.append(histograms.HistoGraph(eff30, legend30, "lp", "P")) myList.append(histograms.HistoGraph(eff40, legend40, "lp", "P")) #myList.append(histograms.HistoGraph(eff50, legend50, "lp", "P")) myList.append(histograms.HistoGraph(eff60, legend60, "lp", "P")) #myList.append(histograms.HistoGraph(eff70, legend70, "lp", "P")) myList.append(histograms.HistoGraph(eff80, legend80, "lp", "P")) #myList.append(histograms.HistoGraph(eff85, legend, "lp", "P")) myList.append(histograms.HistoGraph(eff90, legend90, "lp", "P")) #myList.append(histograms.HistoGraph(eff95, legend95, "lp", "P")) # Define save name saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split( "/")[-1] print "here1" # Plot the efficiency p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) print "here2" plots.drawPlot(p, saveName, **_kwargs) leg = ROOT.TLegend(0.2, 0.8, 0.81, 0.87) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetBorderSize(0) #{"dx": -0.55, "dy": -0.55, "dh": -0.08} leg.SetHeader("t#bar{t}") if "Fake" in numPath: leg.SetHeader("QCD") leg.Draw() #moveLegend = {"dx": -0.0, "dy": +0.0, "dh": +0.1} #moveLegend = {"dx": -0.1, "dy": +0.0, "dh": +0.1} #p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # Save plot in all formats savePath = os.path.join(opts.saveDir, "HplusMasses", numPath.split("/")[0], opts.optMode) #savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut SavePlot(p, saveName, save_path, saveFormats=[".png", ".pdf", ".C"]) return
def 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 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 doPlotSigmaBands(limits, legendLabels, saveName, _opts={}): # Define graphs to be used graphs = [ histograms.HistoGraph(limits[0].expectedGraph(), "Expected", drawStyle="L"), histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"), ] # Set line style graphs[0].getRootHisto().SetLineStyle(ROOT.kSolid) # Create plot base object plot = plots.PlotBase(graphs) ll = { "Expected": None, "Expected1": "%s #pm 1#sigma" % legendLabels[0], "Expected2": "%s #pm 2#sigma" % legendLabels[0], #"Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0], #"Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0], } stGen = styles.generator() nLimits = len(limits) # For-loop: All limits for i in xrange(1, nLimits): name = "Exp%d" % i gr = histograms.HistoGraph(limits[i].expectedGraph(), name, drawStyle="L") stGen(gr) gr.getRootHisto().SetLineWidth(3) gr.getRootHisto().SetLineStyle(1) plot.histoMgr.insertHisto(len(plot.histoMgr) - 2, gr, legendIndex=len(plot.histoMgr)) ll[name] = "%s" % legendLabels[i] # "%s exp. median" % legendLabels[i] # Set histo labels plot.histoMgr.setHistoLegendLabelMany(ll) # Create & set legend nGraphs = len(graphs) # If sigma bands are drawn each legend entry is plotted twice. Correct this in the count if "Sigma1" in name or "Sigma2" in name: nGraphs = nGraphs / 2.0 legend = getLegend(nGraphs + 4, limit, xPosLeg) plot.setLegend(legend) # Determine save name, minimum and maximum of y-axis ymin, ymax, saveName = getYMinMaxAndName(limits, saveName) if _opts.yMin == -1: _opts.yMin = ymin if _opts.yMax == -1: _opts.yMax = ymax # Create the frame and set axes titles plot.createFrame(saveName, opts={"ymin": _opts.yMin, "ymax": _opts.yMax}) # Add cut line? if _opts.cutLine != 999.9: kwargs = {"greaterThan": True} plot.addCutBoxAndLine(cutValue=_opts.cutLine, fillColor=ROOT.kRed, box=False, line=True, **kwargs) if opts.cutLineY != 999.9: kwargs = { "greaterThan": True, "mainCanvas": True, "ratioCanvas": False } plot.addCutBoxAndLineY(cutValue=_opts.cutLineY, fillColor=ROOT.kRed, box=False, line=True, **kwargs) # Set axes titles plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle(limit.BRlimit) # Enable/Disable logscale for axes ROOT.gPad.SetLogy(_opts.logY) ROOT.gPad.SetLogx(_opts.logX) # Draw the plot with standard texts plot.draw() plot.addStandardTexts(cmsTextPosition="outframe") plot.setLuminosity(limits[0].getLuminosity()) addPhysicsText(histograms, limit, x=xPosText) # Save the plots & return SavePlot(plot, _opts.saveDir, saveName, [".png"]) #, ".pdf"]) return
def doLimitError(limits, unblindedStatus): expRelErrors = [] expLabels = {} obsRelErrors = [] obsLabels = {} order = [0, 1, -1, 2, -2] expErrors = [limits.expectedErrorGraph(sigma=s) for s in order] if expErrors[0] != None: exps = [limits.expectedGraph(sigma=s) for s in order] expRelErrors = [(limit.divideGraph(expErrors[i], exps[i]), "ExpRelErr%d" % i) for i in xrange(len(exps))] expLabels = { "ExpRelErr0": "Expected median", "ExpRelErr1": "Expected +1#sigma", "ExpRelErr2": "Expected -1#sigma", "ExpRelErr3": "Expected +2#sigma", "ExpRelErr4": "Expected -2#sigma", } if unblindedStatus: obsErr = limits.observedErrorGraph() if obsErr != None: obs = limits.observedGraph() if obs != None: obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")] obsLabels = {"ObsRelErr": "Observed"} if len(expRelErrors) == 0 and len(obsRelErrors) == 0: return # Create the plot plot = plots.PlotBase() if len(expRelErrors) > 0: plot.histoMgr.extendHistos([ histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp") for x in expRelErrors ]) plot.histoMgr.forEachHisto(styles.generator()) def sty(h): r = h.getRootHisto() r.SetLineStyle(1) r.SetLineWidth(3) r.SetMarkerSize(1.4) plot.histoMgr.forEachHisto(sty) plot.histoMgr.setHistoLegendLabelMany(expLabels) if unblindedStatus: if len(obsRelErrors) > 0: obsRelErrors[0][0].SetMarkerSize(1.4) obsRelErrors[0][0].SetMarkerStyle(25) plot.histoMgr.insertHisto( 0, histograms.HistoGraph(obsRelErrors[0][0], obsRelErrors[0][1], drawStyle="PL", legendStyle="lp")) plot.histoMgr.setHistoLegendLabelMany(obsLabels) plot.setLegend( histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=0.1, dy=-0.1)) if len(limits.mass) == 1: plot.createFrame("limitsBrRelativeUncertainty", opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": 0, "ymaxfactor": 1.5 }) else: plot.createFrame("limitsBrRelativeUncertainty", opts={ "ymin": 0, "ymaxfactor": 1.5 }) plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle("Uncertainty/limit") plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() size = 20 x = 0.2 histograms.addText(x, 0.88, limit.process, size=size) histograms.addText(x, 0.84, limits.getFinalstateText(), size=size) histograms.addText(x, 0.79, limit.BRassumption, size=size) size = 22 x = 0.55 histograms.addText(x, 0.88, "Toy MC relative", size=size) histograms.addText(x, 0.84, "statistical uncertainty", size=size) plot.save()
def doBRlimit(limits, unblindedStatus, opts, log=False): leptonicFS = False graphs = [] if unblindedStatus: gr = limits.observedGraph() if gr != None: gr.SetPoint(gr.GetN() - 1, gr.GetX()[gr.GetN() - 1] - 1e-10, gr.GetY()[gr.GetN() - 1]) if opts.excludedArea: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle=None)) excluded = gr.Clone() excluded.SetPoint(excluded.GetN(), excluded.GetX()[excluded.GetN() - 1], 0.05) excluded.SetPoint(excluded.GetN(), excluded.GetX()[0], 0.05) limit.setExcludedStyle(excluded) graphs.append( histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="lpf", legendLabel="Observed")) else: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle="lp")) graphs.extend([ histograms.HistoGraph(limits.expectedGraph(), "Expected", drawStyle="L"), histograms.HistoGraph(limits.expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(limits.expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"), ]) saveFormats = [".png", ".C", ".pdf"] if not opts.excludedArea: saveFormats.append(".eps") plot = plots.PlotBase(graphs, saveFormats=saveFormats) plot.setLuminosity(limits.getLuminosity()) plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) dy = -0.1 limit.BRassumption = "" #limit.BRassumption = "Assuming B(H^{+}#rightarrow#tau^{+}#nu_{#tau}) = 1" #limit.BRassumption = "Assuming B(H^{+}#rightarrowt#bar{b}) = 1" if limit.BRassumption != "": dy -= 0.05 #if len(limits.getFinalstates()) > 1: # dy -= 0.1 # Create legend x = 0.51 x = 0.45 legend = histograms.createLegend(x, 0.78 + dy, x + 0.4, 0.92 + dy) legend.SetMargin(0.17) # Make room for the final state text if opts.excludedArea: legend.SetFillStyle(1001) plot.setLegend(legend) name = "limitsBr" ymin = 0 ymax = limits.getFinalstateYmaxBR() #fixme: alexandros if opts.logx: name += "_logx" if log: name += "_log" if limits.isHeavyStatus: ymin = 1e-3 ymax = 10.0 if limit.BRassumption != "": ymax = 10.0 else: ymin = 1e-3 ymax = 4e-2 if leptonicFS: ymax = 10 if len(limits.mass) == 1: plot.createFrame(name, opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": ymin, "ymax": ymax }) else: plot.createFrame(name, opts={"ymin": ymin, "ymax": ymax}) # Set x-axis title plot.frame.GetXaxis().SetTitle(limit.mHplus()) if limits.isHeavyStatus: if limit.BRassumption != "": plot.frame.GetYaxis().SetTitle( "95% CL limit for #sigma_{H^{+}} (pb)") else: plot.frame.GetYaxis().SetTitle(limit.sigmaBRlimit) else: plot.frame.GetYaxis().SetTitle(limit.BRlimit) # Enable/Disable logscale for axes if log: plot.getPad().SetLogy(log) if opts.logx: plot.getPad().SetLogx(log) # Draw the plot with standard texts plot.draw() plot.addStandardTexts() # Add physics-process text size = 20 x = 0.51 x = 0.45 process = limit.process if limits.isHeavyStatus: process = limit.processHeavy histograms.addText(x, 0.88, process, size=size) # Add final-state text # histograms.addText(x, 0.84, limits.getFinalstateText(), size=size) #fixme: alexandros histograms.addText(x, 0.84, "fully hadronic final state", size=size) #fixme: alexandros # histograms.addText(x, 0.84, "#tau_{h}+jets and #mu#tau_{h} final states", size=size) # histograms.addText(x, 0.84, "#tau_{h}+jets final state", size=size) # histograms.addText(x, 0.84, "#tau_{h}+jets, #mu#tau_{h}, ee, e#mu, #mu#mu final states", size=size) if leptonicFS: histograms.addText(x, 0.84, "#mu#tau_{h}, ee, e#mu, #mu#mu final states", size=size) if limit.BRassumption != "": histograms.addText(x, 0.79, limit.BRassumption, size=size) plot.save() return
def createDrawPlot(gr, labels, fname): plot = plots.PlotBase( [histograms.HistoGraph(gr, "Fitted", drawStyle="P")]) plot.setLuminosity(lumi) canvasOpts = {} if len(labels) > 15: canvasOpts["addHeight"] = 0.03 * (len(labels) - 15) canvasOpts["addWidth"] = 0.2 plot.createFrame(fname, opts={ "ymin": 0, "xmin": -4.2, "xmax": 2.5 }, canvasOpts=canvasOpts) plot.getFrame().GetXaxis().SetTitle("Fitted value") scale = 1 if "addHeight" in canvasOpts: scale = 1 / (1 + canvasOpts["addHeight"]) plot.getFrame().GetXaxis().SetTickLength( plot.getFrame().GetXaxis().GetTickLength() * scale) plot.getPad().SetBottomMargin(plot.getPad().GetBottomMargin() * scale) plot.getPad().SetTopMargin(plot.getPad().GetTopMargin() * scale) if "addWidth" in canvasOpts: scale = 1 / (1 + canvasOpts["addWidth"]) #plot.getFrame().GetXaxis().SetTickLength(plot.getFrame().GetXaxis().GetTickLength()*scale) plot.getPad().SetRightMargin(0.04) plot.getPad().SetLeftMargin(0.04) plot.getPad().SetLeftMargin(plot.getPad().GetRightMargin()) plot.getPad().Update() ymin = plot.cf.frame.GetYaxis().GetXmin() ymax = plot.cf.frame.GetYaxis().GetXmax() for xval, color in [(0, ROOT.kRed), (-1, ROOT.kBlue), (1, ROOT.kBlue)]: l = ROOT.TLine(xval, ymin, xval, ymax) l.SetLineColor(color) l.SetLineStyle(ROOT.kDotted) l.SetLineWidth(2) plot.prependPlotObject(l) plot.cf.frame.GetYaxis().SetLabelSize(0) plot.draw() plot.addStandardTexts(cmsTextPosition="outframe") # Intentionally not NDC l = ROOT.TLatex() l.SetTextFont(l.GetTextFont() - 20) # bold->normal l.SetTextSize(17) x_nuis = -4.0 x_value = 1.5 l.DrawLatex(x_nuis, ymax * 0.93, "Nuisance parameter") l.DrawLatex(x_value, ymax * 0.93, "Fitted value") for i, label in enumerate(labels): y = gr.GetY()[i] - 0.3 l.DrawLatex(x_nuis, y, label[:40]) l.DrawLatex(x_value, y, "%.2f #pm %.2f" % (gr.GetX()[i], gr.GetErrorX(i))) plot.save()
def PlotHistos(d_noSF, d_withSF, num_histoList, den_histoList, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(num_histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CR1", "CR2"] labels = ["Genuine", "Fake", "Inclusive"] #========================================================================================== # Get Dictionaries #========================================================================================== rhDict_den_noSF = GetRootHistos(d_noSF, den_histoList, regions) rhDict_num_noSF = GetRootHistos(d_noSF, num_histoList, regions) rhDict_num_withSF = GetRootHistos(d_withSF, num_histoList, regions) # ========================================================================================= # Normalization Factors (see: getNormalization.py) # ========================================================================================= #f1=0.626877; f2=0.880767; f1 = 0.625454 f2 = 0.836566 #noTopPtRew #f1 = 0.626893; f2 = 0.880846; #noDeltaRqq #f1 = 0.625454; f2 = 0.836566; #noDeltaRqq, noTopPtRew # ========================================================================================= # (A) Apply Normalization Factors (see: getNormalizations.py) # ========================================================================================= # Normalize all histograms (QCD and TT) to normalization factors for re in regions: rhDict_den_noSF["NormQCD-" + re + "-Inclusive"] = rhDict_den_noSF[ "QCD-" + re + "-Inclusive"].Clone("NormQCD-" + re + "-Inclusive") rhDict_den_noSF["NormQCD-" + re + "-Inclusive"].Scale(f1) rhDict_num_noSF["NormQCD-" + re + "-Inclusive"] = rhDict_num_noSF[ "QCD-" + re + "-Inclusive"].Clone("NormQCD-" + re + "-Inclusive") rhDict_num_noSF["NormQCD-" + re + "-Inclusive"].Scale(f1) rhDict_num_withSF["NormQCD-" + re + "-Inclusive"] = rhDict_num_withSF[ "QCD-" + re + "-Inclusive"].Clone("NormQCD-" + re + "-Inclusive") rhDict_num_withSF["NormQCD-" + re + "-Inclusive"].Scale(f1) for la in labels: rhDict_den_noSF["NormTT-" + re + "-" + la] = rhDict_den_noSF["TT-" + re + "-" + la].Clone("NormTT-" + re + "-" + la) rhDict_den_noSF["NormTT-" + re + "-" + la].Scale(f2) rhDict_num_noSF["NormTT-" + re + "-" + la] = rhDict_num_noSF["TT-" + re + "-" + la].Clone("NormTT-" + re + "-" + la) rhDict_num_noSF["NormTT-" + re + "-" + la].Scale(f2) rhDict_num_withSF["NormTT-" + re + "-" + la] = rhDict_num_withSF["TT-" + re + "-" + la].Clone("NormTT-" + re + "-" + la) rhDict_num_withSF["NormTT-" + re + "-" + la].Scale(f2) # ========================================================================================= # (B) Estimate Inclusive TT in SR # ========================================================================================= # (B1) Inclusive TT in Data (Denominator) = Data - F1*QCD - EWK - ST rhDict_den_noSF["TTinData-SR-Inclusive"] = rhDict_den_noSF[ "Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)") rhDict_den_noSF["TTinData-SR-Inclusive"].Add( rhDict_den_noSF["NormQCD-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Inclusive"].Add( rhDict_den_noSF["EWK-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Inclusive"].Add( rhDict_den_noSF["SingleTop-SR-Inclusive"], -1) # (B2) Inclusive TT in Data (Numerator) = Data - (F1*QCD -EWK - ST)*SF rhDict_num_noSF["TTinData-SR-Inclusive"] = rhDict_num_noSF[ "Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)") rhDict_num_noSF["TTinData-SR-Inclusive"].Add( rhDict_num_withSF["NormQCD-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Inclusive"].Add( rhDict_num_withSF["EWK-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Inclusive"].Add( rhDict_num_withSF["SingleTop-SR-Inclusive"], -1) # ========================================================================================== # (C) Plot Inclusive Efficiency (Data Vs MC) # ========================================================================================== _kwargs["opts"] = {"xmax": 800, "ymaxfactor": 2.0} _kwargs["ratioYlabel"] = "Data/MC" _kwargs["ratio"] = True _kwargs["stackMCHistograms"] = False _kwargs["createLegend"] = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92} _kwargs["ratioInvert"] = True num_data = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone( "t#bar{t}_{SR} (Data)") den_data = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone( "t#bar{t}_{SR} (Data)") num_mc = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)") den_mc = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)") num_data.Rebin(2) num_mc.Rebin(2) den_data.Rebin(2) den_mc.Rebin(2) styles.getABCDStyle("CR4").apply(num_mc) styles.getABCDStyle("CR4").apply(den_mc) # Denominator hName = "InclusiveTT_SR_Denominator" hData_Den = histograms.Histo(den_data, "t#bar{t}_{SR} (Data)", "Data", drawStyle="AP") hData_Den.setIsDataMC(isData=True, isMC=False) hMC_Den = histograms.Histo(den_mc, "t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST") hMC_Den.setIsDataMC(isData=False, isMC=True) pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[]) pDen.setLuminosity(opts.intLumi) pDen.setDefaultStyles() plots.drawPlot(pDen, hName, **_kwargs) SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png"]) # Numerator hName = "InclusiveTT_SR_Numerator" hData_Num = histograms.Histo(num_data, "t#bar{t}_{SR} (Data)", "Data", drawStyle="AP") hData_Num.setIsDataMC(isData=True, isMC=False) hMC_Num = histograms.Histo(num_mc, "t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST") hMC_Num.setIsDataMC(isData=False, isMC=True) pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[]) pNum.setLuminosity(opts.intLumi) pNum.setDefaultStyles() plots.drawPlot(pNum, hName, **_kwargs) SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png"]) # ========================= # Inclusive Efficiency # ========================= _kwargs = { "xlabel": "p_{T} (GeV/c)", "ylabel": "Efficiency", "ratioYlabel": "Data/MC", "ratio": True, "ratioInvert": False, "ratioType": None, "ratioCreateLegend": True, "ratioMoveLegend": { "dx": -0.51, "dy": 0.03, "dh": -0.08 }, "ratioErrorOptions": { "numeratorStatSyst": False, "denominatorStatSyst": False }, "errorBarsX": True, "stackMCHistograms": False, "addMCUncertainty": False, "addLuminosityText": False, "addCmsText": True, "cmsExtraText": "Preliminary", "opts": { "ymin": 0.0, "ymaxfactor": 1.5, "xmax": 600 }, "opts2": { "ymin": 0.6, "ymax": 1.5 }, "log": False, "createLegend": { "x1": 0.64, "y1": 0.80, "x2": 0.95, "y2": 0.92 }, } _kwargs["cutBoxY"] = { "cutValue": 1.10, "fillColor": ROOT.kGray + 1, "fillStyle": 3001, "box": False, "line": True, "greaterThan": True, "mainCanvas": False, "ratioCanvas": True, "mirror": True } bins = [0, 100, 200, 300, 400, 500, 600] xBins = array.array('d', bins) nx = len(xBins) - 1 # Data h0_data_den = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone( "t#bar{t}_{SR} (Data)") h0_data_num = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone( "t#bar{t}_{SR} (Data)") # MC h0_mc_den = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)") h0_mc_num = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)") h0_data_den = h0_data_den.Rebin(nx, "", xBins) h0_data_num = h0_data_num.Rebin(nx, "", xBins) h0_mc_den = h0_mc_den.Rebin(nx, "", xBins) h0_mc_num = h0_mc_num.Rebin(nx, "", xBins) hNumerator_Data, hDenominator_Data = GetHistosForEfficiency( h0_data_num, h0_data_den) hNumerator_MC, hDenominator_MC = GetHistosForEfficiency( h0_mc_num, h0_mc_den) eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data) eff_mc = ROOT.TEfficiency(hNumerator_MC, hDenominator_MC) eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP) eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP) geff_data = convert2TGraph(eff_data) geff_mc = convert2TGraph(eff_mc) styles.dataStyle.apply(geff_data) styles.ttStyle.apply(geff_mc) Graph_Data = histograms.HistoGraph(geff_data, "t#bar{t}_{SR} (Data) ", "p", "P") Graph_MC = histograms.HistoGraph(geff_mc, "t#bar{t}_{SR} (MC)", "p", "P") p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[]) saveName = "Efficiency_InclusiveTT_SR" savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf", ".C"]) # Save results in JSON if (opts.inclusiveEff): name = opts.noSFcrab.split("_")[-4] name = name.replace(opts.analysisName, "") print "name = ", name jsonName = "toptagEff_BDT" + name + "_InclusiveTT_TopMassCut400.json" runRange = "273150-284044" analysis = opts.analysisName label = "2016" plotDir = os.path.join(opts.folder, jsonName) pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geff_data) pythonWriter.addMCParameters(label, geff_mc) fileName_json = jsonName pythonWriter.writeJSON(fileName_json) # ========================================================================================== # (D) Estimate Genuine TT in SR # ========================================================================================== # (D1) Genuine TT in Data - Denominator = Data - F1*QCD - F2*FakeTT - EWK - ST rhDict_den_noSF["TTinData-SR-Genuine"] = rhDict_den_noSF[ "Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") rhDict_den_noSF["TTinData-SR-Genuine"].Add( rhDict_den_noSF["NormQCD-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add( rhDict_den_noSF["NormTT-SR-Fake"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add( rhDict_den_noSF["EWK-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Genuine"].Add( rhDict_den_noSF["SingleTop-SR-Inclusive"], -1) # (D2) Genuine TT in Data - Numerator = Data - [F1*QCD - F2*FakeTT - ST - EWK] * SF rhDict_num_noSF["TTinData-SR-Genuine"] = rhDict_num_noSF[ "Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") rhDict_num_noSF["TTinData-SR-Genuine"].Add( rhDict_num_withSF["NormQCD-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add( rhDict_num_withSF["NormTT-SR-Fake"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add( rhDict_num_withSF["SingleTop-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Genuine"].Add( rhDict_num_withSF["EWK-SR-Inclusive"], -1) # ======================================================================================== # (E) Plot Numerator and Denominator (Data Vs MC) # ======================================================================================== _kwargs = GetHistoKwargs(num_histoList[0]) _kwargs["opts"] = {"xmax": 800, "ymaxfactor": 2.0} _kwargs["ratioYlabel"] = "Data/MC" _kwargs["ratio"] = True _kwargs["stackMCHistograms"] = False _kwargs["createLegend"] = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92} _kwargs["ratioInvert"] = True num_data.Reset() den_data.Reset() num_mc.Reset() den_mc.Reset() num_data = rhDict_num_noSF["TTinData-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (Data)") den_data = rhDict_den_noSF["TTinData-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (Data)") num_mc = rhDict_num_noSF["TT-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (MC)") den_mc = rhDict_den_noSF["TT-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (MC)") num_data.Rebin(2) num_mc.Rebin(2) den_data.Rebin(2) den_mc.Rebin(2) styles.getABCDStyle("CR4").apply(num_mc) styles.getABCDStyle("CR4").apply(den_mc) # Denominator hName = "GenuineTT_SR_Denominator" hData_Den = histograms.Histo(den_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP") hData_Den.setIsDataMC(isData=True, isMC=False) hMC_Den = histograms.Histo(den_mc, "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST") hMC_Den.setIsDataMC(isData=False, isMC=True) pDenumerator = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[]) pDenumerator.setLuminosity(opts.intLumi) pDenumerator.setDefaultStyles() plots.drawPlot(pDenumerator, hName, **_kwargs) SavePlot(pDenumerator, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png"]) # Numerator hName = "GenuineTT_SR_Numerator" hData_Num = histograms.Histo(num_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP") hData_Num.setIsDataMC(isData=True, isMC=False) hMC_Num = histograms.Histo(num_mc, "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST") hMC_Num.setIsDataMC(isData=False, isMC=True) pNumerator = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[]) pNumerator.setLuminosity(opts.intLumi) pNumerator.setDefaultStyles() plots.drawPlot(pNumerator, hName, **_kwargs) SavePlot(pNumerator, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png"]) # ======================================================================================== # (F) Plot Genuine TT Efficiency # ======================================================================================== _kwargs = { "xlabel": "p_{T} (GeV/c)", "ylabel": "Efficiency", "ratioYlabel": "Data/MC", "ratio": True, "ratioInvert": False, "ratioType": None, #"errorScale", "ratioCreateLegend": True, "ratioMoveLegend": { "dx": -0.51, "dy": 0.03, "dh": -0.08 }, "ratioErrorOptions": { "numeratorStatSyst": False, "denominatorStatSyst": False }, "errorBarsX": True, "stackMCHistograms": False, "addMCUncertainty": False, "addLuminosityText": False, "addCmsText": True, "cmsExtraText": "Preliminary", "opts": { "ymin": 0.0, "ymaxfactor": 1.25, "xmax": 600 }, "opts2": { "ymin": 0.55, "ymax": 1.55 }, "log": False, "createLegend": { "x1": 0.54, "y1": 0.80, "x2": 0.95, "y2": 0.92 }, } _kwargs["cutBoxY"] = { "cutValue": 1.10, "fillColor": ROOT.kGray + 1, "fillStyle": 3001, "box": False, "line": True, "greaterThan": True, "mainCanvas": False, "ratioCanvas": True, "mirror": True } bins = [0, 100, 200, 300, 400, 500, 600] xBins = array.array('d', bins) nx = len(xBins) - 1 # Data h1_data_den = rhDict_den_noSF["TTinData-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (Data)") h1_data_num = rhDict_num_noSF["TTinData-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (Data)") # MC h1_mc_den = rhDict_den_noSF["TT-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (MC)") h1_mc_num = rhDict_num_noSF["TT-SR-Genuine"].Clone( "genuine t#bar{t}_{SR} (MC)") h1_data_den = h1_data_den.Rebin(nx, "", xBins) h1_data_num = h1_data_num.Rebin(nx, "", xBins) h1_mc_den = h1_mc_den.Rebin(nx, "", xBins) h1_mc_num = h1_mc_num.Rebin(nx, "", xBins) h_Numerator_Data, h_Denominator_Data = GetHistosForEfficiency( h1_data_num, h1_data_den) h_Numerator_MC, h_Denominator_MC = GetHistosForEfficiency( h1_mc_num, h1_mc_den) effi_data = ROOT.TEfficiency(h_Numerator_Data, h_Denominator_Data) effi_mc = ROOT.TEfficiency(h_Numerator_MC, h_Denominator_MC) effi_data.SetStatisticOption(ROOT.TEfficiency.kFCP) effi_mc.SetStatisticOption(ROOT.TEfficiency.kFCP) geffi_data = convert2TGraph(effi_data) geffi_mc = convert2TGraph(effi_mc) styles.dataStyle.apply(geffi_data) styles.ttStyle.apply(geffi_mc) Graph_Data = histograms.HistoGraph(geffi_data, "genuine t#bar{t}_{SR} (Data) ", "p", "P") Graph_MC = histograms.HistoGraph(geffi_mc, "genuine t#bar{t}_{SR} (MC)", "p", "P") pp = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[]) saveName = "Efficiency_GenuineTT_SR" savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(pp, savePath, **_kwargs) SavePlot(pp, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf", ".C"]) # Save results in JSON if (not opts.inclusiveEff): name = opts.noSFcrab.split("_")[-4] name = name.replace(opts.analysisName, "") jsonName = "toptagEff_BDT" + name + "_GenuineTT_TopMassCut400.json" runRange = "273150-284044" analysis = opts.analysisName label = "2016" plotDir = os.path.join(opts.folder, jsonName) pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geffi_data) pythonWriter.addMCParameters(label, geffi_mc) fileName_json = jsonName pythonWriter.writeJSON(fileName_json) return
def doBRlimit(limits, unblindedStatus, opts, logy=False): graphs = [] if unblindedStatus: gr = limits.observedGraph() if gr != None: gr.SetPoint(gr.GetN() - 1, gr.GetX()[gr.GetN() - 1] - 1e-10, gr.GetY()[gr.GetN() - 1]) if opts.excludedArea: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle=None)) excluded = gr.Clone() excluded.SetPoint(excluded.GetN(), excluded.GetX()[excluded.GetN() - 1], 0.05) excluded.SetPoint(excluded.GetN(), excluded.GetX()[0], 0.05) limit.setExcludedStyle(excluded) graphs.append( histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle="lpf", legendLabel="Observed")) else: graphs.append( histograms.HistoGraph(gr, "Observed", drawStyle="PL", legendStyle="lp")) # Add the expected lines graphs.extend([ histograms.HistoGraph(limits.expectedGraph(), "Expected", drawStyle="L"), histograms.HistoGraph(limits.expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(limits.expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"), ]) # Plot the TGraphs saveFormats = [".png", ".C", ".pdf"] if not opts.excludedArea: saveFormats.append(".eps") plot = plots.PlotBase(graphs, saveFormats=saveFormats) plot.setLuminosity(limits.getLuminosity()) # Customise legend entries plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) # Branching Ratio Assumption if 0: limit.BRassumption = "Assuming B(H^{+}#rightarrowt#bar{b}) = 1" # Create legend xPos = 0.53 legend = getLegend(limit, opts, xPos) plot.setLegend(legend) # Get y-min, y-max, and histogram name to be saved as ymin, ymax, saveName = getYMinMaxAndName(limits, "limitsBr", logy, opts) if opts.yMin != -1: ymin = opts.yMin if opts.yMax != -1: ymax = opts.yMax if len(limits.mass) == 1: plot.createFrame(saveName, opts={ "xmin": limits.mass[0] - 5.0, "xmax": limits.mass[0] + 5.0, "ymin": ymin, "ymax": ymax }) else: plot.createFrame(saveName, opts={"ymin": ymin, "ymax": ymax}) # Add cut box? if opts.cutLine > 0: kwargs = {"greaterThan": True} plot.addCutBoxAndLine(cutValue=opts.cutLine, fillColor=ROOT.kRed, box=False, line=True, **kwargs) # Set x-axis title plot.frame.GetXaxis().SetTitle(limit.mHplus()) if limit.BRassumption != "": plot.frame.GetYaxis().SetTitle("95% CL limit for #sigma_{H^{+}} (pb)") else: plot.frame.GetYaxis().SetTitle(limit.sigmaBRlimit) # plot.frame.GetYaxis().SetTitle(limit.BRlimit) # Enable/Disable logscale for axes if logy: plot.getPad().SetLogy(logy) plot.getPad().SetLogx(opts.logx) # Enable grids in x and y? plot.getPad().SetGridx(opts.gridX) plot.getPad().SetGridy(opts.gridY) # Draw the plot with standard texts plot.draw() plot.addStandardTexts() # Add physics-related text on canvas addPhysicsText(histograms, limit, x=xPos) # Save the canvas plot.save() # Save the plots SavePlot(plot, saveName, os.path.join(opts.saveDir, opts.settings)) return
def 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 PlotHistos(noSF_datasetsMgr, withCR2SF_datasetsMgr, num_histoList, den_histoList, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(num_histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CR1", "CR2"] labels = ["Genuine", "Fake", "Inclusive"] #========================================================================================== # Get Dictionaries #========================================================================================== rhDict_den_noSF = GetRootHistos(noSF_datasetsMgr, den_histoList, regions) rhDict_num_noSF = GetRootHistos(noSF_datasetsMgr, num_histoList, regions) rhDict_num_withCR2SF = GetRootHistos(withCR2SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR2 are only applied in the Numerator on EWK+QCD+ST #========================================================================================= # Normalization Factors (see: getNormalization.py) #========================================================================================= # Marina f1=0.619886; f2=0.904877; # ========================================================================================= # (A) Apply Normalization Factors (see: getNormalizations.py) # ========================================================================================= # Normalize all histograms (QCD and TT) to normalization factors for re in regions: rhDict_den_noSF["NormQCD-"+re+"-Inclusive"] = rhDict_den_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1) rhDict_num_noSF["NormQCD-"+re+"-Inclusive"] =rhDict_num_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1) rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"] = rhDict_num_withCR2SF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Scale(f1) for la in labels: rhDict_den_noSF["NormTT-"+re+"-"+la] = rhDict_den_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_den_noSF["NormTT-"+re+"-"+la].Scale(f2) rhDict_num_noSF["NormTT-"+re+"-"+la] = rhDict_num_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_num_noSF["NormTT-"+re+"-"+la].Scale(f2) # ========================================================================================== # (B) Estimate Inclusive TT in SR # ========================================================================================== # (B1) Inclusive TT in Data - Denominator = Data - F1*QCD - - EWK - ST rhDict_den_noSF["TTinData-SR-Inclusive"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("t#bar{t} (Data)") rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["EWK-SR-Inclusive"], -1) rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1) # (B2) Inclusive TT in Data - Numerator = Data - F1*QCD*SF_{CR2} - ST*SF_{CR2} - EWK*SF_{CR2} rhDict_num_noSF["TTinData-SR-Inclusive"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("t#bar{t} (Data)") rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["NormQCD-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["SingleTop-SR-Inclusive"], -1) rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["EWK-SR-Inclusive"], -1) # (B3) Inclusive TT in MC - Denominator: rhDict_den_noSF["TT-SR-Inclusive"] # (B4) Inclusive TT in MC - Numerator: rhDict_num_noSF["TT-SR-Inclusive"] # ======================================================================================== # (C) Plot Numerator and Denominator (Data Vs MC) # ======================================================================================== _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0} _kwargs["ratioYlabel"] = "Data/MC" _kwargs["ratio"] = True _kwargs["stackMCHistograms"] = False _kwargs["createLegend"] = {"x1": 0.68, "y1": 0.75, "x2": 0.95, "y2": 0.92} _kwargs["ratioInvert"] = True num_data = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)") den_data = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)") num_mc = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)") den_mc = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)") num_data.Rebin(2) num_mc.Rebin(2) den_data.Rebin(2) den_mc.Rebin(2) styles.getABCDStyle("CR4").apply(num_mc) styles.getABCDStyle("CR4").apply(den_mc) # Denominator hName = "InclusiveTT_SR_Denominator_LeadingJet" hData_Den = histograms.Histo( den_data, "t#bar{t} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False) hMC_Den = histograms.Histo( den_mc, "t#bar{t} (MC)", "MC", drawStyle="HIST"); hMC_Den.setIsDataMC(isData=False, isMC=True) pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[]) pDen.setLuminosity(opts.intLumi) pDen.setDefaultStyles() plots.drawPlot(pDen, hName, **_kwargs) SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"]) # Numerator hName = "InclusiveTT_SR_Numerator_LeadingJet" hData_Num = histograms.Histo( num_data, "t#bar{t} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False) hMC_Num = histograms.Histo( num_mc, "t#bar{t} (MC)", "MC", drawStyle="HIST"); hMC_Num.setIsDataMC(isData=False, isMC=True) pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[]) pNum.setLuminosity(opts.intLumi) pNum.setDefaultStyles() plots.drawPlot(pNum, hName, **_kwargs) SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"]) # ======================================================================================== # (D) Plot Genuine TT Efficiency # ======================================================================================== _kwargs = { "xlabel" : "p_{T} (GeV/c)", "ylabel" : "Efficiency", "ratioYlabel" : "Data/MC", "ratio" : True, "ratioInvert" : False, "ratioType" : "errorScale", "ratioCreateLegend": True, "ratioMoveLegend" : {"dx": -0.51, "dy": 0.03, "dh": -0.08}, "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False}, "errorBarsX" : True, "stackMCHistograms": False, "addMCUncertainty" : False, "addLuminosityText": False, "addCmsText" : True, "cmsExtraText" : "Preliminary", "opts" : {"ymin": 0.0, "ymaxfactor": 1.28, "xmax" : 600}, "opts2" : {"ymin": 0.72, "ymax": 1.28}, "log" : False, "createLegend" : {"x1": 0.68, "y1": 0.80, "x2": 0.95, "y2": 0.92}, } bins = [0, 100, 200, 300, 400, 500, 600] xBins = array.array('d', bins) nx = len(xBins)-1 # Data h0_data_den = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)") h0_data_num = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)") # MC h0_mc_den = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)") h0_mc_num = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)") h0_data_den = h0_data_den.Rebin(nx, "", xBins) h0_data_num = h0_data_num.Rebin(nx, "", xBins) h0_mc_den = h0_mc_den.Rebin(nx, "", xBins) h0_mc_num = h0_mc_num.Rebin(nx, "", xBins) hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den) hNumerator_MC, hDenominator_MC = GetHistosForEfficiency(h0_mc_num, h0_mc_den) eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data) eff_mc = ROOT.TEfficiency(hNumerator_MC, hDenominator_MC) eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP) eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP) geff_data = convert2TGraph(eff_data) geff_mc = convert2TGraph(eff_mc) styles.dataStyle.apply(geff_data) styles.ttStyle.apply(geff_mc) Graph_Data = histograms.HistoGraph(geff_data, "t#bar{t} (Data) ", "p", "P") Graph_MC = histograms.HistoGraph(geff_mc, "t#bar{t} (MC)", "p", "P") p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[]) saveName = "Efficiency_InclusiveTT_SR_LeadingJet" savePath = os.path.join(opts.saveDir, opts.optMode) plots.drawPlot(p, savePath, **_kwargs) SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"]) # ============================= # Export JSON file # ============================= #jsonName = "Efficiency_InclusiveTT_SR_MET50_MuIso0p1_InvMET20_InvMuIso0p1.json" #runRange = "273150-284044" #analysis = opts.analysisName #label = "2016" #plotDir = os.path.join(opts.folder, jsonName) #pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geff_data) #pythonWriter.addMCParameters(label, geff_mc) #pythonWriter.writeJSON(jsonName) return
def PlotEfficiency(datasetsMgr, numPath, denPath, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): #if "Fake" in numPath and "TT" in dataset.getName(): # continue # Get the histograms #num = dataset.getDatasetRootHisto(numPath).getHistogram() #den = dataset.getDatasetRootHisto(denPath).getHistogram() n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins) - 1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Remove negative bins and ensure numerator bin <= denominator bin CheckNegatives(num, den, True) # RemoveNegatives(num) # RemoveNegatives(den) # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) # fixme: investigate warnings eff.SetStatisticOption(ROOT.TEfficiency.kFCP) # # Set the weights - Why is this needed? if 0: weight = 1 if dataset.isMC(): weight = dataset.getCrossSection() eff.SetWeight(weight) # Convert to TGraph eff = convert2TGraph(eff) # Apply default style (according to dataset name) plots._plotStyles[dataset.getName()].apply(eff) # Append in list myList.append( histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) # Define save name saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split( "/")[-1] # Plot the efficiency p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) # Save plot in all formats savePath = os.path.join(opts.saveDir, "HplusMasses", numPath.split("/")[0], opts.optMode) #savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) save_path = savePath + opts.MVAcut SavePlot(p, saveName, save_path, saveFormats=[".png", ".pdf", ".C"]) return
def GetScaleFactors(datasetsMgr, num_pathList, den_pathList, intLumi): # Get kwargs _kwargs = GetHistoKwargs(num_pathList[0], opts) _kwargs["stackMCHistograms"] = False _kwargs["opts2"] = {"ymin": 0.50, "ymax": 1.50} _kwargs["ratioType"] = "errorScale" # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CR1", "CR2"] labels = ["Genuine", "Fake", "Inclusive"] # Get Dictionaries rhDict_num = GetRootHistos(datasetsMgr, num_pathList, regions) rhDict_den = GetRootHistos(datasetsMgr, den_pathList, regions) # Marina # Normalization Factors (see: getNormalization.py) f1=0.619886; f2=0.904877; # Marina jsonName = "Efficiency_SystBDT_CR2_MET50_MuIso0p1_InvMET20_InvMuIso0p1_massCut300.json" # ------------------------------------------------------------------------------ # (A) Normalize QCD and TT (MC) in all regions # ------------------------------------------------------------------------------- for re in regions: rhDict_den["NormQCD-"+re+"-Inclusive"] = rhDict_den["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_den["NormQCD-"+re+"-Inclusive"].Scale(f1) rhDict_num["NormQCD-"+re+"-Inclusive"] = rhDict_num["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive") rhDict_num["NormQCD-"+re+"-Inclusive"].Scale(f1) for la in labels: rhDict_den["NormTT-"+re+"-"+la] = rhDict_den["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_den["NormTT-"+re+"-"+la].Scale(f2) rhDict_num["NormTT-"+re+"-"+la] = rhDict_num["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la) rhDict_num["NormTT-"+re+"-"+la].Scale(f2) # ----------------------------------------------------------------------------- # (B) Calculate BKG=QCD+EWK+ST in Data (CR2) # ----------------------------------------------------------------------------- # (B1) Denominator rhDict_den["BKG_Data-CR2-Inclusive"] = rhDict_den["Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)") rhDict_den["BKG_Data-CR2-Inclusive"].Add( rhDict_den["NormTT-CR2-Inclusive"], -1) # (B2) Numerator rhDict_num["BKG_Data-CR2-Inclusive"] = rhDict_num["Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)") rhDict_num["BKG_Data-CR2-Inclusive"].Add( rhDict_num["NormTT-CR2-Inclusive"], -1) # ----------------------------------------------------------------------------- # (C) Calculate BKG=QCD+EWK+ST in MC (CR2) # ----------------------------------------------------------------------------- # (C1) Denominator rhDict_den["BKG_MC-CR2-Inclusive"] = rhDict_den["NormQCD-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (MC)") rhDict_den["BKG_MC-CR2-Inclusive"].Add( rhDict_den["EWK-CR2-Inclusive"], +1) rhDict_den["BKG_MC-CR2-Inclusive"].Add( rhDict_den["SingleTop-CR2-Inclusive"], +1) # (C2) Numerator rhDict_num["BKG_MC-CR2-Inclusive"] = rhDict_num["NormQCD-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (MC)") rhDict_num["BKG_MC-CR2-Inclusive"].Add( rhDict_num["EWK-CR2-Inclusive"], +1) rhDict_num["BKG_MC-CR2-Inclusive"].Add( rhDict_num["SingleTop-CR2-Inclusive"], +1) # Rebinning bins = [0, 100, 200, 300, 400, 500, 600, 800] xBins = array.array('d', bins) nx = len(xBins)-1 Den_QCD = rhDict_den["NormQCD-CR2-Inclusive"].Clone("QCD") Den_EWK = rhDict_den["EWK-CR2-Inclusive"].Clone("EWK") Den_ST = rhDict_den["SingleTop-CR2-Inclusive"].Clone("ST") Num_QCD = rhDict_num["NormQCD-CR2-Inclusive"].Clone("QCD") Num_EWK = rhDict_num["EWK-CR2-Inclusive"].Clone("EWK") Num_ST = rhDict_num["SingleTop-CR2-Inclusive"].Clone("ST") Num_QCD = Num_QCD.Rebin(nx, "", xBins) Num_EWK = Num_EWK.Rebin(nx, "", xBins) Num_ST = Num_ST.Rebin(nx, "", xBins) Den_QCD = Den_QCD.Rebin(nx, "", xBins) Den_EWK = Den_EWK.Rebin(nx, "", xBins) Den_ST = Den_ST.Rebin(nx, "", xBins) # ------------------------------------------------------------------------------ # (D) Plot denominator & numerator (Data Vs MC) # ------------------------------------------------------------------------------ # (D1) Denominator hName = "QCD_EWK_ST_Denominator_CR2" h0 = rhDict_den["BKG_Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)") h1 = rhDict_den["BKG_MC-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (MC)") hData = histograms.Histo( h0, "QCD+EWK (Data)", "Data", drawStyle="AP"); hData.setIsDataMC(isData=True, isMC=False) hMC = histograms.Histo( h1, "QCD+EWK (MC)", "MC", drawStyle="HIST"); hMC.setIsDataMC(isData=False, isMC=True) _kwargs["createLegend"] = {"x1": 0.70, "y1": 0.60, "x2": 0.95, "y2": 0.92} pDen = plots.ComparisonManyPlot(hMC, [hData], saveFormats=[]) pDen.setLuminosity(intLumi) pDen.setDefaultStyles() plots.drawPlot(pDen, hName, **_kwargs) SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"]) # (D2) Numerator hName = "QCD_EWK_ST_Numerator_CR2" h2 = rhDict_num["BKG_Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)") h3 = rhDict_num["BKG_MC-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (MC)") hDataNum = histograms.Histo( h2, "QCD+EWK (Data)", "Data", drawStyle="AP"); hDataNum.setIsDataMC(isData=True, isMC=False) hMCNum = histograms.Histo( h3, "QCD+EWK (MC)", "MC", drawStyle="HIST"); hMCNum.setIsDataMC(isData=False, isMC=True) pNum = plots.ComparisonManyPlot(hMCNum, [hDataNum], saveFormats=[]) pNum.setLuminosity(intLumi) pNum.setDefaultStyles() plots.drawPlot(pNum, hName, **_kwargs) SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"]) # ----------------------------------------------------------------------------------------------------- # (E) Plot Mis-Identification rate in CR2 # ----------------------------------------------------------------------------------------------------- hName = "MisID_CR2" _kwargs = { "xlabel" : "p_{T} (GeV/c)", "ylabel" : "Misidentification rate", "ratioYlabel" : "Data/MC", "ratio" : True, "ratioInvert" : False, "ratioType" : "errorScale", "ratioCreateLegend": True, "ratioMoveLegend" : {"dx": -0.51, "dy": 0.03, "dh": -0.08}, "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False}, "errorBarsX" : True, "stackMCHistograms": False, "addMCUncertainty" : False, "addLuminosityText": False, "addCmsText" : True, "cmsExtraText" : "Preliminary", "opts" : {"ymin": 0.0, "ymaxfactor": 2.0, "xmax" : 600}, "opts2" : {"ymin": 0.30, "ymax": 1.70}, "log" : False, "createLegend" : {"x1": 0.55, "y1": 0.70, "x2": 0.95, "y2": 0.92}, } hNum_Data = rhDict_num["BKG_Data-CR2-Inclusive"].Clone("Numerator (Data)") hDen_Data = rhDict_den["BKG_Data-CR2-Inclusive"].Clone("Denominator (Data)") hNum_MC = rhDict_num["BKG_MC-CR2-Inclusive"].Clone("Numerator (MC)") hDen_MC = rhDict_den["BKG_MC-CR2-Inclusive"].Clone("Denominator (MC)") # Rebinning bins = [0, 100, 200, 300, 400, 500, 600, 800] xBins = array.array('d', bins) nx = len(xBins)-1 hNum_Data = hNum_Data.Rebin(nx, "", xBins) hDen_Data = hDen_Data.Rebin(nx, "", xBins) hNum_MC = hNum_MC.Rebin(nx, "", xBins) hDen_MC = hDen_MC.Rebin(nx, "", xBins) num_data, den_data = GetHistosForEfficiency(hNum_Data, hDen_Data) num_mc, den_mc = GetHistosForEfficiency(hNum_MC, hDen_MC) eff_Data = ROOT.TEfficiency(num_data, den_data) eff_Data.SetStatisticOption(ROOT.TEfficiency.kFCP) geff_Data = convert2TGraph(eff_Data) Graph_Data = histograms.HistoGraph(geff_Data, "QCD+EWK (Data)", "p", "P") eff_MC = ROOT.TEfficiency(num_mc, den_mc) eff_MC.SetStatisticOption(ROOT.TEfficiency.kFCP) geff_MC = convert2TGraph(eff_MC) styles.getABCDStyle("CR1").apply(geff_MC) Graph_MC = histograms.HistoGraph(geff_MC, "QCD+EWK (MC)", "p", "P") # Create efficiency plots p2 = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[]) plots.drawPlot(p2, hName, **_kwargs) SavePlot(p2, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"]) # Dump results in a JSON File runRange = "273150-284044" analysis = opts.analysisName label = "2016" plotDir = os.path.join(opts.folder, jsonName) pythonWriter.addParameters(plotDir, label, runRange, intLumi, geff_Data) pythonWriter.addMCParameters(label, geff_MC) fileName_json = jsonName pythonWriter.writeJSON(fileName_json) return
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, mass): higgs = "h" if "lowMH" in scenario: higgs = "H" excluded = graphs["muexcluded"] limit.setExcludedStyle(excluded) excluded.SetFillStyle(1001) excluded.SetLineWidth(0) excluded.SetLineStyle(0) excluded.SetLineColor(ROOT.kWhite) excludedCopy = excluded.Clone() if not mass in [90]: excludedCopy.SetFillColorAlpha( ROOT.kWhite, 0.0) # actual color doesn't matter, want fully transparent # else: # excluded.SetLineColor(ROOT.kBlack) # Uncomment when we have allowed for n in ["Allowed", "Allowed2"]: a = graphs[n] if a is None: continue a.SetFillStyle(3005) a.SetFillColor(ROOT.kRed) a.SetLineWidth(-302) a.SetLineColor(ROOT.kRed) a.SetLineStyle(1) legend_dh = 0 grs = [] if "observed" in graphs: grs.extend([ histograms.HistoGraph(graphs["observed"], "Observed", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L", legendStyle=None), ]) legend_dh = 0.1 grs.extend([ histograms.HistoGraph(excluded, "Excluded", drawStyle="F"), histograms.HistoGraph(excludedCopy, "ExcludedCopy", drawStyle=None, legendStyle="f"), histograms.HistoGraph(graphs["Allowed"], "Allowed", drawStyle="L", legendStyle="lf"), ]) if graphs["Allowed2"] is not None: grs.append( histograms.HistoGraph(graphs["Allowed2"], "Allowed2", drawStyle="L", legendStyle=None)) plot = plots.PlotBase(grs, saveFormats=[".png", ".pdf", ".C"]) plot.histoMgr.setHistoLegendLabelMany({ "ExcludedCopy": "Excluded", "Allowed": "m_{" + higgs + "}^{MSSM} #neq 125#pm3 GeV", "Excluded": None, }) if "observed" in graphs: plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", }) textPos = "left" dx = 0 dy = -0.15 if mass in [90, 150]: textPos = "right" dx = 0.35 if mass in [155, 160]: textPos = "right" dy = -0.02 plot.setLegend( histograms.createLegend(0.19 + dx, 0.75 + dy - legend_dh, 0.57 + dx, 0.80 + dy)) histograms.moveLegend(plot.legend, dh=0.05, dy=-0.05) #plot.legend.SetFillColor(0) #plot.legend.SetFillStyle(1001) name = name.replace("-", "_") plot.createFrame(name, opts={ "ymin": 0, "ymax": tanbMax, "xmin": 200, "xmax": 3300 }) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts(cmsTextPosition=textPos) size = 20 x = 0.2 + dx histograms.addText(x, 0.9 + dy, limit.process, size=size) histograms.addText(x, 0.863 + dy, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815 + dy, limit.getTypesetScenarioName(scenario.replace( "_mu", "")), size=size) histograms.addText(x, 0.767 + dy, "m_{H^{+}}=%d GeV" % mass, size=size) # histograms.addText(0.2, 0.231, "Min "+limit.BR+"(t#rightarrowH^{+}b)#times"+limit.BR+"(H^{+}#rightarrow#tau#nu)", size=0.5*size) #Adding a LHC label: # ROOT.LHCHIGGS_LABEL(0.97,0.72,1) # FH_version = db.getVersion("FeynHiggs") # histograms.addText(x, 0.55, FH_version) # HD_version = db.getVersion("HDECAY") # histograms.addText(x, 0.55, FH_version+" and "+HD_version, size=size) # histograms.addText(x, 0.48, "Derived from", size=size) # histograms.addText(x, 0.43, "CMS HIG-12-052", size=size) plot.save() print "Created", name
def GetHistoGraphs(datasetsMgr, folder, hName): # Get histogram customisations _kwargs = GetHistoKwargs(opts) # Get histos (Data, EWK) for Inclusive p1 = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[]) kwargs = copy.deepcopy(_kwargs) kwargs["opts"] = {"ymin": 1.0, "ymaxfactor": 10.0} kwargs["xlabelsize"] = 10 kwargs["ratio"] = False plots.drawPlot(p1, hName, **kwargs) SavePlot(p1, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".C", ".png", ".pdf"]) # Clone histograms histoList = [] graphList = [] hgList = [] # Append some bkg samples as well opts.datasets = opts.signal if not opts.acceptance: opts.datasets.extend(opts.backgrounds) for d in opts.datasets: h = p1.histoMgr.getHisto(d).getRootHisto().Clone(d) histoList.append(h) # Create the Efficiency histos for i, h in enumerate(histoList, 1): if opts.efficiency: histo = GetEfficiencyHisto(histoList[i - 1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Efficiency_%d" % (i)) elif opts.events: histo = GetEventsHisto(histoList[i - 1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Events_%d" % (i)) elif opts.acceptance: histo = GetAcceptanceHisto(histoList[i - 1], _kwargs, printValues=True, hideZeros=True) histo.SetName("Acceptance_%d" % (i)) # Convert histos to TGraph (don't do it for acceptance to get better positioning of markers wrt x-axis!) if not opts.acceptance: tgraph = convertHisto2TGraph(histo, printValues=False) else: tgraph = histo # Apply random histo styles and append if "charged" in h.GetName().lower(): s = styles.getSignalStyleHToTB_M(h.GetName().split("M_")[-1]) s.apply(tgraph) if "QCD" in h.GetName(): styles.fakeBStyle.apply(tgraph) if "EWK" in h.GetName(): s = styles.ttStyle.apply(tgraph) # Append to list graphList.append(tgraph) # Create histoGraph object htgraph = histograms.HistoGraph( tgraph, plots._legendLabels[opts.signal[i - 1]], "LP", "LP") # Append to list hgList.append(htgraph) return hgList, _kwargs
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