def Stack(can, reverse=False): if can.GetPrimitive('pad_top'): return Stack(can.GetPrimitive('pad_top'), reverse=reverse) from ROOT import TH1, THStack stack = THStack('stack', 'stack') xaxislabel, yaxislabel = '', '' binlabels = [] if reverse: the_primitives = reversed(can.GetListOfPrimitives()) else: the_primitives = can.GetListOfPrimitives() for i in the_primitives: if issubclass(type(i), TH1): stack.Add(i) if not xaxislabel: xaxislabel = i.GetXaxis().GetTitle() if not yaxislabel: yaxislabel = i.GetYaxis().GetTitle() if not binlabels and i.GetXaxis().GetBinLabel(1): for j in range(i.GetNbinsX()): binlabels.append(i.GetXaxis().GetBinLabel(j + 1)) can.Clear() tobject_collector.append(stack) can.cd() stack.Draw('hist') stack.GetXaxis().SetTitle(xaxislabel) stack.GetYaxis().SetTitle(yaxislabel) if binlabels: for i in range(stack.GetXaxis().GetNbins()): stack.GetXaxis().SetBinLabel(i + 1, binlabels[i]) can.Modified() can.Update() can.RedrawAxis() return
def __draw_stack(self, regions, th1d_dict, output_name): canvas = TCanvas("canvas", 'A basic canvas', 1000, 600) stack = THStack("stack", "stack") leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95) for region in regions: hist = th1d_dict[region] hist.SetLineColor(1) hist.SetLineWidth(1) hist.SetMarkerColor(self.__get_colour(region)) hist.SetMarkerStyle(0) hist.SetFillColor(self.__get_colour(region)) leg.AddEntry(hist, self.__get_label(region), "f") stack.Add(hist) del hist stack.Draw("HIST") stack.GetYaxis().SetTitle("Events") stack.GetXaxis().SetTitle("True #it{E_{T}^{miss}} [GeV]") leg.Draw() canvas.Print(output_name)
def getStack(self, lumi, name, var, nbin, xmin, xmax, cut, options, xlabel): hs = THStack(name, "") for b in self.blocks: AuxName = "auxStack_block_" + name + "_" + b.name haux = b.getTH1F(lumi, AuxName, var, nbin, xmin, xmax, cut, options, xlabel) haux.SetFillColor(b.color) hs.Add(haux) del haux can_aux = TCanvas("can_%s_%s" % (name, b.name)) can_aux.cd() hs.Draw() del can_aux if xmax != xmin: hs.GetXaxis().SetTitle(xlabel) b = int((xmax - xmin) / nbin) ylabel = "Events / " + str(b) + " GeV" else: ylabel = "# events" hs.GetYaxis().SetTitle(ylabel) return hs
def plot_hist_diff(histlist1, histlist2, labellist, log, overflow, filename, options): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist1[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist1), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist1)): entries = histlist1[i].GetEntries() bad_entries = histlist2[i].GetEntries() histlist1[i].SetLineColorAlpha(colorlist[i], 0.65) histlist1[i].SetLineWidth(3) if entries: histlist1[i].Scale(1. / entries) if bad_entries: histlist2[i].Scale(1. / bad_entries) histlist1[i].Add(histlist2[i], -1.) nbins = histlist1[i].GetNbinsX() legend.AddEntry( histlist1[i], "#splitline{" + labellist[i] + "}{#splitline{%d total jets}{%d bad jets}}" % (entries, bad_entries), "l") if overflow: histlist1[i].SetBinContent( nbins, histlist1[i].GetBinContent(nbins) + histlist1[i].GetBinContent(nbins + 1)) #overflow histlist1[i].SetBinContent( 1, histlist1[i].GetBinContent(0) + histlist1[i].GetBinContent(1)) #underflow if histlist1[i].GetMaximum() > maximum: maximum = histlist1[i].GetMaximum() histstack.Add(histlist1[i]) #if i == 0: histlist[i].Draw(options) #else: histlist[i].Draw(same+options) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist1[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist1[0].GetYaxis().GetTitle()) legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def plot_bar(histlist, axislabels, labels, norm, log, filename, options): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) if labels: legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) entries = histlist[i].GetEntries() if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() if labels: legend.AddEntry(histlist[i], labels[i], "l") histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) histstack.GetXaxis().SetNdivisions(len(axislabels)) histstack.GetXaxis().CenterLabels(True) for i, label in enumerate(axislabels): histstack.GetXaxis().ChangeLabel(i + 1, -1, -1, -1, -1, -1, str(label)) if labels: legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def Stack(can,reverse=False) : if can.GetPrimitive('pad_top') : return Stack(can.GetPrimitive('pad_top'),reverse=reverse) from ROOT import TH1,THStack stack = THStack('stack','stack') xaxislabel,yaxislabel = '','' binlabels = [] if reverse : the_primitives = reversed(can.GetListOfPrimitives()) else : the_primitives = can.GetListOfPrimitives() for i in the_primitives : if issubclass(type(i),TH1) : stack.Add(i) if not xaxislabel : xaxislabel = i.GetXaxis().GetTitle() if not yaxislabel : yaxislabel = i.GetYaxis().GetTitle() if not binlabels and i.GetXaxis().GetBinLabel(1) : for j in range(i.GetNbinsX()) : binlabels.append(i.GetXaxis().GetBinLabel(j+1)) # The original objects are cleared from the histogram: can.Clear() tobject_collector.append(stack) # Set draw option of underlying histograms for automatically nice legends for hist in stack.GetHists() : hist.SetOption('f') can.cd() stack.Draw('hist') stack.GetXaxis().SetTitle(xaxislabel) stack.GetYaxis().SetTitle(yaxislabel) if binlabels : for i in range(stack.GetXaxis().GetNbins()) : stack.GetXaxis().SetBinLabel(i+1,binlabels[i]) can.RedrawAxis() can.Modified() can.Update() return
def plotstuff2(cut1,cut2,cutname): events.Draw("eleClT-posClT>>h1(200,-10,10)",cut1,"goff") events.Draw("eleClT-posClT>>h2(200,-10,10)",cut2,"goff") hs = THStack("hs",cutname); hs.Add(gDirectory.Get("h1")) hs.Add(gDirectory.Get("h2")) hs.Draw("nostack") leg = TLegend(0.6,0.75,0.9,0.9) leg.AddEntry(gDirectory.Get("h1"),"after base cuts") leg.AddEntry(gDirectory.Get("h2"),"after vertexing cuts") leg.Draw() gDirectory.Get("h1").SetLineColor(1) gDirectory.Get("h2").SetLineColor(2) hs.GetXaxis().SetTitle("tEle-tPos [ns]") hs.GetYaxis().SetTitle("events/(0.1 ns)") c.Print(sys.argv[1]+".pdf")
def histo_creation(lumi2017_param, variable_param, binHist_param, minHist_param, maxHist_param, titleX_param, titleY_param): histo = [] legend = TLegend(0.5, 0.5, 0.9, 0.9) canvas = TCanvas() if (lumi2017_param): legend.SetHeader("41.53 fb-1", "C") canvas.SetName(variable_param + "2017") else: legend.SetHeader("35.9 fb-1", "C") canvas.SetName(variable_param + "2016") for i in range(len(MC_sample)): foo = TH1F("essaie{}".format(i), "essaie{}".format(i), binHist_param, minHist_param, maxHist_param) rootfile[i].Get('events').Project("essaie{}".format(i), variable_param, "weight") histo.append(foo) histo[i].SetFillColor(color[i]) histo[i].Scale(luminosity2017 * 1000 * cross_sec[i] / eventsN0[i]) if (not lumi2017_param): histo[i].Scale(lumiRatio) print(histo[i].GetEntries() * lumiRatio * luminosity2017 * 1000 * cross_sec[i] / eventsN0[i]) histo[i].Draw() legend.AddEntry(histo[i], MC_name[i], "f") stack = THStack(variable_param, "") for i in range(len(MC_sample)): stack.Add(histo[len(MC_sample) - (i + 1)]) stack.Draw("HIST") stack.GetXaxis().SetTitle(titleX_param) stack.GetYaxis().SetTitle(titleY_param) legend.Draw() if (lumi2017_param): canvas.SaveAs(localisation + "/results/MC_" + variable_param + "2017.png") else: canvas.SaveAs(localisation + "/results/MC_" + variable_param + "2016.png") canvas.Write()
def timing(data, leg_entries): """ Plot different timing delays after receiving the trigger. """ stack = THStack('stack', 'Counts per BX') leg = TLegend(.8, .5, 1., .9) for idx, list in enumerate(data): h = TH1F('', '', 100, 0, 220) h.SetFillColor(idx+2) leg.AddEntry(h, leg_entries[idx], 'f') for val in list: h.Fill(val) stack.Add(h) canvas = TCanvas() stack.Draw() stack.GetXaxis().SetTitle('BX') stack.GetYaxis().SetTitle('Counts') leg.Draw() canvas.SaveAs('timing.pdf')
def plotstuff3(cuts,cutname): hs = THStack("hs",cutname); hs.Add(gDirectory.Get("h1")) leg = TLegend(0.6,0.75,0.9,0.9) events.Draw("eleClT-posClT>>h0(200,-10,10)",cuts[0],"goff") leg.AddEntry(gDirectory.Get("h0"),"after base cuts") hs.Add(gDirectory.Get("h0")) gDirectory.Get("h0").SetLineColor(1) #gDirectory.Get("h1").SetTitle(cutname) for i in range(1,len(cuts)): events.Draw("eleClT-posClT>>h{0}(100,-10,10)".format(i),makeCutString(cuts[0:i+1]),"goff") leg.AddEntry(gDirectory.Get("h{0}".format(i)),"after {0} cut".format(cutnames[i])) hs.Add(gDirectory.Get("h{0}".format(i))) gDirectory.Get("h{0}".format(i)).SetLineColor(i+1) hs.Draw("nostack") leg.Draw() hs.GetXaxis().SetTitle("tEle-tPos [ns]") hs.GetYaxis().SetTitle("events/(0.1 ns)") c.Print(sys.argv[1]+".pdf")
def plotstuff(cut1,cut2,cut3,cutname): events.Draw("eleClT-posClT>>h1(200,-10,10)",cut1,"goff") events.Draw("eleClT-posClT>>h2(200,-10,10)",cut2,"goff") events.Draw("eleClT-posClT>>h3(200,-10,10)",cut3,"goff") hs = THStack("hs","Effect of "+cutname+" cut"); hs.Add(gDirectory.Get("h1")) hs.Add(gDirectory.Get("h2")) hs.Add(gDirectory.Get("h3")) hs.Draw("nostack") leg = TLegend(0.6,0.75,0.9,0.9) leg.AddEntry(gDirectory.Get("h1"),"passed all but this cut") leg.AddEntry(gDirectory.Get("h2"),"passed all cuts") leg.AddEntry(gDirectory.Get("h3"),"failed this cut") leg.Draw() gDirectory.Get("h1").SetLineColor(1) gDirectory.Get("h2").SetLineColor(4) gDirectory.Get("h3").SetLineColor(2) hs.GetXaxis().SetTitle("tEle-tPos [ns]") hs.GetYaxis().SetTitle("events/(0.1 ns)") c.Print(sys.argv[1]+".pdf")
def main(): extension = "pdf" luminosity = 44307.4 ymin = 0 ymax = 0.024 data_set_names = [ (["SZee_all_susy_2l_0jets.root", "SZmumu_all_susy_2l_0jets.root"], "Z#rightarrowll", 860 + 0, 23), (["ZZ_1in3_susy_2l_0jets.root"], "ZZ#rightarrowll#nu#nu", 416 + 3, 43), (["WZ_1in3_susy_2l_0jets.root"], "WZ#rightarrowl#null", 416 - 8, 33), (["WW_1in3_susy_2l_0jets.root"], "WW#rightarrowl#nul#nu", 416 + 0, 20), ([ "ttbar_1in3_susy_2l_0jets.root", "top_1in3_susy_2l_0jets.root", "antitop_1in3_susy_2l_0jets.root" ], "Top", 800 + 4, 21), ] DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data", "SR_SUSY") ## Creating the plots gROOT.SetStyle("ATLAS") gROOT.ForceStyle() gStyle.SetErrorX(0.5) canvas = TCanvas("canvas", 'A basic canvas', 800, 600) # canvas.SetLogy() ## Adding in the legend leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95, ncols=1) ## Creating the stack stack = THStack("stack", "stack") stack.SetMinimum(ymin) stack.SetMaximum(ymax) ## Cycling through the different datasets for datasets, label, colour, style in data_set_names: ## Creating the total histogram which will be filled myhist = TH1D(label, label, 50, 0, 150) myhist.SetStats(True) myhist.StatOverflows(True) for dataset in datasets: ## The root file is opened rootfile_name = os.path.join(DATA_dir, dataset) print(rootfile_name) root_file = TFile.Open(rootfile_name, 'read') tree = root_file.Get("mt2_Truth") ## Creating the current histogram which will be filled thishist = TH1D(label, label, 50, 0, 150) thishist.SetStats(True) thishist.StatOverflows(True) ## Drawing the tree and saving the hist to the matrix execution = "mt2>>{}".format(label) tree.Draw(execution, "", "goff") thishist.SetDirectory(0) myhist.Add(thishist) ## We are dont with the file root_file.Close() del root_file ## Changing the properties of the histogram myhist.Scale(1 / myhist.Integral("width")) myhist.SetLineColor(colour) myhist.SetMarkerColor(colour) myhist.SetMarkerStyle(style) myhist.SetMarkerSize(1.5) ## Adding the legend entry leg.AddEntry(myhist, label, "p") ## Adding the object to the stack stack.Add(myhist) del myhist ## Drawing the stack on the currrent canvas stack.Draw("NOSTACK HIST P") leg.Draw() ## Setting axis labels stack.GetXaxis().SetTitle("m_{T2} (True #it{E}_{T}^{miss}) [GeV]") stack.GetYaxis().SetTitle("Normalised Distributions") ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) ## Drawing all text left = 0.2 size = 1.0 shift = 0.06 pos = 0.88 Plotting.Draw_ATLASLabel(left, pos, "Simulation", scale=1.0) pos -= shift Plotting.Draw_Text(left, pos, "work in progress", scale=size) pos -= shift Plotting.Draw_Lumi(left, pos, 0, scale=size) pos -= shift ## Updating the canvas canvas.Update() out_file = "true_strans.{}".format(extension) canvas.Print(out_file) del canvas return 0
def plotFractionsOfBxId(self): ##BX right plotting pt canvasBxRightPt = TCanvas("cBxRightPt","cBxRightPt",1200,1200) canvasBxRightPt.cd().SetLeftMargin(0.15) hBxRightPt = self.fileHandler.getHistogram('BxRightGen_Pt').Clone() setPlotStyle() hBxRightPt.Rebin(50) hBxRightPt.GetXaxis().SetRangeUser(0,200) hBxRightPt.GetYaxis().SetTitle("normalized Entries / 5 GeV") hBxRightPt.GetXaxis().SetTitle("p_{T} Gen") hBxRightPt.GetYaxis().SetTitleOffset(2) hBxRightPt.SetTitle("Events with right BX ID vs. p_{T}") hBxRightPt.SetStats(0) hBxRightPt.SetLineWidth(2) hBxRightPt.Scale(1/hBxRightPt.Integral()) hBxRightPt.Draw() label = getLabelCmsPrivateSimulation() label.Draw() self.storeCanvas(canvasBxRightPt,"bxRightPt") ##BX wrong plotting pt canvasBxWrongPt = TCanvas("cBxWrongPt","cBxWrongPt",1200,1200) canvasBxWrongPt.cd().SetLeftMargin(0.15) hBxWrongPt = self.fileHandler.getHistogram('BxWrongGen_Pt').Clone() setPlotStyle() hBxWrongPt.Rebin(50) hBxWrongPt.GetXaxis().SetRangeUser(0,200) hBxWrongPt.GetYaxis().SetTitle("normalized Entries / 5 GeV") hBxWrongPt.GetXaxis().SetTitle("p_{T} Gen") hBxWrongPt.GetYaxis().SetTitleOffset(2) hBxWrongPt.SetTitle("Events with wrong BX ID vs. p_{T}") hBxWrongPt.SetStats(0) hBxWrongPt.SetLineWidth(2) hBxWrongPt.Scale(1/hBxWrongPt.Integral()) hBxWrongPt.DrawCopy() label = getLabelCmsPrivateSimulation() label.Draw() self.storeCanvas(canvasBxWrongPt,"bxWrongPt") #Plot the histogram stack canvasStack = TCanvas("cStacked","cStacked",1200,1200) canvasStack.cd().SetLeftMargin(0.15) hWrong = self.fileHandler.getHistogram('BxWrongGen_Pt') hRight = self.fileHandler.getHistogram('BxRightGen_Pt') hRightFraction = TH1D('hRightFraction','',100,0,500) hWrongFraction = TH1D('hWrongFraction','',100,0,500) #hWrong.Rebin(50) #hRight.Rebin(50) #Fill the histograms with the bin wise fractions for i in range(0,hRight.GetNbinsX()): nRight = hRight.GetBinContent(i+1) nWrong = hWrong.GetBinContent(i+1) if(nRight + nWrong == 0): continue hRightFraction.SetBinContent(i+1,nRight/(nRight+nWrong)) hWrongFraction.SetBinContent(i+1,nWrong/(nRight+nWrong)) #Create the stack stack = THStack("hstack","Fractions of events for BX ID correct and wrong") nRight = hRight.Integral() nWrong = hWrong.Integral() hRightFraction.SetLineColor(colorRwthDarkBlue) hRightFraction.SetFillColor(colorRwthDarkBlue) hRightFraction.SetFillStyle(3002) hWrongFraction.SetLineColor(colorRwthMagenta) hWrongFraction.SetFillColor(colorRwthMagenta) hWrongFraction.SetFillStyle(3002) stack.Add(hRightFraction) stack.Add(hWrongFraction) stack.Draw() stack.GetXaxis().SetRangeUser(0.5,201) stack.GetYaxis().SetTitle('rel. fraction / 5 GeV') stack.GetYaxis().SetTitleOffset(2) stack.GetXaxis().SetTitle('p_{T} Gen') stack.SetMinimum(0.9) stack.SetMaximum(1) legend = TLegend(0.6,0.75,0.9,0.9) legend.AddEntry(hRightFraction,"BX ID right","f") legend.AddEntry(hWrongFraction,"BX ID wrong","f") legend.Draw() label = getLabelCmsPrivateSimulation() label.Draw() canvasStack.Update() self.storeCanvas(canvasStack,"bxStacked")
chic0.Project('fromchic0', 'raw_ge') chic1.Project('fromchic1', 'raw_ge') chic2.Project('fromchic2', 'raw_ge') fromchic0.Scale(214404 / 9997) fromchic1.Scale(214404 / 10399) fromchic2.Scale(214404 / 10177) hs.Add(fromchic0) hs.Add(fromchic1) hs.Add(fromchic2) mbc.cd() hs.Draw() hs.GetXaxis().SetTitle('E_{#gamma} (GeV)') hs.GetYaxis().SetTitle(ytitle) hs.GetYaxis().SetTitleOffset(1.5) #f1 = TFile('run/chic2incl/hist_inclusiveMC/chic2incl_psip_mc_event_merged_ncostag.root') #h_E = f1.Get('h_gam1_E') #h_E.Draw('same') legend = TLegend(0.5, 0.6, 0.72, 0.8) legend.AddEntry('fromchic0', 'E_{#gamma} in process chic0') legend.AddEntry('fromchic1', 'E_{#gamma} in process chic0') legend.AddEntry('fromchic2', 'E_{#gamma} in process chic0') #legend.SetNColums(1) legend.SetBorderSize(0) legend.SetFillColor(0)
def ClusterSizeOneTrouble(self): RootDirectory = 'FTClusterMonitor' for files in self.ListOfFiles: tfile = TFile.Open(files) OutFileMantisse = files[:files.find( '-histos')] + "/" + RootDirectory + "_" + time.strftime( '%y-%m-%d_%H-%M', time.localtime()) self.CreateDir(OutFileMantisse) tdir = tfile.GetDirectory(RootDirectory) for type in {"x_position", "Channel"}: All = tdir.Get("Cluster_" + type + "_resolution_1Ch") Cell0 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell0") Cell127 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell127") Cell63 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell63") Cell64 = tdir.Get("Cluster_" + type + "_resolution_1Ch_Cell64") CellNeighbour = tdir.Get( "Cluster_" + type + "_resolution_1Ch_WithNeighbouringCell") All.SetLineColor(4) Cell0.SetLineColor(2) Cell127.SetLineColor(7) Cell63.SetLineColor(6) Cell64.SetLineColor(40) CellNeighbour.SetLineColor(28) # Standard drawing ClusterMoniSizeOneTroublecvs = TCanvas( "ClusterSizeOneTroublecvs", "ClusterSizeOneTrouble") ClusterMoniSizeOneTroublecvs.SetGrid() ClusterMoniSizeOneTroublecvs.cd() All.Draw("H") Cell0.Draw("HSAME") Cell127.Draw("HSAME") Cell63.Draw("HSAME") Cell64.Draw("HSAME") CellNeighbour.Draw("HSAME") Leg = TLegend(0.11, 0.7, 0.4, 0.89) Leg.AddEntry(All, "All Cells", "l") Leg.AddEntry(Cell63, "Cell 63", "l") Leg.AddEntry(Cell64, "Cell 64", "l") Leg.AddEntry(Cell0, "Cell 0", "l") Leg.AddEntry(Cell127, "Cell 127", "l") Leg.AddEntry(CellNeighbour, "Cells with left/right neighbour", "l") Leg.Draw() ClusterMoniSizeOneTroublecvs.SaveAs( OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) + "_" + All.GetName() + self.OutFileType) # Stack drawing Cell0.SetFillColor(2) Cell127.SetFillColor(7) Cell63.SetFillColor(6) Cell64.SetFillColor(40) CellNeighbour.SetFillColor(28) HistoStack = THStack("HistoStack", "Stacked 1D histograms") HistoStack.Add(Cell63) HistoStack.Add(Cell64) HistoStack.Add(Cell0) HistoStack.Add(Cell127) HistoStack.Add(CellNeighbour) ClusterMoniSizeOneTroubleStackcvs = TCanvas( "ClusterSizeOneTroubleStackcvs", "ClusterSizeOneTroubleStack") ClusterMoniSizeOneTroubleStackcvs.SetGrid() ClusterMoniSizeOneTroubleStackcvs.cd() HistoStack.Draw("H") HistoStack.GetXaxis().SetTitle(All.GetXaxis().GetTitle()) HistoStack.GetYaxis().SetTitle(All.GetYaxis().GetTitle()) #ClusterMoniSizeOneTroubleStackcvs.Update() All.Draw("HSAME") LegStack = TLegend(0.11, 0.7, 0.4, 0.89) LegStack.AddEntry(All, "All Cells", "l") LegStack.AddEntry(Cell63, "Cell 63", "f") LegStack.AddEntry(Cell64, "Cell 64", "f") LegStack.AddEntry(Cell0, "Cell 0", "l=f") LegStack.AddEntry(Cell127, "Cell 127", "f") LegStack.AddEntry(CellNeighbour, "Cells with left/right neighbour", "f") LegStack.Draw() ClusterMoniSizeOneTroubleStackcvs.SaveAs( OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) + "_" + All.GetName() + "_Stack" + self.OutFileType) # Details on cells with neighbours Cell1to4 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4") Cell59to62 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell59to62") Cell65to68 = tdir.Get("Cluster_Channel_resolution_1Ch_Cell65to68") Cell122to126 = tdir.Get( "Cluster_Channel_resolution_1Ch_Cell122to126") CellAllOthers = tdir.Get( "Cluster_Channel_resolution_1Ch_AllOtherNeighbors") Cell1to4.SetLineColor(2) Cell1to4.SetFillColor(2) Cell59to62.SetLineColor(3) Cell59to62.SetFillColor(3) Cell65to68.SetLineColor(4) Cell65to68.SetFillColor(4) Cell122to126.SetLineColor(5) Cell122to126.SetFillColor(5) CellAllOthers.SetLineColor(6) CellAllOthers.SetFillColor(6) NeighbourStack = THStack("NeighbourStack", "Stacked 1D histograms") NeighbourStack.Add(Cell1to4) NeighbourStack.Add(Cell59to62) NeighbourStack.Add(Cell65to68) NeighbourStack.Add(Cell122to126) NeighbourStack.Add(CellAllOthers) ClusterMoniSizeOneTroubleNeighbourhoodcvs = TCanvas( "ClusterSizeOneTroubleNeighbourhoodcvs", "ClusterSizeOneTroubleNeighbourhood") ClusterMoniSizeOneTroubleNeighbourhoodcvs.SetGrid() ClusterMoniSizeOneTroubleNeighbourhoodcvs.cd() NeighbourStack.Draw("nostack") NeighbourStack.GetXaxis().SetTitle(Cell1to4.GetXaxis().GetTitle()) NeighbourStack.GetYaxis().SetTitle(Cell1to4.GetYaxis().GetTitle()) CellNeighbour.Draw("SAME") ClusterMoniSizeOneTroubleNeighbourhoodcvs.SaveAs( OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) + "_NeighboringStudy_Stack" + self.OutFileType) # Details on cells with/without Cluster size=4 neighbours #CellWithCl4Neighbour = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4") CellWithCl4Neighbour = tdir.Get( "Cluster_Channel_resolution_1Ch_withSize4neigh") #CellWithoutCl4Neighbour = tdir.Get("Cluster_Channel_resolution_1Ch_Cell1to4") CellWithoutCl4Neighbour = tdir.Get( "Cluster_Channel_resolution_1Ch_withoutSize4neigh") CellWithCl4Neighbour.SetLineColor(2) CellWithCl4Neighbour.SetFillColor(2) CellWithoutCl4Neighbour.SetLineColor(3) CellWithoutCl4Neighbour.SetFillColor(3) Clus4NeighbourStack = THStack("Clus4NeighbourStack", "St histograms") Clus4NeighbourStack.Add(CellWithCl4Neighbour) Clus4NeighbourStack.Add(CellWithoutCl4Neighbour) Clus4TroubleNeighbourhoodcvs = TCanvas( "Clus4TroubleNeighbourhoodcvs", "Clus4TroubleNeighbourhoodcvs") Clus4TroubleNeighbourhoodcvs.SetGrid() Clus4TroubleNeighbourhoodcvs.cd() Clus4NeighbourStack.Draw("H") Clus4NeighbourStack.GetXaxis().SetTitle( CellWithCl4Neighbour.GetXaxis().GetTitle()) Clus4NeighbourStack.GetYaxis().SetTitle( CellWithCl4Neighbour.GetYaxis().GetTitle()) All.Draw("HSAME") LegClus4Size = TLegend(0.11, 0.7, 0.4, 0.89) LegClus4Size.AddEntry(All, "All Cells", "l") LegClus4Size.AddEntry(CellWithCl4Neighbour, "With size 4 neighbour ", "f") LegClus4Size.AddEntry(CellWithoutCl4Neighbour, "Without size 4 neighbour ", "f") LegClus4Size.Draw() Clus4TroubleNeighbourhoodcvs.SaveAs( OutFileMantisse + "/" + (OutFileMantisse.split('/')[0]) + "_CluS4NeighboringStudy_Stack" + self.OutFileType)
def createCompoundPlots(detector, plot, geometry): """Produce the requested plot for the specified detector. Function that will plot the requested @plot for the specified @detector. The specified detector could either be a real detector or a compound one. The list of available plots are the keys of plots dictionary (imported from plot_utils. """ setTDRStyle() theDirname = 'Images' if not checkFile_(theDirname): os.mkdir(theDirname) goodToGo, theDetectorFilename = paramsGood_(detector, plot, geometry) if not goodToGo: return hist_X0_elements = OrderedDict() # stack stackTitle = "%s;%s;%s" % (detector, plots[plot].abscissa, plots[plot].ordinate) stack_X0 = THStack("stack_X0", stackTitle); theLegend = TLegend(0.50, 0.70, 0.70, 0.90); def setRanges(h): legendSpace = 1. + 0.3 # 30% minY = h.GetYaxis().GetXmin() maxY = h.GetBinContent(h.GetMaximumBin()) * legendSpace h.GetYaxis().SetRangeUser(minY, maxY) for label, [num, color, leg] in six.iteritems(hist_label_to_num): # We don't want the sum to be added as part of the stack if label is 'SUM': continue hist_X0_elements[label] = get1DHisto_(detector, num + plots[plot].plotNumber, geometry) hist_X0_elements[label].SetFillColor(color) hist_X0_elements[label].SetLineColor(kBlack) stack_X0.Add(hist_X0_elements[label]) if hist_X0_elements[label].Integral() > 0.: theLegend.AddEntry(hist_X0_elements[label], leg, "f") # canvas canname = "MBCan_1D_%s_%s" % (detector, plot) can = TCanvas(canname, canname, 800, 800) can.Range(0,0,25,25) gStyle.SetOptTitle(0) # Draw setRanges(stack_X0.GetStack().Last()) stack_X0.Draw("HIST"); stack_X0.GetXaxis().SetLabelSize(0.035) stack_X0.GetYaxis().SetLabelSize(0.035) theLegend.Draw(); cmsMark = TLatex() cmsMark.SetNDC(); cmsMark.SetTextAngle(0); cmsMark.SetTextColor(kBlack); cmsMark.SetTextFont(61) cmsMark.SetTextSize(5e-2) cmsMark.SetTextAlign(11) cmsMark.DrawLatex(0.16,0.86,"CMS") simuMark = TLatex() simuMark.SetNDC(); simuMark.SetTextAngle(0); simuMark.SetTextColor(kBlack); simuMark.SetTextSize(3e-2) simuMark.SetTextAlign(11) simuMark.DrawLatex(0.16,0.82,"#font[52]{Simulation Internal}") # Store can.Update(); can.SaveAs( "%s/%s_%s_%s.pdf" % (theDirname, detector, plot, geometry)) can.SaveAs( "%s/%s_%s_%s.png" % (theDirname, detector, plot, geometry))
errorband.SetFillColor(kBlack) errorband.SetFillStyle(3245) errorband.SetMarkerSize(0) legend.AddEntry(rebinnedData, "Data", 'pe') legend.AddEntry(errorband, "Uncertainty", "f") for ih in rebinnedHist: legend.AddEntry(rebinnedHist[ih], ih, 'f') pad1.cd() stack.Draw('HIST') rebinnedData.Draw('E,X0,SAME') legend.Draw("same") stack.GetXaxis().SetTitle('') stack.GetXaxis().SetLabelSize(0) stack.GetYaxis().SetLabelSize(gStyle.GetLabelSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleSize(gStyle.GetTitleSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() * (1. - padRatio + padOverlap)) #stack.SetTitle(';;<Events/GeV>')# '%rebin) #CMS_lumi.channelText = (channelText+"\\n"+regionText) #if postfitPlots: CMS_lumi.channelText =channelText+"\\n "+regionText+"\\n "+chi2Text CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText, regionText) if postfitPlots: CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText + ";" +
if drawLog == '1': gPad.SetLogy() if not legOnly: hs.Draw("Hist") for ihist in reversed(templates[4:10]): print ihist.GetName() if not legOnly: ihist.Draw("same, hist") xTitle = h_top.GetXaxis().GetTitle() yTitle = h_top.GetYaxis().GetTitle() if var == 'hCutflow': hs.SetMinimum(10000) hs.GetXaxis().SetRangeUser(1,10) setTitle(hs, xTitle, yTitle) gPad.RedrawAxis() ll = TLatex() ll.SetNDC(kTRUE) ll.SetTextSize(0.05) ll.DrawLatex(0.63, 0.92, "3000 fb^{-1} (14 TeV)"); prel = TLatex() prel.SetNDC(kTRUE) prel.SetTextFont(52) prel.SetTextFont(52) prel.SetTextSize(0.05) prel.DrawLatex(0.28, 0.92, "Simulation")
def createPlots_(plot, geometry): """Cumulative material budget from simulation. Internal function that will produce a cumulative profile of the material budget inferred from the simulation starting from the single detectors that compose the tracker. It will iterate over all existing detectors contained in the DETECTORS dictionary. The function will automatically skip non-existent detectors. """ IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"] theDirname = "Figures" if plot not in plots.keys(): print("Error: chosen plot name not known %s" % plot) return hist_X0_detectors = OrderedDict() hist_X0_IB = None hist_X0_elements = OrderedDict() for subDetector,color in six.iteritems(DETECTORS): h = get1DHisto_(subDetector,plots[plot].plotNumber,geometry) if not h: print('Warning: Skipping %s'%subDetector) continue hist_X0_detectors[subDetector] = h # Merge together the "inner barrel detectors". if subDetector in IBs: hist_X0_IB = assignOrAddIfExists_( hist_X0_IB, hist_X0_detectors[subDetector] ) # category profiles for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue hist_label = get1DHisto_(subDetector, num + plots[plot].plotNumber, geometry) hist_X0_elements[label] = assignOrAddIfExists_( hist_X0_elements.setdefault(label,None), hist_label, ) hist_X0_elements[label].SetFillColor(color) cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg", hist_X0_IB.GetNbinsX(), hist_X0_IB.GetXaxis().GetXmin(), hist_X0_IB.GetXaxis().GetXmax()) cumulative_matbdg.SetDirectory(0) # colors for det, color in six.iteritems(DETECTORS): setColorIfExists_(hist_X0_detectors, det, color) # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside # stack stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % ( plots[plot].abscissa,plots[plot].ordinate) stack_X0_SubDetectors = THStack("stack_X0",stackTitle_SubDetectors) for det, histo in six.iteritems(hist_X0_detectors): stack_X0_SubDetectors.Add(histo) cumulative_matbdg.Add(histo, 1) # canvas can_SubDetectors = TCanvas("can_SubDetectors","can_SubDetectors",800,800) can_SubDetectors.Range(0,0,25,25) can_SubDetectors.SetFillColor(kWhite) # Draw stack_X0_SubDetectors.SetMinimum(plots[plot].ymin) stack_X0_SubDetectors.SetMaximum(plots[plot].ymax) stack_X0_SubDetectors.Draw("HIST") stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_SubDetectors = TLegend(0.180,0.8,0.98,0.92) theLegend_SubDetectors.SetNColumns(3) theLegend_SubDetectors.SetFillColor(0) theLegend_SubDetectors.SetFillStyle(0) theLegend_SubDetectors.SetBorderSize(0) for det, histo in six.iteritems(hist_X0_detectors): theLegend_SubDetectors.AddEntry(histo, det, "f") theLegend_SubDetectors.Draw() # text text_SubDetectors = TPaveText(0.180,0.727,0.402,0.787,"NDC") text_SubDetectors.SetFillColor(0) text_SubDetectors.SetBorderSize(0) text_SubDetectors.AddText("CMS Simulation") text_SubDetectors.SetTextAlign(11) text_SubDetectors.Draw() # Store can_SubDetectors.Update() if not checkFile_(theDirname): os.mkdir(theDirname) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" % (theDirname, plot)) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" % (theDirname, plot)) # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR + # Outside stack stackTitle_Materials = "Tracker Material Budget;%s;%s" % (plots[plot].abscissa, plots[plot].ordinate) stack_X0_Materials = THStack("stack_X0",stackTitle_Materials) stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"]) for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue stack_X0_Materials.Add(hist_X0_elements[label]) # canvas can_Materials = TCanvas("can_Materials","can_Materials",800,800) can_Materials.Range(0,0,25,25) can_Materials.SetFillColor(kWhite) # Draw stack_X0_Materials.SetMinimum(plots[plot].ymin) stack_X0_Materials.SetMaximum(plots[plot].ymax) stack_X0_Materials.Draw("HIST") stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_Materials = TLegend(0.180,0.8,0.95,0.92) theLegend_Materials.SetNColumns(3) theLegend_Materials.SetFillColor(0) theLegend_Materials.SetBorderSize(0) theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe", "f") for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f") theLegend_Materials.Draw() # text text_Materials = TPaveText(0.180,0.727,0.402,0.787,"NDC") text_Materials.SetFillColor(0) text_Materials.SetBorderSize(0) text_Materials.AddText("CMS Simulation") text_Materials.SetTextAlign(11) text_Materials.Draw() # Store can_Materials.Update() can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot)) can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot)) return cumulative_matbdg
for i, hist in enumerate(rateHists): hist.SetFillColor(colors[i % len(colors)]) hist.SetLineColor(colors[i % len(colors)]) if i >= len(colors): hist.SetFillStyle(3004) hs1.Add(hist) # add individual event entries to legend l1.AddEntry(hist, filterNames_mAug[i], "f") # draw individual filter stack + overall rate hist hs1.Draw("HIST") totalRateHist.Draw("pSAME") ## configure axes # set axis titles hs1.GetXaxis().SetTitle("lumi block") hs1.GetYaxis().SetTitle("n events") hs1.GetYaxis().SetTitleOffset(.75) # set axis ranges hs1.GetXaxis().SetRangeUser(first_lb - 20, last_lb + 20) hs1.GetYaxis().SetRangeUser(0, 100) # set tick marks on all axes gPad.SetTicks(1, 1) # draw legend l1.Draw() # add text to plot latex1 = ROOT.TLatex(0.52, 0.875, "#font[72]{ATLAS }#font[42]{Internal}") latex1.SetNDC() latex1.SetTextSize(0.05)
TH1.AddDirectory(0) # gStyle.SetPalette(53) hist_met_.SetFillColor(color[i]) #hist_met_.SetLineColor(color[i]) bkgStack.Add(hist_met_, 'hist') legend.AddEntry(hist_met_, processesLegend[i], "f") i = i + 1 c = TCanvas() c.SetLogy(1) bkgStack.Draw() j = 0 for iregion in region: bkgStack.GetXaxis().SetBinLabel(j + 1, iregion) j = j + 1 legend.Draw() latex = TLatex(0.15, 0.85, 'CMS') latex.SetTextSize(0.036) latex.SetTextAlign(12) latex.SetNDC(kTRUE) latex.SetTextFont(61) latex.Draw() latex1 = TLatex(0.13, 0.82, 'Preliminary') latex1.SetTextSize(0.036) latex1.SetTextAlign(12) latex1.SetNDC(kTRUE) latex1.SetTextFont(61)
hs.Add(inMCDY_list[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.3 * max(hs.GetMaximum(), inDATA_list[i].GetMaximum())) inDATA_list[i].SetMaximum( 1.3 * max(hs.GetMaximum(), inDATA_list[i].GetMaximum())) hs.Draw("histo") inDATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle(inDATA_list[i].GetTitle()) hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15) hs.GetYaxis().SetTitle("Events") gStyle.SetOptStat(0) if "Pt" in inDATA_list[i].GetTitle(): pad1.SetLogy() # legend
#if flavour_name == 'g': tmp_histogram_sublist[-1].SetFillStyle(3001) tmp_histogram_sublist[-1].SetLineColor(kBlack) tmp_histogram_sublist[-1].SetMarkerColor(flavour_color) #tmp_histogram_sublist[-1].SetStats(kTRUE) #tmp_histogram_sublist[-1].Draw() #tmp_canvas_single.Write() #tmp_canvas_single.SaveAs(histogram_name+"_"+flavour_name+'_Canvas.pdf') tmp_stack.Add(tmp_histogram_sublist[-1]) tmp_legend.AddEntry(tmp_histogram_sublist[-1],flavour_name,'f') tmp_process_sublist.append(tmp_histogram_sublist) stack_process_sublist.append(tmp_stack) tmp_canvas=TCanvas(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack','') #tmp_canvas.cd() #tmp_histogram_sublist[-1].Draw('histo') tmp_stack.Draw('histo') tmp_stack.GetXaxis().SetTitle(histogram_xaxis) tmp_stack.GetYaxis().SetTitle(histogram_yaxis) tmp_stack.SetTitle(histogram_description) tmp_legend.Draw() #tmp_canvas.BuildLegend(0.2,0.2,0.8,0.8)#tmp_legend.Draw() #autolegend=tmp_canvas.BuildLegend() stackcanvas_process_sublist.append(tmp_canvas) # outfile.Cd() if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subJetNSecondaryVertices","subCSV"]: tmp_canvas.SetLogy() tmp_canvas.Write() if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subFlightDistance3dSig","subVertexMassJTC","subJetNSecondaryVertices","subVertexNTracks","subCSV"]: tmp_canvas.SaveAs(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack.pdf') #tmp_stack.Write() input_histos.append(tmp_process_sublist) output_histos.append(stack_process_sublist)
def plot_hist(histlist, labellist, norm, log, overflow, filename, options, scaling=[]): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if len(scaling) > 1 and scaling[1] == 0: scaling = [] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): entries = histlist[i].GetEntries() mean = histlist[i].GetMean() histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) nbins = histlist[i].GetNbinsX() legend.AddEntry( histlist[i], "#splitline{" + labellist[i] + "}{#splitline{%d entries}{mean=%.2f}}" % (entries, mean), "l") if overflow: histlist[i].SetBinContent( nbins, histlist[i].GetBinContent(nbins) + histlist[i].GetBinContent(nbins + 1)) #overflow histlist[i].SetBinContent(1, histlist[i].GetBinContent(0) + histlist[i].GetBinContent(1)) #underflow if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) xlimit = [ histlist[0].GetBinLowEdge(1), histlist[0].GetBinLowEdge(histlist[0].GetNbinsX()) + histlist[0].GetBinWidth(histlist[0].GetNbinsX()) ] if len(scaling) != 0: top_axis = TGaxis(xlimit[0], maximum * 1.4, xlimit[1], maximum * 1.4, (xlimit[0] - scaling[0]) / scaling[1], (xlimit[1] - scaling[0]) / scaling[1], 510, "-") top_axis.SetTitle("normalized scale") top_axis.SetTickSize(0) top_axis.Draw("SAME") legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
latex.SetTextAlign(align_) extraTextSize = extraOverCmsTextSize * cmsTextSize latex.SetTextFont(extraTextFont) latex.SetTextAlign(align_) latex.SetTextSize(0.8 * extraTextSize * t) hs.SetMaximum(1.6 * hs.GetMaximum()) fPads1.cd() hs.Draw("HIST") hs.GetYaxis().SetTitle("Events/bin") hs.GetYaxis().SetTitleSize(0.04) hs.GetYaxis().SetTickLength(0.02) hs.GetYaxis().SetTitleOffset(1.2) hs.GetXaxis().SetTitleOffset(1.3) hs.GetXaxis().SetLabelSize(0.0) hs.GetXaxis().SetTitle("M_{jj} [GeV]") bin_width_signal = ['500', '600', '700', '1000', 'inf'] bin_width_control = ['200', '300', '400', '500'] hs.Print("all") x1 = array('d', (4, 4)) y1 = array('d', (0, 1.1 * hs.GetMaximum())) g1 = TGraph(2, x1, y1) g1.SetLineColor(1) g1.SetLineStyle(2) g1.SetLineWidth(2) x2 = array('d', (8, 8)) y2 = array('d', (0, 1.1 * hs.GetMaximum()))
def plotStack(): inputfile = TFile(filename, "read") if inputfile.IsZombie(): print("inputfile is Zombie") sys.exit() # loop over features for feature, values in features.items(): file = open( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s.txt" % (outputdir, feature, plotname, normalization, showStats, blind), "w") file.write( "\\begin{table}[]\n\\resizebox{!}{.33\\paperheight}{\n \\begin{tabular}{|l|l|l|}\n\\hline\nProcess & Yield & Entries \\\\ \\hline \n" ) # set up legend legend = TLegend(0.2, 0.6, 0.7, 0.88) legend.SetHeader("%i %s" % (year, region)) legend.SetNColumns(4) legend.SetBorderSize(0) c, pad1, pad2 = createCanvasPads() hstack = THStack("hstack", "hstack") hstack.SetTitle( "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} %i at %.2f fb^{-1}(13TeV)}" % (year, luminosity[year])) histName = "TTH_" + feature # assuming TTH is always there if not inputfile.GetListOfKeys().Contains(histName): print("%s doesn't have histogram %s, please use another hist " % (inputfile, histName)) sys.exit() h0 = inputfile.Get(histName) h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalsig.SetMarkerStyle(20) h_totalsig.Sumw2() h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalbkg.SetMarkerStyle(20) h_totalbkg.Sumw2() h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray + 3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") #h_totalmc.SetMinimum(0.8) #h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) # loop over samples for sample in Samples: hist = h_totalmc.Clone(sample) hist.SetDirectory(0) hist.Reset() if sample not in Process: print("sample %s is not in Process " % sample) continue # loop over data: if sample == "Data" or sample == "data": for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (inputfile, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) h_dataobs.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if not blind: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) # loop over mc # loop over signal elif sample in Signals: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalsig.Add(h1, -1) h_totalmc.Add(h1, -1) else: hist.Add(h1) h_totalsig.Add(h1) h_totalmc.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") # create required parts # loop over bkg else: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % p) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalmc.Add(h1, -1) h_totalbkg.Add(h1, -1) else: hist.Add(h1) h_totalmc.Add(h1) h_totalbkg.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") error = Double(0) h_totalsig.IntegralAndError(0, h_totalsig.GetNbinsX(), error) file.write("signal & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalsig.Integral(), error, h_totalsig.GetEntries())) error = Double(0) h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), error) file.write("bkg & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalbkg.Integral(), error, h_totalbkg.GetEntries())) # create required parts if blind: h_sqrtB = createSqrt(h_totalbkg) h_MCerr = createTotalMCErr(h_sqrtB, values["xlabel"]) h_ratio = createRatio(h_totalsig, h_sqrtB, values["xlabel"], normalization) else: h_MCerr = createTotalMCErr(h_totalmc, feature) h_ratio = createRatio(h_dataobs, h_totalmc, values["xlabel"], normalization) legend.AddEntry(h_dataobs, "observed", "lep") legend.AddEntry(h_totalmc, "Uncertainty", "f") # draw everything pad1.cd() if values["logy"] == 1: pad1.SetLogy() maximum = h_dataobs.GetMaximum() upperbound = 2. * maximum lowerbound = -maximum / 40. if values["logy"] == 1: upperbound = 1000 * maximum lowerbound = 0.1 hstack.SetMinimum(lowerbound) hstack.SetMaximum(upperbound) hstack.Draw("HISTY") # Adjust y-axis settings y = hstack.GetYaxis() y.SetTitle("Events ") y.SetTitleSize(25) y.SetTitleFont(43) y.SetTitleOffset(1.55) y.SetLabelFont(43) y.SetLabelSize(20) nbins = h_ratio.GetNbinsX() #hstack.GetXaxis().SetRange(0, nbins+1) hstack.GetXaxis().SetRangeUser(values["min"], values["max"]) h_totalmc.Draw("e2same") if not blind: h_dataobs.Draw("same") legend.Draw("same") pad2.cd() if blind: h_ratio.SetMinimum(0.) #maximum = h_ratio.GetMaximum() #upperbound = 1.5*maximum #h_ratio.SetMaximum(upperbound) h_ratio.SetMaximum(3.) h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"]) h_ratio.Draw("") else: h_MCerr.SetMinimum(0.5) h_MCerr.SetMaximum(1.8) h_MCerr.GetXaxis().SetRangeUser(values["min"], values["max"]) h_MCerr.Draw("e2") h_ratio.Draw("same") c.SaveAs( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s_stack.png" % (outputdir, feature, plotname, normalization, showStats, blind)) file.write("\\end{tabular}\n}\n\\end{table}\n") file.close() inputfile.Close()
def Draw_1D_Comp(rootfile_name, var, min, max, WP_list, leg, isTail=False): gStyle.SetErrorX(0.5) ## The TStack is created with min and max set stack = THStack("stack", var.name) stack.SetMinimum(min) stack.SetMaximum(max) for wp in WP_list: ## Loading the graph using its name and file location graph_name = "{}_{}".format(var.name, wp.name) if isTail: graph_name += "_cumulative" graph = GetGraphFromFile(rootfile_name, graph_name) if graph == -1: continue ## Setting the colors specific to the working point graph.SetLineColor(wp.colour) graph.SetMarkerColor(wp.colour) graph.SetMarkerStyle((wp.marker)) leg.AddEntry(graph, wp.name, "p") width = graph.GetBinWidth(0) ## We check if the legend requires values for statistics if leg.GetNColumns() == 2: ## Calculate the MEAN and RMSE and add to the legend mean = graph.GetMean() stdev = graph.GetStdDev() rms = np.sqrt(mean * mean + stdev * stdev) ## Adding the legend entry # leg.AddEntry( 0, "{:5.2f}".format(mean), "") leg.AddEntry(0, "{:5.2f}".format(rms), "") ## Adding the object to the stack stack.Add(graph) del graph ## Checking to see if any graphs were found for this variable if stack.GetNhists() == 0: print("\n\n\nNo graphs found for working point {}\n\n\n".format( wp.name)) return -1 ## Drawing the stack on the currrent canvas stack.Draw("nostack EP") leg.Draw() ## Setting axis labels if isTail: stack.GetXaxis().SetTitle(var.x_label + " threshold " + var.units) stack.GetYaxis().SetTitle("#it{f}_{tail}") else: stack_y_label = "Events per {:.0f} GeV".format( width) if width > 1 else "Events per GeV" stack.GetXaxis().SetTitle(var.x_label + " " + var.units) stack.GetYaxis().SetTitle(stack_y_label) ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) return stack
def Direct_Estimator(var, cut, year): from root_numpy import root2array, fill_hist, array2root import numpy.lib.recfunctions as rfn ### Preliminary Operations ### treeRead = not cut in [ "nnqq", "en", "enqq", "mn", "mnqq", "ee", "eeqq", "mm", "mmqq", "em", "emqq", "qqqq" ] # Read from tree channel = cut unit = '' if "GeV" in variable[var]['title']: unit = ' GeV' isBlind = BLIND and 'SR' in channel isAH = False #'qqqq' in channel or 'hp' in channel or 'lp' in channel showSignal = False if 'SB' in cut or 'TR' in cut else True #'SR' in channel or channel=='qqqq'#or len(channel)==5 stype = "HVT model B" if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM" elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV" if treeRead: for k in sorted(alias.keys(), key=len, reverse=True): if BTAGGING == 'semimedium': if k in cut: cut = cut.replace(k, aliasSM[k]) else: if k in cut: cut = cut.replace( k, alias[k].format(WP=working_points[BTAGGING])) print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " cut :", cut if var == 'jj_deltaEta_widejet': if "jj_deltaEta_widejet<1.1 && " in cut: print print "omitting jj_deltaEta_widejet<1.1 cut to draw the deltaEta distribution" print cut = cut.replace("jj_deltaEta_widejet<1.1 && ", "") else: print print "no 'jj_deltaEta_widejet<1.1 && ' in the cut string detected, so it cannot be ommited explicitly" print ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} ### Create and fill MC histograms ### for i, s in enumerate(back + sign): if True: #FIXME if variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " );" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() for j, ss in enumerate(sample[s]['files']): if not 'data' in s: if year == "run2" or year in ss: arr = root2array( NTUPLEDIR + ss + ".root", branches=[ var, "jpt_1", "jpt_2", "eventWeightLumi", "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)==5", "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)!=5", "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)==5", "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)!=5" ], selection=cut if len(cut) > 0 else "") print "imported " + NTUPLEDIR + ss + ".root" arr.dtype.names = [ var, "jpt_1", "jpt_2", "eventWeightLumi", "bb", "bq", "qb", "qq" ] MANtag_eff1 = np.array(map(MANtag_eff, arr["jpt_1"])) MANtag_eff2 = np.array(map(MANtag_eff, arr["jpt_2"])) MANtag_mis1 = np.array(map(MANtag_mis, arr["jpt_1"])) MANtag_mis2 = np.array(map(MANtag_mis, arr["jpt_2"])) MANtag_weight = np.multiply( arr["eventWeightLumi"], np.multiply(arr['bb'], np.multiply(MANtag_eff1, MANtag_eff2)) + np.multiply( arr['bq'], np.multiply(MANtag_eff1, MANtag_mis2)) + np.multiply(arr['qb'], np.multiply(MANtag_mis1, MANtag_eff2)) + np.multiply(arr['qq'], np.multiply(MANtag_mis1, MANtag_mis2))) fill_hist(hist[s], arr[var], weights=MANtag_weight) deepCSV_eff1 = np.array(map(deepCSV_eff, arr["jpt_1"])) deepCSV_eff2 = np.array(map(deepCSV_eff, arr["jpt_2"])) deepCSV_mis1 = np.array(map(deepCSV_mis, arr["jpt_1"])) deepCSV_mis2 = np.array(map(deepCSV_mis, arr["jpt_2"])) deepCSV_weight = np.multiply( arr["eventWeightLumi"], np.multiply( arr['bb'], np.multiply(deepCSV_eff1, deepCSV_eff2)) + np.multiply( arr['bq'], np.multiply(deepCSV_eff1, deepCSV_mis2)) + np.multiply( arr['qb'], np.multiply(deepCSV_mis1, deepCSV_eff2)) + np.multiply( arr['qq'], np.multiply(deepCSV_mis1, deepCSV_mis2))) if var == "jj_mass_widejet" and options.save and not "data" in ss: arr = rfn.append_fields(arr, "MANtag_weight", MANtag_weight, usemask=False) arr = rfn.append_fields(arr, "deepCSV_weight", deepCSV_weight, usemask=False) array2root(arr, NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root", treename="tree", mode='recreate') print "saved as", NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root" arr = None hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) if channel.endswith('TR') and channel.replace('TR', '') in topSF: hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0]) hist['ST'].Scale(topSF[channel.replace('TR', '')][0]) hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) # Create data and Bkg sum histograms if options.blind or 'SR' in channel: hist['data_obs'] = hist['BkgSum'].Clone("data_obs") hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) for i, s in enumerate(back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s][ 'plot'] = True #sample[s]['plot'] and s.startswith(channel[:2]) if isAH: for i, s in enumerate(back): hist[s].SetFillStyle(3005) hist[s].SetLineWidth(2) #for i, s in enumerate(sign): # hist[s].SetFillStyle(0) if not var == "Events": sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral() print "Applying SF:", sfnorm for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(sfnorm) if BLIND and var.endswith("Mass"): for i, s in enumerate(data + back + ['BkgSum']): first, last = hist[s].FindBin(65), hist[s].FindBin(135) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if BLIND and var.endswith("Tau21"): for i, s in enumerate(data): first, last = hist[s].FindBin(0), hist[s].FindBin(0.6) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) # Create stack if variable[var]['nbins'] > 0: bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " )") else: bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = variable[var]['log'] #"log" in hist['BkgSum'].GetZaxis().GetTitle() if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data if 'sync' in hist: hist['sync'].Draw("SAME, PE") #data_graph.Draw("SAME, PE") if showSignal: smagn = 1. #if treeRead else 1.e2 #if log else 1.e2 for i, s in enumerate(sign): # if sample[s]['plot']: hist[s].Scale(smagn) hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02, stype + " (x%d)" % smagn, True) #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.GetYaxis().SetTitleOffset(0.9) #bkg.GetYaxis().SetTitleOffset(2.) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) #bkg.GetYaxis().SetMoreLogLabels(True) bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) #if log: bkg.SetMinimum(1) leg.Draw() #drawCMS(LUMI[year], "Preliminary") drawCMS(LUMI[year], "Work in Progress", suppressCMS=True) drawRegion('XVH' + channel, True) drawAnalysis(channel) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / MC") err.GetYaxis().SetTitleOffset(0.9) err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if 'sync' in hist: res.SetMarkerColor(2) res.SetMarkerStyle(31) res.Reset() for i in range(0, res.GetNbinsX() + 1): x = hist['data_obs'].GetXaxis().GetBinCenter(i) if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0: res.SetBinContent( i, hist['data_obs'].GetBinContent( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) res.SetBinError( i, hist['data_obs'].GetBinError( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if gROOT.IsBatch(): if channel == "": channel = "nocut" varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) suffix = '' if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year + suffix + ".png") c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year + suffix + ".pdf") # Print table printTable(hist, sign)
#upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) LepBDTDATA_list[i].SetMaximum( 1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) hs.SetMinimum(10) #EF for ele BDT hs.Draw("histo") LepBDTDATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle("BDT score") hs.GetXaxis().SetRangeUser(0.75, 1) #EF for ele BDT hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15) hs.GetYaxis().SetTitle("Events") gStyle.SetOptStat(0) pad1.SetLogy() # legend legend = TLegend(0.1, 0.75, 0.3, 0.9) #left alignment
def DeepCSV_pt_distribution( year): ## everything below is jsut copy&past from above from root_numpy import root2array, fill_hist, array2root import numpy.lib.recfunctions as rfn from aliases import alias_deepCSV, WP_deepCSV ### Preliminary Operations ### treeRead = True var = 'jpt_1' channel = 'preselection' cut = alias_deepCSV['preselection'] unit = '' if "GeV" in variable[var]['title']: unit = ' GeV' isBlind = BLIND and 'SR' in channel isAH = False showSignal = True stype = "HVT model B" if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM" elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV" if treeRead: for k in sorted(alias_deepCSV.keys(), key=len, reverse=True): if k in cut: cut = cut.replace( k, alias_deepCSV[k].format(WP=WP_deepCSV[BTAGGING][year])) print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " cut :", cut ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} N_signal_tot = 0. N_signal_tag = 0. ### Create and fill MC histograms ### for i, s in enumerate(back + sign): if variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";jet p_{T};Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " );" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";jet p_{T};Events" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() for j, ss in enumerate(sample[s]['files']): if not 'data' in s: if year == "run2" or year in ss: arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_1", "eventWeightLumi"], selection=cut + " && jdeepCSV_1>" + str(WP_deepCSV[BTAGGING][year])) if 'signal' in ss.lower(): N_signal_tag += len(arr['jpt_1'][arr['jpt_1'] > 3500]) print "imported " + NTUPLEDIR + ss + ".root" fill_hist(hist[s], arr["jpt_1"], weights=arr["eventWeightLumi"]) arr = None arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_2", "eventWeightLumi"], selection=cut + " && jdeepCSV_2>" + str(WP_deepCSV[BTAGGING][year])) print "imported " + NTUPLEDIR + ss + ".root" if 'signal' in ss.lower(): N_signal_tag += len(arr['jpt_2'][arr['jpt_2'] > 3500]) fill_hist(hist[s], arr["jpt_2"], weights=arr["eventWeightLumi"]) arr = None if 'signal' in ss.lower(): arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_1", "eventWeightLumi"], selection=cut) N_signal_tot += len(arr['jpt_1'][arr['jpt_1'] > 3500]) arr = None arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_2", "eventWeightLumi"], selection=cut) N_signal_tot += len(arr['jpt_2'][arr['jpt_2'] > 3500]) arr = None hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) if channel.endswith('TR') and channel.replace('TR', '') in topSF: hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0]) hist['ST'].Scale(topSF[channel.replace('TR', '')][0]) hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) # Create data and Bkg sum histograms if options.blind or 'SR' in channel: hist['data_obs'] = hist['BkgSum'].Clone("data_obs") hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) for i, s in enumerate(back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s][ 'plot'] = True #sample[s]['plot'] and s.startswith(channel[:2]) if isAH: for i, s in enumerate(back): hist[s].SetFillStyle(3005) hist[s].SetLineWidth(2) #for i, s in enumerate(sign): # hist[s].SetFillStyle(0) if not var == "Events": sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral() print "Applying SF:", sfnorm for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(sfnorm) if BLIND and var.endswith("Mass"): for i, s in enumerate(data + back + ['BkgSum']): first, last = hist[s].FindBin(65), hist[s].FindBin(135) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if BLIND and var.endswith("Tau21"): for i, s in enumerate(data): first, last = hist[s].FindBin(0), hist[s].FindBin(0.6) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) # Create stack if variable[var]['nbins'] > 0: bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " )") else: bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = variable[var]['log'] #"log" in hist['BkgSum'].GetZaxis().GetTitle() if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data if 'sync' in hist: hist['sync'].Draw("SAME, PE") #data_graph.Draw("SAME, PE") if showSignal: smagn = 1. #if treeRead else 1.e2 #if log else 1.e2 for i, s in enumerate(sign): # if sample[s]['plot']: hist[s].Scale(smagn) hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02, stype + " (x%d)" % smagn, True) #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.GetYaxis().SetTitleOffset(0.9) #bkg.GetYaxis().SetTitleOffset(2.) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) #bkg.GetYaxis().SetMoreLogLabels(True) bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) #if log: bkg.SetMinimum(1) leg.Draw() #drawCMS(LUMI[year], "Preliminary") drawCMS(LUMI[year], "", suppressCMS=True) drawRegion('XVH' + channel, True) drawAnalysis(channel) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / MC") err.GetYaxis().SetTitleOffset(0.9) err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if 'sync' in hist: res.SetMarkerColor(2) res.SetMarkerStyle(31) res.Reset() for i in range(0, res.GetNbinsX() + 1): x = hist['data_obs'].GetXaxis().GetBinCenter(i) if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0: res.SetBinContent( i, hist['data_obs'].GetBinContent( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) res.SetBinError( i, hist['data_obs'].GetBinError( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if gROOT.IsBatch(): if channel == "": channel = "nocut" varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) suffix = '' if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix + ".png") c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix + ".pdf") # Print table printTable(hist, sign) print 'deepCSV efficiency:', N_signal_tag / N_signal_tot