def rtauGen(h, name, rebin=2, ratio=False, defaultStyles=True): if defaultStyles: h.setDefaultStyles() h.histoMgr.forEachHisto(styles.generator()) h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin)) xlabel = "PF E_{T}^{miss} (GeV)" ylabel = "Events / %.2f" % h.binWidth() if "LeptonsInMt" in name: xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})" ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth() if "NoLeptonsRealTau" in name: xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})" ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth() if "Mass" in name: xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})" ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth() kwargs = {"ymin": 0.1, "ymax": 1000} if "LeptonsInMt" in name: kwargs = {"ymin": 0., "xmax": 300} if "NoLeptonsRealTau" in name: kwargs = {"ymin": 0., "xmax": 300} if "Rtau" in name: kwargs = {"ymin": 0.0001, "xmax": 1.1} kwargs = {"ymin": 0.1, "xmax": 1.1} h.getPad().SetLogy(True) # kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}} if ratio: kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5} kwargs["createRatio"] = True # name = name+"_log" h.createFrame(name, **kwargs) # histograms.addText(0.65, 0.7, "BR(t #rightarrow bH^{#pm})=0.05", 20) h.getPad().SetLogy(True) leg = histograms.createLegend(0.6, 0.75, 0.8, 0.9) if "LeptonsInMt" in name: h.getPad().SetLogy(False) leg = histograms.moveLegend(leg, dx=-0.18) histograms.addText(0.5, 0.65, "TailKiller cut: Tight", 20) h.setLegend(leg) plots._legendLabels["MetNoJetInHole"] = "Jets outside dead cells" plots._legendLabels["MetJetInHole"] = "Jets within dead cells" histograms.addText(300, 300, "p_{T}^{jet} > 50 GeV/c", 20) kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5} kwargs["createRatio"] = True # if ratio: # h.createFrameFraction(name, opts=opts, opts2=opts2) # h.setLegend(leg) common(h, xlabel, ylabel)
def PlotHistos(datasetName, hPath): _kwargs = GetHistoKwargs(hPath, opts) datasetsMgr_list = [] j = 0 histoList = [] # For-loop: All pseudo-multicrabs while j < len(opts.mcrabs): textweight = opts.mcrabs[j].split("_")[-1] dMgr = GetDatasetsFromDir(opts, j) dMgr.updateNAllEventsToPUWeighted() dMgr.loadLuminosities() # from lumi.json # Set/Overwrite cross-sections if "ChargedHiggs" in datasetName: dMgr.getDataset(datasetName).setCrossSection(1.0) # Get dataset dataset = dMgr.getDataset(datasetName) # Get Histogram from dataset histo = dataset.getDatasetRootHisto(hPath).getHistogram() # Set style styles.styles[j].apply(histo) if (j == 0): # refHisto = histograms.Histo(histo, "Nominal", legendStyle = "F", drawStyle="HIST") # refHisto.getRootHisto().SetFillStyle(1001) # refHisto.getRootHisto().SetFillColor(ROOT.kBlue) refHisto = histograms.Histo(histo, "Nominal", legendStyle = "L", drawStyle="HIST") refHisto.getRootHisto().SetLineStyle(ROOT.kSolid) refHisto.getRootHisto().SetLineWidth(3) else: text = str(j) histoList.append(histograms.Histo(histo, "Weight " + textweight, legendStyle = "LP", drawStyle="AP")) j = j + 1 # Create the plotter object p = plots.ComparisonManyPlot(refHisto, histoList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setLegendHeader(plots._legendLabels[datasetName]) # Draw the plots plots.drawPlot(p, opts.saveDir, **_kwargs) # Add text if 0: histograms.addText(0.65, 0.1, "#\pm %.1f %% band" % (opts.bandValue), 20) # Save plot in all formats saveName = hPath.split("/")[-1] + "_" + datasetName SavePlot(p, saveName, opts.saveDir, saveFormats = [".png", ".pdf", ".C"]) return
def MCPlot(datasetsMgr, json): Verbose("Creating MC plot") # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi") #if json["normalization"]=="normalizeToLumi": if 0: kwargs = {} p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=float(json["luminosity"]), **kwargs) else: #kwargs = {json["normalization"]: True} kwargs = {"normalizeToOne": True} p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs) # Label size (optional. Commonly Used in counters) xlabelSize = None if "xlabelsize" in json: xlabelSize = json["xlabelsize"] ylabelSize = None if "ylabelsize" in json: ylabelSize = json["ylabelsize"] # Draw a customised plot saveName = os.path.join(json["saveDir"], json["title"]) plots.drawPlot(p, saveName, xlabel = json["xlabel"], ylabel = json["ylabel"], rebinX = json["rebinX"], rebinY = json["rebinY"], stackMCHistograms = json["stackMCHistograms"]=="True", addMCUncertainty = False, #json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne", addLuminosityText = False, addCmsText = json["addCmsText"]=="True", cmsExtraText = json["cmsExtraText"], opts = json["opts"], log = json["logY"]=="True", errorBarsX = json["errorBarsX"]=="True", moveLegend = json["moveLegend"], # cutLine = json["cutValue"], #cannot have this and "cutBox" defined cutBox = {"cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"]=="True", "line": json["cutLine"]=="True", "greaterThan": json["cutGreaterThan"]=="True"}, xlabelsize = xlabelSize, ylabelsize = ylabelSize, ) # Remove legend? if json["removeLegend"] == "True": p.removeLegend() # Additional text histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") ) # Save in all formats chosen by user saveFormats = json["saveFormats"] for i, ext in enumerate(saveFormats): Print("%s" % saveName + ext, i==0) p.saveAs(saveName, formats=saveFormats) return
def MCPlot(datasetsMgr, json): Verbose("Creating MC plot") # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi") if json["normalization"]=="normalizeToLumi": kwargs = {} p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=float(json["luminosity"]), **kwargs) else: kwargs = {json["normalization"]: True} p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs) # Label size (optional. Commonly Used in counters) xlabelSize = None if "xlabelsize" in json: xlabelSize = json["xlabelsize"] ylabelSize = None if "ylabelsize" in json: ylabelSize = json["ylabelsize"] # Draw a customised plot saveName = os.path.join(json["saveDir"], json["title"]) plots.drawPlot(p, saveName, xlabel = json["xlabel"], ylabel = json["ylabel"], rebinX = json["rebinX"], rebinY = json["rebinY"], stackMCHistograms = json["stackMCHistograms"]=="True", addMCUncertainty = json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne", addLuminosityText = json["normalization"]=="normalizeToLumi", addCmsText = json["addCmsText"]=="True", cmsExtraText = json["cmsExtraText"], opts = json["opts"], log = json["logY"]=="True", errorBarsX = json["errorBarsX"]=="True", moveLegend = json["moveLegend"], # cutLine = json["cutValue"], #cannot have this and "cutBox" defined cutBox = {"cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"]=="True", "line": json["cutLine"]=="True", "greaterThan": json["cutGreaterThan"]=="True"}, xlabelsize = xlabelSize, ylabelsize = ylabelSize, ) # Remove legend? if json["removeLegend"] == "True": p.removeLegend() # Additional text histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") ) # Save in all formats chosen by user saveFormats = json["saveFormats"] for i, ext in enumerate(saveFormats): Print("%s" % saveName + ext, i==0) p.saveAs(saveName, formats=saveFormats) return
def DataMCPlot(datasetsMgr, json): Verbose("Creating Data-MC plot") # Create the Data-MC Plot p = plots.DataMCPlot(datasetsMgr, json["histogram"]) # Label size (optional. Commonly Used in counters) xlabelSize = None if "xlabelsize" in json: xlabelSize = json["xlabelsize"] ylabelSize = None if "ylabelsize" in json: ylabelSize = json["ylabelsize"] # Draw a customised plot saveName = os.path.join(json["saveDir"], json["title"]) plots.drawPlot(p, saveName, xlabel = json["xlabel"], ylabel = json["ylabel"], rebinX = json["rebinX"], rebinY = json["rebinY"], ratioYlabel = json["ratioYlabel"], ratio = json["ratio"]=="True", stackMCHistograms = json["stackMCHistograms"]=="True", ratioInvert = json["ratioInvert"]=="True", addMCUncertainty = json["addMCUncertainty"]=="True", addLuminosityText = json["addLuminosityText"]=="True", addCmsText = json["addCmsText"]=="True", cmsExtraText = json["cmsExtraText"], opts = json["opts"], opts2 = json["ratioOpts"], log = json["logY"]=="True", errorBarsX = json["errorBarsX"]=="True", moveLegend = json["moveLegend"], # cutLine = json["cutValue"], #cannot have this and "cutBox" defined cutBox = {"cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"]=="True", "line": json["cutLine"]=="True", "greaterThan": json["cutGreaterThan"]=="True"}, xlabelsize = xlabelSize, ylabelsize = ylabelSize, ) # Remove legend? if json["removeLegend"] == "True": p.removeLegend() # Additional text histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") ) # Save in all formats chosen by user saveFormats = json["saveFormats"] for i, ext in enumerate(saveFormats): Print("%s" % saveName + ext, i==0) p.saveAs(saveName, formats=saveFormats) return
def 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 plotClosure(mt_nom, mts_var, name, optMode): #for mt_var in mts_var: # printSummedDifference(mt_nom, mt_var) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot(mt_nom, mts_var) plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True) moveLegend={"dx": -0.325,"dy": 0.02,"dw":-0.14,"dh":-0.12} plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText(0.65, 0.3, optMode.replace("OptQCDTailKiller","R_{BB} ").replace("Plus",""), 25) histograms.addStandardTexts() plot.draw() plot.save()
def plotClosure(mt_nom, mts_var, name, optMode): #for mt_var in mts_var: # printSummedDifference(mt_nom, mt_var) style = tdrstyle.TDRStyle() plot = plots.ComparisonManyPlot(mt_nom, mts_var) plot.createFrame(optMode.replace("Opt", "mT_Closure_" + name + "_"), createRatio=True) moveLegend = {"dx": -0.325, "dy": 0.02, "dw": -0.14, "dh": -0.12} plot.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText( 0.65, 0.3, optMode.replace("OptQCDTailKiller", "R_{BB} ").replace("Plus", ""), 25) histograms.addStandardTexts() plot.draw() plot.save()
def doPlot(mass, name, nuisance, thetas): f = ROOT.TFile.Open("lands_histograms_hplushadronic_m%d.root" % mass) h = f.Get(name) hUp = f.Get("%s_%dUp" % (name, nuisance)) hDown = f.Get("%s_%dDown" % (name, nuisance)) shapes = [] ll = {} for i, theta in enumerate(thetas): morphed = doShape(h, hUp, hDown, theta) shapes.append(histograms.Histo(morphed, "Theta%d" % i, drawStyle="HIST", legendStyle="l")) ll["Theta%d" % i] = "#theta=%.2f (%.1f)" % (theta, _integral(morphed)) plot = plots.PlotBase(shapes) plot.histoMgr.forEachHisto(styles.generator()) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) plot.histoMgr.setHistoLegendLabelMany(ll) plot.setLegend(histograms.createLegend()) plot.createFrame("shape_theta_%s_syst%d_m%d" % (name, nuisance, mass)) plot.frame.GetXaxis().SetTitle("m_{T} (GeV)") plot.frame.GetYaxis().SetTitle("Rate") plot.draw() x = 0.6 size = 20 histograms.addText(x, 0.70, "Sample %s" % name, size=size) histograms.addText(x, 0.65, "Nuisance %d" % nuisance, size=size) histograms.addText(x, 0.60, "m_{H^{+}}=%d GeV" % mass, size=size) plot.save() f.Close()
def doPlot(limits, legendLabels, graphs, name, ylabel, opts={}, plotLabel=None, moveLegend={}, log=False): hg = [] ll = {} for i in xrange(len(graphs)): hg.append(histograms.HistoGraph(graphs[i], "Graph%d"%i, drawStyle="PL", legendStyle="lp")) ll["Graph%d"%i] = legendLabels[i] plot = plots.PlotBase(hg) plot.histoMgr.forEachHisto(styles.Generator(styleList[0:len(limits)])) def sty(h): r = h.getRootHisto() r.SetLineWidth(3) r.SetLineStyle(1) plot.histoMgr.forEachHisto(sty) plot.histoMgr.setHistoLegendLabelMany(ll) legend = histograms.createLegend(0.48, 0.65, 0.85, 0.92) if len(limits[0].getFinalstates()) > 1: legend = histograms.moveLegend(legend, dy=-0.1) if plotLabel: legend = histograms.moveLegend(legend, dy=-0.04) legend = histograms.moveLegend(legend, **moveLegend) plot.setLegend(legend) opts_ = {"ymin": 0} opts_.update(opts) plot.createFrame(name, opts=opts_) plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle(ylabel) ROOT.gPad.SetLogy(log) plot.draw() plot.setLuminosity(limits[0].getLuminosity()) plot.addStandardTexts(cmsTextPosition="outframe") size = 20 x = 0.18 histograms.addText(x, 0.88, limit.process, size=size) histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size) histograms.addText(x, 0.79, limit.BRassumption, size=size) if plotLabel: histograms.addText(legend.GetX1()+0.01, legend.GetY2(), plotLabel, size=size) plot.save()
def addPhysicsText(histograms, limit, x=0.45, y=0.84, size=20): ''' Add physics-process text on canvas ''' # Add process text on canvas histograms.addText(x, y + 0.04, limit.processHeavyHtb, size=size) # Add final-state text histograms.addText(x, y, "fully hadronic final state", size=size) if limit.BRassumption != "": histograms.addText(x, y - 0.05, limit.BRassumption, size=size) return
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 doPlot2(limits, legendLabels, name): 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"), ] graphs[0].getRootHisto().SetLineStyle(1) plot = plots.PlotBase(graphs) ll = { "Expected": None, "Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0], "Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0], } stGen = styles.generator() for i in xrange(1, len(limits)): gr = histograms.HistoGraph(limits[i].expectedGraph(), "Exp%d"%i, 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["Exp%d"%i] = "%s exp. median" % legendLabels[i] plot.histoMgr.setHistoLegendLabelMany(ll) legend = histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=-0.02) if len(limits[0].getFinalstates()) > 1: legend = histograms.moveLegend(legend, dy=-0.1) plot.setLegend(legend) plot.createFrame(name+"_limits", opts={"ymin": 0, "ymax": limits[0].getFinalstateYmaxBR()}) plot.frame.GetXaxis().SetTitle(limit.mHplus()) plot.frame.GetYaxis().SetTitle(limit.BRlimit) plot.draw() plot.setLuminosity(limits[0].getLuminosity()) plot.addStandardTexts(cmsTextPosition="outframe") size = 20 x = 0.2 histograms.addText(x, 0.88, limit.process, size=size) histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size) histograms.addText(x, 0.79, limit.BRassumption, size=size) plot.save()
def doPlot(mass, name, nuisance, thetas): f = ROOT.TFile.Open("lands_histograms_hplushadronic_m%d.root" % mass) h = f.Get(name) hUp = f.Get("%s_%dUp" % (name, nuisance)) hDown = f.Get("%s_%dDown" % (name, nuisance)) shapes = [] ll = {} for i, theta in enumerate(thetas): morphed = doShape(h, hUp, hDown, theta) shapes.append( histograms.Histo(morphed, "Theta%d" % i, drawStyle="HIST", legendStyle="l")) ll["Theta%d" % i] = "#theta=%.2f (%.1f)" % (theta, _integral(morphed)) plot = plots.PlotBase(shapes) plot.histoMgr.forEachHisto(styles.generator()) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) plot.histoMgr.setHistoLegendLabelMany(ll) plot.setLegend(histograms.createLegend()) plot.createFrame("shape_theta_%s_syst%d_m%d" % (name, nuisance, mass)) plot.frame.GetXaxis().SetTitle("m_{T} (GeV)") plot.frame.GetYaxis().SetTitle("Rate") plot.draw() x = 0.6 size = 20 histograms.addText(x, 0.70, "Sample %s" % name, size=size) histograms.addText(x, 0.65, "Nuisance %d" % nuisance, size=size) histograms.addText(x, 0.60, "m_{H^{+}}=%d GeV" % mass, size=size) plot.save() f.Close()
dy = 0.12 legend = ROOT.TLegend(x-0.01, 0.50+dy, x+0.40+0.30*(len(myScenarios)>1), 0.80+dy) if len(myScenarios) == 1: legend.AddEntry("", "MSSM %s"%scenToLabel(myScenarios[0]), "") for j in range(0, len(myFinalStates)): if len(myScenarios) == 1: # One scenario in one plot legend.AddEntry(myObjects[j], myFinalStates[j].replace(":",""), "lp") else: # Multiple scenarios in one plot for i in range(0, len(myScenarios)): if i == 0: legend.AddEntry("", myFinalStates[j], "") else: legend.AddEntry("","","") for i in range(0, len(myScenarios)): legend.AddEntry(myObjects[j*len(myScenarios)+i], "MSSM %s"%scenToLabel(myScenarios[i]), "lp") legend.SetNColumns(len(myScenarios)) legend.SetFillStyle(0) legend.SetBorderSize(0) #legend.SetTextSize(20) legend.Draw() #plot.setLegend(legend) #plot.draw() # Save plot histograms.addText(0.45, 0.23, "Values from LHCHXSWG used", size=20) histograms.addText(0.45, 0.18, "m_{H^{+}}=%s GeV"%m, size=20) plot.save() print "Created plot %s"%name
def main(opts): style = tdrstyle.TDRStyle() style.setOptStat(True) style.setWide(True, 0.15) ### style = tdrstyle.TDRStyle() ### #style.setWide(True) ### style.setPaletteMy() ### ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() style.setWide(True, 0.15) # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # ======================================== # Datasets # ======================================== # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) intLumi = GetLumi(datasetsMgr) datasetsMgr.updateNAllEventsToPUWeighted() datasetsMgr.PrintCrossSections() #datasetsMgr.PrintLuminosities() # Set/Overwrite cross-sections for d in datasetsMgr.getAllDatasets(): if "ChargedHiggs" in d.getName(): datasetsMgr.getDataset(d.getName()).setCrossSection(1.0) # Merge datasts (Note: Merged MC histograms must be normalized to something) plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets if 0: datasetsMgr.remove("TTJets") datasetsMgr.remove( filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # Print dataset information datasetsMgr.PrintInfo() # For-loop: All Histogram names for counter, hName in enumerate(hNames): savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a plot p = plots.PlotBase([refHisto], kwargs.get("saveFormats")) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Customize # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL" p.histoMgr.forEachHisto( lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.00001)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.05)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(2)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(2)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0009)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0041)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0012)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.00435)) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().GetZaxis().SetTitle("Arbitrary Units")) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(2.)) #ROOT.gPad.RedrawAxis() # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=opts) # Customise frame p.getFrame().GetXaxis().SetTitle(getTitleX(refHisto, **kwargs)) #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = {"lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.removeLegend() # Add MC Uncertainty (Invalid method for a 2-d histogram) #p.addMCUncertainty() # Customise histogram (after frame is created) # Draw plots p.draw() # Customise text #Soti lumitext histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.17, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.17, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter == 0) return
def main(): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir #datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets #datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr.remove(filter(lambda name: not kwargs.get("refDataset") in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) # datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for hName in hNames: savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a plot p = plots.PlotBase([refHisto], kwargs.get("saveFormats")) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Customize # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL" # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=opts) # Customise frame p.getFrame().GetXaxis().SetTitle( getTitleX(refHisto, **kwargs) ) p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = { "lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.removeLegend() # Add MC Uncertainty (Invalid method for a 2-d histogram) #p.addMCUncertainty() # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.20, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def __call__(self, x, y): mass = "m_{H^{#pm}} = %d GeV/c^{2}" % self.mass br = "BR(t #rightarrow bH^{#pm})=%.2f" % self.br histograms.addText(x, y, mass, size=self.size) histograms.addText(x, y-self.separation, br, size=self.size)
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 analyze(analysis=None): paths = [sys.argv[1]] if (len(sys.argv) == 3): howAnalyse = sys.argv[2] else: howAnalyse = "--fit" # howAnalyse = "--bin" if not analysis == None: datasets = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, excludeTasks="Silver|GluGluHToTauTau_M125") else: datasets = dataset.getDatasetsFromMulticrabDirs( paths, excludeTasks="Silver|GluGluHToTauTau_M125") analysis = datasets.getAllDatasets()[0].getAnalysisName() # datasetsDY = None datasetsDY = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL") datasetsDY = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL|Zprime") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="GluGluHToTauTau_M125|TTJets") datasetsH125 = None # datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125",emptyDatasetsAsNone=True) # datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125") datasets.loadLuminosities() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 # dataset2 = datasets.getMCDatasets() if not datasetsDY == None: dataset2 = datasetsDY.getMCDatasets() histeff1 = getEfficiency(dataset1) histeff2 = getEfficiency(dataset2) eff1 = convert2TGraph(histeff1) eff2 = convert2TGraph(histeff2) if isinstance(datasetsH125, dataset.DatasetManager): histeff3 = getEfficiency(datasetsH125.getMCDatasets()) eff3 = convert2TGraph(histeff3) styles.dataStyle.apply(eff1) styles.mcStyle.apply(eff2) eff1.SetMarkerSize(1) # eff2.SetMarkerSize(1.5) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3) eff3.SetMarkerSize(1.5) eff3.SetMarkerColor(4) eff3.SetLineColor(4) # p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"), # histograms.HistoGraph(eff2, "eff2", "p", "P")) if isinstance(datasetsH125, dataset.DatasetManager): p = plots.ComparisonManyPlot( histograms.HistoGraph(eff1, "eff1", "p", "P"), [ histograms.HistoGraph(eff2, "eff2", "p", "P"), histograms.HistoGraph(eff3, "eff3", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"), histograms.HistoGraph(eff2, "eff2", "p", "P")) else: p = plots.PlotBase([histograms.HistoGraph(eff1, "eff1", "p", "P")]) ## FIT FUNCTIONS: "Sigmoid", "Error", "Gompertz", "Richard","Crystal" ## ## FIT TYPES: binned max likelihood: "ML" , Chi2-fit: "Chi" ## if (howAnalyse == "--fit"): datafit = fitType("Data", p, histeff1, eff1, 20, 500, "Crystal", "ML") mcfit = fitType("MC", p, histeff2, eff2, 20, 500, "Crystal", "ML") if isinstance(datasetsH125, dataset.DatasetManager): fit("H125", p, eff3, 20, 200) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} # moveLegend = {"dx": -0.55, "dy": -0.15, "dh": -0.1} moveLegend = {"dx": -0.2, "dy": -0.5, "dh": -0.1} name = "TauMET_" + analysis + "_DataVsMC_PFTauPt" legend1 = "Data" # legend2 = "MC (DY)" legend2 = "Simulation" legend3 = "MC (H125)" createRatio = False p.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) createRatio = True if isinstance(datasetsH125, dataset.DatasetManager): p.histoMgr.setHistoLegendLabelMany({ "eff1": legend1, "eff2": legend2, "eff3": legend3 }) if createRatio: p.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.getFrame().GetYaxis().SetTitle("HLT tau efficiency") # p.getFrame().GetXaxis().SetTitle("#tau-jet p_{T} (GeV/c)") p.getFrame().GetXaxis().SetTitle("#tau_{h} p_{T} (GeV/c)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau120_Trk50_eta2p1", 17) # histograms.addText(0.5, 0.6, "VLooseIsoPFTau140_Trk50_eta2p1", 17) # label = analysis.split("_")[len(analysis.split("_")) -1] label = "2016" histograms.addText(0.5, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.5, 0.46, "Runs " + runRange, 17) p.draw() ## does the ratio of the fits if (howAnalyse == "--fit"): funcRatio = ROOT.TH1F("", "", 480, 20, 500) for i in range(0, 480): ratio = datafit.Eval(i + 20 - 1) / mcfit.Eval(i + 20 - 1) funcRatio.SetBinContent(i, ratio) p.getPad().GetCanvas().cd(2) funcRatio.Draw("SAME") p.getPad().GetCanvas().cd(1) ## lumi = 0.0 for d in datasets.getDataDatasets(): if (d.getName() != "SingleMuon_Run2016F_03Feb2017_v1_277932_278800" and d.getName() != "SingleMuon_Run2016C_03Feb2017_v1_275656_276283"): print "luminosity", d.getName(), d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum", lumi histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) if (howAnalyse == "--fit"): pythonWriter.addParameters(plotDir, label, runRange, lumi, datafit) pythonWriter.addMCParameters(label, mcfit) pythonWriter.writeJSON( os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + "_fit.json")) pythonWriter.__init__() #need to clear the Json arrays # if (howAnalyse == "--bin"): pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1) pythonWriter.addMCParameters(label, eff2) pythonWriter.writeJSON( os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + "_bin.json")) # if not createRatio: # sys.exit() ######################################################################### histeff1eta = getEfficiency(dataset1, "NumeratorEta", "DenominatorEta") histeff2eta = getEfficiency(dataset2, "NumeratorEta", "DenominatorEta") eff1eta = convert2TGraph(histeff1eta) eff2eta = convert2TGraph(histeff2eta) if isinstance(datasetsH125, dataset.DatasetManager): histeff3eta = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorEta", "DenominatorEta") eff3eta = convert2TGraph(histeff3eta) styles.dataStyle.apply(eff1eta) styles.mcStyle.apply(eff2eta) eff1eta.SetMarkerSize(1) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3eta) eff3eta.SetMarkerSize(1.5) eff3eta.SetMarkerColor(4) eff3eta.SetLineColor(4) if isinstance(datasetsH125, dataset.DatasetManager): p_eta = plots.ComparisonManyPlot( histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), [ histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"), histograms.HistoGraph(eff3eta, "eff3eta", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p_eta = plots.ComparisonPlot( histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), histograms.HistoGraph(eff2eta, "eff2eta", "p", "P")) else: p_eta = plots.PlotBase( [histograms.HistoGraph(eff1eta, "eff1eta", "p", "P")]) p_eta.histoMgr.setHistoLegendLabelMany({"eff1eta": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p_eta.histoMgr.setHistoLegendLabelMany({ "eff1eta": legend1, "eff2eta": legend2 }) if isinstance(datasetsH125, dataset.DatasetManager): p_eta.histoMgr.setHistoLegendLabelMany({ "eff1eta": legend1, "eff2eta": legend2, "eff3eta": legend3 }) name = "TauMET_" + analysis + "_DataVsMC_PFTauEta" if createRatio: p_eta.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_eta.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) moveLegendEta = {"dx": -0.5, "dy": -0.65, "dh": -0.1} p_eta.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendEta)) p_eta.getFrame().GetYaxis().SetTitle("HLT tau efficiency") p_eta.getFrame().GetXaxis().SetTitle("#tau-jet #eta") if createRatio: p_eta.getFrame2().GetYaxis().SetTitle("Ratio") p_eta.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.38, label, 17) histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17) p_eta.draw() histograms.addStandardTexts(lumi=lumi) p_eta.save(formats) ######################################################################### histeff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi") histeff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi") eff1phi = convert2TGraph(histeff1phi) eff2phi = convert2TGraph(histeff2phi) if isinstance(datasetsH125, dataset.DatasetManager): histeff3phi = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorPhi", "DenominatorPhi") eff3phi = convert2TGraph(histeff3phi) styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsH125, dataset.DatasetManager): styles.mcStyle.apply(eff3phi) eff3phi.SetMarkerSize(1.5) eff3phi.SetMarkerColor(4) eff3phi.SetLineColor(4) if isinstance(datasetsH125, dataset.DatasetManager): p_phi = plots.ComparisonManyPlot( histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), [ histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"), histograms.HistoGraph(eff3phi, "eff3phi", "p", "P") ]) elif isinstance(datasetsDY, dataset.DatasetManager): p_phi = plots.ComparisonPlot( histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), histograms.HistoGraph(eff2phi, "eff2phi", "p", "P")) else: p_phi = plots.PlotBase( [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")]) p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1}) if isinstance(datasetsDY, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2 }) if isinstance(datasetsH125, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2, "eff3phi": legend3 }) name = "TauMET_" + analysis + "_DataVsMC_PFTauPhi" if createRatio: p_phi.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) moveLegendPhi = {"dx": -0.5, "dy": -0.65, "dh": -0.1} p_phi.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("HLT tau efficiency") p_phi.getFrame().GetXaxis().SetTitle("#tau-jet #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.38, label, 17) histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### namePU = "TauMET_" + analysis + "_DataVsMC_nVtx" histeff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU") histeff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU") eff1PU = convert2TGraph(histeff1PU) eff2PU = convert2TGraph(histeff2PU) styles.dataStyle.apply(eff1PU) styles.mcStyle.apply(eff2PU) eff1PU.SetMarkerSize(1) eff2PU.SetMarkerSize(1.5) if isinstance(datasetsDY, dataset.DatasetManager): pPU = plots.ComparisonManyPlot( histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({ "eff1": legend1, "eff2": legend2 }) else: pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) optsPU = {"ymin": 0.01, "ymax": 1.0} createRatio = False if createRatio: pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=optsPU, opts2=opts2) else: pPU.createFrame(os.path.join(plotDir, namePU), opts=optsPU, opts2=opts2) moveLegend = {"dx": -0.5, "dy": -0.5, "dh": -0.1} pPU.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("HLT tau efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") if createRatio: pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.53, label, 17) histograms.addText(0.2, 0.46, "Runs " + datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) ######################################################################### """ hName = "Pull" # hName = "Sub" namePull = "TauMET_"+analysis+"_DataVsMC_"+hName+"s" plots.mergeRenameReorderForDataMC(datasets) datasets.merge("MC", ["TT","WJets","DYJetsToLL","SingleTop","QCD"], keepSources=True) drh1 = datasets.getDataset("Data").getDatasetRootHisto(hName) drh2 = datasets.getDataset("MC").getDatasetRootHisto(hName) drh1.normalizeToOne() drh2.normalizeToOne() pull1 = drh1.getHistogram() pull2 = drh2.getHistogram() if isinstance(datasetsH125,dataset.DatasetManager): plots.mergeRenameReorderForDataMC(datasetsH125) drh3 = datasetsH125.getMCDatasets()[0].getDatasetRootHisto(hName) drh3.normalizeToOne() pull3 = drh3.getHistogram() styles.dataStyle.apply(pull1) styles.mcStyle.apply(pull2) pull1.SetMarkerSize(1) if isinstance(datasetsH125,dataset.DatasetManager): styles.mcStyle.apply(pull3) pull3.SetMarkerSize(1.5) pull3.SetMarkerColor(4) pull3.SetLineColor(4) if isinstance(datasetsH125,dataset.DatasetManager): p_pull = plots.ComparisonManyPlot(histograms.Histo(pull1, "pull1", "p", "P"), [histograms.Histo(pull2, "pull2", "p", "P"), histograms.Histo(pull3, "pull3", "p", "P")]) else: p_pull = plots.ComparisonPlot(histograms.Histo(pull1, "pull1", "p", "P"), histograms.Histo(pull2, "pull2", "p", "P")) p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2}) if isinstance(datasetsH125,dataset.DatasetManager): p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2, "pull3": legend3}) p_pull.createFrame(os.path.join(plotDir, namePull), createRatio=True, opts=opts, opts2=opts2) moveLegendPull = {"dx": -0.5, "dy": -0.35, "dh": -0.1} p_pull.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPull)) p_pull.getFrame().GetYaxis().SetTitle("Arbitrary units") # p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T} - #tau-jet p_{T} (GeV/c)") p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T}/ #tau-jet p_{T} - 1") p_pull.getFrame2().GetYaxis().SetTitle("Ratio") p_pull.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.75, "LooseIsoPFTau50_Trk30_eta2p1", 17) histograms.addText(0.2, 0.68, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.2, 0.61, "Runs "+runRange, 17) p_pull.draw() histograms.addStandardTexts(lumi=lumi) p_pull.save(formats) """ ######################################################################### print "Output written in", plotDir
def DataMCPlot(datasetsMgr, json): Verbose("Creating Data-MC plot") ##ATHER # evtCount = counter.EventCounter(datasetsMgr) # evtCount.normalizeToOne() # Print dataset information # datasetsMgr.PrintInfo() # #ATHER # Create the Data-MC Plot p = plots.DataMCPlot(datasetsMgr, json["histogram"]) # Label size (optional. Commonly Used in counters) xlabelSize = None if "xlabelsize" in json: xlabelSize = json["xlabelsize"] ylabelSize = None if "ylabelsize" in json: ylabelSize = json["ylabelsize"] # Draw a customised plot saveName = os.path.join(json["saveDir"], json["title"]) plots.drawPlot( p, saveName, xlabel=json["xlabel"], ylabel=json["ylabel"], rebinX=json["rebinX"], rebinY=json["rebinY"], ratioYlabel=json["ratioYlabel"], ratio=json["ratio"] == "True", stackMCHistograms=json["stackMCHistograms"] == "True", ratioInvert=json["ratioInvert"] == "True", addMCUncertainty=json["addMCUncertainty"] == "True", addLuminosityText=json["addLuminosityText"] == "True", addCmsText=json["addCmsText"] == "True", cmsExtraText=json["cmsExtraText"], opts=json["opts"], opts2=json["ratioOpts"], log=json["logY"] == "True", errorBarsX=json["errorBarsX"] == "True", moveLegend=json["moveLegend"], # cutLine = json["cutValue"], #cannot have this and "cutBox" defined cutBox={ "cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"] == "True", "line": json["cutLine"] == "True", "greaterThan": json["cutGreaterThan"] == "True" }, xlabelsize=xlabelSize, ylabelsize=ylabelSize, ) # Remove legend? if json["removeLegend"] == "True": p.removeLegend() # Additional text histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size")) # Save in all formats chosen by user saveFormats = json["saveFormats"] for i, ext in enumerate(saveFormats): Print("%s" % saveName + ext, i == 0) p.saveAs(saveName, formats=saveFormats) return
def 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 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 _generateDQMPlot(self): ''' Create a Data Quality Monitor (DQM) style plot to easily check the error for each transfer factor and whether it is within an acceptable relative error ''' # Define error warning/tolerance on relative errors okay = 1.0/(len(self._BinLabelMap.keys())) warn = 0.5*okay NEvts = [] # Check the uncertainties on the normalization factors for k in self._BinLabelMap: relErrorUp = abs(self._TF_Up[k])/(self._TF[k]) relErrorDown = abs(self._TF_Down[k])/(self._TF[k]) relError = self._TF_Error[k]/self._TF[k] if 0: print "bin = %s , relErrorUp = %s, relErrorDown = %s " % (k, relErrorUp, relErrorDown) # Add DQM entries NCR1 = 0 NCR2 = 0 NCR3 = 0 NCR4 = 0 for j in self._NEvtsCR1: NCR1 += self._NEvtsCR1[j] NEvts.append(self._NEvtsCR1[j]) for j in self._NEvtsCR2: NCR2 += self._NEvtsCR2[j] NEvts.append(self._NEvtsCR2[j]) for j in self._NEvtsCR3: NCR3 += self._NEvtsCR3[j] NEvts.append(self._NEvtsCR3[j]) for j in self._NEvtsCR4: NCR4 += self._NEvtsCR4[j] NEvts.append(self._NEvtsCR4[j]) if 0: print "NCR1[%s] = %0.1f, NCR2[%s] = %0.1f, k = %s" % (k, self._NEvtsCR1[k], k, self._NEvtsCR2[k], k) print "NCR1 = %s, NCR2 = %s, k = %s" % (NCR1, NCR2, k) print "error/NCR1[%s] = %0.2f, error/NCR2[%s] = %0.2f" % (k, self._NEvtsCR1_Error[k]/self._NEvtsCR1[k], k, self._NEvtsCR2_Error[k]/self._NEvtsCR2[k]) # Add DQM plot entries self._addDqmEntry(self._BinLabelMap[k], "N_{CR1}", self._NEvtsCR1[k], NCR1*okay, NCR1*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR2}", self._NEvtsCR2[k], NCR2*okay, NCR2*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR3}", self._NEvtsCR3[k], NCR3*okay, NCR3*warn) self._addDqmEntry(self._BinLabelMap[k], "N_{CR4}", self._NEvtsCR4[k], NCR4*okay, NCR4*warn) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR1}}{N_{CR1}}", self._NEvtsCR1_Error[k]/NCR1, 0.05, 0.15) # self._addDqmEntry(self._BinLabelMap[k], "#frac{#sigma_{CR2}}{N_{CR2}}", self._NEvtsCR2_Error[k]/NCR2, 0.05, 0.15) # Construct the DQM histogram nBinsX = len(self._dqmKeys[self._dqmKeys.keys()[0]].keys()) nBinsY = len(self._dqmKeys.keys()) h = ROOT.TH2F("FakeB DQM", "FakeB DQM", nBinsX, 0, nBinsX, nBinsY, 0, nBinsY) # Customise axes h.GetXaxis().SetLabelSize(15) h.GetYaxis().SetLabelSize(10) # Set Min and Max of z-axis if 0: # red, yellow, green for DQM h.SetMinimum(0) h.SetMaximum(3) else: # pure entries instead of red, yellow, green h.SetMinimum(min(NEvts)*0.25) h.SetMaximum(round(max(NCR1, NCR2, NCR3, NCR4))) h.SetContour(10) #h.SetContour(3) if 0: h.GetXaxis().LabelsOption("v") h.GetYaxis().LabelsOption("v") nWarnings = 0 nErrors = 0 # For-loop: All x-axis bins for i in range(h.GetNbinsX()): # For-loop: All y-axis bins for j in range(h.GetNbinsY()): ykey = self._dqmKeys.keys()[j] xkey = self._dqmKeys[ykey].keys()[i] # Set the bin content h.SetBinContent(i+1, j+1, self._dqmKeys[ykey][xkey]) h.GetXaxis().SetBinLabel(i+1, xkey) h.GetYaxis().SetBinLabel(j+1, ykey) if self._dqmKeys[ykey][xkey] > 2: nErrors += 1 elif self._dqmKeys[ykey][xkey] > 1: nWarnings += 1 # Apply TDR style style = tdrstyle.TDRStyle() style.setOptStat(False) style.setGridX(False) style.setGridY(False) style.setWide(True, 0.15) # Set the colour styling (red, yellow, green) if 0: palette = array.array("i", [ROOT.kGreen+1, ROOT.kYellow, ROOT.kRed]) ROOT.gStyle.SetPalette(3, palette) else: # https://root.cern.ch/doc/master/classTColor.html ROOT.gStyle.SetPalette(ROOT.kLightTemperature) # ROOT.gStyle.SetPalette(ROOT.kColorPrintableOnGrey) #tdrstyle.setRainBowPalette() #tdrstyle.setDeepSeaPalette() # Create canvas c = ROOT.TCanvas() c.SetLogx(False) c.SetLogy(False) c.SetLogz(True) c.SetGridx() c.SetGridy() h.Draw("COLZ") #"COLZ TEXT" # Add CMS text and text with colour keys histograms.addStandardTexts(cmsTextPosition="outframe") if 0: histograms.addText(0.55, 0.80, "green < %.0f %%" % (okay*100), size=20) histograms.addText(0.55, 0.84, "yellow < %.0f %%" % (warn*100), size=20) histograms.addText(0.55, 0.88, "red > %.0f %%" % (warn*100), size=20) # Save the canvas to a file backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kWarning plotName = os.path.join(self._plotDirName, "FakeBNormalisationDQM") # For-loop: Save formats for ext in ["png", "C", "pdf"]: saveName ="%s.%s" % (plotName, ext) c.Print(saveName) ROOT.gErrorIgnoreLevel = backup ROOT.gStyle.SetPalette(1) msg = "Obtained %d warnings and %d errors for the normalisation" % (nWarnings, nErrors) self.Verbose(msg) if nWarnings > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % (nWarnings, nErrors, os.path.basename(plotName)) self.Verbose(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) #if nWarnings > 0 or nErrors > 0: if nErrors > 0: msg = "DQM has %d warnings and %d errors! Please have a look at %s.png." % (nWarnings, nErrors, os.path.basename(plotName)) self.Verbose(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) return
def doPlot(name, graphs, limits, xlabel, scenario, progversion): obs = graphs["obs"] # excluded = ROOT.TGraph(obs) # excluded.SetName("ExcludedArea") # excluded.SetFillColor(ROOT.kGray) ## excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN()-1], tanbMax) ## excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) # excluded.SetPoint(excluded.GetN(), -1, 1) # excluded.SetPoint(excluded.GetN(), -1, 100) # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], 100) # if not obs.GetY()[0] == 100: # excluded.SetPoint(excluded.GetN(), obs.GetX()[0], obs.GetY()[0]) """ excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetPoint(excluded.GetN(), 0, tanbMax) excluded.SetPoint(excluded.GetN(), 0, 1) excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN()-1], 1) """ # excluded.SetFillColor(ROOT.kGray) # excluded.SetFillStyle(3354) # excluded.SetLineWidth(0) # excluded.SetLineColor(ROOT.kWhite) expected = graphs["exp"] expected.SetLineStyle(2) expected1 = graphs["exp1"] expected1.SetLineStyle(2) expected2 = graphs["exp2"] expected2.SetLineStyle(2) plot = plots.PlotBase([ histograms.HistoGraph(graphs["obs"], "Observed", drawStyle="PL", legendStyle="lp"), histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L"), histograms.HistoGraph(graphs["excluded"], "Excluded", drawStyle="F", legendStyle="f"), histograms.HistoGraph(expected, "Expected", drawStyle="L"), #histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), #### histograms.HistoGraph(graphs["Allowed"], "Allowed by \nm_{H} = 125.9#pm3.0 "+GeVUnit, drawStyle="F", legendStyle="f"), #### histograms.HistoGraph(graphs["Allowed"], "AllowedCopy", drawStyle="L", legendStyle="f"), # histograms.HistoGraph(graphs["mintanb"], "MinTanb", drawStyle="L"), #histograms.HistoGraph(graphs["exp1"], "Expected1", drawStyle="F", legendStyle="fl"), #histograms.HistoGraph(graphs["exp2"], "Expected2", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected1, "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected2, "Expected2", drawStyle="F", legendStyle="fl"), ]) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Expected": None, # "MinTanb": None, #### "AllowedCopy": None, "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma" }) # plot.setLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355)) plot.setLegend(histograms.createLegend(0.19, 0.60, 0.57, 0.80)) plot.legend.SetFillColor(0) plot.legend.SetFillStyle(1001) plot.createFrame(name, opts={ "ymin": 0, "ymax": tanbMax, "xmin": 180, "xmax": 600 }) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() histograms.addStandardTexts(lumi="2.3-4.9", addCmsText=False) size = 20 x = 0.2 histograms.addText(x, 0.9, limit.processHeavy, size=size) histograms.addText(x, 0.863, limits.getFinalstateText(), size=size) #### histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size) histograms.addText(x, 0.815, scenario, size=size) # histograms.addText(x, 0.775, limit.BRassumption, size=size) # histograms.addText(x, 0.735, "#mu=%d %s"%(mu, limit.massUnit()), size=size) # histograms.addText(0.7, 0.23, "Min "+limit.BR+"(t#rightarrowH^{+}b)#times"+limit.BR+"(H^{+}#rightarrow#tau#nu)", size=0.5*size) #Adding a LHC label: ROOT.LHCHIGGS_LABEL(0.97, 0.72, 1) histograms.addText(x, 0.55, progversion, size=size) histograms.addText(x, 0.48, "Derived from", size=size) histograms.addText(x, 0.43, "CMS HIG-13-XXX", size=size) # histograms.addText(x, 0.38, "JHEP07(2012)143", size=size) plot.save()
def main(argv): dirs = [] if len(sys.argv) < 2: usage() dirs.append(sys.argv[1]) dirs_signal = ["../../SignalAnalysis_140605_143702/"] QCDInvertedNormalization = sort(QCDInvertedNormalizationFactors.QCDInvertedNormalization) labels,QCDInvertedNormalizationFilteredEWKFakeTaus = getSortedLabelsAndFactors(QCDInvertedNormalizationFactorsFilteredEWKFakeTaus.QCDInvertedNormalization) analysis_inverted = "signalAnalysisInvertedTau" analysis = "signalAnalysis" optModes = [] #optModes.append("OptQCDTailKillerZeroPlus") optModes.append("OptQCDTailKillerLoosePlus") optModes.append("OptQCDTailKillerMediumPlus") optModes.append("OptQCDTailKillerTightPlus") varHistoName = "shapeEWKGenuineTausTransverseMass" nomHistoName = "shapeTransverseMass" signalHistoName = "shapeEWKFakeTausTransverseMass" #Optimal: 0.8, 0.82, 0.9 ###w_list = [0.65, 0.7, 0.76] #old baseline ft w_list = [0.66, 0.67, 0.75] #w_list = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1] #defaultBinning = systematics.getBinningForPlot("shapeTransverseMass") defaultBinning = [0,20,40,60,80,100,120,140,160,200,400] defaultBinning_array = array.array("d",defaultBinning) diff_opt = [] for optMode in optModes: diff_list = [] for w in w_list: var_values = [] nom_values = [] # baseline fake taus mt_baseline_faketaus_data = getDataSets(dirs_signal, dataEra, searchMode, analysis, optMode) mtplot_signalfaketaus = plots.DataMCPlot(mt_baseline_faketaus_data, signalHistoName) mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto("EWK").getRootHisto().Clone(signalHistoName) # inverted fake taus mt_inverted_faketaus_data = getDataSets(dirs, dataEra, searchMode, analysis_inverted, optMode) histonames_var = mt_inverted_faketaus_data.getDataset("Data").getDirectoryContent(varHistoName) histonames_nom = mt_inverted_faketaus_data.getDataset("Data").getDirectoryContent(nomHistoName) bins_var = getBins(histonames_var, varHistoName) bins_nom = getBins(histonames_nom, nomHistoName) normalization_var_qg = getNormalization(bins_var,w,QCDInvertedNormalizationFilteredEWKFakeTaus,True,True) normalization_var = getNormalization(bins_var,w,QCDInvertedNormalizationFilteredEWKFakeTaus,True,False) normalization_nom = getNormalization(bins_nom,w,QCDInvertedNormalization,False,False) mt_var_qg = getMt(mt_inverted_faketaus_data,bins_var,varHistoName,normalization_var_qg) mt_var = getMt(mt_inverted_faketaus_data,bins_var,varHistoName,normalization_var) mt_nom = getMt(mt_inverted_faketaus_data,bins_nom,nomHistoName,normalization_nom) mt_nom.Add(mt_signalfaketaus) mt_var_qg.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau), q-g bal.") mt_var.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)") mt_nom.SetName("QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)") mt_var_qg.SetLineWidth(4) mt_var.SetLineColor(14) mt_nom.SetLineColor(2) mt_var_qg = mt_var_qg.Rebin(len(defaultBinning)-1,"",defaultBinning_array) mt_var = mt_var.Rebin(len(defaultBinning)-1,"",defaultBinning_array) mt_nom = mt_nom.Rebin(len(defaultBinning)-1,"",defaultBinning_array) for i in range(0,mt_nom.GetSize()): var_values.append(mt_var_qg.GetBinContent(i)) nom_values.append(mt_nom.GetBinContent(i)) style = tdrstyle.TDRStyle() varPlots = [mt_var, mt_var_qg] plot = plots.ComparisonManyPlot(mt_nom,varPlots) plot.createFrame(optMode.replace("Opt","Mt_DataDrivenVsMC_"+"w="+str(w)+"_"), createRatio=True) moveLegend={"dx": -0.35,"dy": 0.05} plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText(0.65, 0.3, optMode.replace("OptQCDTailKiller","R_{BB} ").replace("Plus",""), 25) histograms.addCmsPreliminaryText() histograms.addEnergyText() lumi=mt_inverted_faketaus_data.getDataset("Data").getLuminosity() histograms.addLuminosityText(x=None, y=None, lumi=lumi) plot.draw() plot.save() mt_var_qg.Delete() mt_var.Delete() mt_nom.Delete() #TFile.CurrentFile().Close("R") mt_baseline_faketaus_data.close() mt_inverted_faketaus_data.close() ROOT.gROOT.CloseFiles() ROOT.gROOT.GetListOfCanvases().Delete() ROOT.gDirectory.GetList().Delete() #print var_values #print nom_values # difference metrics num = 0 denom = 0 for i in range(0,len(nom_values)): num += var_values[i]*(var_values[i]-nom_values[i])**2 denom += var_values[i] diff = num/denom diff_list.append(diff) diff_opt.append(diff_list) os.system("rm MtOptimal/*") os.system("mkdir -p MtOptimal") print "\nWeights:\t",w_list,'\n' optimalWeights = {} for i in range(0,len(diff_opt)): print optModes[i] print "Differences:\t",diff_opt[i],"- Optimal: w =",w_list[diff_opt[i].index(min(diff_opt[i]))] optimalWeights[optModes[i]] = w_list[diff_opt[i].index(min(diff_opt[i]))] command = "cp *" + str(w_list[diff_opt[i].index(min(diff_opt[i]))])+"*"+optModes[i].replace("Opt","") + ".eps MtOptimal" os.system(command) print optimalWeights writeWeightsToFile("OptimalWeights.py",optimalWeights) writeNormalizationToFile("QCDPlusEWKFakeTauNormalizationFactors.py",normalization_var_qg,labels)
def drawAllInOne(self, myAllShapeNuisances, luminosity): myMaxSize = len(myAllShapeNuisances) # Create pads canvasHeight = _cHeaderHeight + _cBodyHeight * myMaxSize + _cFooterHeight c = ROOT.TCanvas("","",600,canvasHeight) c.Divide(1,myMaxSize) myHeightBefore = canvasHeight myHeightAfter = canvasHeight for i in range(0,myMaxSize): myHeightBefore = myHeightAfter p = c.cd(i+1) myTopMargin = 0.0 myBottomMargin = 0.0 if i == 0: # Top histogram with header myHeightAfter -= _cHeaderHeight + _cBodyHeight myTopMargin = float(_cHeaderHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: # Bottom histogram with x axis label and title myHeightAfter -= _cFooterHeight + _cBodyHeight myBottomMargin = float(_cFooterHeight) / float(_cFooterHeight+_cBodyHeight) else: # Middle histogram, only body myHeightAfter -= _cBodyHeight (xlow, ylow, xup, yup) = [ROOT.Double(x) for x in [0.0]*4] p.GetPadPar(xlow, ylow, xup, yup) p.SetPad(xlow, float(myHeightAfter)/float(canvasHeight), xup, float(myHeightBefore)/float(canvasHeight)) p.SetBorderMode(0) p.SetFillStyle(4000) p.SetTopMargin(myTopMargin) p.SetBottomMargin(myBottomMargin) # Draw plots if len(self._ratioPlotList) == 0: print "No ratioplots in list! Cannot draw all-in-one plot!" return o = self._ratioPlotList[0].getFrame2() myEmptyPlot = aux.Clone(o) # Keep the clone if it is needed to draw the x axis for i in range(0,myMaxSize): p = c.cd(i+1) # Find plot myPlotIndex = None for j in range(0,len(self._systNameList)): if myAllShapeNuisances[i] == self._systNameList[j]: myPlotIndex = j plot = None if myPlotIndex != None: plot = self._ratioPlotList[myPlotIndex].getFrame2() else: if i == myMaxSize-1: plot = myEmptyPlot # Use this to draw the x axis else: plot = self._ratioPlotList[0].getFrame2() # Only the empty frame matters # Draw plot if i == myMaxSize-1: # Bottom histogram plot.GetXaxis().SetTitleOffset(0.6*myMaxSize+0.6) # 6.6/10, 3.6/5 else: plot.GetXaxis().SetTitleSize(0) plot.GetXaxis().SetLabelSize(0) plot.GetYaxis().SetLabelSize(26) plot.GetYaxis().SetTitleOffset(0.34*myMaxSize+0.1) # 3.5/10, 1.8/5 # plot.SetMinimum(0.001) # plot.SetMaximum(1.999) plot.SetMinimum(0.601) plot.SetMaximum(1.399) plot.Draw() # Plot frame for every nuisance if myPlotIndex != None: self._ratioPlotList[myPlotIndex].ratioHistoMgr.draw() # Plot content only if affected self._ratioPlotList[0].ratioLine.Draw("L") p.RedrawAxis() # Labels for shape nuisance and dataset myHeight = 0.82 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.18, y=myHeight, text=myAllShapeNuisances[i], size=30) myHeight = 0.08 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.93, y=myHeight, text=self._dsetName, size=30, align="right") # Header labels if i == 0: histograms.addStandardTexts(lumi=luminosity, cmsTextPosition="outframe") # Labels for non-existing nuisances if myPlotIndex == None: myHeight = 0.44 if i == 0: myHeight = myHeight*float(_cBodyHeight) / float(_cHeaderHeight+_cBodyHeight) elif i == myMaxSize-1: myHeight = (myHeight*float(_cBodyHeight)+float(_cFooterHeight)) / float(_cFooterHeight +_cBodyHeight) histograms.addText(x=0.555, y=myHeight, text="Not affected", size=30, align="center") # Save plot myPlotName = "shapeSystRatioOnlyAll_%s"%(self._dsetName) backup = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError for suffix in [".png",".C",".eps"]: c.Print("%s/%s%s"%(_dirname,myPlotName,suffix)) ROOT.gErrorIgnoreLevel = backup
def main(): if len(sys.argv) < 2: usage() paths = [sys.argv[1]] analysis = "METLeg_2015D_MET80" # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) styles.mcStyle.apply(eff2_MET80) eff1_MET80.SetMarkerSize(1) eff2_MET80.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_"+analysis+"_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1, "eff2_MET80": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) label = analysis.split("_")[1] histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 0.46, "Runs "+runRange, 17) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity",d.getName(),d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum",lumi histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) pythonWriter.addParameters(plotDir,label,runRange,lumi,eff1_MET80) pythonWriter.addMCParameters(label,eff2_MET80) pythonWriter.writeJSON(os.path.join(plotDir,"metLegTriggerEfficiency2015.json")) """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET #### MET80 analysisc = "METLeg_2015D_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity",d.getName(),d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum",lumi histograms.addStandardTexts(lumi=lumi) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ ######################################################################### namePU = "TauMET_"+analysis+"_DataVsMC_nVtx" eff1PU = getEfficiency(dataset1,"NumeratorPU","DenominatorPU") eff2PU = getEfficiency(dataset2,"NumeratorPU","DenominatorPU") styles.dataStyle.apply(eff1PU) styles.mcStyle.apply(eff2PU) eff1PU.SetMarkerSize(1) eff2PU.SetMarkerSize(1.5) pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) opts = {"ymin": 0.001, "ymax": 0.1} pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pPU.getPad1().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.25, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) histograms.addText(0.4, 0.18, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.11, "Runs "+datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in",plotDir
def main(argv): dirs = [] if len(sys.argv) < 2: usage() dirs.append(sys.argv[1]) QCDInvertedNormalization = QCDInvertedNormalizationFactors.QCDInvertedNormalization QCDInvertedNormalizationFilteredEWKFakeTaus = QCDInvertedNormalizationFactorsFilteredEWKFakeTaus.QCDInvertedNormalization analysis = "signalAnalysisInvertedTau" optModes = [] #optModes.append("OptQCDTailKillerZeroPlus") optModes.append("OptQCDTailKillerLoosePlus") optModes.append("OptQCDTailKillerMediumPlus") optModes.append("OptQCDTailKillerTightPlus") #optModes.append("OptQCDTailKillerVeryTightPlus") #optModes.append("OnlyGenuineMCTausFalse") #optModes.append("OnlyGenuineMCTausTrue") #Optimal: 0.8, 0.82, 0.9 #w1_list = [0.8, 0.82, 0.84, 0.87] #w1_list = [0.8, 0.82, 0.9, 1] w1_list = [0.9] defaultBinning = systematics.getBinningForPlot("shapeTransverseMass") diff_opt = [] for optMode in optModes: diff_list = [] for w1 in w1_list: var_values = [] nom_values = [] w2 = 1 - w1 color = 1 #signal dirs_signal = ["../../SignalAnalysis_140605_143702/"] datasets_signal = dataset.getDatasetsFromMulticrabDirs( dirs_signal, dataEra=dataEra, searchMode=searchMode, analysisName=analysis.replace("InvertedTau", ""), optimizationMode=optMode) datasets_signal.updateNAllEventsToPUWeighted() datasets_signal.loadLuminosities() datasets_signal.remove( filter(lambda name: "TTToHplus" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "HplusTB" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "Hplus_taunu_t-channel" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "Hplus_taunu_tW-channel" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "TTJets_SemiLept" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "TTJets_FullLept" in name, datasets_signal.getAllDatasetNames())) datasets_signal.remove( filter(lambda name: "TTJets_Hadronic" in name, datasets_signal.getAllDatasetNames())) plots.mergeRenameReorderForDataMC(datasets_signal) datasets_signal.merge( "EWK", ["TTJets", "WJets", "DYJetsToLL", "SingleTop", "Diboson"]) mtplot_signalfaketaus = plots.DataMCPlot( datasets_signal, "shapeEWKFakeTausTransverseMass") mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto( "EWK").getRootHisto().Clone("shapeEWKFakeTausTransverseMass") mt_signalfaketaus.SetName("BaselineFakeTaus") myBinning = [0, 20, 40, 60, 80, 100, 120, 140, 160, 200, 400] myArray = array.array("d", myBinning) fitBinning = [] for i in range(0, 45): fitBinning.append(i * 10) fitArray = array.array("d", fitBinning) mt_baseline = mt_signalfaketaus #rangeMin = mt_signalfaketaus.GetXaxis().GetXmin() #rangeMax = mt_signalfaketaus.GetXaxis().GetXmax() #theFit = TF1('theFit',FitFunction(),rangeMin,rangeMax,4) #theFit.SetParLimits(0,0.5,10000) #theFit.SetParLimits(1,90,10000) #theFit.SetParLimits(2,30,10000) #theFit.SetParLimits(3,0.001,10000) #mt_signalfaketaus.Fit(theFit,"R") #theFit.SetRange(mt_signalfaketaus.GetXaxis().GetXmin(),mt_signalfaketaus.GetXaxis().GetXmax()) #theFit.SetLineStyle(2) #theFit.SetLineColor(4) #theFit.SetLineWidth(3) #theFit.Draw() #mt_corr = theFit.GetHistogram() #mt_corr = mt_corr.Rebin(len(fitBinning)-1,"",fitArray) #mt_corr.Scale(mt_baseline.GetMaximum()/mt_corr.GetMaximum()) for HISTONAME in histoNameList: var = False if HISTONAME == "shapeEWKGenuineTausTransverseMass": var = True datasets = dataset.getDatasetsFromMulticrabDirs( dirs, dataEra=dataEra, searchMode=searchMode, analysisName=analysis, optimizationMode=optMode) datasets.updateNAllEventsToPUWeighted() datasets.loadLuminosities() plots.mergeRenameReorderForDataMC(datasets) datasets.merge( "EWK", ["TTJets", "WJets", "DYJetsToLL", "SingleTop", "Diboson"]) histonames = datasets.getDataset("Data").getDirectoryContent( HISTONAME) bins = [] for histoname in histonames: binname = histoname.replace(HISTONAME, "") if not binname == "Inclusive": bins.append(binname) for i, bin in enumerate(bins): mtplot = plots.DataMCPlot( datasets, HISTONAME + "/" + HISTONAME + bin) if i == 0: mt = mtplot.histoMgr.getHisto( "Data").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) mt_ewk = mtplot.histoMgr.getHisto( "EWK").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) mtn = mtplot.histoMgr.getHisto( "Data").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) mtn_ewk = mtplot.histoMgr.getHisto( "EWK").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) if var: legendName = "QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)" else: legendName = "QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)" legendName = legendName.replace("Plus", "") mt.SetName(legendName) mt.SetLineColor(color) mt.Add(mt_ewk, -1) mtn.Add(mtn_ewk, -1) mtn.Scale(QCDInvertedNormalization[str(i)]) if var: scale = w1 * QCDInvertedNormalizationFilteredEWKFakeTaus[ str( i )] + w2 * QCDInvertedNormalizationFilteredEWKFakeTaus[ str(i) + "EWK_FakeTaus"] mt.Scale(scale) else: mt.Scale(QCDInvertedNormalization[str(i)]) color += 1 if color == 5: color += 1 else: h = mtplot.histoMgr.getHisto( "Data").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) mt_ewk = mtplot.histoMgr.getHisto( "EWK").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) hn = mtplot.histoMgr.getHisto( "Data").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) mtn_ewk = mtplot.histoMgr.getHisto( "EWK").getRootHisto().Clone(HISTONAME + "/" + HISTONAME + bin) h.Add(mt_ewk, -1) hn.Add(mtn_ewk, -1) hn.Scale(QCDInvertedNormalization[str(i)]) if var: scale = w1 * QCDInvertedNormalizationFilteredEWKFakeTaus[ str( i )] + w2 * QCDInvertedNormalizationFilteredEWKFakeTaus[ str(i) + "EWK_FakeTaus"] h.Scale(scale) else: h.Scale(QCDInvertedNormalization[str(i)]) mt.Add(h) mtn.Add(hn) #mt = mt.Rebin(len(myBinning)-1,"",myArray) #mt_corr = mt_corr.Rebin(len(myBinning)-1,"",myArray) if not var: mt.Add(mt_baseline) #mt.Add(mt_corr) #myBinning = [] #for i in range(0,11): # myBinning.append(20*i) #myBinning.append(400) #myArray = array.array("d",defaultBinning) mt = mt.Rebin(len(myBinning) - 1, "", myArray) for i in range(0, mt.GetSize()): if var: var_values.append(mt.GetBinContent(i)) else: nom_values.append(mt.GetBinContent(i)) if var: #mt.SetLineStyle(2) var_hist = mt else: #mt.SetLineStyle(2) nom_hist = mt style = tdrstyle.TDRStyle() #gStyle.SetOptStat(1101) #mt_data.SetStats(1) #gPad.Update() bins = [0, 390, 400] arr = array.array("d", bins) mtn = mtn.Rebin(len(bins) - 1, "", arr) plot_data = plots.PlotBase() plot_data.histoMgr.appendHisto(histograms.Histo(mtn, "Data")) plot_data.createFrame("Data_" + HISTONAME + "_" + optMode + "_" + str(w1)) plot_data.draw() plot_data.save() plot = plots.ComparisonPlot(nom_hist, var_hist) plot.createFrame(optMode.replace( "Opt", "Mt_" + "w1=" + str(w1) + "_w2=" + str(w2) + "_DataDrivenVsMC_"), createRatio=True) moveLegend = {"dx": -0.295, "dy": 0.05} plot.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText( 0.65, 0.20, optMode.replace("OptQCDTailKiller", "R_{BB} ").replace("Plus", ""), 25) histograms.addCmsPreliminaryText() histograms.addEnergyText() lumi = datasets.getDataset("Data").getLuminosity() histograms.addLuminosityText(x=None, y=None, lumi=lumi) plot.draw() plot.save() num = 0 denom = 0 #print var_values for i in range(0, len(nom_values)): num += var_values[i] * (var_values[i] - nom_values[i])**2 denom += var_values[i] diff = num / denom diff_list.append(diff) diff_opt.append(diff_list) print w1_list, '\n' for i in range(0, len(diff_opt)): print diff_opt[i] print w1_list[diff_opt[i].index(min(diff_opt[i]))] mt_baseline = mt_baseline.Rebin(len(bins) - 1, "", arr) plot_bft = plots.PlotBase() plot_bft.histoMgr.appendHisto(histograms.Histo(mt_baseline, "baseline")) #mt_corr.Scale(2) #plot_bft.histoMgr.appendHisto(histograms.Histo(mt_corr,"test")) #rangeMin = mt_signalfaketaus.GetXaxis().GetXmin() #rangeMax = mt_signalfaketaus.GetXaxis().GetXmax() #theFit = TF1('theFit',FitFunction(),rangeMin,rangeMax,4) #theFit.SetParLimits(0,0.5,10000) #theFit.SetParLimits(1,90,10000) #theFit.SetParLimits(2,30,10000) #theFit.SetParLimits(3,0.001,10000) #mt_signalfaketaus.Fit(theFit,"R") #theFit.SetRange(mt_signalfaketaus.GetXaxis().GetXmin(),mt_signalfaketaus.GetXaxis().GetXmax()) #theFit.SetLineStyle(2) #theFit.SetLineColor(4) #theFit.SetLineWidth(3) #theFit.Draw() #mt_corr = theFit.GetHistogram() #mt_corr = mt_corr.Rebin(len(fitBinning)-1,"",fitArray) #mt_corr.Scale(mt_baseline.GetMaximum()/mt_corr.GetMaximum()) #plot_bft.histoMgr.appendHisto(histograms.Histo(mt_corr,"test")) #plot_bft.histoMgr.appendHisto(histograms.Histo(theFit,"theFit")) plot_bft.createFrame('BaselineFakeTaus') plot_bft.draw() plot_bft.save()
def main(opts): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # ======================================== # Datasets # ======================================== # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) intLumi = GetLumi(datasetsMgr) datasetsMgr.updateNAllEventsToPUWeighted() datasetsMgr.PrintCrossSections() #datasetsMgr.PrintLuminosities() # Set/Overwrite cross-sections for d in datasetsMgr.getAllDatasets(): if "ChargedHiggs" in d.getName(): datasetsMgr.getDataset(d.getName()).setCrossSection(1.0) # Merge datasts (Note: Merged MC histograms must be normalized to something) plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets if 0: datasetsMgr.remove("TTJets") datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # Print dataset information datasetsMgr.PrintInfo() # For-loop: All Histogram names for counter, hName in enumerate(hNames): savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a plot p = plots.PlotBase([refHisto], kwargs.get("saveFormats")) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Customize # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL" p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(2)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(2)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0045)) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=opts) # Customise frame p.getFrame().GetXaxis().SetTitle( getTitleX(refHisto, **kwargs) ) #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = { "lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.removeLegend() # Add MC Uncertainty (Invalid method for a 2-d histogram) #p.addMCUncertainty() # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.17, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.17, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter==0) return
def doPlot(name, graphs, limits, xlabel, scenario, isMA=False): blinded = True if "obs" in graphs.keys(): blinded = False higgs = "h" if scenario == "lowMH-LHCHXSWG": higgs = "H" if not blinded: obs = graphs["obs"] excluded = ROOT.TGraph(obs) excluded.SetName("ExcludedArea") if "_mA_" in name: rightX = obs.GetX()[obs.GetN()-1]+100 rightY = obs.GetY()[obs.GetN()-1] excluded.SetPoint(excluded.GetN(), rightX, rightY) excluded.SetPoint(excluded.GetN(), rightX, 1) else: excluded.SetPoint(excluded.GetN(), obs.GetX()[obs.GetN()-1], 0.5) excluded.SetPoint(excluded.GetN(), 0, 0.5) excluded.SetPoint(excluded.GetN(), 0, tanbMax) excluded.SetPoint(excluded.GetN(), obs.GetX()[0], tanbMax) excluded.SetPoint(excluded.GetN(), obs.GetX()[0], obs.GetY()[0]) limit.setExcludedStyle(excluded) 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) # allowed = graphs["Allowed"] # if not allowed == None: # allowed.SetFillStyle(3005) # allowed.SetFillColor(ROOT.kRed) # allowed.SetLineWidth(-302) # allowed.SetLineColor(ROOT.kRed) # allowed.SetLineStyle(1) if not blinded: graphs["obs_th_plus"].SetLineStyle(9) # graphs["obs_th_minus"].SetLineStyle(9) excludedCopy = excluded.Clone() # excludedCopy.SetFillColorAlpha(ROOT.kWhite, 0.0) # actual color doesn't matter, want fully transparent 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["isomass"], "IsoMass", drawStyle="L"), # histograms.HistoGraph(graphs["isomass"], "IsoMassCopy", drawStyle="F"), histograms.HistoGraph(excluded, "Excluded", drawStyle="F", legendStyle=None), histograms.HistoGraph(excludedCopy, "ExcludedCopy", drawStyle=None, legendStyle="f"), histograms.HistoGraph(expected, "Expected", drawStyle="L"), # histograms.HistoGraph(graphs["exp"], "Expected", drawStyle="L"), # histograms.HistoGraph(graphs["Allowed"], "Allowed", drawStyle="L", legendStyle="lf"), # 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") ], saveFormats=[".png", ".pdf", ".C"] ) plot.histoMgr.setHistoLegendLabelMany({ "ObservedPlus": "Observed #pm1#sigma (th.)", "ObservedMinus": None, "Excluded": None, "ExcludedCopy": "Excluded", "Expected": None, "MinTanb": None, # "Allowed": "m_{"+higgs+"}^{MSSM} #neq 125#pm3 GeV", "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma", # "IsoMass": None, # "IsoMassCopy": None }) else: if not graphs["isomass"] == None: graphs["isomass"].SetFillColor(0) graphs["isomass"].SetFillStyle(1) plot = plots.PlotBase([ histograms.HistoGraph(expected, "Expected", drawStyle="L"), histograms.HistoGraph(graphs["isomass"], "IsoMass", drawStyle="L"), histograms.HistoGraph(graphs["isomass"], "IsoMassCopy", drawStyle="F"), # histograms.HistoGraph(graphs["Allowed"], "Allowed", drawStyle="L", legendStyle="lf"), # histograms.HistoGraph(graphs["Allowed"], "AllowedCopy", drawStyle="L", legendStyle="f"), histograms.HistoGraph(graphs["mintanb"], "MinTanb", drawStyle="L"), histograms.HistoGraph(expected1, "Expected1", drawStyle="F", legendStyle="fl"), histograms.HistoGraph(expected2, "Expected2", drawStyle="F", legendStyle="fl"), ], saveFormats=[".png", ".pdf", ".C"] ) plot.histoMgr.setHistoLegendLabelMany({ "Expected": None, "MinTanb": None, # "Allowed": "m_{"+higgs+"}^{MSSM} #neq 125#pm3 GeV", "Expected1": "Expected median #pm 1#sigma", "Expected2": "Expected median #pm 2#sigma", "IsoMass": None, "IsoMassCopy": None }) # Move the m_h,H allowed region to the last in the legend histoNames = [h.getName() for h in plot.histoMgr.getHistos()] plot.histoMgr.reorderLegend(filter(lambda n: "Allowed" not in n, histoNames)) size = 20 x = 0.2 # dy = -0.15 dy = -0.13 plot.setLegend(histograms.createLegend(x-0.01, 0.50+dy, x+0.45, 0.80+dy)) plot.legend.SetMargin(0.17) # plot.legend.SetFillColor(0) #plot.legend.SetFillColorAlpha(ROOT.kWhite, 50) # plot.legend.SetFillStyle(1001) if blinded: name += "_blinded" name = os.path.basename(name) name = name.replace("-","_") frameXmax = 160 if "_mA_" in name: frameXmax = 145 plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax, "xmin": 90, "xmax": frameXmax}) plot.frame.GetXaxis().SetTitle(xlabel) plot.frame.GetYaxis().SetTitle(limit.tanblimit) plot.draw() plot.setLuminosity(limits.getLuminosity()) plot.addStandardTexts() histograms.addText(x, 0.9+dy, "t #rightarrow H^{+}b, H^{+} #rightarrow c#bar{s}", size=size) # histograms.addText(x, 0.863+dy, limits.getFinalstateText(), size=size) histograms.addText(x, 0.815+dy, limit.getTypesetScenarioName(scenario), 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) # Too small to be visible # if not graphs["isomass"] == None: # histograms.addText(0.8, 0.15, "m_{H^{#pm}} = 160 GeV", 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+dy, FH_version, size=size) # 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 main(): if len(sys.argv) == 1: usage() rootfile = "" root_re = re.compile("(?P<rootfile>(\S*\.root))") match = root_re.search(sys.argv[1]) if match: rootfile = match.group(0) limits = limit.BRLimits() # Apply TDR style style = tdrstyle.TDRStyle() if limit.forPaper: histograms.cmsTextMode = histograms.CMSMode.PAPER xvar = "mHp" yvars = [] yvars.append("BR_Hp_taunu") yvars.append("BR_Hp_tb") yvars.append("BR_Hp_h0W") yvars.append("BR_Hp_A0W") yvars.append("BR_Hp_HW") # yvars.append("BR_Hp_Neu1Cha1") # yvars.append("BR_Hp_Neu2Cha1") susyvars = [] susyvars.append("BR_Hp_Neu1Cha1") susyvars.append("BR_Hp_Neu2Cha1") # susyvars.append("BR_Hp_Neu3Cha1") # susyvars.append("BR_Hp_Neu4Cha1") # susyvars.append("BR_Hp_Neu1Cha2") # susyvars.append("BR_Hp_Neu2Cha2") # susyvars.append("BR_Hp_Neu3Cha2") # susyvars.append("BR_Hp_Neu4Cha2") # db = BRXSDB.BRXSDatabaseInterface(rootfile,heavy=True,program="2HDMC") db = BRXSDB.BRXSDatabaseInterface(rootfile, heavy=True, program="FeynHiggs") progversion = db.GetProgram() + " v" + db.GetVersion() selection = "tanb==10" # scenario = "2HDM Type II" scenario = "mhmax" graphs = {} for icolor, yvar in enumerate(yvars): tmpsel = selection br = db.getGraph(xvar, yvar, tmpsel) xarray = array.array('d') yarray = array.array('d') for i in range(0, br.GetN()): x = ROOT.Double() y = ROOT.Double() br.GetPoint(i, x, y) xarray.append(x) yarray.append(y) newx, newy = sort(xarray, yarray) newGraph = ROOT.TGraph(len(newx), newx, newy) newGraph.SetLineWidth(3) newGraph.SetLineColor(1 + icolor) graphs[yvar] = newGraph xsusy = array.array('d') ysusy = array.array('d') for yvar in susyvars: tmpsel = selection br = db.getGraph(xvar, yvar, tmpsel) xarray = array.array('d') yarray = array.array('d') for i in range(0, br.GetN()): x = ROOT.Double() y = ROOT.Double() br.GetPoint(i, x, y) xarray.append(x) yarray.append(y) print "check x,y", x, y xsusy, ysusy = add(xsusy, ysusy, xarray, yarray) print "check len", len(xsusy) newx, newy = sort(xsusy, ysusy) for i in range(len(newx)): print newx[i], newy[i] susyGraph = ROOT.TGraph(len(newx), newx, newy) susyGraph.SetLineWidth(3) susyGraph.SetLineColor(1 + len(graphs)) graphs["BR_Hp_SUSY"] = susyGraph plot = plots.PlotBase([ histograms.HistoGraph(graphs["BR_Hp_taunu"], "BR(H^{+}#rightarrow#tau#nu)", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["BR_Hp_tb"], "BR(H^{+}#rightarrow tb)", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["BR_Hp_h0W"], "BR(H^{+}#rightarrow hW)", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["BR_Hp_A0W"], "BR(H^{+}#rightarrow AW)", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["BR_Hp_HW"], "BR(H^{+}#rightarrow HW)", drawStyle="L", legendStyle="l"), histograms.HistoGraph(graphs["BR_Hp_SUSY"], "BR(H^{+}#rightarrow#chi_{i}^{0}#chi_{j}^{+})", drawStyle="L", legendStyle="l"), # histograms.HistoGraph(graphs["BR_Hp_Neu1Cha1"], "BR(H^{+}#rightarrow#chi_{1}^{0}#chi_{1}^{+})", drawStyle="L", legendStyle="l"), # histograms.HistoGraph(graphs["BR_Hp_Neu2Cha1"], "BR(H^{+}#rightarrow#chi_{2}^{0}#chi_{1}^{+})", drawStyle="L", legendStyle="l"), ]) plot.setLegend(histograms.createLegend(0.57, 0.60, 0.87, 0.80)) plot.legend.SetFillColor(0) plot.legend.SetFillStyle(1001) plot.createFrame("br", opts={ "ymin": 0.0001, "ymax": 1, "xmin": 180, "xmax": 600 }) plot.frame.GetXaxis().SetTitle("m_{H^{+}} (" + GeVUnit + ")") plot.frame.GetYaxis().SetTitle("BR") ROOT.gPad.SetLogy(True) plot.draw() size = 20 x = 0.57 # 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.863, scenario, size=size) selectiontxt = selection.replace("==", "=") histograms.addText(x, 0.815, selectiontxt, size=size) #Adding a LHC label: ROOT.LHCHIGGS_LABEL(0.97, 0.72, 1) # histograms.addText(x, 0.55, progversion, size=size) plot.save()
def main(): if len(sys.argv) < 2: usage() dirs = [] dirs.append(sys.argv[1]) #datasets = dataset.getDatasetsFromMulticrabDirs(dirs) datasets = dataset.getDatasetsFromMulticrabDirs(dirs,dataEra=dataEra, searchMode=searchMode, analysisName=analysis) # consistencyCheck.checkConsistencyStandalone(dirs[0],datasets,name="QCD inverted") datasets.loadLuminosities() datasets.updateNAllEventsToPUWeighted() # erik # datasets.remove(filter(lambda name: "TTJets_SemiLept" in name, datasets.getAllDatasetNames())) # datasets.remove(filter(lambda name: "TTJets_FullLept" in name, datasets.getAllDatasetNames())) # datasets.remove(filter(lambda name: "TTJets_Hadronic" in name, datasets.getAllDatasetNames())) datasets.remove(filter(lambda name: "WJetsToLNu" in name and not "WJetsToLNu_HT" in name, datasets.getAllDatasetNames())) plots.mergeRenameReorderForDataMC(datasets) datasets.merge("EWK", [ "TT", "WJetsHT", "DYJetsToLLHT", "SingleTop", # "Diboson" ]) style = tdrstyle.TDRStyle() plot = plots.PlotBase() legends = {} name_re = re.compile("SelectedTau_pT_(?P<name>\S+)") for i,histo in enumerate(HISTONAMES): plot.histoMgr.appendHisto(purityGraph(i,datasets,histo)) name = histo match = name_re.search(histo) if match: name = match.group("name") legends["Purity%s"%i] = name # if "AfterMetCut" in name: # legends["Purity%s"%i] = "MET > 60 GeV" if "SelectedTau_pT_CollinearCuts" in name: legends["Purity%s"%i] = "Collinear cuts" if "AfterBtagging" in name: legends["Purity%s"%i] = "B tagging" if "AfterBveto" in name: legends["Purity%s"%i] = "B-jet veto" if "AfterBvetoPhiCuts" in name: legends["Purity%s"%i] = "B-jet veto, TailKiller" if "SelectedTau_pT_BackToBackCuts" in name: legends["Purity%s"%i] = "BackToBack cuts" # plot.createFrame("purity_QCD_only", opts={"xmin": 40, "xmax": 160, "ymin": 0., "ymax": 1.05}) plot.createFrame("purity_QCD_only", opts={"xmin": 40, "xmax": 400, "ymin": 0., "ymax":1}) plot.frame.GetXaxis().SetTitle("p_{T}^{#tau jet} (GeV/c)") plot.frame.GetYaxis().SetTitle("QCD purity") # plot.setEnergy(datasets.getEnergies()) # plot.histoMgr.appendHisto(histograms.Histo(histo,"InvertedTauPtAfterAllSelections")) plot.histoMgr.setHistoLegendLabelMany(legends) ### plot.setLegend(histograms.createLegend(0.2, 0.35, 0.6, 0.5)) # histograms.addText(0.2, 0.3, "TailKiller: MediumPlus", 18) # histograms.addText(0.35, 0.28, "BackToBack cuts: TightPlus", 20) # histograms.addText(0.35, 0.22, "2011B", 20) histograms.addText(0.3, 0.35, "QCD only", 20) histograms.addText(0.3, 0.3, "After all selection cuts", 20) # histograms.addText(0.2, 0.3, "QCD only", 18) histograms.addCmsPreliminaryText() histograms.addEnergyText(s="%s TeV"%(datasets.getEnergies()[0])) histograms.addLuminosityText(x=None, y=None, lumi=datasets.getDataset("Data").getLuminosity()) plot.draw() plot.save()
def PlotTemplates(datasetsMgr, histoName, analysisType="Inverted"): Verbose("Plotting EWK Vs QCD unity-normalised histograms") # Create comparison plot p1 = plots.ComparisonPlot( getHisto(datasetsMgr, "Data", histoName, "Baseline"), getHisto(datasetsMgr, "Data", histoName, "Inverted") ) p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity()) defaultFolder = "ForFakeBMeasurement" genuineBFolder = defaultFolder + "EWKGenuineB" fakeBFolder = defaultFolder + "EWKFakeB" histoNameNew = histoName.replace( defaultFolder, genuineBFolder) p2 = plots.ComparisonPlot( getHisto(datasetsMgr, "EWK", histoNameNew, "Baseline"), getHisto(datasetsMgr, "EWK", histoNameNew, "Inverted") ) p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity()) # Get EWKGenuineB histos EWKGenuineB_baseline = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline-EWKGenuineB") EWKGenuineB_inverted = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted-EWKGenuineB") # Get FakeB histos FakeB_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-FakeB") FakeB_baseline.Add(EWKGenuineB_baseline, -1) FakeB_inverted = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-FakeB") FakeB_inverted.Add(EWKGenuineB_inverted, -1) # Normalize histograms to unit area EWKGenuineB_baseline.Scale(1.0/EWKGenuineB_baseline.Integral()) EWKGenuineB_inverted.Scale(1.0/EWKGenuineB_inverted.Integral()) FakeB_baseline.Scale(1.0/FakeB_baseline.Integral()) FakeB_inverted.Scale(1.0/FakeB_inverted.Integral()) # Create the final plot object comparisonList = [EWKGenuineB_baseline] p = plots.ComparisonManyPlot(FakeB_inverted, comparisonList, saveFormats=[]) p.setLuminosity(GetLumi(datasetsMgr)) # Apply styles p.histoMgr.forHisto("Baseline-EWKGenuineB", styles.getBaselineStyle() ) p.histoMgr.forHisto("Inverted-FakeB" , styles.getInvertedStyle() ) # Set draw style p.histoMgr.setHistoDrawStyle("Baseline-EWKGenuineB", "AP") p.histoMgr.setHistoDrawStyle("Inverted-FakeB" , "HIST") # Set legend style p.histoMgr.setHistoLegendStyle("Baseline-EWKGenuineB", "LP") p.histoMgr.setHistoLegendStyle("Inverted-FakeB" , "LP") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Baseline-EWKGenuineB": "GenuineB (EWK)", # (Baseline) "Inverted-FakeB" : "FakeB", # (Inverted) }) # Append analysisType to histogram name saveName = histoName # Draw the histograms #alex plots.drawPlot(p, saveName, **GetHistoKwargs(histoName) ) #the "**" unpacks the kwargs_ # _kwargs = {"lessThan": True} # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs) # Add text text = opts.optMode.replace("OptChiSqrCutValue", "#chi^{2} #leq ") histograms.addText(0.21, 0.85, text) # Save plot in all formats saveDir = os.path.join(opts.saveDir, "Templates", opts.optMode) SavePlot(p, saveName, saveDir, saveFormats = [".C", ".png", ".pdf"]) return
def 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 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 analyze(analysis=None): paths = [sys.argv[1]] if not analysis == None: # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis, includeOnlyTasks="Tau|TT") datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) else: datasets = dataset.getDatasetsFromMulticrabDirs(paths) analysis = datasets.getAllDatasets()[0].getAnalysisName() analysisList = [] # analysisList.append("METLeg_2016MET80_MET80") # analysisList.append("METLeg_2016ICHEP_MET90") # analysisList.append("METLeg_2016_MET90") met_re = re.compile("_(?P<met>MET\d+)$") if True: #for analysis in analysisList: met = "METX" met_match = met_re.search(analysis) if met_match: met = met_match.group("met") print "Analysis",analysis datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") # datasetsMC = None datasetsMC = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 createRatio = False if isinstance(datasetsMC,dataset.DatasetManager): dataset2 = datasetsMC.getMCDatasets() createRatio = True eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) eff1_MET80.SetMarkerSize(1) if createRatio: styles.mcStyle.apply(eff2_MET80) eff2_MET80.SetMarkerSize(1.5) if createRatio: p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) else: p = plots.PlotBase([histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P")]) #from plotTauLegEfficiency import fit #fit("Data",p,eff1_MET80,20,300) #fit("MC",p,eff2_MET80,20,300) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_"+analysis+"_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" #legend2 = "MC" legend2 = "Simulation" if createRatio: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1, "eff2_MET80": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) else: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1}) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) histograms.addText(0.4, 0.87, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) # label = analysis.split("_")[1] # label = "2016" label = string.replace(analysis,"METLeg_","") histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 0.46, "Runs "+runRange, 17) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity",d.getName(),d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum",lumi histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) pythonWriter.addParameters(plotDir,label,runRange,lumi,eff1_MET80) pythonWriter.addMCParameters(label,eff2_MET80) pythonWriter.writeJSON(os.path.join(plotDir,"metLegTriggerEfficiency_"+label+".json")) ######################################################################### eff1phi = getEfficiency(dataset1,"NumeratorPhi","DenominatorPhi") eff2phi = getEfficiency(dataset2,"NumeratorPhi","DenominatorPhi") styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsMC,dataset.DatasetManager): p_phi = plots.ComparisonPlot(histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), histograms.HistoGraph(eff2phi, "eff2phi", "p", "P")) else: p_phi = plots.PlotBase([histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")]) p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1}) if isinstance(datasetsMC,dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1, "eff2phi": legend2}) opts = {"ymin": 0, "ymax": 0.3} name = "TauMET_"+analysis+"_DataVsMC_PFMETPhi" if createRatio: p_phi.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) # moveLegendPhi = {"dx": -0.5, "dy": -0.6, "dh": -0.1} moveLegendPhi = {"dx": -0.55, "dy": -0.15, "dh": -0.1} p_phi.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p_phi.getFrame().GetXaxis().SetTitle("MET Type 1 #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.86, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs "+datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET """ #### MET80 analysisc = "METLeg_2016B_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity",d.getName(),d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum",lumi histograms.addStandardTexts(lumi=lumi) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ ######################################################################### namePU = "TauMET_"+analysis+"_DataVsMC_nVtx" eff1PU = getEfficiency(dataset1,"NumeratorPU","DenominatorPU") eff2PU = getEfficiency(dataset2,"NumeratorPU","DenominatorPU") styles.dataStyle.apply(eff1PU) styles.mcStyle.apply(eff2PU) eff1PU.SetMarkerSize(1) eff2PU.SetMarkerSize(1.5) if isinstance(datasetsMC,dataset.DatasetManager): pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2}) else: pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) opts = {"ymin": 0.001, "ymax": 1.0} moveLegend = {"dx": -0.33, "dy": -0.25, "dh": -0.1} createRatio = False if createRatio: pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) else: pPU.createFrame(os.path.join(plotDir, namePU), opts=opts, opts2=opts2) pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") if createRatio: pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.85, "LooseIsoPFTau50_Trk30_eta2p1_MET90", 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs "+datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in",plotDir
def 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 doPlot(mass, mu, mul=None): f = openFile(mass) tree_obs = f.Get("TESTED_R%s"%mu) if not tree_obs: print "Did not find TESTED_R%s TTree in file %s" % (mu, f.GetName()) listMu(mass, f) f.Close() return tree_sb = f.Get("SAMPLING_SB_TESTED_R%s" % mu) if not tree_sb: raise Exception("Did not find SAMPLING_SB_TESTED_R%s from file %s" % (mu, f.GetName())) tree_b = f.Get("SAMPLING_B_TESTED_R%s" % mu) if not tree_b: raise Exception("Did not find SAMPLING_B_TESTED_R%s from file %s" % (mu, f.GetName())) xmin = min(tree_sb.GetMinimum("brT"), tree_b.GetMinimum("brT")) xmax = max(tree_sb.GetMaximum("brT"), tree_b.GetMaximum("brT")) obsval = tree_obs.GetMinimum("brT") # Get the distributions tree_sb.Draw("brT >>hsb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff") h_sb = tree_sb.GetHistogram() tree_b.Draw("brT >>hb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff") h_b = tree_b.GetHistogram() # Set obsval to bin boundary obsval_bin = obsval for bin in xrange(0, h_sb.GetNbinsX()+1): edge = h_sb.GetBinLowEdge(bin) if obsval > edge: obsval_bin = edge # Normalize the distributions to unit area dataset._normalizeToOne(h_sb) dataset._normalizeToOne(h_b) plot = plots.PlotBase([ histograms.Histo(h_b, "B"), histograms.Histo(h_sb, "SB") ]) mulegend = mul if mul == None: mulegend = mu plot.histoMgr.setHistoLegendLabelMany({ "B": "f(#tilde{q}_{#mu=%s} | #mu=0, #hat{#bf{#theta}}_{0}^{obs})" % mulegend, "SB": "f(#tilde{q}_{#mu=%s} | #mu=%s, #hat{#bf{#theta}}_{#mu=%s}^{obs})" % (mulegend, mulegend, mulegend), }) plot.setLegend(histograms.moveLegend(histograms.createLegend(0.6, 0.8, 0.9, 0.9), dy=0.02, dx=-0.05)) plot.histoMgr.forEachHisto(styles.generator()) fname = "teststat_m%s_mu%s" % (mass, mu) plot.createFrame(fname.replace(".", "_"), opts={"ymin": 1e-6, "ymaxfactor": 2}) plot.frame.GetXaxis().SetTitle("Test statistic #tilde{q}_{#mu}") plot.frame.GetYaxis().SetTitle("Arbitrary units") plot.getPad().SetLogy(True) area_sb = h_sb.Clone("AreaSB") area_sb.SetFillColor(area_sb.GetLineColor()) area_sb.SetFillStyle(3005) area_sb.SetLineWidth(0) area_b = h_b.Clone("AreaB") area_b.SetFillColor(area_b.GetLineColor()) area_b.SetFillStyle(3004) area_b.SetLineWidth(0) for bin in xrange(0, area_sb.GetNbinsX()+1): if area_sb.GetBinLowEdge(bin) < obsval_bin: area_sb.SetBinContent(bin, 0) if area_b.GetBinLowEdge(bin) >= obsval_bin: area_b.SetBinContent(bin, 0) plot.appendPlotObject(area_b, "HIST ][") plot.appendPlotObject(area_sb, "HIST ][") plot.addCutBoxAndLine(box=False, cutValue=obsval_bin) plot.draw() size = 26 histograms.addText(0.35, 0.4, "CL_{s+b}", size=size) histograms.addText(0.18, 0.4, "1-CL_{b}", size=size) size = 20 # x = obsval_bin/(plot.frame.GetXaxis().GetXmax() - plot.frame.GetXaxis().GetXmin())+0.02 x = (obsval_bin - plot.getPad().GetX1()) / (plot.getPad().GetX2() - plot.getPad().GetX1()) x += 0.01 histograms.addText(x, 0.88, "Observed", size=size) histograms.addText(x, 0.85, "value", size=size) histograms.addText(0.62, 0.78, "m_{H^{+}} = %s %s" % (mass, limit.massUnit()), size=size) # size = 20 # x = 0.2 # histograms.addText(x, 0.88, brlimit.process, size=size) # histograms.addText(x, 0.84, brlimit._finalstateLabels["taujets"], size=size) # histograms.addText(x, 0.79, brlimit.BRassumption, size=size) plot.save() f.Close()
def PlotBaselineVsInvertedTemplates(datasetsMgr, histoName, addQcdBaseline=False): Verbose("Plotting EWK Vs QCD unity-normalised histograms") # Create comparison plot p1 = plots.ComparisonPlot( getHisto(datasetsMgr, "Data", "topSelection_Baseline/%s" % histoName, "Baseline"), getHisto(datasetsMgr, "EWK", "topSelection_Baseline/%s" % histoName, "Baseline")) p1.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) p2 = plots.ComparisonPlot( getHisto(datasetsMgr, "Data", "topSelection_Inverted/%s" % histoName, "Inverted"), getHisto(datasetsMgr, "EWK", "topSelection_Inverted/%s" % histoName, "Inverted")) p2.histoMgr.normalizeMCToLuminosity( datasetsMgr.getDataset("Data").getLuminosity()) # Get EWK histos EWK_baseline = p1.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone( "Baseline-EWK") EWK_inverted = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone( "Inverted-EWK") # Get QCD histos QCD_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone( "Baseline-QCD") QCD_inverted = p2.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone( "Inverted-QCD") # Create QCD histos: QCD = Data-EWK QCD_baseline.Add(EWK_baseline, -1) QCD_inverted.Add(EWK_inverted, -1) # Normalize histograms to unit area EWK_baseline.Scale(1.0 / EWK_baseline.Integral()) EWK_inverted.Scale(1.0 / EWK_inverted.Integral()) QCD_baseline.Scale(1.0 / QCD_baseline.Integral()) QCD_inverted.Scale(1.0 / QCD_inverted.Integral()) # Create the final plot object if addQcdBaseline: compareHistos = [EWK_baseline, QCD_baseline] else: compareHistos = [EWK_baseline] p = plots.ComparisonManyPlot(QCD_inverted, compareHistos, saveFormats=[]) p.setLuminosity(GetLumi(datasetsMgr)) # Apply styles p.histoMgr.forHisto("Baseline-EWK", styles.getBaselineStyle()) if addQcdBaseline: p.histoMgr.forHisto("Baseline-QCD", styles.getInvertedLineStyle()) p.histoMgr.forHisto("Inverted-QCD", styles.getInvertedStyle()) # Set draw style p.histoMgr.setHistoDrawStyle("Baseline-EWK", "AP") p.histoMgr.setHistoLegendStyle("Baseline-EWK", "LP") if addQcdBaseline: p.histoMgr.setHistoDrawStyle("Baseline-QCD", "HIST") p.histoMgr.setHistoLegendStyle("Baseline-QCD", "FL") p.histoMgr.setHistoDrawStyle("Inverted-QCD", "AP") p.histoMgr.setHistoLegendStyle("Inverted-QCD", "LP") # Set legend labels if addQcdBaseline: p.histoMgr.setHistoLegendLabelMany({ "Baseline-EWK": "EWK (Baseline)", "Baseline-QCD": "QCD (Baseline)", "Inverted-QCD": "QCD (Inverted)", }) else: p.histoMgr.setHistoLegendLabelMany({ "Baseline-EWK": "EWK (Baseline)", "Inverted-QCD": "QCD (Inverted)", }) # Append analysisType to histogram name saveName = histoName # Draw the histograms #alex plots.drawPlot(p, saveName, **GetHistoKwargs(histoName)) #the "**" unpacks the kwargs_ # _kwargs = {"lessThan": True} # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs) # Add text text = opts.optMode.replace("OptChiSqrCutValue", "#chi^{2} #leq ") histograms.addText(0.21, 0.85, text) # Save plot in all formats saveDir = os.path.join(opts.saveDir, "Templates", opts.optMode) SavePlot(p, saveName, saveDir, saveFormats=[".C", ".png", ".pdf"]) return
def main(argv): dirs = [] if len(sys.argv) < 2: usage() dirs.append(sys.argv[1]) dirs_signal = ["../../SignalAnalysis_140605_143702/"] QCDInvertedNormalization = sort( QCDInvertedNormalizationFactors.QCDInvertedNormalization) labels, QCDInvertedNormalizationFilteredEWKFakeTaus = getSortedLabelsAndFactors( QCDInvertedNormalizationFactorsFilteredEWKFakeTaus. QCDInvertedNormalization) analysis_inverted = "signalAnalysisInvertedTau" analysis = "signalAnalysis" optModes = [] #optModes.append("OptQCDTailKillerZeroPlus") optModes.append("OptQCDTailKillerLoosePlus") optModes.append("OptQCDTailKillerMediumPlus") optModes.append("OptQCDTailKillerTightPlus") varHistoName = "shapeEWKGenuineTausTransverseMass" nomHistoName = "shapeTransverseMass" signalHistoName = "shapeEWKFakeTausTransverseMass" #Optimal: 0.8, 0.82, 0.9 ###w_list = [0.65, 0.7, 0.76] #old baseline ft w_list = [0.66, 0.67, 0.75] #w_list = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1] #defaultBinning = systematics.getBinningForPlot("shapeTransverseMass") defaultBinning = [0, 20, 40, 60, 80, 100, 120, 140, 160, 200, 400] defaultBinning_array = array.array("d", defaultBinning) diff_opt = [] for optMode in optModes: diff_list = [] for w in w_list: var_values = [] nom_values = [] # baseline fake taus mt_baseline_faketaus_data = getDataSets(dirs_signal, dataEra, searchMode, analysis, optMode) mtplot_signalfaketaus = plots.DataMCPlot(mt_baseline_faketaus_data, signalHistoName) mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto( "EWK").getRootHisto().Clone(signalHistoName) # inverted fake taus mt_inverted_faketaus_data = getDataSets(dirs, dataEra, searchMode, analysis_inverted, optMode) histonames_var = mt_inverted_faketaus_data.getDataset( "Data").getDirectoryContent(varHistoName) histonames_nom = mt_inverted_faketaus_data.getDataset( "Data").getDirectoryContent(nomHistoName) bins_var = getBins(histonames_var, varHistoName) bins_nom = getBins(histonames_nom, nomHistoName) normalization_var_qg = getNormalization( bins_var, w, QCDInvertedNormalizationFilteredEWKFakeTaus, True, True) normalization_var = getNormalization( bins_var, w, QCDInvertedNormalizationFilteredEWKFakeTaus, True, False) normalization_nom = getNormalization(bins_nom, w, QCDInvertedNormalization, False, False) mt_var_qg = getMt(mt_inverted_faketaus_data, bins_var, varHistoName, normalization_var_qg) mt_var = getMt(mt_inverted_faketaus_data, bins_var, varHistoName, normalization_var) mt_nom = getMt(mt_inverted_faketaus_data, bins_nom, nomHistoName, normalization_nom) mt_nom.Add(mt_signalfaketaus) mt_var_qg.SetName( "QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau), q-g bal.") mt_var.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)") mt_nom.SetName("QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)") mt_var_qg.SetLineWidth(4) mt_var.SetLineColor(14) mt_nom.SetLineColor(2) mt_var_qg = mt_var_qg.Rebin( len(defaultBinning) - 1, "", defaultBinning_array) mt_var = mt_var.Rebin( len(defaultBinning) - 1, "", defaultBinning_array) mt_nom = mt_nom.Rebin( len(defaultBinning) - 1, "", defaultBinning_array) for i in range(0, mt_nom.GetSize()): var_values.append(mt_var_qg.GetBinContent(i)) nom_values.append(mt_nom.GetBinContent(i)) style = tdrstyle.TDRStyle() varPlots = [mt_var, mt_var_qg] plot = plots.ComparisonManyPlot(mt_nom, varPlots) plot.createFrame(optMode.replace( "Opt", "Mt_DataDrivenVsMC_" + "w=" + str(w) + "_"), createRatio=True) moveLegend = {"dx": -0.35, "dy": 0.05} plot.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) histograms.addText( 0.65, 0.3, optMode.replace("OptQCDTailKiller", "R_{BB} ").replace("Plus", ""), 25) histograms.addCmsPreliminaryText() histograms.addEnergyText() lumi = mt_inverted_faketaus_data.getDataset("Data").getLuminosity() histograms.addLuminosityText(x=None, y=None, lumi=lumi) plot.draw() plot.save() mt_var_qg.Delete() mt_var.Delete() mt_nom.Delete() #TFile.CurrentFile().Close("R") mt_baseline_faketaus_data.close() mt_inverted_faketaus_data.close() ROOT.gROOT.CloseFiles() ROOT.gROOT.GetListOfCanvases().Delete() ROOT.gDirectory.GetList().Delete() #print var_values #print nom_values # difference metrics num = 0 denom = 0 for i in range(0, len(nom_values)): num += var_values[i] * (var_values[i] - nom_values[i])**2 denom += var_values[i] diff = num / denom diff_list.append(diff) diff_opt.append(diff_list) os.system("rm MtOptimal/*") os.system("mkdir -p MtOptimal") print "\nWeights:\t", w_list, '\n' optimalWeights = {} for i in range(0, len(diff_opt)): print optModes[i] print "Differences:\t", diff_opt[i], "- Optimal: w =", w_list[ diff_opt[i].index(min(diff_opt[i]))] optimalWeights[optModes[i]] = w_list[diff_opt[i].index(min( diff_opt[i]))] command = "cp *" + str(w_list[diff_opt[i].index(min( diff_opt[i]))]) + "*" + optModes[i].replace("Opt", "") + ".eps MtOptimal" os.system(command) print optimalWeights writeWeightsToFile("OptimalWeights.py", optimalWeights) writeNormalizationToFile("QCDPlusEWKFakeTauNormalizationFactors.py", normalization_var_qg, labels)
def main(): style = tdrstyle.TDRStyle() #style.setWide(True) style.setPaletteMy() ROOT.gStyle.SetNumberContours(20) # tdrstyle.setDeepSeaPalette() # tdrstyle.setRainBowPalette() # tdrstyle.setDarkBodyRadiatorPalette() # tdrstyle.setGreyScalePalette() # tdrstyle.setTwoColorHuePalette() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(parseOpts.batchMode) # Get all datasets from the mcrab dir #datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis")) datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets #datasetsMgr.remove(kwargs.get("rmDataset")) datasetsMgr.remove( filter(lambda name: not kwargs.get("refDataset") in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections # d.getDataset("TT_ext3").setCrossSection(831.76) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC( datasetsMgr ) #WARNING: Merged MC histograms must be normalized to something! # Remove datasets (for merged names) # datasetsMgr.remove(kwargs.get("rmDataset")) # For-loop: All Histogram names for hName in hNames: savePath, saveName = GetSavePathAndName(hName, **kwargs) # Get Histos for Plotter refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs) # Create a plot p = plots.PlotBase([refHisto], kwargs.get("saveFormats")) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Customize # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL" # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015)) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax"))) # Create a frame opts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=opts) # Customise frame p.getFrame().GetXaxis().SetTitle(getTitleX(refHisto, **kwargs)) p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs)) # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = {"lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.removeLegend() # Add MC Uncertainty (Invalid method for a 2-d histogram) #p.addMCUncertainty() # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22) histograms.addText(0.20, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def main(opts): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # Get all datasets from the mcrab dir # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) #kwargs.get("analysis")) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # Print the cross datasetsMgr.PrintCrossSections() for h_prefix in ["reco"]: # Get ref histo here and the fixed histos (TT, QCD, QCD-b inclusiveHisto, fixedHistos = GetHistosForPlotter(datasetsMgr, h_prefix + "MET_Et", **kwargs) inclusiveHisto.setName("Inclusive") inclusiveHisto.setLegendLabel("Inclusive") #for hi in fixedHistos: # print(type(hi), hi.getName()) #return # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(h_prefix + hName[0], **kwargs) saveName = savePath + h_prefix + hSaveNames[counter] # Get Histos for Plotter refHisto_, otherHistos_ = GetHistosForPlotter(datasetsMgr, h_prefix + hName[0], **kwargs) refHisto1, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[1], **kwargs) refHisto2, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[2], **kwargs) refHisto3, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[3], **kwargs) refHisto4, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[4], **kwargs) refHisto5, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[5], **kwargs) refHisto = inclusiveHisto # customize histos refHisto_.setName(hLegends[counter][0]) refHisto_.setLegendLabel(hLegends[counter][0]) refHisto_.setDrawStyle("P") refHisto_.setLegendStyle("P") styleDict[hStyles[0]].apply(refHisto_.getRootHisto()) refHisto1.setName(hLegends[counter][1]) refHisto1.setLegendLabel(hLegends[counter][1]) refHisto1.setDrawStyle("P") refHisto1.setLegendStyle("P") styleDict[hStyles[1]].apply(refHisto1.getRootHisto()) refHisto2.setName(hLegends[counter][2]) refHisto2.setLegendLabel(hLegends[counter][2]) refHisto2.setDrawStyle("P") refHisto2.setLegendStyle("P") styleDict[hStyles[2]].apply(refHisto2.getRootHisto()) refHisto3.setName(hLegends[counter][3]) refHisto3.setLegendLabel(hLegends[counter][3]) refHisto3.setDrawStyle("P") refHisto3.setLegendStyle("P") styleDict[hStyles[3]].apply(refHisto3.getRootHisto()) refHisto4.setName(hLegends[counter][4]) refHisto4.setLegendLabel(hLegends[counter][4]) refHisto4.setDrawStyle("P") refHisto4.setLegendStyle("P") styleDict[hStyles[4]].apply(refHisto4.getRootHisto()) refHisto5.setName(hLegends[counter][5]) refHisto5.setLegendLabel(hLegends[counter][5]) refHisto5.setDrawStyle("P") refHisto5.setLegendStyle("P") styleDict[hStyles[5]].apply(refHisto5.getRootHisto()) otherHistos = [refHisto_, refHisto1, refHisto2, refHisto3, refHisto4, refHisto5] #for hi in otherHistos: # print hi.getName() #return # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame if kwargs.get("logY")==True: opts = {"ymin": 8e-5, "ymax": 2} #opts = {"ymin": 1e-3, "ymax": 1} else: opts = {"ymin": 8.e-5, "ymax": 2} ratioOpts = {"ymin": 0.1, "ymax": 10.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) ) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.7) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = { "lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) histograms.addText(0.2, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return
def 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 doPlotMu(name, graphs, styleList, limits, xlabel, xvarName, legendVariable): objs = [] ll = {} cutValue = 100 # for cutting a slice +- cutValue around 0 from the (mu,tanb) plot for gr, mu in graphs: if xvarName == "mu": histo = histograms.HistoGraph(gr, "Obs%d"%mu, drawStyle="LP", legendStyle="lp") plus = gr.Clone() minus = gr.Clone() N = gr.GetN() for i in range(0,N): j = N - 1 - i x = gr.GetX()[j] if x > -cutValue: minus.RemovePoint(j) if x < cutValue: plus.RemovePoint(0) objs.append(histograms.HistoGraph(minus, "Obs%d"%mu, drawStyle="LP", legendStyle="lp")) objs.append(histograms.HistoGraph(plus, "ObsCopy%d"%mu, drawStyle="LP", legendStyle="lp")) ll["ObsCopy%d"%mu] = None else: objs.append(histograms.HistoGraph(gr, "Obs%d"%mu, drawStyle="LP", legendStyle="lp")) ll["Obs%d"%mu] = "Observed, "+legendVariable+"=%d %s" % (mu, limit.massUnit()) # N = gr.GetN() # for i in range(0,N): # j = N - 1 - i # if gr.GetY()[j] == 1: # gr.RemovePoint(j) plot = plots.PlotBase(objs) if xvarName == "mu": doubleStyleList = [] for style in styleList: doubleStyleList.append(style) doubleStyleList.append(style) plot.histoMgr.forEachHisto(styles.Generator(doubleStyleList)) else: 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.GetXaxis().SetLabelSize(20) 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.72, "FeynHiggs 2.9.4", size=size) histograms.addText(x, 0.65, "Derived from", size=size) histograms.addText(x, 0.6, "CMS HIG-12-052", size=size) # histograms.addText(x, 0.6, "CMS HIG-11-019", size=size) # histograms.addText(x, 0.55, "JHEP07(2012)143", size=size) #Adding a LHC label: ROOT.LHCHIGGS_LABEL(0.97,0.72,1) plot.save() print print "Plotting",name print
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 addPhysicsText(histograms, limit, x=0.45, y=0.84, size=20): ''' Add physics-process text on canvas ''' # Add process text on canvas histograms.addText(x, y+0.04, limit.processHeavyHtb, size=size) # Add final-state text histograms.addText(x, y, "fully hadronic final state", size=size) if 0: histograms.addText(x, y, "#tau_{h}+jets and #mu#tau_{h} final states", size=size) histograms.addText(x, y, "#tau_{h}+jets final state", size=size) histograms.addText(x, y, "#tau_{h}+jets, #mu#tau_{h}, ee, e#mu, #mu#mu final states", size=size) if limit.BRassumption != "": histograms.addText(x, y-0.05, limit.BRassumption, size=size) return
def main(opts): # Suppress warnings about weight being re-applied ROOT.gErrorIgnoreLevel = ROOT.kError # Obtain dsetMgrCreator and register it to module selector dsetMgrCreator = dataset.readFromMulticrabCfg(directory=opts.mcrab) # Get list of eras, modes, and optimisation modes erasList = dsetMgrCreator.getDataEras() modesList = dsetMgrCreator.getSearchModes() optList = dsetMgrCreator.getOptimizationModes() sysVarList = dsetMgrCreator.getSystematicVariations() sysVarSrcList = dsetMgrCreator.getSystematicVariationSources() # If user does not define optimisation mode do all of them if opts.optMode == None: if len(optList) < 1: optList.append("") else: pass optModes = optList else: optModes = [opts.optMode] opts.optMode = "" mcrabName = opts.mcrab RunEra = mcrabName.split("_")[1] # Setup ROOT and style ROOT.gROOT.SetBatch(opts.batchMode) style = tdrstyle.TDRStyle() style.setGridX(opts.gridX) style.setGridY(opts.gridY) if opts.paper: style.setGridX(False) style.setGridY(False) # Setup & configure the dataset manager datasetsMgr = GetDatasetsFromDir(opts) # Remove some QCD samples (the cross sections of these samples are not calculated) if 0: msg = "Removing following samples:" Print(ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) for d in getDatasetsToExclude(): Print(d, False) datasetsMgr.remove(d) # Get run-range minRunRange, maxRunRange, runRange = GetRunRange(datasetsMgr) # Get int lumi intLumi = GetLumi(datasetsMgr) # Update to PU & load luminosities datasetsMgr.updateNAllEventsToPUWeighted() datasetsMgr.loadLuminosities() #datasetsMgr.normalizeMCByLuminosity() # Print luminisoties and cross-sections datasetsMgr.PrintLuminosities() datasetsMgr.PrintCrossSections() # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) # Get datasets datasetsMgr.mergeMC() dataset_Data = datasetsMgr.getDataDatasets() dataset_MC = datasetsMgr.getMCDatasets() # Define lists of Triggers to be plotted and Variables xVars = ["pt6thJet", "eta6thJet", "phi6thJet", "Ht", "nBTagJets", "pu", "JetMulti", "BJetMulti"] trgList = ["1BTag", "2BTag", "OR", "OR_PFJet450"] if opts.fast: trgList = ["OR_PFJet450"] xVars = ["pt6thJet", "Ht"] nPlots = len(trgList)*len(xVars) counter = 0 # For-loop: All signal triggers for i, trg in enumerate(trgList, 1): # For-loop: All x-variables for j, xVar in enumerate(xVars, 1): counter+=1 msg = "{:<9} {:>3} {:<1} {:<3} {:<50}".format("Histogram", "%i" % counter, "/", "%s:" % (nPlots), "%s Vs %s" % (trg, xVar)) Print(ShellStyles.SuccessStyle() + msg + ShellStyles.NormalStyle(), counter==1) # Define names hNumerator = "hNum_%s_RefTrg_OfflineSel_Signal%s" % (xVar, trg) hDenominator = "hDen_%s_RefTrg_OfflineSel" % (xVar) plotName = "Eff_%s_%s" % (xVar, trg) # Get Efficiency Plots _kwargs = GetHistoKwargs(xVar, opts) eff_Data = GetEfficiency(datasetsMgr, dataset_Data, hNumerator, hDenominator , **_kwargs) eff_MC = GetEfficiency(datasetsMgr, dataset_MC, hNumerator, hDenominator, **_kwargs) # Apply Styles styles.dataStyle.apply(eff_Data) styles.mcStyle.apply(eff_MC) # Create the plot p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data", "p", "P"), histograms.HistoGraph(eff_MC, "eff_MC" , "p", "P"), saveFormats=[]) # Define the legend entries p.histoMgr.setHistoLegendLabelMany( { "eff_Data": "Data", "eff_MC" : "Simulation" } ) # Draw and save the plot p.setLuminosity(intLumi) plots.drawPlot(p, plotName, **_kwargs) # Draw histograms.addText(0.65, 0.06, "Runs "+ runRange, 17) histograms.addText(0.65, 0.10, "2016", 17) # Save the canvas to a file SavePlot(p, plotName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".pdf", ".png", ".C"] ) Print("All plots saved under directory %s" % (ShellStyles.NoteStyle() + aux.convertToURL(opts.saveDir, opts.url) + ShellStyles.NormalStyle()), True) return
def 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 PlotHistoGraphs(hGraphList, _kwargs): # Create & draw the plot p = plots.ComparisonManyPlot(hGraphList[0], hGraphList[1:], saveFormats=[]) p.setLuminosity(opts.intLumi) if 0: p.histoMgr.setHistoLegendStyleAll("P") p.histoMgr.setHistoDrawStyleAll("LP") p.histoMgr.setHistoDrawStyle(hGraphList[0].getRootHisto().GetName(), "HIST") if opts.saveName == None: opts.saveName = hGraphList[0].getRootHisto().GetName().split( "_")[0] + "VsCutflow" # Draw the plot p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerSize(1.3)) #1.2 if opts.acceptance: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle)) plots.drawPlot(p, opts.saveName, **_kwargs) if not opts.acceptance: p.getPad2().SetLogy(True) # Add some text if opts.refCounter == "passed PV": xPos = [0.15, 0.24, 0.37, 0.50, 0.65, 0.77, 0.90] #does not work for every reference counter! else: xPos = [ 0.15 + float(i) / (float(len(opts.binLabels))) for i in range(0, len(opts.binLabels)) ] # For-loop: All bin labels for i, b in enumerate(opts.binLabels, 0): if opts.acceptance: break # Calculate coordinats dx = 0.10 * (i) dy = 0.0 if _kwargs["ratio"]: dy = -0.4 # Basic text replacemenets to get compact bin text bin = b.replace("passed ", "").replace(")", "").replace( "selection", "").replace("(", "").replace("Selection", "").replace("PV", "pv") label = bin.replace("mu", "#mu").replace("Passed", "").replace( "tau", "#tau").replace(" Veto", "-veto").replace("Selected Events", "selected") label = label.replace("jet", "jets").replace("-", " ") if 1: #histograms.addText(0.16+dx, 0.08+dy, label, 19) histograms.addText(xPos[i], 0.08 + dy, label, 19) else: # Automatic assignment (not perfect, yet!) x = opts.xValues[i] / opts.xValues[-1] xlow = opts.xErrLow[i] / opts.xErrLow[-1] xhigh = opts.xErrHigh[i] / opts.xErrHigh[-1] if i == 0: x = 0.15 if i > 2: x -= 0.05 if i == len(opts.binLabels) - 1: x = 0.92 if not opts.acceptance: histograms.addText(x, 0.08 + dy, label, 19) # Save the plot SavePlot(p, opts.saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".C", ".png", ".pdf"]) return
def analyze(analysis=None): paths = [sys.argv[1]] if not analysis == None: # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis, includeOnlyTasks="Tau|TT") datasets = dataset.getDatasetsFromMulticrabDirs(paths, analysisName=analysis) else: datasets = dataset.getDatasetsFromMulticrabDirs(paths) analysis = datasets.getAllDatasets()[0].getAnalysisName() analysisList = [] # analysisList.append("METLeg_2016MET80_MET80") # analysisList.append("METLeg_2016ICHEP_MET90") # analysisList.append("METLeg_2016_MET90") met_re = re.compile("_(?P<met>MET\d+)$") if True: #for analysis in analysisList: met = "METX" met_match = met_re.search(analysis) if met_match: met = met_match.group("met") print "Analysis", analysis datasets = dataset.getDatasetsFromMulticrabDirs(paths, analysisName=analysis) # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$") # datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$") # datasetsMC = None datasetsMC = dataset.getDatasetsFromMulticrabDirs( paths, analysisName=analysis, excludeTasks="Tau_") for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = dataset1 createRatio = False if isinstance(datasetsMC, dataset.DatasetManager): dataset2 = datasetsMC.getMCDatasets() createRatio = True eff1_MET80 = getEfficiency(dataset1) eff2_MET80 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET80) eff1_MET80.SetMarkerSize(1) if createRatio: styles.mcStyle.apply(eff2_MET80) eff2_MET80.SetMarkerSize(1.5) if createRatio: p = plots.ComparisonPlot( histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"), histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P")) else: p = plots.PlotBase( [histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P")]) #from plotTauLegEfficiency import fit #fit("Data",p,eff1_MET80,20,300) #fit("MC",p,eff2_MET80,20,300) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "TauMET_" + analysis + "_DataVsMC_PFMET" legend1 = "Data" # legend2 = "MC (TTJets)" #legend2 = "MC" legend2 = "Simulation" if createRatio: p.histoMgr.setHistoLegendLabelMany({ "eff1_MET80": legend1, "eff2_MET80": legend2 }) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) else: p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1}) p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) p.setLegend( histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") if createRatio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) # histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17) histograms.addText(0.4, 0.87, "LooseIsoPFTau50_Trk30_eta2p1_" + met, 17) # histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17) # label = analysis.split("_")[1] # label = "2016" label = string.replace(analysis, "METLeg_", "") histograms.addText(0.2, 0.53, label, 17) runRange = datasets.loadRunRange() histograms.addText(0.2, 0.46, "Runs " + runRange, 17) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity", d.getName(), d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum", lumi histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1_MET80) pythonWriter.addMCParameters(label, eff2_MET80) pythonWriter.writeJSON( os.path.join(plotDir, "metLegTriggerEfficiency_" + label + ".json")) ######################################################################### eff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi") eff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi") styles.dataStyle.apply(eff1phi) styles.mcStyle.apply(eff2phi) eff1phi.SetMarkerSize(1) if isinstance(datasetsMC, dataset.DatasetManager): p_phi = plots.ComparisonPlot( histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), histograms.HistoGraph(eff2phi, "eff2phi", "p", "P")) else: p_phi = plots.PlotBase( [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")]) p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1}) if isinstance(datasetsMC, dataset.DatasetManager): p_phi.histoMgr.setHistoLegendLabelMany({ "eff1phi": legend1, "eff2phi": legend2 }) opts = {"ymin": 0, "ymax": 0.3} name = "TauMET_" + analysis + "_DataVsMC_PFMETPhi" if createRatio: p_phi.createFrame(os.path.join(plotDir, name), createRatio=createRatio, opts=opts, opts2=opts2) else: p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2) # moveLegendPhi = {"dx": -0.5, "dy": -0.6, "dh": -0.1} moveLegendPhi = {"dx": -0.55, "dy": -0.15, "dh": -0.1} p_phi.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegendPhi)) p_phi.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p_phi.getFrame().GetXaxis().SetTitle("MET Type 1 #phi") if createRatio: p_phi.getFrame2().GetYaxis().SetTitle("Ratio") p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.86, "LooseIsoPFTau50_Trk30_eta2p1_" + met, 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17) p_phi.draw() histograms.addStandardTexts(lumi=lumi) p_phi.save(formats) ######################################################################### """ #### MET120 analysis = "METLeg_2015CD_MET120" datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis) for d in datasets.getAllDatasets(): print d.getName() style = tdrstyle.TDRStyle() dataset1 = datasets.getDataDatasets() dataset2 = datasets.getMCDatasets() eff1_MET120 = getEfficiency(dataset1) eff2_MET120 = getEfficiency(dataset2) styles.dataStyle.apply(eff1_MET120) styles.mcStyle.apply(eff2_MET120) eff1_MET120.SetMarkerSize(1) eff2_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"), histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P")) opts = {"ymin": 0, "ymax": 1.1} opts2 = {"ymin": 0.5, "ymax": 1.5} moveLegend = {"dx": -0.55, "dy": -0.15} name = "DataVsMC_L1HLTMET_PFMET_MET120" legend1 = "Data" legend2 = "MC" p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2}) p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ # CaloMET """ #### MET80 analysisc = "METLeg_2016B_CaloMET_MET80" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$") # datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$") style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() # eff1c_MET80 = getEfficiency(dataset1c) eff2c_MET80 = getEfficiency(dataset2c) # styles.dataStyle.apply(eff1c_MET80) styles.mcStyle.apply(eff2c_MET80) # eff1c_MET80.SetMarkerSize(1) eff2c_MET80.SetMarkerSize(1.5) eff2c_MET80.SetMarkerColor(4) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"), histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P")) namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 80" p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 for d in datasets.getDataDatasets(): print "luminosity",d.getName(),d.getLuminosity() lumi += d.getLuminosity() print "luminosity, sum",lumi histograms.addStandardTexts(lumi=lumi) histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ """ #### MET120 analysisc = "METLeg_2015A_CaloMET_MET120" datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc) style = tdrstyle.TDRStyle() dataset1c = datasetsc.getDataDatasets() dataset2c = datasetsc.getMCDatasets() eff1c_MET120 = getEfficiency(dataset1c) eff2c_MET120 = getEfficiency(dataset2c) styles.dataStyle.apply(eff1c_MET120) styles.mcStyle.apply(eff1c_MET120) eff1c_MET120.SetMarkerSize(1) eff2c_MET120.SetMarkerSize(1.5) p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"), histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P")) namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET" legend1c = "MC, trigger bit" legend2c = "MC, CaloMET > 120" p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c}) p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2) p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend)) p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)") p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.6) p.draw() lumi = 0.0 histograms.addStandardTexts(lumi=lumi) if not os.path.exists(plotDir): os.mkdir(plotDir) p.save(formats) """ ######################################################################### namePU = "TauMET_" + analysis + "_DataVsMC_nVtx" eff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU") eff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU") styles.dataStyle.apply(eff1PU) styles.mcStyle.apply(eff2PU) eff1PU.SetMarkerSize(1) eff2PU.SetMarkerSize(1.5) if isinstance(datasetsMC, dataset.DatasetManager): pPU = plots.ComparisonManyPlot( histograms.HistoGraph(eff1PU, "eff1", "p", "P"), [histograms.HistoGraph(eff2PU, "eff2", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({ "eff1": legend1, "eff2": legend2 }) else: pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")]) pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1}) opts = {"ymin": 0.001, "ymax": 1.0} moveLegend = {"dx": -0.33, "dy": -0.25, "dh": -0.1} createRatio = False if createRatio: pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2) else: pPU.createFrame(os.path.join(plotDir, namePU), opts=opts, opts2=opts2) pPU.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) # if createRatio: # pPU.getPad1().SetLogy(True) # else: # pPU.getPad().SetLogy(True) pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency") pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices") if createRatio: pPU.getFrame2().GetYaxis().SetTitle("Ratio") pPU.getFrame2().GetYaxis().SetTitleOffset(1.6) histograms.addText(0.4, 0.85, "LooseIsoPFTau50_Trk30_eta2p1_MET90", 17) # histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17) histograms.addText(0.4, 0.78, "2016", 17) histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17) pPU.draw() histograms.addStandardTexts(lumi=lumi) pPU.save(formats) print "Output written in", plotDir
def 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 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 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 Plot2d(datasetsMgr, dataset, histoName, kwargs, opts): ''' ''' # Definitions saveName = histoName.replace("/", "_") # Get Histos for the plotter object refHisto = GetHisto(datasetsMgr, dataset, histoName) # Create the plotting object p = plots.PlotBase(datasetRootHistos=[refHisto], saveFormats=kwargs.get("saveFormats")) if 0: p.histoMgr.normalizeMCToLuminosity(opts.intLumi) # Customise axes (before drawing histo) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY"))) if 0: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle(kwargs.get("xlabel"))) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetTitle(kwargs.get("ylabel"))) # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle( h.getRootHisto().GetXaxis().GetTitle() + "%0.1f" )) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(kwargs.get("xmin"), kwargs.get("xmax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(kwargs.get("zmin"), kwargs.get("zmax"))) # Create a frame fOpts = {"ymin": 0.0, "ymaxfactor": 1.0} p.createFrame(saveName, opts=fOpts) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box if 1: _kwargs = { "lessThan": True} p.addCutBoxAndLine(cutValue=400.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs) p.addCutBoxAndLineY(cutValue=200.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs) # Customise Legend moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **kwargs.get("moveLegend"))) p.removeLegend() # Customise histogram (after frame is created) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle("Events")) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.4)) #ROOT.gPad.RedrawAxis() p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zmin"))) #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zmax"))) # Drawing style p.histoMgr.setHistoDrawStyle(dataset, "COLZ") p.histoMgr.setHistoDrawStyleAll("COLZ") # The lines below do nothing since the Legend is disabled if 0: p.histoMgr.setHistoLegendStyle(dataset, "F") if "FakeB" in dataset: p.histoMgr.setHistoLegendLabelMany({ dataset: "QCD (Data)", }) if dataset == "QCD": p.histoMgr.setHistoLegendLabelMany({ dataset: "QCD (MC)", }) # Draw the plot p.draw() # Add canvas text if kwargs.get("addLuminosityText"): histograms.addStandardTexts(lumi=opts.intLumi) else: histograms.addStandardTexts() # Add dataset name on the canvas if dataset == "QCD": histograms.addText(0.17, 0.88, "QCD (H_{T} binned)", 27) else: histograms.addText(0.17, 0.88, plots._legendLabels[dataset], 27) # Save the plots SavePlot(p, saveName, os.path.join(opts.saveDir, opts.analysisName, opts.folder, dataset, opts.optMode), [".png", ".pdf"] ) return
def main(opts): style = tdrstyle.TDRStyle() # Set ROOT batch mode boolean ROOT.gROOT.SetBatch(opts.batchMode) # Get all datasets from the mcrab dir # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) #kwargs.get("analysis")) # Determine Integrated Luminosity (If Data datasets present) intLumi = GetLumi(datasetsMgr) # Update to PU datasetsMgr.updateNAllEventsToPUWeighted() # Remove datasets datasetsMgr.remove(kwargs.get("rmDataset")) # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames())) # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames())) # Set custom XSections #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0) #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0) # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson" plots.mergeRenameReorderForDataMC(datasetsMgr) # Remove datasets (for merged names) datasetsMgr.remove(kwargs.get("rmDataset")) # Print the cross datasetsMgr.PrintCrossSections() for h_prefix in ["reco", "gen"]: # Get ref histo here and the fixed histos (TT, QCD, QCD-b inclusiveHisto, fixedHistos = GetHistosForPlotter( datasetsMgr, h_prefix + "MHT", **kwargs) inclusiveHisto.setName("Inclusive") inclusiveHisto.setLegendLabel("Inclusive") #for hi in fixedHistos: # print(type(hi), hi.getName()) #return # For-loop: All Histogram names for counter, hName in enumerate(hNames): # Get the save path and name savePath, saveName = GetSavePathAndName(h_prefix + hName[0], **kwargs) saveName = savePath + h_prefix + hSaveNames[counter] # Get Histos for Plotter refHisto_, otherHistos_ = GetHistosForPlotter( datasetsMgr, h_prefix + hName[0], **kwargs) refHisto2, otherHistos2 = GetHistosForPlotter( datasetsMgr, h_prefix + hName[1], **kwargs) refHisto = inclusiveHisto # customize histos refHisto_.setName(hLegends[counter][0]) refHisto_.setLegendLabel(hLegends[counter][0]) refHisto_.setDrawStyle("P") refHisto_.setLegendStyle("P") styleDict[hStyles[0]].apply(refHisto_.getRootHisto()) refHisto2.setName(hLegends[counter][1]) refHisto2.setLegendLabel(hLegends[counter][1]) refHisto2.setDrawStyle("P") refHisto2.setLegendStyle("P") styleDict[hStyles[1]].apply(refHisto2.getRootHisto()) otherHistos = [refHisto_, refHisto2] #for hi in otherHistos: # print hi.getName() #return # Create a comparison plot p = plots.ComparisonManyPlot(refHisto, otherHistos) # Remove negative contributions #RemoveNegativeBins(datasetsMgr, hName, p) # Create a frame if kwargs.get("logY") == True: opts = {"ymin": 8e-5, "ymax": 2} #opts = {"ymin": 1e-3, "ymax": 1} else: opts = {"ymin": 8.e-5, "ymax": 2} ratioOpts = {"ymin": 0.1, "ymax": 10.0} p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts) # Customise Legend moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1} p.setLegend( histograms.moveLegend(histograms.createLegend(), **moveLegend)) #p.removeLegend() # Customise frame p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs)) #p.setEnergy("13") if kwargs.get("createRatio"): p.getFrame2().GetYaxis().SetTitle("Ratio") p.getFrame2().GetYaxis().SetTitleOffset(1.7) # SetLog SetLogAndGrid(p, **kwargs) # Add cut line/box _kwargs = {"lessThan": kwargs.get("cutLessThan")} p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs) # Move the refDataset to first in the draw order (back) histoNames = [h.getName() for h in p.histoMgr.getHistos()] p.histoMgr.reorder( filter( lambda n: plots._legendLabels[kwargs.get("refDataset")] not in n, histoNames)) # Draw plots p.draw() # Customise text histograms.addStandardTexts(lumi=intLumi) # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17) histograms.addText(0.2, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17) # Save canvas under custom dir if not os.path.exists(savePath): os.mkdir(savePath) SaveAs(p, savePath, saveName, kwargs.get("saveFormats")) return