def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Get histogram<->kwargs dictionary kwargs = GetHistoKwargs(histo, opts) # Customise style for i, m in enumerate(signalMass): massNum = m.rsplit("M_")[-1] if i==len(signalMass)-1: p.histoMgr.setHistoDrawStyle(m, "HIST") p.histoMgr.setHistoLegendStyle(m, "F") p.histoMgr.forHisto(m, styles.getSignalStyleHToTB()) # p.histoMgr.forHisto(m, styles. getSignalfillStyleHToTB()) # p.histoMgr.forHisto(m, datasetsMgr.getDataset(m).getRootHisto().SetMarkerStyle(6)) # h = GetRootHisto(datasetsMgr, m, histo) # h.SetFillStyle(1001) # p.histoMgr.setHistoLegendStyle(dName, "LP") h = datasetsMgr.getDataset(m).getDatasetRootHisto(histo).getHistogram() styles.qcdFillStyle.apply(h) else: p.histoMgr.forHisto(m, styles.getSignalStyleHToTB_M(massNum)) p.histoMgr.setHistoLegendStyle(m, "LP") # Plot customised histogram plots.drawPlot(p, histo, xlabel = kwargs.get("xlabel"), ylabel = kwargs.get("ylabel"), log = kwargs.get("log"), rebinX = kwargs.get("rebinX"), cmsExtraText = "Preliminary", #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92}, moveLegend = kwargs.get("moveLegend"), opts = kwargs.get("opts"), opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = kwargs.get("cutBox"), ) # Customise styling if 0: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) # Save plot in all formats saveName = histo.split("/")[-1] if opts.folder == "": savePath = os.path.join(opts.saveDir, opts.optMode) else: savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, [".png", ".pdf"]) return
def GetSignificanceHisto(p, datasetsMgr, cutDir=">=", signalDataset="ChargedHiggs_HplusTB_HplusToTB_M_500"): allowedDirs = [">=", "<="] if cutDir not in allowedDirs: raise Exception("Unsupported cut direction \"%s\". Please select from > and <" % (cutDir)) p.setLuminosity(opts.intLumi) if type(signalDataset) != str: siganlDataset = str(signalDataset) hSignal = p.histoMgr.getHisto(signalDataset).getRootHisto().Clone(signalDataset + "_Histo") hSignif = p.histoMgr.getHisto(signalDataset).getRootHisto().Clone(signalDataset) hSignif.Reset() hBkg = p.histoMgr.getHisto(signalDataset).getRootHisto().Clone("Bkg") hBkg.Reset() # For-loop: All dataset names for dset in datasetsMgr.getAllDatasets(): d = dset.getName() if dset.isData(): continue if "Charged" in d: continue # Add up all bkg MC hBkg.Add(p.histoMgr.getHisto(d).getRootHisto(), +1) nBins = hSignif.GetNbinsX()+1 # For-loop: All histo bins for i in range (1, nBins+1): sigmaB = ROOT.Double(0) if cutDir == ">=": s = hSignal.Integral(i, nBins) b = hBkg.IntegralAndError(i, nBins, sigmaB) else: s = hSignal.Integral(0, i) b = hBkg.IntegralAndError(0, i, sigmaB) # Calculate the significance signif = stat.significance(s, b, sigmaB, option="Asimov") Verbose("%s, bin %i: Signif = %.3f" % (hSignif.GetName(), i, signif), i==0) if 0: Print("%s, bin %i: Signif = %.3f" % (hSignif.GetName(), i, signif), True) signif = stat.significance(s, b, sigmaB=0.0, option="Simple") signif = stat.significance(s, b, sigmaB=0.0, option="Asimov") signif = stat.significance(s, b, sigmaB, option="Simple") signif = stat.significance(s, b, sigmaB, option="Asimov") # Set signif for this bin hSignif.SetBinContent(i, signif) # Apply style s = styles.getSignalStyleHToTB_M(hSignif.GetName().split("_")[-1]) s.apply(hSignif) return hSignif
def PlotHistograms(datasetsMgr, histoName): # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] # histoName.replace("/", "_") kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object if "Data" in datasetsMgr.getAllDatasetNames(): p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) else: if opts.normalizeToLumi: p = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[]) elif opts.normalizeByCrossSection: p = plots.MCPlot(datasetsMgr, histoName, normalizeByCrossSection=True, saveFormats=[], **{}) elif opts.normalizeToOne: p = plots.MCPlot(datasetsMgr, histoName, normalizeToOne=True, saveFormats=[], **{}) else: raise Exception("One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\").") # Overwite signal style? style = [200, 500, 800, 1000, 2000, 5000] lstyle = [ROOT.kSolid, ROOT.kDashed, ROOT.kDashDotted, ROOT.kDotted, ROOT.kDotted, ROOT.kSolid] for i, d in enumerate(datasetsMgr.getAllDatasets(), 0): p.histoMgr.forHisto(d.getName(), styles.getSignalStyleHToTB_M(style[i])) if 1: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.setHistoLegendLabelMany({ #"ChargedHiggs_HplusTB_HplusToTB_M_500_MVA0p30": "H^{+} m_{H^{+}} = 500 GeV (BDT #geq 0.3)", "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p30" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.3)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p40" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.4)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p50" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.5)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p60" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.6)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p70" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.7)" % (opts.signalMass), }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot saveName += "_M%s" % (opts.signalMass) plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Save the plots in custom list of saveFormats SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder), [".png", ".pdf"] ) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 # logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = {"cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 100 elif "trijetmass" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 #1005 elif "ht" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 2000 elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1500 #3500.0 elif "dijetmass" in histo.lower(): _rebinX = 1 #5 #10 #4 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{W} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 300 elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetbdt_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 # elif "topcandmass" in histo.lower(): # _rebinX = 2 # _units = "GeV/c^{2}" # _format = "%0.0f " + _units # _xlabel = "m_{jjb} (%s)" % _units # _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} # _opts["xmax"] = 505 elif "matched_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 elif "bdtvalue" in histo.lower(): _format = "%0.1f" elif "foxwolframmoment" in histo.lower(): _format = "%0.1f" _cutBox = {"cutValue": 0.5, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "absdeltamvamax_mctruth_sameobjfakes" in histo.lower(): _format = "%0.1f" _xlabel = "|#Delta BDTG| response" elif "deltamvamin_mctruth_sameobjfakespassbdt" in histo.lower(): _opts["xmax"] = 1 _opts["xmin"] = -1 elif "bdtmultiplicity" in histo.lower(): _opts["xmax"] = 15 else: pass if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "LP") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel,#"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, # createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Get histogram<->kwargs dictionary kwargs = GetHistoKwargs(histo, opts) # Customise styling if 0: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6)) # Customise signal for d in datasetsMgr.getAllDatasetNames(): if "Charged" not in d: continue else: #p.histoMgr.setHistoDrawStyle(d, "HIST") p.histoMgr.setHistoLegendStyle(d, "L") p.histoMgr.setHistoLegendStyle(d, "L") # Customise QCD style p.histoMgr.setHistoDrawStyle("QCD", "P") p.histoMgr.setHistoLegendStyle("QCD", "P") p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: dName = "ChargedHiggs_HplusTB_HplusToTB_M_%s" % m if dName in datasetsMgr.getAllDatasetNames(): p.histoMgr.forHisto(dName, styles.getSignalStyleHToTB_M(m)) p.histoMgr.setHistoLegendStyle(dName, "LP") # Plot customised histogram plots.drawPlot( p, histo, xlabel=kwargs.get("xlabel"), ylabel=kwargs.get("ylabel"), log=kwargs.get("log"), rebinX=kwargs.get("rebinX"), cmsExtraText="Preliminary", #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92}, moveLegend=kwargs.get("moveLegend"), opts=kwargs.get("opts"), opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=kwargs.get("cutBox"), ) # Save plot in all formats saveName = histo.split("/")[-1] if opts.folder == "": savePath = os.path.join(opts.saveDir, opts.optMode) else: savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, [".png", ".pdf"]) return
def PlotSignificance(h, datasetsMgr, intLumi): Verbose("Plotting Significance") significanceList = [] for mass in signalMass: xValues = [] yValues = [] maxSignificance = 0.0 hSignal = getHisto(datasetsMgr, h, mass, intLumi) hBackground = getHisto(datasetsMgr, h, "QCD", intLumi) for i in range(0, hSignal.GetXaxis().GetNbins()): # Cut value cut = hSignal.GetBinCenter(i) s = hSignal.Integral(i, hSignal.GetXaxis().GetNbins()) b = hBackground.Integral(i, hSignal.GetXaxis().GetNbins()) significance = float(s) / math.sqrt(float(b + s)) if (significance > maxSignificance): maxSignificance = significance maxSignificanceCut = cut xValues.append(cut) yValues.append(significance) # Create the Significance Plot tGraph = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues)) styles.getSignalStyleHToTB_M(mass.split("_")[-1]).apply(tGraph) drawStyle = "CPE" legName = plots._legendLabels[mass] significanceGraph = histograms.HistoGraph(tGraph, legName, "lp", drawStyle) significanceList.append(significanceGraph) saveName = "QGLRSignificance" # Create the plot with all the significance plots p = plots.PlotBase(significanceList, saveFormats=["pdf"]) p.createFrame(saveName) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetLabelSize(18) p.getFrame().GetXaxis().SetLabelSize(20) p.getFrame().GetYaxis().SetTitle("S/#sqrt{S+B} / 0.01") p.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.15, "dy": -0.5, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.draw() savePath = opts.saveDir if opts.url: savePath = opts.saveDir.replace("/publicweb/m/mkolosov/", "http://home.fnal.gov/~mkolosov/") savePath = os.path.join(opts.saveDir, opts.folder, saveName, opts.optMode) SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.1f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 #logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = { "cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 100 elif "trijetjets_deltarmin" in histo.lower(): _xlabel = "#Delta R_{min}" _rebinX = 2 _opts["xmax"] = 3 _units = "" _format = "%0.1f " _cutBox = { "cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True } elif "trijetjets_deltarmax" in histo.lower(): _xlabel = "#Delta R_{max}" _rebinX = 2 _opts["xmax"] = 3.5 _units = "" _format = "%0.1f " _cutBox = { "cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True } elif "trijetdijetdr" in histo.lower(): _rebinX = 1 units = "" _format = "%0.1f " _opts["xmax"] = 3.5 _cutBox = { "cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True } elif "trijetdijetpt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetdijetmass" in histo.lower(): _rebinX = 1 _units = "GeV/c^{2}" _format = "%0.0f " + _units _opts["xmax"] = 200 _xlabel = "m_{w} (%s)" % _units _cutBox = { "cutValue": 80.39, "fillColor": 16, "box": False, "line": True, "greaterThan": True } if "cevts_ldgtrijetmatchedtofatjet_fatjetpt" in histo.lower(): _rebin = 1 _opts["xmax"] = 3 elif "pt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetmass" in histo.lower(): _rebinX = 1 # logY = False _units = "GeV/c^{2}" # _format = "%0.0f " + _units _format = "%0.0f" + (_units) _xlabel = "m_{jjb} (%s)" % _units _cutBox = { "cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 305 #1005 _opts["xmin"] = 55 #1005 elif "topcandmass" in histo.lower(): _rebinX = 1 # logY = False _units = "GeV/c^{2}" # _format = "%0.0f " + _units _format = "%0.0f" + (_units) _xlabel = "m_{jjb}^{BDTG} (%s)" % _units _cutBox = { "cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 505 #1005 _opts["xmin"] = 0 #1005 # elif "ht" in histo.lower(): # _rebinX = 2 ## logY = False # _units = "GeV" # _format = "%0.0f " + _units # _xlabel = "H_{T} (%s)" % _units # _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True} # _opts["xmax"] = 2000 elif "tetrajetptd" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c^{2}" # _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 2000 #3500.0 _cutBox = { "cutValue": 400, "fillColor": 16, "box": False, "line": True, "greaterThan": True } elif "tetrajetmass" in histo.lower() or "tetrajetmass_" in histo.lower(): #ROOT.gStyle.SetNdivisions(10, "X") # h = dataset.getDatasetRootHisto(histo).getHistogram() # h.SetTickLength(100, "X") _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1500 #3500.0 _cutBox = { "cutValue": 500, "fillColor": 16, "box": False, "line": False, "greaterThan": True } elif "dijetmass" in histo.lower(): _rebinX = 1 #5 #10 #4 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{W} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = { "cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 205 elif "trijetmultiplicitypassbdt" in histo.lower(): _rebinX = 1 _opts["xmax"] = 5 _format = "%0.0f " elif "bdtg" or "bdtvalue" in histo.lower(): _rebinX = 1 _format = "%0.2f " elif "trijetbdt_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _opts["xmax"] = 800 # if "eta" or "phi" or "delta" in histo.lower(): #_rebinX = 1 #5 #10 #4 # _units = "" # _format = "%0.1f " # if "eta" in histo.lower(): # _xlabel = "#eta" # if "phi" in histo.lower(): # _xlabel = "#phi" # if "pt" in histo.lower(): # _opts["xmax"] = 800 elif "boosted" in histo.lower(): _xlabel = "Trijet Counter" elif "matched_dijetpt" in histo.lower(): _units = "(GeV/c)" _xlabel = "p_{T}" + _units elif "deltar_bdttrijets_tetrajetbjet" in histo.lower(): _xlabel = "#Delta R(Trijet,b_{free})" elif "tetrajetbjetbdisc" in histo.lower(): _rebinX = 2 _opts["xmax"] = 1.05 # if "matched_dijetmass" in histo.lower(): # _rebinX = 2 # if "higgstop_dijetmass" in histo.lower(): # _rebinX = 2 elif "trijet_deltaeta_trijet_tetrajetbjet" in histo.lower(): _rebinX = 2 _xlabel = "#Delta #eta (Trijet, b_{free})" elif "trijet_deltaphi_trijet_tetrajetbjet" in histo.lower(): _xlabel = "#Delta #phi (Trijet, b_{free})" elif "cevts_closejettotetrajetbjet_isbtagged" in histo.lower(): _units = "" _format = "%0.0f " + _units # if "higgstop_" in histo.lower(): # _rebinX = 2 if "eventtrijetpt2t" in histo.lower(): _rebinX = 2 if "ldgfatjetpt" in histo.lower(): _opts["xmax"] = 1000 if "deltar_w" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "ldgtrijet_deltar" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "higgstop_deltar" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "allfatjet" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 else: pass if opts.normaliseToOne: logY = True Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle()) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "HIST") p.histoMgr.setHistoLegendStyle("TT", "LP") # if "M_200" in datasetsMgr.getAllDatasets() or "M_300" in datasetsMgr.getAllDatasets(): # p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) # p.histoMgr.setHistoDrawStyle("QCD", "P") # p.histoMgr.setHistoLegendStyle("QCD", "F") # elif d.getName() == "TT" or d.getName() == "QCD" or d.getName() == "Data": # otherHisto = histograms.Histo(histo, legName, "LP", "P") # otherHistos.append(otherHisto) # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m, styles.getSignalStyleHToTB_M(m)) #soti # p.histoMgr.setHistoDrawStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "LP") # p.histoMgr.setHistoLegendStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "P") plots.drawPlot( p, histo, xlabel=_xlabel, ylabel= Ylabel, #"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), # ylabel = "Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log=logY, rebinX=_rebinX, cmsExtraText="Preliminary", #_rebinX #createLegend = {"x1": 0.48, "y1": 0.45, "x2": 0.92, "y2": 0.92}, #All datasets # createLegend = {"x1": 0.58, "y1": 0.7, "x2": 0.92, "y2": 0.92}, createLegend={ "x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.87 }, #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, #One dataset opts=_opts, opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=_cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/TT/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None logY = False _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = {"cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 100 elif "trijetmass" in histo.lower(): _rebinX = 4 logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 805 #1005 elif "ht" in histo.lower(): _rebinX = 2 logY = False _units = "GeV" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True} #_opts["xmin"] = 500 _opts["xmax"] = 2000 elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _cutBox = {"cutValue": 500.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 1500 #3500.0 #_rebinX = 10 #_opts["xmax"] = 3500 elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 600 elif "foxwolframmoment" in histo.lower(): _format = "%0.1f" _cutBox = {"cutValue": 0.5, "fillColor": 16, "box": False, "line": True, "greaterThan": True} else: pass if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 else: _opts["ymin"] = 1e0 # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "LP") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = "Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Get histogram<->kwargs dictionary kwargs = GetHistoKwargs(histo, opts) # Customise styling if 0: p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6)) # Customise signal for d in datasetsMgr.getAllDatasetNames(): if "Charged" not in d: continue else: #p.histoMgr.setHistoDrawStyle(d, "HIST") p.histoMgr.setHistoLegendStyle(d, "L") p.histoMgr.setHistoLegendStyle(d, "L") # Customise QCD style p.histoMgr.setHistoDrawStyle("QCD", "P") p.histoMgr.setHistoLegendStyle("QCD", "P") p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: dName = "ChargedHiggs_HplusTB_HplusToTB_M_%s" %m if dName in datasetsMgr.getAllDatasetNames(): p.histoMgr.forHisto(dName, styles.getSignalStyleHToTB_M(m)) p.histoMgr.setHistoLegendStyle(dName, "LP") # Plot customised histogram plots.drawPlot(p, histo, xlabel = kwargs.get("xlabel"), ylabel = kwargs.get("ylabel"), log = kwargs.get("log"), rebinX = kwargs.get("rebinX"), cmsExtraText = "Preliminary", #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92}, moveLegend = kwargs.get("moveLegend"), opts = kwargs.get("opts"), opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = kwargs.get("cutBox"), ) # Save plot in all formats saveName = histo.split("/")[-1] if opts.folder == "": savePath = os.path.join(opts.saveDir, opts.optMode) else: savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, [".png", ".pdf"]) return
def GetHistoGraphs(datasetsMgr, folder, hName): # Get histogram customisations _kwargs = GetHistoKwargs(opts) # Get histos (Data, EWK) for Inclusive p1 = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[]) kwargs = copy.deepcopy(_kwargs) kwargs["opts"] = {"ymin": 1.0, "ymaxfactor": 10.0} kwargs["xlabelsize"] = 10 kwargs["ratio"] = False plots.drawPlot(p1, hName, **kwargs) SavePlot(p1, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".C", ".png", ".pdf"] ) # Clone histograms histoList = [] graphList = [] hgList = [] # Append some bkg samples as well opts.datasets = opts.signal if not opts.acceptance: opts.datasets.extend(opts.backgrounds) for d in opts.datasets: h = p1.histoMgr.getHisto(d).getRootHisto().Clone(d) histoList.append(h) # Create the Efficiency histos for i, h in enumerate(histoList, 1): if opts.efficiency: histo = GetEfficiencyHisto(histoList[i-1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Efficiency_%d" % (i)) elif opts.events: histo = GetEventsHisto(histoList[i-1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Events_%d" % (i)) elif opts.acceptance: histo = GetAcceptanceHisto(histoList[i-1], _kwargs, printValues=True, hideZeros=True) histo.SetName("Acceptance_%d" % (i)) # Convert histos to TGraph (don't do it for acceptance to get better positioning of markers wrt x-axis!) if not opts.acceptance: tgraph = convertHisto2TGraph(histo, printValues=False) else: tgraph = histo # Apply random histo styles and append if "charged" in h.GetName().lower(): s = styles.getSignalStyleHToTB_M(h.GetName().split("M_")[-1]) s.apply(tgraph) if "QCD" in h.GetName(): styles.fakeBStyle.apply(tgraph) if "EWK" in h.GetName(): s = styles.ttStyle.apply(tgraph) # Append to list graphList.append(tgraph) # Create histoGraph object htgraph = histograms.HistoGraph( tgraph, plots._legendLabels[opts.signal[i-1]], "LP", "LP") # Append to list hgList.append(htgraph) return hgList, _kwargs
def DataMCPlot(datasetsMgr, json, opts): Verbose("Creating Data-MC plot") if opts.saveDir == None: saveDir = json["saveDir"] else: saveDir = json["saveDir"] # Create the Data-MC Plot p = plots.DataMCPlot(datasetsMgr, json["histogram"], saveFormats=[]) # 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"] # Customise style if opts.signal != None: p.histoMgr.forHisto( "ChargedHiggs_HplusTB_HplusToTB_M_%.0f" % (opts.signal), styles.getSignalStyleHToTB_M("%.0f" % opts.signal)) # Draw a customised plot, os.path.join(opts.saveDir, "Fit") plots.drawPlot( p, json["title"], #os.path.join(saveDir, json["title"]) 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 custom formats SavePlot(p, json["title"], os.path.join(saveDir, opts.optMode), json["saveFormats"]) return
def PlotMC(datasetsMgr, datasetsMgr1, histo, intLumi): kwargs = {} print "here1" if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[".pdf", "png"], **kwargs) p = plots.MCPlot(datasetsMgr1, histo, normalizeToOne=True, saveFormats=[".pdf", ".png"], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[".pdf", ".png"], **kwargs) p = plots.MCPlot(datasetsMgr1, histo, normalizeToOne=True, saveFormats=[".pdf", "png"], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None logY = False _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} print "here2" if "Pt" in histo: _rebinX = 2 xMin = 0.0 # rebinX = 2 xMax = 805.0 # xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV/c)" units = "GeV/c" _format = "%0.0f" + units # yTitle = "Efficiency / " + str(binwidth) + " "+units # yMin = 0.0 # yMax = 1.1 else: pass if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) print "here3" histoDef = datasetsMgr.getDataset("TT").getDatasetRootHisto(histo) histoDR = datasetsMgr1.getDataset("TT").getDatasetRootHisto(histo) histoDef.normalizeToOne() histoDR.normalizeToOne() hDef = histoDef.getHistogram() hDR = histoDR.getHistogram() p = plots.ComparisonPlot(histograms.Histo(hDR,"DeltaR08", "l", "L"), histograms.Histo(hDef,"Default", "l", "L")) p.histoMgr.setHistoLegendLabelMany({"DeltaR08": "#DeltaR(q,q')>0.8", "Default": "Default"}) p.histoMgr.forHisto("DeltaR08", styles.getQCDLineStyle() ) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.setHistoDrawStyle("DeltaR08", "HIST") #HIST p.histoMgr.setHistoLegendStyle("DeltaR08", "L") #F p.histoMgr.setHistoDrawStyle("Default", "HIST") #HIST p.histoMgr.setHistoLegendStyle("Default", "L") #F p.histoMgr.forHisto("Default", styles.ttStyle) print "here4" # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) print "here5" plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = "Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.58, "y1": 0.75, "x2": 0.92, "y2": 0.92}, # createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) print "here6" # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath) print "here7" return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 # logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = {"cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 100 elif "trijetmass" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 #1005 elif "ht" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 2000 elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1500 #3500.0 elif "dijetmass" in histo.lower(): _rebinX = 1 #5 #10 #4 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{W} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 300 elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetbdt_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 # elif "topcandmass" in histo.lower(): # _rebinX = 2 # _units = "GeV/c^{2}" # _format = "%0.0f " + _units # _xlabel = "m_{jjb} (%s)" % _units # _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} # _opts["xmax"] = 505 elif "matched_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 elif "bdtvalue" in histo.lower(): _format = "%0.1f" elif "foxwolframmoment" in histo.lower(): _format = "%0.1f" _cutBox = {"cutValue": 0.5, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "absdeltamvamax_mctruth_sameobjfakes" in histo.lower(): _format = "%0.1f" _xlabel = "|#Delta BDTG| response" elif "deltamvamin_mctruth_sameobjfakespassbdt" in histo.lower(): _opts["xmax"] = 1 _opts["xmin"] = -1 elif "bdtmultiplicity" in histo.lower(): _opts["xmax"] = 15 else: pass if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "LP") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel,#"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, # createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def CalcEfficiency(datasetsMgr, numPath, denPath, intLumi): # Definitions myList = [] index = 0 _kwargs = GetHistoKwargs(numPath, opts) # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): x = [] y = [] n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins)-1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) for i in range(1, num.GetNbinsX()+1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) if nbin < 0: nbin = 0 if dbin < 0: nbin = 0 dbin = 1 if nbin > dbin: nbin = dbin x.append(num.GetBinLowEdge(i)+0.5*num.GetBinWidth(i)) y.append(nbin/dbin) n = num.GetNbinsX() eff = ROOT.TGraph(n, array.array("d",x), array.array("d",y)) # Apply default style (according to dataset name) plots._plotStyles[dataset.getName()].apply(eff) # Apply random histo styles and append if "charged" in dataset.getName().lower(): mass = dataset.getName().split("M_")[-1] s = styles.getSignalStyleHToTB_M(mass) s.apply(eff) # Append in list myList.append(histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) # Define save name saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split("/")[-1] # Plot the efficiency p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) # Save plot in all formats savePath = os.path.join(opts.saveDir, numPath.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, saveFormats = [".png"])#, ".pdf"]) return
def PlotEfficiency(datasetsMgr, numPath, denPath, intLumi): # Definitions myList = [] myBckList = [] index = 0 _kwargs = GetHistoKwargs(denPath, opts) counter = 0 # For-loop: All datasets for dataset in datasetsMgr.getAllDatasets(): name_N = numPath name_D = denPath # Get the histograms #num = dataset.getDatasetRootHisto(numPath).getHistogram() #den = dataset.getDatasetRootHisto(denPath).getHistogram() #if "TT" in dataset.getName(): # numPath = numPath.replace("HiggsTop", "AllTop") # denPath = denPath.replace("HiggsTop", "AllTop") # numPath = numPath.replace("AssocTop", "AllTop") # denPath = denPath.replace("AssocTop", "AllTop") n = dataset.getDatasetRootHisto(numPath) n.normalizeToLuminosity(intLumi) num = n.getHistogram() d = dataset.getDatasetRootHisto(denPath) d.normalizeToLuminosity(intLumi) den = d.getHistogram() if "binList" in _kwargs: xBins = _kwargs["binList"] nx = len(xBins)-1 num = num.Rebin(nx, "", xBins) den = den.Rebin(nx, "", xBins) for i in range(1, num.GetNbinsX()+1): nbin = num.GetBinContent(i) dbin = den.GetBinContent(i) #print dataset.getName(), nbin, dbin if (nbin > dbin): print "error" # Sanity checks if den.GetEntries() == 0 or num.GetEntries() == 0: continue if num.GetEntries() > den.GetEntries(): continue # Remove negative bins and ensure numerator bin <= denominator bin #CheckNegatives(num, den, False) #CheckNegatives(num, den, True) #RemoveNegatives(num) #RemoveNegatives(den) # Sanity check (Histograms are valid and consistent) - Always false! # if not ROOT.TEfficiency.CheckConsistency(num, den): # continue # Create Efficiency plots with Clopper-Pearson stats eff = ROOT.TEfficiency(num, den) # fixme: investigate warnings eff.SetStatisticOption(ROOT.TEfficiency.kFCP) # # Set the weights - Why is this needed? if 0: weight = 1 if dataset.isMC(): weight = dataset.getCrossSection() eff.SetWeight(weight) # Convert to TGraph eff = convert2TGraph(eff) # Apply default style (according to dataset name) plots._plotStyles[dataset.getName()].apply(eff) # Apply random histo styles and append if "charged" in dataset.getName().lower(): counter +=1 mass = dataset.getName().split("M_")[-1] styles.markerStyles[counter].apply(eff) if "300" in mass or "650" in mass: s = styles.getSignalStyleHToTB_M(mass) s.apply(eff) eff.SetLineStyle(ROOT.kSolid) eff.SetLineWidth(3) eff.SetMarkerSize(1.2) ''' mass = dataset.getName().split("M_")[-1] mass = mass.replace("650", "1000") s = styles.getSignalStyleHToTB_M(mass) s.apply(eff) ''' ''' ttStyle = styles.getEWKLineStyle() if "tt" in dataset.getName().lower(): ttStyle.apply(eff) ''' # Append in list #if "charged" in dataset.getName().lower(): # if "m_500" in dataset.getName().lower(): if 1: #if "tt" in dataset.getName().lower(): if "m_500" in dataset.getName().lower(): eff_ref = histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P") else: myList.append(histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P")) #elif "tt" in dataset.getName().lower(): # eff_ref = histograms.HistoGraph(eff, plots._legendLabels[dataset.getName()], "lp", "P") # Define save name saveName = "Eff_" + name_N.split("/")[-1] + "Over"+ name_D.split("/")[-1] # Plot the efficiency #p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[]) p = plots.ComparisonManyPlot(eff_ref, myList, saveFormats=[]) plots.drawPlot(p, saveName, **_kwargs) # Save plot in all formats savePath = os.path.join(opts.saveDir, name_N.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, saveFormats = [".png", ".C", ".pdf"])#, ".pdf"]) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "Gluon" in histo: _rebinX = 2 _units = "" _xlabel = "Gluon Jets QGL" _format = 0.02 if "Light" in histo: _rebinX = 2 _xlabel = "Quark Jets QGL" _format = 0.02 if "QGLR" in histo: _rebinX = 2 _units = "" _xlabel = "QGLR" logY = True _format = 0.02 if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 else: _opts["ymin"] = 1e0 # Customise styling p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) # QCD p.histoMgr.forHisto("QCD", styles.getAltQCDStyle()) #getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") # TT #p.histoMgr.forHisto("TT", styles.getAltTTStyle()) #p.histoMgr.setHistoDrawStyle("TT", "HIST") #p.histoMgr.setHistoLegendStyle("TT", "F") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot( p, histo, xlabel=_xlabel, ylabel= Ylabel, #"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log=logY, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92 }, opts=_opts, opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=_cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] if "False" in opts.folder: saveName += "_False" if "True" in opts.folder: saveName += "_True" savePath = os.path.join(opts.saveDir, "", histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} #_opts = {"ymin": 1e-3, "ymax": 60} if "pt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} #_opts["xmax"] = 505 #1005 if "ht" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _opts["xmax"] = 2000 #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} #_opts["xmax"] = 505 #1005 if "eta" in histo.lower(): _units = "" _format = "%0.1f " + _units _xlabel = "#eta %s" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 2.5 _opts["xmin"] = -2.5 if "trijetmass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 #1005 if "ldg" in histo.lower(): _xlabel = "m_{jjb}^{ldg} (%s)" % _units elif "tetrajetmass" in histo.lower(): _rebinX = 10 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 2500 #3500.0 elif "tetrajetpt" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1000 #3500.0 elif "dijetmass" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jj} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 300 if "ldg" in histo.lower(): _xlabel = "m_{jj}^{ldg} (%s)" % (_units) elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,bjet} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jjb}^{ldg} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetdijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jj}^{ldg} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "topbdt_" in histo.lower(): _format = "%0.1f" _cutBox = {"cutValue": +0.40, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _xlabel = "BDTG discriminant" if "gentop_pt" in histo.lower(): _rebinX = 1 if "genquark_pt" in histo.lower(): _rebinX = 1 _opts["xmax"] = 500 else: pass if "delta" in histo.lower(): _format = "%0.1f " if "phi" in histo.lower(): _xlabel = "#Delta #phi" if "deltar" in histo.lower(): _rebinX = 2 if "DiBjetMaxMass_Mass" in histo: _units = "GeV" _rebinX = 4 _xlabel = "m_{max}(bb) (%s)" % (_units) _format = "%0.0f " + _units if "DiJetDeltaRmin_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _xlabel = "m_{#DeltaR_{min}(jj)}(jj) (%s)" % (_units) _opts["xmax"] = 200 if "DiBjetDeltaRmin_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _rebinX= 2 _xlabel = "m_{#DeltaR_{min}(bb)}(bb) (%s)" % (_units) _opts["xmax"] = 600 if "LdgBjet_SubldgBjet_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _rebinX= 4 _xlabel = "m(b_{ldg}b_{sldg}) (%s)" % (_units) if "DeltaR_LdgTop_DiBjetDeltaRmin" in histo: _rebinX= 2 _format = "%0.1f " _xlabel = "#DeltaR (top_{ldg}, bb_{#Delta Rmin})" if "DeltaR_SubldgTop_DiBjetDeltaRmin" in histo: _rebinX= 2 _format = "%0.1f " _xlabel = "#DeltaR (top_{sldg}, bb_{#Delta Rmin})" if "over" in histo.lower(): _opts["xmax"] = 15 _opts["xmax"] = +0.8 _opts["xmin"] = -0.8 _xlabel = "#Delta p_{T}(j-q)/p_{T,q}" _cutBox = {"cutValue": +0.32, "fillColor": 16, "box": False, "line": True, "greaterThan": True} if "within" in histo.lower(): _opts["xmax"] = +0.8 _opts["xmin"] = -0.8 _xlabel = "#Delta p_{T}(j-q)/p_{T,q}" _cutBox = {"cutValue": +0.32, "fillColor": 16, "box": False, "line": True, "greaterThan": True} if "axis2" in histo.lower(): _opts["xmax"] = +0.2 _opts["xmin"] = 0.0 _xlabel = "axis2" _units = "" _format = "%0.1f "+_units if "axis2" in histo.lower(): _opts["xmax"] = +0.2 _opts["xmin"] = 0.0 _xlabel = "axis2" _units = "" _format = "%0.2f "+_units if "mass" in histo.lower(): _xlabel = "M (GeV/c^{2})" _units = "GeV/c^{2}" _format = "%0.0f "+_units if "mult" in histo.lower(): _xlabel = "mult" _units = "" _format = "%0.0f "+_units if "BQuarkFromH_Pt" in histo: _opts["xmax"] = 200 _rebinX= 1 if "order" in histo.lower(): _opts["xmax"] = 15 _rebinX= 1 if "pt" in histo.lower(): _xlabel = "indx_{p_{T}}" if "csv" in histo.lower(): _xlabel = "indx_{csv}" if "phi_alpha" in histo.lower() or "phi_beta" in histo.lower() or "r_alpha" in histo.lower() or "r_beta" in histo.lower(): _format = "%0.1f " _opts["xmin"] = 0.0 if "phi" in histo.lower(): _xlabel = "#phi" _opts["xmax"] = 5.5 else: _xlabel = "r" _opts["xmax"] = 6.5 if "alpha" in histo.lower(): _xlabel = _xlabel+"_{#alpha}" else: _xlabel = _xlabel+"_{#beta}" if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 if "order" in histo.lower(): _opts["ymin"] = 1e-3 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.forHisto("QCD", styles.getQCDLineStyle()) #getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasetNames(): TTStyle = styles.StyleCompound([styles.StyleFill(fillColor=ROOT.kMagenta-2), styles.StyleLine(lineColor=ROOT.kMagenta-2, lineStyle=ROOT.kSolid, lineWidth=3), styles.StyleMarker(markerSize=1.2, markerColor=ROOT.kMagenta-2, markerSizes=None, markerStyle=ROOT.kFullTriangleUp)]) p.histoMgr.forHisto("TT", TTStyle) p.histoMgr.setHistoDrawStyle("TT", "HIST") #AP p.histoMgr.setHistoLegendStyle("TT", "F") #LP # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel, log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", #createLegend = {"x1": 0.59, "y1": 0.65, "x2": 0.92, "y2": 0.92}, createLegend = {"x1": 0.59, "y1": 0.70, "x2": 0.92, "y2": 0.92}, #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) ''' if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" ''' SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.01f" _xlabel = None logY = False _opts = {"ymin": 1e-3, "ymaxfactor": 1.2} if "Pt" in histo: if "Gluon" in histo: _xlabel = "Gluon Jets p_{T} (GeV)" elif "Light" in histo: _xlabel = "Light Jets p_{T} (GeV)" if "JetsN" in histo: if "Gluon" in histo: _xlabel = "Gluon Jets Multiplicity" elif "Light" in histo: _xlabel = "Light Jets Multiplicity" if "QGL" in histo: _opts["xmin"] = 0.0 _opts["xmax"] = 1.0 _units = "" _format = "%0.01f " + _units if "Gluon" in histo: _xlabel = "Gluon Jets QGL" elif "Light" in histo: _xlabel = "Light Jets QGL" # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = "Arbitrary Units",# / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.70, "y1": 0.65, "x2": 0.98, "y2": 0.92}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "", "", opts.optMode) SavePlot(p, saveName, savePath) return
def DataMCHistograms(datasetsMgr, histoName): Verbose("Plotting Data-MC Histograms") # Skip 2-D plots skipStrings = [] if opts.folder == "topbdtSelection_": skipStrings = ["_Vs_", "Vs", "Matched", "MCtruth", "TopQuark", "RealSelected", "DeltaMVAgt1", "SelectedTop", "LdgTrijetFake", "LdgTrijetFakeJJB", "TrijetFake", "FakeInTopDir", "LdgTrijetFakeJJB_BDT", "LdgTrijetFake_BDT"] if opts.folder == "counters": skipStrings = ["weighted"] if opts.folder == "eSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "muSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "tauSelection_Veto": skipStrings = ["riggerMatch", "NprongsMatrix", "Resolution"] if opts.folder == "PUDependency": skipStrings = ["WithProbabilisticBtag", "AngularCuts", "AntiIsolatedTau", "NvtxTau", "METSelection", "NvtxAllSelections"] #latter is empty! if opts.folder == "jetSelection_": skipStrings = ["JetMatching", "SeventhJet"] if opts.folder == "bjetSelection_": skipStrings = ["MatchDeltaR", "btagSFRelUncert", "_dEta", "_dPhi", "_dPt", "_dR"] if opts.folder == "metSelection_": skipStrings = [""] if opts.folder == "topologySelection_": skipStrings = ["_Vs_"] if opts.folder == "topSelectionBDT_": skipStrings = ["RelUncert"] if "ForDataDrivenCtrlPlots" in opts.folder: skipStrings = ["_Vs_", "JetEtaPhi", "MinDeltaPhiJet", "MaxDeltaPhiJet", "MinDeltaRJet"] # Skip histograms if they contain a given string for keyword in skipStrings: if keyword in histoName: return # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] # histoName.replace("/", "_") kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Overwite signal style? if 0: if opts.signalMass != 0: p.histoMgr.forHisto(opts.signal, styles.getSignalStyleHToTB_M(opts.signalMass)) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Replace bin labels if "counter" in opts.folder and "counter" in histoName.split("/")[-1]: # p.getFrame().GetXaxis().LabelsOption("v") #vertical orientation of bin labels replaceBinLabels(p, saveName) #pass # Save the plots in custom list of saveFormats SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder), [".png", ".pdf"] ) return
def PlotCutFlowEfficiency(h, datasetsMgr, intLumi): Verbose("Plotting Cut Flow Efficiency") efficiencyList = [] signalMass.append("QCD") for mass in signalMass: xValues = [] yValues = [] hSignal = getHisto(datasetsMgr, h, mass, intLumi) for i in range (0, hSignal.GetXaxis().GetNbins()): # Cut value cut = hSignal.GetBinCenter(i) passed = hSignal.Integral(i, hSignal.GetXaxis().GetNbins()) total = hSignal.Integral() eff = float(passed)/total xValues.append(cut) yValues.append(eff) # Create the Significance Plot tGraph = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues)) if "M_" in mass: styles.getSignalStyleHToTB_M(mass.split("_")[-1]).apply(tGraph) else: styles.getQCDStyle().apply(tGraph) drawStyle = "CPE" legName = plots._legendLabels[mass] effGraph = histograms.HistoGraph(tGraph, legName, "lp", drawStyle) efficiencyList.append(effGraph) saveName = "QGLREfficiency" # Create the plot with all the significance plots p = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) p.createFrame(saveName) # Customise frame p.setEnergy("13") p.getFrame().GetYaxis().SetLabelSize(18) p.getFrame().GetXaxis().SetLabelSize(20) p.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") p.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) p.draw() savePath = opts.saveDir if opts.url: savePath = opts.saveDir.replace("/publicweb/m/mkolosov/", "http://home.fnal.gov/~mkolosov/") savePath = os.path.join(opts.saveDir, opts.folder, saveName, opts.optMode) SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=opts.intLumi, saveFormats=[], **kwargs) p.setLuminosity(opts.intLumi) p1 = "a" p2 = "b" if "Htb_tbW_WBoson_Quark_Htb_tbW_WBoson_AntiQuark" in histo: p1 = "q_{1}" p2 = "q_{2}" if "Htb_tbW_BQuark_Htb_tbW_Wqq_Quark" in histo: p1 = "b_{2}" p2 = "q_{1}" if "Htb_tbW_BQuark_Htb_tbW_Wqq_AntiQuark" in histo: p1 = "b_{2}" p2 = "q_{2}" if "Htb_tbW_WBoson_Htb_tbW_BQuark_dR" in histo: p1 = "W^{+}" p2 = "b_{2}" # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _format = "%0.2f" _logY = True _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "pt" in histo.lower(): _format = "%0.0f" _rebinX = 2 _format = "%0.0f GeV/c" if "eta" in histo.lower(): _cutBox = { "cutValue": 0.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmin"] = -3.0 _opts["xmax"] = +3.0 if "dPhi" in histo: _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = +3.2 _xlabel = "#Delta#phi(%s, %s)" % (p1, p2) if "dEta" in histo: _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = 3.2 _xlabel = "#Delta#eta(%s, %s)" % (p1, p2) if "dR" in histo: _format = "%0.2f" _rebinX = 2 _opts["xmin"] = 0.0 _opts["xmax"] = 5.0 #_cutBox = {"cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _xlabel = "#DeltaR(%s, %s)" % (p1, p2) if _logY: _opts["ymaxfactor"] = 2.0 else: _opts["ymaxfactor"] = 1.2 if opts.normaliseToOne: _opts["ymin"] = 1e-3 else: _opts["ymin"] = 1e0 # Customise Dataset styling for signal in opts.signalMass: m = signal.split("M_")[-1] p.histoMgr.forHisto(signal, styles.getSignalStyleHToTB_M(m)) # Draw the customised plot plots.drawPlot( p, histo, xlabel=_xlabel, ylabel="Arbitrary Units / %s" % (_format), log=_logY, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.60, "y1": 0.72, "x2": 0.92, "y2": 0.92 }, opts=_opts, addLuminosityText=(opts.intLumi != -1), ratio=False, opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=_cutBox, ) if 0: histograms.addText(0.20, 0.88, "test", 27) # Save plot in all formats saveName = histo.split("/")[-1] saveDict = {} saveDict["Htb_tbW_WBoson_Htb_tbW_BQuark_dR"] = "dR_W_b2" saveDict["Htb_tbW_WBoson_Quark_Htb_tbW_WBoson_AntiQuark_dR"] = "dR_q1_q2" saveDict["Htb_tbW_BQuark_Htb_tbW_Wqq_Quark_dR"] = "dR_b2_q1" saveDict["Htb_tbW_BQuark_Htb_tbW_Wqq_AntiQuark_dR"] = "dR_b2_q2" savePath = os.path.join(opts.saveDir, histo.split("/")[0], "", opts.optMode) if saveName in saveDict.keys(): SavePlot(p, saveDict[saveName], savePath) else: SavePlot(p, saveName, savePath) return
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CRone", "CRtwo"] rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= manager = FakeBNormalization.FakeBNormalizationManager(binLabels, opts.mcrab, opts.optMode, verbose=False) if opts.inclusiveOnly: #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"]) binLabel = "Inclusive" manager.CalculateTransferFactor("Inclusive", rhDict["FakeB-CRone-Inclusive"], rhDict["FakeB-CRtwo-Inclusive"]) else: for bin in binLabels: manager.CalculateTransferFactor(bin, rhDict["FakeB-CRone-%s" % bin], rhDict["FakeB-CRtwo-%s" % bin]) # Get unique a style for each region for k in rhDict: dataset = k.split("-")[0] region = k.split("-")[1] styles.getABCDStyle(region).apply(rhDict[k]) if "FakeB" in k: styles.getFakeBStyle().apply(rhDict[k]) # sr.apply(rhDict[k]) # ========================================================================================= # Create the final plot object # ========================================================================================= rData_SR = rhDict["Data-SR-Inclusive"] rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"] rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive") rBkgSum_SR.Reset() if opts.inclusiveOnly: bin = "Inclusive" # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print( "Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) else: # For-loop: All bins for i, bin in enumerate(binLabels, 1): if bin == "Inclusive": continue # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print( "Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), i == 1) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) #Print("Got Verification Region (VR) shape %s%s%s" % (ShellStyles.NoteStyle(), rFakeB_VR.GetName(), ShellStyles.NormalStyle()), True) # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) #VRtoSR_TF = manager.GetTransferFactor("Inclusive") #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) #rBkgSum_SR.Scale(VRtoSR_TF) # Plot histograms if opts.altPlot: # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] ) rBkgSum_SR.Add(rEWKGenuineB_SR, +1) # Change style styles.getGenuineBStyle().apply(rBkgSum_SR) # Remove unsupported settings of kwargs _kwargs["stackMCHistograms"] = False _kwargs["addLuminosityText"] = False # Create the plot p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[]) # Set draw / legend style p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P") p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive", "LP") p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST") p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive", "F") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Data-SR": "Data", "BkgSum-SR": "Fake-b + Gen-b", }) else: # Create empty histogram stack list myStackList = [] # Signal p2 = plots.DataMCPlot(datasetsMgr, "ForTestQGLR/QGLR_SR/QGLR_SRInclusive", saveFormats=[]) hSignal_800 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto() hhSignal_800 = histograms.Histo( hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800', "H^{+} m_{H^+}=800 GeV") hhSignal_800.setIsDataMC(isData=False, isMC=True) myStackList.append(hhSignal_800) hSignal_250 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto() hhSignal_250 = histograms.Histo( hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250', "H^{+} m_{H^+}=250 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250']) hhSignal_250.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_250) hSignal_500 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto() hhSignal_500 = histograms.Histo( hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500', "H^{+} m_{H^+}=500 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_500.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_500) hSignal_1000 = p2.histoMgr.getHisto( 'ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto() hhSignal_1000 = histograms.Histo( hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000', "H^{+} m_{H^+}=1000 GeV" ) #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_1000.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_1000) # Add the FakeB data-driven background to the histogram list hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b") hFakeB.setIsDataMC(isData=False, isMC=True) myStackList.append(hFakeB) # Add the EWKGenuineB MC background to the histogram list hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB", "EWK Genuine-b") hGenuineB.setIsDataMC(isData=False, isMC=True) myStackList.append(hGenuineB) # Add the collision datato the histogram list hData = histograms.Histo(rData_SR, "Data", "Data") hData.setIsDataMC(isData=True, isMC=False) myStackList.insert(0, hData) p = plots.DataMCPlot2(myStackList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setDefaultStyles() # Draw the plot and save it hName = "test" plots.drawPlot(p, hName, **_kwargs) SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================== # Calculate Cut-Flow Efficiency #========================================================================================== kwargs = { "rebinX": 1, "xlabel": "QGLR", "ylabel": "Significance / %.02f ", "opts": { "ymin": 0.0, "ymaxfactor": 1.3 }, "createLegend": { "x1": 0.55, "y1": 0.70, "x2": 0.92, "y2": 0.92 }, # "cutBox" : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True}, } efficiencyList = [] xValues = [] yValues_250 = [] yValues_500 = [] yValues_800 = [] yValues_1000 = [] yValues_Bkg = [] nBins = hSignal_250.GetNbinsX() + 1 hBkg = p.histoMgr.getHisto( "ChargedHiggs_HplusTB_HplusToTB_M_800").getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) for i in range(0, nBins): # Cut value cut = hSignal_250.GetBinCenter(i) passed_250 = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins()) passed_500 = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins()) passed_800 = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins()) passed_1000 = hSignal_1000.Integral(i, hSignal_1000.GetXaxis().GetNbins()) passed_Bkg = hBkg.Integral(i, hBkg.GetXaxis().GetNbins()) total_250 = hSignal_250.Integral() total_500 = hSignal_500.Integral() total_800 = hSignal_800.Integral() total_1000 = hSignal_1000.Integral() total_Bkg = hBkg.Integral() eff_250 = float(passed_250) / total_250 eff_500 = float(passed_500) / total_500 eff_800 = float(passed_800) / total_800 eff_1000 = float(passed_1000) / total_1000 eff_Bkg = float(passed_Bkg) / total_Bkg xValues.append(cut) yValues_250.append(eff_250) yValues_500.append(eff_500) yValues_800.append(eff_800) yValues_1000.append(eff_1000) yValues_Bkg.append(eff_Bkg) # Create the Efficiency Plot tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_250)) tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_500)) tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_800)) tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_1000)) tGraph_Bkg = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_Bkg)) styles.getSignalStyleHToTB_M("200").apply(tGraph_250) styles.getSignalStyleHToTB_M("500").apply(tGraph_500) styles.getSignalStyleHToTB_M("800").apply(tGraph_800) styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000) styles.getQCDLineStyle().apply(tGraph_Bkg) drawStyle = "CPE" effGraph_250 = histograms.HistoGraph(tGraph_250, "H^{+} m_{H^{+}} = 250 GeV", "lp", drawStyle) effGraph_500 = histograms.HistoGraph(tGraph_500, "H^{+} m_{H^{+}} = 500 GeV", "lp", drawStyle) effGraph_800 = histograms.HistoGraph(tGraph_800, "H^{+} m_{H^{+}} = 800 GeV", "lp", drawStyle) effGraph_1000 = histograms.HistoGraph(tGraph_1000, "H^{+} m_{H^{+}} = 1000 GeV", "lp", drawStyle) effGraph_Bkg = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle) efficiencyList.append(effGraph_250) efficiencyList.append(effGraph_500) efficiencyList.append(effGraph_800) efficiencyList.append(effGraph_1000) efficiencyList.append(effGraph_Bkg) # Efficiency plot pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) pE.createFrame("QGLR_Efficiency") pE.setEnergy("13") pE.getFrame().GetYaxis().SetLabelSize(18) pE.getFrame().GetXaxis().SetLabelSize(20) pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") pE.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} pE.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pE.draw() # plots.drawPlot(pE, "QGLR_Efficiency", **kwargs) SavePlot(pE, "QGLR_Efficiency", os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================== # Calculate Significance #========================================================================================== SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800" hSignif_250 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_500 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_800 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone( SignalName) hSignif_250.Reset() hSignif_500.Reset() hSignif_800.Reset() hSignif_1000.Reset() hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) nBins = hSignif_250.GetNbinsX() + 1 # For-loop: All histo bins for i in range(1, nBins + 1): sigmaB = ROOT.Double(0) b = hBkg.IntegralAndError(i, nBins, sigmaB) s_250 = hSignal_250.Integral(i, nBins) s_500 = hSignal_500.Integral(i, nBins) s_800 = hSignal_800.Integral(i, nBins) s_1000 = hSignal_1000.Integral(i, nBins) # Calculate significance signif_250 = stat.significance(s_250, b, sigmaB, option="Simple") #Asimov") signif_500 = stat.significance(s_500, b, sigmaB, option="Simple") #Asimov") signif_800 = stat.significance(s_800, b, sigmaB, option="Simple") #Asimov") signif_1000 = stat.significance(s_1000, b, sigmaB, option="Simple") #"Asimov") # Set signif for this bin hSignif_250.SetBinContent(i, signif_250) hSignif_500.SetBinContent(i, signif_500) hSignif_800.SetBinContent(i, signif_800) hSignif_1000.SetBinContent(i, signif_1000) # Apply style s_250 = styles.getSignalStyleHToTB_M("200") s_250.apply(hSignif_250) s_500 = styles.getSignalStyleHToTB_M("500") s_500.apply(hSignif_500) s_800 = styles.getSignalStyleHToTB_M("800") s_800.apply(hSignif_800) s_1000 = styles.getSignalStyleHToTB_M("1000") s_1000.apply(hSignif_1000) hList = [] hList.append(hSignif_250) hList.append(hSignif_500) hList.append(hSignif_800) hList.append(hSignif_1000) hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV") hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV") hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV") hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV") pS = plots.PlotBase(hList, saveFormats=["png", "pdf"]) pS.setLuminosity(opts.intLumi) # Drawing style pS.histoMgr.setHistoDrawStyleAll("HIST") pS.histoMgr.setHistoLegendStyleAll("L") pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0)) pS.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) pS.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle)) # Draw the plot name = "QGLR_Signif" + "GE" plots.drawPlot(pS, name, **kwargs) SavePlot(pS, name, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"]) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= Verbose("Write the normalisation factors to a python file", True) fileName = os.path.join( opts.mcrab, "FakeBTransferFactors%s.py" % (getModuleInfoString(opts))) manager.writeNormFactorFile(fileName, opts) return
def GetHistoGraphs(datasetsMgr, folder, hName): # Get histogram customisations _kwargs = GetHistoKwargs(opts) # Get histos (Data, EWK) for Inclusive p1 = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[]) kwargs = copy.deepcopy(_kwargs) kwargs["opts"] = {"ymin": 1.0, "ymaxfactor": 10.0} kwargs["xlabelsize"] = 10 kwargs["ratio"] = False plots.drawPlot(p1, hName, **kwargs) SavePlot(p1, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".C", ".png", ".pdf"]) # Clone histograms histoList = [] graphList = [] hgList = [] # Append some bkg samples as well opts.datasets = opts.signal if not opts.acceptance: opts.datasets.extend(opts.backgrounds) for d in opts.datasets: h = p1.histoMgr.getHisto(d).getRootHisto().Clone(d) histoList.append(h) # Create the Efficiency histos for i, h in enumerate(histoList, 1): if opts.efficiency: histo = GetEfficiencyHisto(histoList[i - 1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Efficiency_%d" % (i)) elif opts.events: histo = GetEventsHisto(histoList[i - 1], opts.refCounter, _kwargs, printValues=True, hideZeros=True) histo.SetName("Events_%d" % (i)) elif opts.acceptance: histo = GetAcceptanceHisto(histoList[i - 1], _kwargs, printValues=True, hideZeros=True) histo.SetName("Acceptance_%d" % (i)) # Convert histos to TGraph (don't do it for acceptance to get better positioning of markers wrt x-axis!) if not opts.acceptance: tgraph = convertHisto2TGraph(histo, printValues=False) else: tgraph = histo # Apply random histo styles and append if "charged" in h.GetName().lower(): s = styles.getSignalStyleHToTB_M(h.GetName().split("M_")[-1]) s.apply(tgraph) if "QCD" in h.GetName(): styles.fakeBStyle.apply(tgraph) if "EWK" in h.GetName(): s = styles.ttStyle.apply(tgraph) # Append to list graphList.append(tgraph) # Create histoGraph object htgraph = histograms.HistoGraph( tgraph, plots._legendLabels[opts.signal[i - 1]], "LP", "LP") # Append to list hgList.append(htgraph) return hgList, _kwargs
def PlotHistograms(datasetsMgr, histoName): # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] # histoName.replace("/", "_") kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object if "Data" in datasetsMgr.getAllDatasetNames(): p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) else: if opts.normalizeToLumi: p = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[]) elif opts.normalizeByCrossSection: p = plots.MCPlot(datasetsMgr, histoName, normalizeByCrossSection=True, saveFormats=[], **{}) elif opts.normalizeToOne: p = plots.MCPlot(datasetsMgr, histoName, normalizeToOne=True, saveFormats=[], **{}) else: raise Exception( "One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\")." ) # Overwite signal style? style = [200, 500, 800, 1000, 2000, 3000, 5000] lstyle = [ ROOT.kSolid, ROOT.kDashed, ROOT.kDashDotted, ROOT.kDotted, ROOT.kDotted, ROOT.kSolid ] for i, d in enumerate(datasetsMgr.getAllDatasets(), 0): p.histoMgr.forHisto(d.getName(), styles.getSignalStyleHToTB_M(style[i])) if 1: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.setHistoLegendLabelMany({ #"ChargedHiggs_HplusTB_HplusToTB_M_500_MVA0p30": "H^{+} m_{H^{+}} = 500 GeV (BDT #geq 0.3)", "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p30" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.3)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p40" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.4)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p50" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.5)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p60" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.6)" % (opts.signalMass), "ChargedHiggs_HplusTB_HplusToTB_M_%s_MVA0p70" % (opts.signalMass): "m_{H^{+}}=%s GeV (BDT #geq 0.7)" % (opts.signalMass), }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot saveName += "_M%s" % (opts.signalMass) plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Save the plots in custom list of saveFormats SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder), [".png", ".pdf"]) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Get histogram<->kwargs dictionary kwargs = GetHistoKwargs(histo, opts) # Customise style for i, m in enumerate(signalMass): massNum = m.rsplit("M_")[-1] if i == len(signalMass) - 1: p.histoMgr.setHistoDrawStyle(m, "HIST") p.histoMgr.setHistoLegendStyle(m, "F") p.histoMgr.forHisto(m, styles.getSignalStyleHToTB()) # p.histoMgr.forHisto(m, styles. getSignalfillStyleHToTB()) # p.histoMgr.forHisto(m, datasetsMgr.getDataset(m).getRootHisto().SetMarkerStyle(6)) # h = GetRootHisto(datasetsMgr, m, histo) # h.SetFillStyle(1001) # p.histoMgr.setHistoLegendStyle(dName, "LP") h = datasetsMgr.getDataset(m).getDatasetRootHisto( histo).getHistogram() styles.qcdFillStyle.apply(h) else: p.histoMgr.forHisto(m, styles.getSignalStyleHToTB_M(massNum)) p.histoMgr.setHistoLegendStyle(m, "LP") # Plot customised histogram plots.drawPlot( p, histo, xlabel=kwargs.get("xlabel"), ylabel=kwargs.get("ylabel"), log=kwargs.get("log"), rebinX=kwargs.get("rebinX"), cmsExtraText="Preliminary", #createLegend = {"x1": 0.62, "y1": 0.75, "x2": 0.92, "y2": 0.92}, moveLegend=kwargs.get("moveLegend"), opts=kwargs.get("opts"), opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=kwargs.get("cutBox"), ) # Customise styling if 0: p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0)) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(6)) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) # Save plot in all formats saveName = histo.split("/")[-1] if opts.folder == "": savePath = os.path.join(opts.saveDir, opts.optMode) else: savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath, [".png", ".pdf"]) return
def plot(self): style = tdrstyle.TDRStyle() ROOT.gStyle.SetErrorX( 0.5 ) #required for x-axis error bars! (must be called AFTER tdrstyle.TDRStyle()) histolist = [] #styles.dataStyle.apply(self.h_data) hhd = histograms.Histo(self.h_data, "Data", legendStyle="PL", drawStyle="E1P") hhd.setIsDataMC(isData=True, isMC=False) histolist.append(hhd) if 0: aux.PrintTH1Info(hhd.getRootHisto()) # For-loop: All signal histo for i, hsignal in enumerate(self.h_signal, 1): mass = hsignal.GetName().replace("Hp", "") Verbose("Customing signal histogram for Mass = \"%s\"" % (mass), i == 1) hhs = histograms.Histo(hsignal, hsignal.GetTitle(), legendStyle="L", drawStyle="HIST") hhs.setIsDataMC(isData=False, isMC=True) signalStyle = styles.getSignalStyleHToTB_M(mass) signalStyle.apply(hhs.getRootHisto()) histolist.append(hhs) # For-loop: All bkg histos for i, hname in enumerate(self.histonames, 1): # Safety net for empty histos if hname in opts.empty: msg = "Skipping %s. Not a histogram!" % (hname) Print( ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(), True) continue else: #print hname pass myLabel = self.labels[hname] myHisto = self.histograms[hname] Verbose( "Creating histogram \"%s\" from ROOT file \"%s\" (Integral = %.1f)" % (hname, myHisto.GetName(), myHisto.Integral()), i == 1) hhp = histograms.Histo(myHisto, hname, legendStyle="F", drawStyle="HIST", legendLabel=myLabel) hhp.setIsDataMC(isData=False, isMC=True) histolist.append(hhp) if 0: aux.PrintTH1Info(hhp.getRootHisto()) # Sanity check for i, h in enumerate(histolist, 1): hName = h.getRootHisto().GetName() Verbose(hName, i == 1) # Do the plot p = plots.DataMCPlot2(histolist) p.setDefaultStyles() p.stackMCHistograms() p.setLuminosity(opts.lumi) if opts.fitUncert: p.addMCUncertainty( postfit=not opts.prefit) # boolean changes only the legend if opts.prefit: p.setLegendHeader("Pre-Fit") else: p.setLegendHeader("Post-Fit") # Customise histogram units = "GeV" #(GeV/c^{2}) myParams = {} myParams["xlabel"] = "m_{jjbb} (%s)" % (units) myParams["ylabel"] = "< Events / " + units + " >" myParams["ratio"] = True myParams["ratioYlabel"] = "Data/Bkg. " myParams["logx"] = self.gOpts.logX myParams["log"] = self.gOpts.logY myParams["ratioType"] = "errorScale" myParams["ratioErrorOptions"] = { "numeratorStatSyst": False, "denominatorStatSyst": True } myParams["opts"] = self.opts myParams["optsLogx"] = self.optsLogx myParams["opts2"] = self.opts2 myParams[ "divideByBinWidth"] = True #not opts.fitUncert # Error when used for "TGraphAsymmErrors" (uncert.) myParams["errorBarsX"] = True myParams["xlabelsize"] = 25 myParams["ylabelsize"] = 25 myParams["addMCUncertainty"] = True myParams["addLuminosityText"] = True myParams["moveLegend"] = self.moveLegend #myParams["saveFormats"] = [] # Draw the plot if not os.path.exists(opts.saveDir): os.makedirs(opts.saveDir) plots.drawPlot(p, os.path.join(opts.saveDir, self.gOpts.saveName), **myParams) # Save the plot (not needed - drawPlot saves the canvas already) SavePlot(p, self.gOpts.saveName, opts.saveDir, saveFormats=[".png", ".pdf", ".C"]) return
p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") for d in datasetsMgr.getAllDatasets(): if "TT" in d.getName(): p.histoMgr.forHisto("TT", styles.getTTFillStyle() ) #p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "F") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel,#"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, # createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, )
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} #_opts = {"ymin": 1e-3, "ymax": 60} if "pt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} #_opts["xmax"] = 505 #1005 if "eta" in histo.lower(): _units = "" _format = "%0.1f " + _units _xlabel = "#eta %s" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 2.5 _opts["xmin"] = -2.5 if "trijetmass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 #1005 if "ldg" in histo.lower(): _xlabel = "m_{jjb}^{ldg} (%s)" % _units elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 2500 #3500.0 elif "tetrajetpt" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1000 #3500.0 elif "dijetmass" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jj} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 300 if "ldg" in histo.lower(): _xlabel = "m_{jj}^{ldg} (%s)" % (_units) elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,bjet} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jjb}^{ldg} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetdijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T,jj}^{ldg} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "topbdt_" in histo.lower(): _format = "%0.1f" _cutBox = {"cutValue": +0.40, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _xlabel = "BDTG discriminant" if "gentop_pt" in histo.lower(): _rebinX = 1 if "genquark_pt" in histo.lower(): _rebinX = 1 _opts["xmax"] = 500 else: pass if "delta" in histo.lower(): _format = "%0.1f " if "phi" in histo.lower(): _xlabel = "#Delta #phi" if "deltar" in histo.lower(): _rebinX = 2 if "DiBjetMaxMass_Mass" in histo: _units = "GeV" _rebinX = 4 _xlabel = "m_{max}(bb) (%s)" % (_units) _format = "%0.0f " + _units if "DiJetDeltaRmin_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _xlabel = "m_{#DeltaR_{min}(jj)}(jj) (%s)" % (_units) _opts["xmax"] = 200 if "DiBjetDeltaRmin_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _rebinX= 2 _xlabel = "m_{#DeltaR_{min}(bb)}(bb) (%s)" % (_units) _opts["xmax"] = 600 if "LdgBjet_SubldgBjet_Mass" in histo: _units = "GeV" _format = "%0.0f " + _units _rebinX= 4 _xlabel = "m(b_{ldg}b_{sldg}) (%s)" % (_units) if "DeltaR_LdgTop_DiBjetDeltaRmin" in histo: _rebinX= 2 _format = "%0.1f " _xlabel = "#DeltaR (top_{ldg}, bb_{#Delta Rmin})" if "DeltaR_SubldgTop_DiBjetDeltaRmin" in histo: _rebinX= 2 _format = "%0.1f " _xlabel = "#DeltaR (top_{sldg}, bb_{#Delta Rmin})" if "phi_alpha" in histo.lower() or "phi_beta" in histo.lower() or "r_alpha" in histo.lower() or "r_beta" in histo.lower(): _format = "%0.1f " _opts["xmin"] = 0.0 if "phi" in histo.lower(): _xlabel = "#phi" _opts["xmax"] = 5.5 else: _xlabel = "r" _opts["xmax"] = 6.5 if "alpha" in histo.lower(): _xlabel = _xlabel+"_{#alpha}" else: _xlabel = _xlabel+"_{#beta}" if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.forHisto("QCD", styles.getQCDLineStyle()) #getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasetNames(): TTStyle = styles.StyleCompound([styles.StyleFill(fillColor=ROOT.kMagenta-2), styles.StyleLine(lineColor=ROOT.kMagenta-2, lineStyle=ROOT.kSolid, lineWidth=3), styles.StyleMarker(markerSize=1.2, markerColor=ROOT.kMagenta-2, markerSizes=None, markerStyle=ROOT.kFullTriangleUp)]) p.histoMgr.forHisto("TT", TTStyle) p.histoMgr.setHistoDrawStyle("TT", "HIST") #AP p.histoMgr.setHistoLegendStyle("TT", "F") #LP # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel, log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", #createLegend = {"x1": 0.59, "y1": 0.65, "x2": 0.92, "y2": 0.92}, createLegend = {"x1": 0.59, "y1": 0.70, "x2": 0.92, "y2": 0.92}, #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) ''' if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" ''' SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=opts.intLumi, saveFormats=[], **kwargs) p.setLuminosity(opts.intLumi) p1 = "a" p2 = "b" if "Htb_tbW_WBoson_Quark_Htb_tbW_WBoson_AntiQuark" in histo: p1 = "q_{1}" p2 = "q_{2}" if "Htb_tbW_BQuark_Htb_tbW_Wqq_Quark" in histo: p1 = "b_{2}" p2 = "q_{1}" if "Htb_tbW_BQuark_Htb_tbW_Wqq_AntiQuark" in histo: p1 = "b_{2}" p2 = "q_{2}" if "Htb_tbW_WBoson_Htb_tbW_BQuark_dR" in histo: p1 = "W^{+}" p2 = "b_{2}" # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _format = "%0.2f" _logY = True _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "pt" in histo.lower(): _format = "%0.0f" _rebinX = 2 _format = "%0.0f GeV/c" if "eta" in histo.lower(): _cutBox = {"cutValue": 0.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmin"] = -3.0 _opts["xmax"] = +3.0 if "dPhi" in histo: _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = +3.2 _xlabel = "#Delta#phi(%s, %s)" % (p1, p2) if "dEta" in histo: _format = "%0.2f" _opts["xmin"] = 0.0 _opts["xmax"] = 3.2 _xlabel = "#Delta#eta(%s, %s)" % (p1, p2) if "dR" in histo: _format = "%0.2f" _rebinX = 2 _opts["xmin"] = 0.0 _opts["xmax"] = 5.0 #_cutBox = {"cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _xlabel = "#DeltaR(%s, %s)" % (p1, p2) if _logY: _opts["ymaxfactor"] = 2.0 else: _opts["ymaxfactor"] = 1.2 if opts.normaliseToOne: _opts["ymin"] = 1e-3 else: _opts["ymin"] = 1e0 # Customise Dataset styling for signal in opts.signalMass: m = signal.split("M_")[-1] p.histoMgr.forHisto(signal, styles.getSignalStyleHToTB_M(m)) # Draw the customised plot plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = "Arbitrary Units / %s" % (_format), log = _logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.60, "y1": 0.72, "x2": 0.92, "y2": 0.92}, opts = _opts, addLuminosityText = (opts.intLumi!=-1), ratio = False, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) if 0: histograms.addText(0.20, 0.88, "test", 27) # Save plot in all formats saveName = histo.split("/")[-1] saveDict = {} saveDict["Htb_tbW_WBoson_Htb_tbW_BQuark_dR"] = "dR_W_b2" saveDict["Htb_tbW_WBoson_Quark_Htb_tbW_WBoson_AntiQuark_dR"] = "dR_q1_q2" saveDict["Htb_tbW_BQuark_Htb_tbW_Wqq_Quark_dR"] = "dR_b2_q1" saveDict["Htb_tbW_BQuark_Htb_tbW_Wqq_AntiQuark_dR"] = "dR_b2_q2" savePath = os.path.join(opts.saveDir, histo.split("/")[0], "", opts.optMode) if saveName in saveDict.keys(): SavePlot(p, saveDict[saveName], savePath) else: SavePlot(p, saveName, savePath) return
def DataMCHistograms(datasetsMgr, qcdDatasetName): Verbose("Plotting Data-MC Histograms") # Definitions histoNames = [] saveFormats = [".png"] #[".C", ".png", ".pdf"] # Get list of histograms dataPath = "ForDataDrivenCtrlPlots" allHistos = datasetsMgr.getDataset(datasetsMgr.getAllDatasetNames()[0]).getDirectoryContent(dataPath) histoList = [h for h in allHistos if "StandardSelections" in h] histoList.extend([h for h in allHistos if "AllSelections" in h]) histoList = [h for h in histoList if "_MCEWK" not in h] histoList = [h for h in histoList if "_Purity" not in h] histoPaths = [dataPath + "/" + h for h in histoList] # Get histogram<->kwargs dictionary histoKwargs = GetHistoKwargs(histoPaths, opts) # For-loop: All histograms in list for histoName in histoPaths: #if "Mass" not in histoName: # continue if "JetEtaPhi" in histoName: continue if opts.signalMass == 0: if "LdgTrijetMass" in histoName: continue if "LdgTetrajetMass" in histoName: continue if "Vs" in histoName: continue # Not used in this analysis (yet) if "MHT" in histoName: continue # By definition of the Inverted sample the following histos cannot agree! if "NBjets_" in histoName: continue if "BJetPt_" in histoName: continue if "_BJetEta_" in histoName: continue if "_BtagDiscriminator_" in histoName: continue kwargs_ = histoKwargs[histoName] saveName = histoName.replace("/", "_") # Create the plotting object p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Apply QCD data-driven style if opts.signalMass != 0: signal = "ChargedHiggs_HplusTB_HplusToTB_M_%.0f" % opts.signalMass mHPlus = "%s" % int(opts.signalMass) p.histoMgr.forHisto(signal, styles.getSignalStyleHToTB_M(mHPlus)) #p.histoMgr.forHisto(opts.signalMass, styles.getSignalStyleHToTB()) if opts.mcQCD: pass else: p.histoMgr.forHisto(qcdDatasetName, styles.getAltQCDStyle()) p.histoMgr.setHistoDrawStyle(qcdDatasetName, "HIST") p.histoMgr.setHistoLegendStyle(qcdDatasetName, "F") if not opts.mcQCD: p.histoMgr.setHistoLegendLabelMany({ qcdDatasetName: "QCD (Data)", }) else: p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode) ) return
def PlotMC(datasetsMgr, datasetsMgr1, histo, intLumi): kwargs = {} print "here1" if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[".pdf", "png"], **kwargs) p = plots.MCPlot(datasetsMgr1, histo, normalizeToOne=True, saveFormats=[".pdf", ".png"], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[".pdf", ".png"], **kwargs) p = plots.MCPlot(datasetsMgr1, histo, normalizeToOne=True, saveFormats=[".pdf", "png"], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None logY = False _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} print "here2" if "Pt" in histo: _rebinX = 2 xMin = 0.0 # rebinX = 2 xMax = 805.0 # xMax = 555.0 # For topPt < 500GeV xTitle = "p_{T} (GeV/c)" units = "GeV/c" _format = "%0.0f" + units # yTitle = "Efficiency / " + str(binwidth) + " "+units # yMin = 0.0 # yMax = 1.1 else: pass if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) print "here3" histoDef = datasetsMgr.getDataset("TT").getDatasetRootHisto(histo) histoDR = datasetsMgr1.getDataset("TT").getDatasetRootHisto(histo) histoDef.normalizeToOne() histoDR.normalizeToOne() hDef = histoDef.getHistogram() hDR = histoDR.getHistogram() p = plots.ComparisonPlot(histograms.Histo(hDR, "DeltaR08", "l", "L"), histograms.Histo(hDef, "Default", "l", "L")) p.histoMgr.setHistoLegendLabelMany({ "DeltaR08": "#DeltaR(q,q')>0.8", "Default": "Default" }) p.histoMgr.forHisto("DeltaR08", styles.getQCDLineStyle()) p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) p.histoMgr.setHistoDrawStyle("DeltaR08", "HIST") #HIST p.histoMgr.setHistoLegendStyle("DeltaR08", "L") #F p.histoMgr.setHistoDrawStyle("Default", "HIST") #HIST p.histoMgr.setHistoLegendStyle("Default", "L") #F p.histoMgr.forHisto("Default", styles.ttStyle) print "here4" # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m, styles.getSignalStyleHToTB_M(m)) print "here5" plots.drawPlot( p, histo, xlabel=_xlabel, ylabel="Arbitrary Units / %s" % (_format), log=logY, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.58, "y1": 0.75, "x2": 0.92, "y2": 0.92 }, # createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92}, opts=_opts, opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=_cutBox, ) print "here6" # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath) print "here7" return
def plot(self): style = tdrstyle.TDRStyle() ROOT.gStyle.SetErrorX(0.5) #required for x-axis error bars! (must be called AFTER tdrstyle.TDRStyle()) histolist = [] #styles.dataStyle.apply(self.h_data) hhd = histograms.Histo(self.h_data,"Data", legendStyle="PL", drawStyle="E1P") hhd.setIsDataMC(isData=True, isMC=False) histolist.append(hhd) # For-loop: All signal histo for i, hsignal in enumerate(self.h_signal, 1): mass = hsignal.GetName().replace("Hp", "") Verbose( "Customing signal histogram for Mass = \"%s\"" % (mass), i==1) hhs = histograms.Histo(hsignal,hsignal.GetTitle(), legendStyle="L", drawStyle="HIST") hhs.setIsDataMC(isData=False, isMC=True) signalStyle = styles.getSignalStyleHToTB_M(mass) signalStyle.apply(hhs.getRootHisto()) histolist.append(hhs) # For-loop: All bkg histos for hname in self.histonames: hhp = histograms.Histo(self.histograms[hname],hname,legendStyle="F", drawStyle="HIST",legendLabel=self.labels[hname]) hhp.setIsDataMC(isData=False,isMC=True) histolist.append(hhp) # Sanity check for i, h in enumerate(histolist, 1): hName = h.getRootHisto().GetName() Verbose(hName, i==1) # Do the plot p = plots.DataMCPlot2(histolist) p.setDefaultStyles() p.stackMCHistograms() p.setLuminosity(opts.lumi) if opts.fitUncert: p.addMCUncertainty(postfit=not opts.prefit) # boolean changes only the legend if opts.prefit: p.setLegendHeader("Pre-Fit") else: p.setLegendHeader("Post-Fit") # Customise histogram units = "GeV" #(GeV/c^{2}) myParams = {} myParams["xlabel"] = "m_{jjbb} (%s)" % (units) myParams["ylabel"] = "< Events / " + units + " >" myParams["ratio"] = True myParams["ratioYlabel"] = "Data/Bkg. " myParams["logx"] = self.gOpts.logX myParams["log"] = self.gOpts.logY myParams["ratioType"] = "errorScale" myParams["ratioErrorOptions"] = {"numeratorStatSyst": False, "denominatorStatSyst": True} myParams["opts"] = self.opts myParams["optsLogx"] = self.optsLogx myParams["opts2"] = self.opts2 myParams["divideByBinWidth"] = True #not opts.fitUncert # Error when used for "TGraphAsymmErrors" (uncert.) myParams["errorBarsX"] = True myParams["xlabelsize"] = 25 myParams["ylabelsize"] = 25 myParams["addMCUncertainty"] = True myParams["addLuminosityText"] = True myParams["moveLegend"] = self.moveLegend #myParams["saveFormats"] = [] # Draw the plot if not os.path.exists(opts.saveDir): os.makedirs(opts.saveDir) plots.drawPlot(p, os.path.join(opts.saveDir, self.gOpts.saveName), **myParams) # Save the plot (not needed - drawPlot saves the canvas already) SavePlot(p, self.gOpts.saveName, opts.saveDir, saveFormats = [".png", ".pdf", ".C"]) return
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts): # Get the histogram customisations (keyword arguments) _kwargs = GetHistoKwargs(histoList[0]) # Get the root histos for all datasets and Control Regions (CRs) regions = ["SR", "VR", "CRone", "CRtwo"] rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= manager = FakeBNormalization.FakeBNormalizationManager(binLabels, opts.mcrab, opts.optMode, verbose=False) if opts.inclusiveOnly: #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"]) binLabel = "Inclusive" manager.CalculateTransferFactor("Inclusive", rhDict["FakeB-CRone-Inclusive"], rhDict["FakeB-CRtwo-Inclusive"]) else: for bin in binLabels: manager.CalculateTransferFactor(bin, rhDict["FakeB-CRone-%s" % bin], rhDict["FakeB-CRtwo-%s" % bin]) # Get unique a style for each region for k in rhDict: dataset = k.split("-")[0] region = k.split("-")[1] styles.getABCDStyle(region).apply(rhDict[k]) if "FakeB" in k: styles.getFakeBStyle().apply(rhDict[k]) # sr.apply(rhDict[k]) # ========================================================================================= # Create the final plot object # ========================================================================================= rData_SR = rhDict["Data-SR-Inclusive"] rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"] rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive") rBkgSum_SR.Reset() if opts.inclusiveOnly: bin = "Inclusive" # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) else: # For-loop: All bins for i, bin in enumerate(binLabels, 1): if bin == "Inclusive": continue # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) binHisto_VR = rhDict["FakeB-VR-%s" % (bin)] VRtoSR_TF = manager.GetTransferFactor(bin) Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), i==1) binHisto_VR.Scale(VRtoSR_TF) # Add the normalised histogram to the final Inclusive SR (predicted) histo rBkgSum_SR.Add(binHisto_VR, +1) #Print("Got Verification Region (VR) shape %s%s%s" % (ShellStyles.NoteStyle(), rFakeB_VR.GetName(), ShellStyles.NormalStyle()), True) # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) ) #VRtoSR_TF = manager.GetTransferFactor("Inclusive") #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True) #rBkgSum_SR.Scale(VRtoSR_TF) # Plot histograms if opts.altPlot: # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] ) rBkgSum_SR.Add(rEWKGenuineB_SR, +1) # Change style styles.getGenuineBStyle().apply(rBkgSum_SR) # Remove unsupported settings of kwargs _kwargs["stackMCHistograms"] = False _kwargs["addLuminosityText"] = False # Create the plot p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[]) # Set draw / legend style p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P") p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive" , "LP") p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST") p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive" , "F") # Set legend labels p.histoMgr.setHistoLegendLabelMany({ "Data-SR" : "Data", "BkgSum-SR" : "Fake-b + Gen-b", }) else: # Create empty histogram stack list myStackList = [] # Signal p2 = plots.DataMCPlot(datasetsMgr, "ForTestQGLR/QGLR_SR/QGLR_SRInclusive", saveFormats=[]) hSignal_800 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto() hhSignal_800= histograms.Histo(hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800', "H^{+} m_{H^+}=800 GeV") hhSignal_800.setIsDataMC(isData=False, isMC=True) myStackList.append(hhSignal_800) hSignal_250 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto() hhSignal_250= histograms.Histo(hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250', "H^{+} m_{H^+}=250 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250']) hhSignal_250.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_250) hSignal_500 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto() hhSignal_500= histograms.Histo(hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500', "H^{+} m_{H^+}=500 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_500.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_500) hSignal_1000 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto() hhSignal_1000= histograms.Histo(hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000', "H^{+} m_{H^+}=1000 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500']) hhSignal_1000.setIsDataMC(isData=False, isMC=True) #myStackList.append(hhSignal_1000) # Add the FakeB data-driven background to the histogram list hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b") hFakeB.setIsDataMC(isData=False, isMC=True) myStackList.append(hFakeB) # Add the EWKGenuineB MC background to the histogram list hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB", "EWK Genuine-b") hGenuineB.setIsDataMC(isData=False, isMC=True) myStackList.append(hGenuineB) # Add the collision datato the histogram list hData = histograms.Histo(rData_SR, "Data", "Data") hData.setIsDataMC(isData=True, isMC=False) myStackList.insert(0, hData) p = plots.DataMCPlot2( myStackList, saveFormats=[]) p.setLuminosity(opts.intLumi) p.setDefaultStyles() # Draw the plot and save it hName = "test" plots.drawPlot(p, hName, **_kwargs) SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"]) #========================================================================================== # Calculate Cut-Flow Efficiency #========================================================================================== kwargs = { "rebinX" : 1, "xlabel" : "QGLR", "ylabel" : "Significance / %.02f ", "opts" : {"ymin": 0.0, "ymaxfactor": 1.3}, "createLegend": {"x1": 0.55, "y1": 0.70, "x2": 0.92, "y2": 0.92}, # "cutBox" : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True}, } efficiencyList = [] xValues = [] yValues_250 = [] yValues_500 = [] yValues_800 = [] yValues_1000 = [] yValues_Bkg = [] nBins = hSignal_250.GetNbinsX()+1 hBkg = p.histoMgr.getHisto("ChargedHiggs_HplusTB_HplusToTB_M_800").getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) for i in range (0, nBins): # Cut value cut = hSignal_250.GetBinCenter(i) passed_250 = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins()) passed_500 = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins()) passed_800 = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins()) passed_1000 = hSignal_1000.Integral(i, hSignal_1000.GetXaxis().GetNbins()) passed_Bkg = hBkg.Integral(i, hBkg.GetXaxis().GetNbins()) total_250 = hSignal_250.Integral() total_500 = hSignal_500.Integral() total_800 = hSignal_800.Integral() total_1000 = hSignal_1000.Integral() total_Bkg = hBkg.Integral() eff_250 = float(passed_250)/total_250 eff_500 = float(passed_500)/total_500 eff_800 = float(passed_800)/total_800 eff_1000 = float(passed_1000)/total_1000 eff_Bkg = float(passed_Bkg)/total_Bkg xValues.append(cut) yValues_250.append(eff_250) yValues_500.append(eff_500) yValues_800.append(eff_800) yValues_1000.append(eff_1000) yValues_Bkg.append(eff_Bkg) # Create the Efficiency Plot tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_250)) tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_500)) tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_800)) tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_1000)) tGraph_Bkg = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_Bkg)) styles.getSignalStyleHToTB_M("200").apply(tGraph_250) styles.getSignalStyleHToTB_M("500").apply(tGraph_500) styles.getSignalStyleHToTB_M("800").apply(tGraph_800) styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000) styles.getQCDLineStyle().apply(tGraph_Bkg) drawStyle = "CPE" effGraph_250 = histograms.HistoGraph(tGraph_250, "H^{+} m_{H^{+}} = 250 GeV", "lp", drawStyle) effGraph_500 = histograms.HistoGraph(tGraph_500, "H^{+} m_{H^{+}} = 500 GeV", "lp", drawStyle) effGraph_800 = histograms.HistoGraph(tGraph_800, "H^{+} m_{H^{+}} = 800 GeV", "lp", drawStyle) effGraph_1000 = histograms.HistoGraph(tGraph_1000, "H^{+} m_{H^{+}} = 1000 GeV", "lp", drawStyle) effGraph_Bkg = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle) efficiencyList.append(effGraph_250) efficiencyList.append(effGraph_500) efficiencyList.append(effGraph_800) efficiencyList.append(effGraph_1000) efficiencyList.append(effGraph_Bkg) # Efficiency plot pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"]) pE.createFrame("QGLR_Efficiency") pE.setEnergy("13") pE.getFrame().GetYaxis().SetLabelSize(18) pE.getFrame().GetXaxis().SetLabelSize(20) pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01") pE.getFrame().GetXaxis().SetTitle("QGLR Cut") # Add Standard Texts to plot histograms.addStandardTexts() # Customise Legend moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1} pE.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)) pE.draw() # plots.drawPlot(pE, "QGLR_Efficiency", **kwargs) SavePlot(pE, "QGLR_Efficiency", os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] ) #========================================================================================== # Calculate Significance #========================================================================================== SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800" hSignif_250 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_500 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_800 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName) hSignif_250.Reset() hSignif_500.Reset() hSignif_800.Reset() hSignif_1000.Reset() hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg") hBkg.Reset() # Bkg: FakeB + Genuine B hBkg.Add(hFakeB.getRootHisto(), +1) hBkg.Add(hGenuineB.getRootHisto(), +1) nBins = hSignif_250.GetNbinsX()+1 # For-loop: All histo bins for i in range (1, nBins+1): sigmaB = ROOT.Double(0) b = hBkg.IntegralAndError(i, nBins, sigmaB) s_250 = hSignal_250.Integral(i, nBins) s_500 = hSignal_500.Integral(i, nBins) s_800 = hSignal_800.Integral(i, nBins) s_1000 = hSignal_1000.Integral(i, nBins) # Calculate significance signif_250 = stat.significance(s_250, b, sigmaB, option="Simple")#Asimov") signif_500 = stat.significance(s_500, b, sigmaB, option="Simple")#Asimov") signif_800 = stat.significance(s_800, b, sigmaB, option="Simple")#Asimov") signif_1000 = stat.significance(s_1000, b, sigmaB, option="Simple")#"Asimov") # Set signif for this bin hSignif_250.SetBinContent(i, signif_250) hSignif_500.SetBinContent(i, signif_500) hSignif_800.SetBinContent(i, signif_800) hSignif_1000.SetBinContent(i, signif_1000) # Apply style s_250 = styles.getSignalStyleHToTB_M("200") s_250.apply(hSignif_250) s_500 = styles.getSignalStyleHToTB_M("500") s_500.apply(hSignif_500) s_800 = styles.getSignalStyleHToTB_M("800") s_800.apply(hSignif_800) s_1000 = styles.getSignalStyleHToTB_M("1000") s_1000.apply(hSignif_1000) hList = [] hList.append(hSignif_250) hList.append(hSignif_500) hList.append(hSignif_800) hList.append(hSignif_1000) hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV") hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV") hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV") hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV") pS = plots.PlotBase(hList, saveFormats=["png", "pdf"]) pS.setLuminosity(opts.intLumi) # Drawing style pS.histoMgr.setHistoDrawStyleAll("HIST") pS.histoMgr.setHistoLegendStyleAll("L") pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0)) pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle)) # Draw the plot name = "QGLR_Signif" + "GE" plots.drawPlot(pS, name, **kwargs) SavePlot(pS, name, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] ) #========================================================================================= # Calculate the Transfer Factor (TF) and save to file #========================================================================================= Verbose("Write the normalisation factors to a python file", True) fileName = os.path.join(opts.mcrab, "FakeBTransferFactors%s.py"% ( getModuleInfoString(opts) ) ) manager.writeNormFactorFile(fileName, opts) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.1f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 #logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = {"cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 100 elif "trijetjets_deltarmin" in histo.lower(): _xlabel = "#Delta R_{min}" _rebinX = 2 _opts["xmax"] = 3 _units = "" _format = "%0.1f " _cutBox = {"cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "trijetjets_deltarmax" in histo.lower(): _xlabel = "#Delta R_{max}" _rebinX = 2 _opts["xmax"] = 3.5 _units = "" _format = "%0.1f " _cutBox = {"cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "trijetdijetdr" in histo.lower(): _rebinX = 1 units = "" _format = "%0.1f " _opts["xmax"] = 3.5 _cutBox = {"cutValue": 0.8, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "trijetdijetpt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetdijetmass" in histo.lower(): _rebinX = 1 _units = "GeV/c^{2}" _format = "%0.0f " + _units _opts["xmax"] = 200 _xlabel = "m_{w} (%s)" % _units _cutBox = {"cutValue": 80.39, "fillColor": 16, "box": False, "line": True, "greaterThan": True} if "cevts_ldgtrijetmatchedtofatjet_fatjetpt" in histo.lower(): _rebin = 1 _opts["xmax"] = 3 elif "pt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 elif "trijetmass" in histo.lower(): _rebinX = 1 # logY = False _units = "GeV/c^{2}" # _format = "%0.0f " + _units _format = "%0.0f" + (_units) _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 305 #1005 _opts["xmin"] = 55 #1005 elif "topcandmass" in histo.lower(): _rebinX = 1 # logY = False _units = "GeV/c^{2}" # _format = "%0.0f " + _units _format = "%0.0f" + (_units) _xlabel = "m_{jjb}^{BDTG} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 505 #1005 _opts["xmin"] = 0 #1005 # elif "ht" in histo.lower(): # _rebinX = 2 ## logY = False # _units = "GeV" # _format = "%0.0f " + _units # _xlabel = "H_{T} (%s)" % _units # _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True} # _opts["xmax"] = 2000 elif "tetrajetptd" in histo.lower(): _rebinX = 2 #5 #10 #4 _units = "GeV/c^{2}" # _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 2000 #3500.0 _cutBox = {"cutValue": 400, "fillColor": 16, "box": False, "line": True, "greaterThan": True} elif "tetrajetmass" in histo.lower() or "tetrajetmass_" in histo.lower(): #ROOT.gStyle.SetNdivisions(10, "X") # h = dataset.getDatasetRootHisto(histo).getHistogram() # h.SetTickLength(100, "X") _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1500 #3500.0 _cutBox = {"cutValue": 500, "fillColor": 16, "box": False, "line": False, "greaterThan": True} elif "dijetmass" in histo.lower(): _rebinX = 1 #5 #10 #4 # logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{W} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 205 elif "trijetmultiplicitypassbdt" in histo.lower(): _rebinX = 1 _opts["xmax"] = 5 _format = "%0.0f " elif "bdtg" or "bdtvalue" in histo.lower(): _rebinX = 1 _format = "%0.2f " elif "trijetbdt_mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _opts["xmax"] = 800 # if "eta" or "phi" or "delta" in histo.lower(): #_rebinX = 1 #5 #10 #4 # _units = "" # _format = "%0.1f " # if "eta" in histo.lower(): # _xlabel = "#eta" # if "phi" in histo.lower(): # _xlabel = "#phi" # if "pt" in histo.lower(): # _opts["xmax"] = 800 elif "boosted" in histo.lower(): _xlabel = "Trijet Counter" elif "matched_dijetpt" in histo.lower(): _units = "(GeV/c)" _xlabel = "p_{T}" +_units elif "deltar_bdttrijets_tetrajetbjet" in histo.lower(): _xlabel = "#Delta R(Trijet,b_{free})" elif "tetrajetbjetbdisc" in histo.lower(): _rebinX = 2 _opts["xmax"] = 1.05 # if "matched_dijetmass" in histo.lower(): # _rebinX = 2 # if "higgstop_dijetmass" in histo.lower(): # _rebinX = 2 elif "trijet_deltaeta_trijet_tetrajetbjet" in histo.lower(): _rebinX = 2 _xlabel = "#Delta #eta (Trijet, b_{free})" elif "trijet_deltaphi_trijet_tetrajetbjet" in histo.lower(): _xlabel = "#Delta #phi (Trijet, b_{free})" elif "cevts_closejettotetrajetbjet_isbtagged" in histo.lower(): _units = "" _format = "%0.0f " + _units # if "higgstop_" in histo.lower(): # _rebinX = 2 if "eventtrijetpt2t" in histo.lower(): _rebinX = 2 if "ldgfatjetpt" in histo.lower(): _opts["xmax"] = 1000 if "deltar_w" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "ldgtrijet_deltar" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "higgstop_deltar" in histo.lower(): _rebinX = 2 _xlabel = "#Delta R" _format = "%0.1f " _opts["xmax"] = 5 logY = True if "allfatjet" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _opts["xmax"] = 800 else: pass if opts.normaliseToOne: logY = True Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "HIST") p.histoMgr.setHistoLegendStyle("TT", "LP") # if "M_200" in datasetsMgr.getAllDatasets() or "M_300" in datasetsMgr.getAllDatasets(): # p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) # p.histoMgr.setHistoDrawStyle("QCD", "P") # p.histoMgr.setHistoLegendStyle("QCD", "F") # elif d.getName() == "TT" or d.getName() == "QCD" or d.getName() == "Data": # otherHisto = histograms.Histo(histo, legName, "LP", "P") # otherHistos.append(otherHisto) # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) #soti # p.histoMgr.setHistoDrawStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "LP") # p.histoMgr.setHistoLegendStyle("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, "P") plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel,#"Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), # ylabel = "Arbitrary Units / %s" % (_format), #"Events / %s" % (_format), #"Arbitrary Units / %s" % (_format), log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", #_rebinX #createLegend = {"x1": 0.48, "y1": 0.45, "x2": 0.92, "y2": 0.92}, #All datasets # createLegend = {"x1": 0.58, "y1": 0.7, "x2": 0.92, "y2": 0.92}, createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.87}, #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, #One dataset opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/TT/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" # SavePlot(p, saveName, savePath) SavePlot(p, saveName, save_path) return
def DataMCHistograms(datasetsMgr): Verbose("Plotting Data-MC Histograms") # Definitions histoNames = [] saveFormats = [".png"] #[".C", ".png", ".pdf"] # Get list of histograms dataPath = "ForDataDrivenCtrlPlots" allHistos = datasetsMgr.getDataset(datasetsMgr.getAllDatasetNames()[0]).getDirectoryContent(dataPath) histoList = [h for h in allHistos if "StandardSelections" in h] histoList.extend([h for h in allHistos if "AllSelections" in h]) histoList = [h for h in histoList if "_MCEWK" not in h] histoList = [h for h in histoList if "_Purity" not in h] histoPaths = [dataPath + "/" + h for h in histoList] # Get histogram<->kwargs dictionary histoKwargs = GetHistoKwargs(histoPaths, opts) # For-loop: All histograms in list for histoName in histoPaths: if "Mass" not in histoName: #if "LdgTetrajetMass" not in histoName: continue if "JetEtaPhi" in histoName: continue if opts.signalMass == 0: if "LdgTrijetMass" in histoName: continue if "LdgTetrajetMass" in histoName: continue if "Vs" in histoName: continue # Not used in this analysis (yet) if "MHT" in histoName: continue # By definition of the Inverted sample the following histos cannot agree! if "NBjets_" in histoName: continue if "BJetPt_" in histoName: continue if "_BJetEta_" in histoName: continue if "_BtagDiscriminator_" in histoName: continue kwargs_ = histoKwargs[histoName] saveName = histoName.replace("/", "_") # Create the plotting object p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Apply QCD data-driven style if opts.signalMass != 0: signal = "ChargedHiggs_HplusTB_HplusToTB_M_%.0f" % opts.signalMass mHPlus = "%s" % int(opts.signalMass) p.histoMgr.forHisto(signal, styles.getSignalStyleHToTB_M(mHPlus)) #p.histoMgr.forHisto(opts.signalMass, styles.getSignalStyleHToTB()) p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), [".png"] ) return
def PlotHistograms(datasetsMgr, datasetsMgr_matched, histoName, intLumi): Verbose("Plotting Data-MC Histograms") # Skip 2-D plots skipStrings = [] if "topbdtSelection_" in opts.folder: skipStrings = ["_Vs_", "Vs", "MCtruth", "TopQuark", "RealSelected", "DeltaMVAgt1", "SelectedTop", "LdgTrijetFake", "LdgTrijetFakeJJB", "TrijetFake", "FakeInTopDir", "LdgTrijetFakeJJB_BDT", "LdgTrijetFake_BDT", "Cevts",] #, "Matched" if opts.folder == "AnalysisTriplets": skipStrings = ["Cevts"] if opts.folder == "counters": skipStrings = ["weighted"] if opts.folder == "eSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "muSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "tauSelection_Veto": skipStrings = ["riggerMatch", "NprongsMatrix", "Resolution"] if opts.folder == "PUDependency": skipStrings = ["WithProbabilisticBtag", "AngularCuts", "AntiIsolatedTau", "NvtxTau"] if opts.folder == "jetSelection_": skipStrings = ["JetMatching"] if opts.folder == "bjetSelection_": skipStrings = ["MatchDeltaR", "btagSFRelUncert", "_dEta", "_dPhi", "_dPt", "_dR"] if opts.folder == "metSelection_": skipStrings = [""] if opts.folder == "topologySelection_": skipStrings = ["_Vs_"] if "ForDataDrivenCtrlPlots" in opts.folder: skipStrings = ["_Vs_", "JetEtaPhi", "MinDeltaPhiJet", "MaxDeltaPhiJet", "MinDeltaRJet", "SubldgTetrajet"] # Skip histograms if they contain a given string for keyword in skipStrings: if keyword in histoName: return # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object if opts.onlyMC: if "Matched" in histoName: p = plots.MCPlot(datasetsMgr_matched, histoName, saveFormats=[], normalizeToLumi=intLumi) elif opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histoName, saveFormats=[], normalizeToOne=True) else: p = plots.MCPlot(datasetsMgr, histoName, saveFormats=[], normalizeToLumi=intLumi) else: p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Apply style if opts.signalMass != 0: p.histoMgr.forHisto(opts.signal, styles.getSignalStyleHToTB_M(opts.signalMass)) # p.histoMgr.forHisto(opts.signalMass, styles.getSignalStyleHToTB()) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Replace bin labels if "counter" in opts.folder: replaceBinLabels(p, histoName) if opts.normaliseToOne: saveDir = opts.saveDir +"/normToOne/logY/" else: saveDir = opts.saveDir + "/normToLumi/" # Save the plots in custom list of saveFormats SavePlot(p, saveName, os.path.join(saveDir, opts.folder, opts.optMode), [".png", ".pdf"] ) return
def DataMCHistograms(datasetsMgr, histoName): Verbose("Plotting Data-MC Histograms") # Skip 2-D plots skipStrings = [] if opts.folder == "topbdtSelection_": skipStrings = ["_Vs_", "Vs", "Matched", "MCtruth", "TopQuark", "RealSelected", "DeltaMVAgt1", "SelectedTop", "LdgTrijetFake", "LdgTrijetFakeJJB", "TrijetFake", "FakeInTopDir", "LdgTrijetFakeJJB_BDT", "LdgTrijetFake_BDT"] if opts.folder == "counters": skipStrings = ["weighted"] if opts.folder == "eSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "muSelection_Veto": skipStrings = ["Resolution"] if opts.folder == "tauSelection_Veto": skipStrings = ["riggerMatch", "NprongsMatrix", "Resolution"] if opts.folder == "PUDependency": skipStrings = ["WithProbabilisticBtag", "AngularCuts", "AntiIsolatedTau", "NvtxTau"] if opts.folder == "jetSelection_": skipStrings = ["JetMatching"] if opts.folder == "bjetSelection_": skipStrings = ["MatchDeltaR", "btagSFRelUncert", "_dEta", "_dPhi", "_dPt", "_dR"] if opts.folder == "metSelection_": skipStrings = [""] if opts.folder == "topologySelection_": skipStrings = ["_Vs_"] if "ForDataDrivenCtrlPlots" in opts.folder: skipStrings = ["_Vs_", "JetEtaPhi", "MinDeltaPhiJet", "MaxDeltaPhiJet", "MinDeltaRJet"] # Skip histograms if they contain a given string for keyword in skipStrings: if keyword in histoName: return # Get Histogram name and its kwargs saveName = histoName.rsplit("/")[-1] # histoName.replace("/", "_") kwargs_ = GetHistoKwargs(saveName, opts) # Create the plotting object p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[]) # Overwite signal style? if 0: if opts.signalMass != 0: p.histoMgr.forHisto(opts.signal, styles.getSignalStyleHToTB_M(opts.signalMass)) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.setHistoLegendLabelMany({ "QCD": "QCD (MC)", }) # Apply blinding of signal region if "blindingRangeString" in kwargs_: startBlind = float(kwargs_["blindingRangeString"].split("-")[1]) endBlind = float(kwargs_["blindingRangeString"].split("-")[0]) plots.partiallyBlind(p, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs_["moveBlindedText"]) # Draw and save the plot plots.drawPlot(p, saveName, **kwargs_) #the "**" unpacks the kwargs_ dictionary # Replace bin labels if "counter" in opts.folder and "counter" in histoName.split("/")[-1]: # p.getFrame().GetXaxis().LabelsOption("v") #vertical orientation of bin labels replaceBinLabels(p, saveName) #pass # Save the plots in custom list of saveFormats SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder), [".png", ".pdf"] ) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None logY = False _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "ChiSqr" in histo: _rebinX = 1 logY = True _units = "" _format = "%0.1f " + _units _xlabel = "#chi^{2}" _cutBox = { "cutValue": 10.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 100 elif "trijetmass" in histo.lower(): _rebinX = 4 logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = { "cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 805 #1005 elif "ht" in histo.lower(): _rebinX = 2 logY = False _units = "GeV" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = { "cutValue": 500, "fillColor": 16, "box": False, "line": True, "greaterThan": True } #_opts["xmin"] = 500 _opts["xmax"] = 2000 elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 logY = False _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _cutBox = { "cutValue": 500.0, "fillColor": 16, "box": False, "line": True, "greaterThan": True } _opts["xmax"] = 1500 #3500.0 #_rebinX = 10 #_opts["xmax"] = 3500 elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 600 elif "foxwolframmoment" in histo.lower(): _format = "%0.1f" _cutBox = { "cutValue": 0.5, "fillColor": 16, "box": False, "line": True, "greaterThan": True } else: pass if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto( lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasets(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle()) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasets(): p.histoMgr.setHistoDrawStyle("TT", "AP") p.histoMgr.setHistoLegendStyle("TT", "LP") # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" % m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot( p, histo, xlabel=_xlabel, ylabel="Arbitrary Units / %s" % (_format), log=logY, rebinX=_rebinX, cmsExtraText="Preliminary", createLegend={ "x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92 }, opts=_opts, opts2={ "ymin": 0.6, "ymax": 1.4 }, cutBox=_cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode) SavePlot(p, saveName, savePath) return
def PlotMC(datasetsMgr, histo, intLumi): kwargs = {} if opts.normaliseToOne: p = plots.MCPlot(datasetsMgr, histo, normalizeToOne=True, saveFormats=[], **kwargs) else: p = plots.MCPlot(datasetsMgr, histo, normalizeToLumi=intLumi, saveFormats=[], **kwargs) # Draw the histograms _cutBox = None _rebinX = 1 _format = "%0.0f" _xlabel = None _opts = {"ymin": 1e-3, "ymaxfactor": 1.0} if "pt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 805 #1005 if "bdisc" in histo.lower(): _rebinX = 2 _units = "" _format = "%0.2f " + _units _xlabel = "b-discriminator" #(%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 1.2 if "ht" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "H_{T} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 1505 #1005 if "met" in histo.lower(): _rebinX = 1 _units = "GeV" _format = "%0.0f " + _units _xlabel = "E_{T,missing} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": False, "greaterThan": True} _opts["xmax"] = 205 #1005 if "mult" in histo.lower(): _units = "" _format = "%0.0f " + _units _xlabel = "jet multiplicity" _opts["xmax"] = 10 if "mass" in histo.lower(): _rebinX = 2 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjb} (%s)" % _units _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 350 #1005 elif "tetrajetmass" in histo.lower(): _rebinX = 5 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{jjbb} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 1500 #3500.0 elif "dijetmass" in histo.lower(): _rebinX = 1 #5 #10 #4 _units = "GeV/c^{2}" _format = "%0.0f " + _units _xlabel = "m_{W} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 #3500.0 _cutBox = {"cutValue": 80.4, "fillColor": 16, "box": False, "line": True, "greaterThan": True} _opts["xmax"] = 300 elif "tetrajetbjetpt" in histo.lower(): _rebinX = 2 _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "ldgtrijetpt" in histo.lower(): _rebinX = 2 # logY = False _units = "GeV/c" _format = "%0.0f " + _units _xlabel = "p_{T} (%s)" % (_units) _format = "%0.0f " + _units _opts["xmax"] = 800 elif "tau" in histo.lower(): _format = "%0.2f " elif "deltar" in histo.lower(): _format = "%0.2f " elif "bdtvalue" in histo.lower(): _format = "%0.1f" else: pass if opts.normaliseToOne: logY = False Ylabel = "Arbitrary Units / %s" % (_format) else: logY = True Ylabel = "Events / %s" % (_format) if logY: yMaxFactor = 2.0 else: yMaxFactor = 1.2 _opts["ymaxfactor"] = yMaxFactor if opts.normaliseToOne: _opts["ymin"] = 1e-3 #_opts = {"ymin": 1e-3, "ymaxfactor": yMaxFactor, "xmax": None} else: _opts["ymin"] = 1e0 #_opts["ymaxfactor"] = yMaxFactor #_opts = {"ymin": 1e0, "ymaxfactor": yMaxFactor, "xmax": None} # Customise styling p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid)) if "QCD" in datasetsMgr.getAllDatasetNames(): p.histoMgr.forHisto("QCD", styles.getQCDFillStyle() ) p.histoMgr.setHistoDrawStyle("QCD", "HIST") p.histoMgr.setHistoLegendStyle("QCD", "F") if "TT" in datasetsMgr.getAllDatasetNames(): TTStyle = styles.StyleCompound([styles.StyleFill(fillColor=ROOT.kMagenta-2), styles.StyleLine(lineColor=ROOT.kMagenta-2, lineStyle=ROOT.kSolid, lineWidth=3), styles.StyleMarker(markerSize=1.2, markerColor=ROOT.kMagenta-2, markerSizes=None, markerStyle=ROOT.kFullTriangleUp)]) p.histoMgr.forHisto("TT", TTStyle) p.histoMgr.setHistoDrawStyle("TT", "HIST") #AP p.histoMgr.setHistoLegendStyle("TT", "F") #LP # Customise style signalM = [] for m in signalMass: signalM.append(m.rsplit("M_")[-1]) for m in signalM: p.histoMgr.forHisto("ChargedHiggs_HplusTB_HplusToTB_M_%s" %m, styles.getSignalStyleHToTB_M(m)) plots.drawPlot(p, histo, xlabel = _xlabel, ylabel = Ylabel, log = logY, rebinX = _rebinX, cmsExtraText = "Preliminary", createLegend = {"x1": 0.68, "y1": 0.82, "x2": 1.0, "y2": 0.92}, #createLegend = {"x1": 0.73, "y1": 0.85, "x2": 0.97, "y2": 0.77}, opts = _opts, opts2 = {"ymin": 0.6, "ymax": 1.4}, cutBox = _cutBox, ) # Save plot in all formats saveName = histo.split("/")[-1] savePath = os.path.join(opts.saveDir, histo.split("/")[0], opts.optMode) ''' if opts.normaliseToOne: save_path = savePath + opts.MVAcut if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" else: save_path = savePath + opts.MVAcut + "/normToLumi/" if opts.noQCD: save_path = savePath + opts.MVAcut + "/noQCD/" ''' SavePlot(p, saveName, savePath) return