def GetStack(self, colors='', pr=''): if pr == '': pr = self.processList elif isinstance(pr, str) and ',' in pr: pr = pr.replace(' ', '').split(',') npr = len(pr) if isinstance(colors, dict): colors = [colors[p] for p in pr] elif colors == '': colors = [1] * npr elif isinstance(colors, str) and ',' in colors: colors = colors.replace(' ', '').split(',') hStack = THStack('hStack', '') for p, col in zip(pr, colors): if isinstance(self.histoname, list): for hname in self.histoname: self.indic[p][hname].SetFillColor(col) self.indic[p][hname].SetFillStyle(1000) self.indic[p][hname].SetLineColor(0) self.indic[p][hname].SetLineStyle(0) self.indic[p][hname].SetLineWidth(0) hStack.Add(self.indic[p][hname]) else: self.indic[p][self.histoname].SetFillColor(col) self.indic[p][self.histoname].SetFillStyle(1000) self.indic[p][self.histoname].SetLineColor(0) self.indic[p][self.histoname].SetLineStyle(0) self.indic[p][self.histoname].SetLineWidth(0) hStack.Add(self.indic[p][self.histoname]) return hStack
def make_pdf_plot(key, pos=(0.7, 0.7, 0.9, 0.9)): h = getHist(f_all, key) h.SetLineStyle(1) h.SetLineWidth(5) #h.SetFillStyle(1001) h.SetLineColor(kBlack) hs = THStack("hs_" + key, "") h0 = getHist(f_0, key) h1 = getHist(f_1, key) h2 = getHist(f_2, key) h0.SetLineStyle(5) h0.SetFillStyle(3005) h0.SetFillColor(kRed) h0.SetLineColor(kRed) hs.Add(h0) h1.SetLineStyle(5) h1.SetFillStyle(3005) h1.SetFillColor(kBlue) h1.SetLineColor(kBlue) hs.Add(h1) h2.SetLineStyle(5) h2.SetFillStyle(3005) h2.SetFillColor(kGreen) h2.SetLineColor(kGreen) hs.Add(h2) leg = TLegend(pos[0], pos[1], pos[2], pos[3]) leg.AddEntry(h, 'total') leg.AddEntry(h0, 'y == Pred == 0') leg.AddEntry(h1, 'y == Pred == 1') leg.AddEntry(h2, 'y == Pred == 2') return h, hs, leg
def drawAppMVAOutputPlots(region, method, isMC): MCstr = "" if isMC: MCstr = "BsMC12" Region = region[:1].upper() + region[ 1:] #capitalize first letter for retrieving file names HistName = "ApplicationOutput" + MCstr + Region + method CvsName = "canvasMVA_" + MCstr + method + region canvas = TCanvas(CvsName, CvsName) stackBDT = THStack(HistName, HistName) histos = [] appFiles = [] canvas.Draw() # note: TMVApp file name structure: "TMVApp"+Region+method+sample+".root" # "BsMC12TMVApp"+Region+method+sample+".root" appFile = TFile(MCstr + "TMVApp" + Region + method + ".root") histo = appFile.Get("MVA_" + method).Clone(HistName) histo.Scale(1 / histo.GetEntries()) stackBDT.Add(histo) for sample in range(3): appFiles.append( TFile(MCstr + "TMVApp" + Region + method + str(sample) + ".root")) histos.append(appFiles[sample].Get("MVA_" + method).Clone("HistName" + str(sample))) histos[sample].SetLineColor(2 * sample) histos[sample].Scale(1 / histos[sample].GetEntries()) stackBDT.Add(histos[sample]) stackBDT.Draw("nostack") if isMC: applicationBDTLegend = TLegend(0.2, 0.7, 0.5, 0.9, "", "brNDC") #applicationBDTLegend.SetHeader("Bs MC "+region.split("BsMC")[1]) applicationBDTLegend.SetHeader("Bs MC " + Region) else: applicationBDTLegend = TLegend(0.55, 0.7, 0.85, 0.9, "", "brNDC") applicationBDTLegend.SetHeader(Region) applicationBDTLegend.AddEntry(histo, "Full sample", "l") applicationBDTLegend.AddEntry(histos[0], "Trained on 0, tested on 1, applied on 2", "l") applicationBDTLegend.AddEntry(histos[1], "Trained on 1, tested on 2, applied on 0", "l") applicationBDTLegend.AddEntry(histos[2], "Trained on 2, tested on 0, applied on 1", "l") applicationBDTLegend.Draw("same") applicationBDTLegend.SetFillColor(0) applicationBDTLegend.SetLineColor(0) canvas.SaveAs(figuresDir + "Application" + method + "Output_" + MCstr + region + ".pdf")
def study_cal_eff(): # Import data and MC files: f_data = TFile.Open("../trees_5gev_e/data_nn50.root", 'read') t_data = f_data.data f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read') t_mc = f_mc.lumical t_mc.AddFriend("lumical_noise=lumical", "../trees_5gev_e/lucas_geocuts_noise_cal.root") t_mc.AddFriend("lumical_eff=lumical", "../trees_5gev_e/lucas_geocuts_noise_cal_eff.root") c = TCanvas() hs = THStack("hs", "title") t_data.Draw("energy*(layer > 1)>>h_data50(200, 0, 50)", "energy*(layer > 1) > 0") h_data50 = gROOT.FindObject("h_data50") h_data50.SetTitle("Data") h_data50.SetLineWidth(2) h_data50.SetLineColor(1) hs.Add(h_data50, "histo") t_mc.Draw("cal_energy_new/0.0885>>h_mc(200, 0, 50)", "cal_energy_new/0.0885 > 0", "", 100000) h_mc = gROOT.FindObject("h_mc") h_mc.SetTitle("MC smearing and cal eff") h_mc.SetLineWidth(2) h_mc.SetLineColor(3) h_mc.Scale(t_data.GetEntries() / 100000) #t_mc.GetEntries()) hs.Add(h_mc, "histo") t_mc.Draw("cal_energy_smeared7/0.0885>>h_mc7(200, 0, 50)", "cal_energy_smeared7/0.0885 > 0", "", 100000) h_mc7 = gROOT.FindObject("h_mc7") h_mc7.SetTitle("MC smearing=0.7*#sigma") h_mc7.SetLineWidth(2) h_mc7.SetLineColor(2) h_mc7.Scale(t_data.GetEntries() / 100000) #t_mc.GetEntries()) hs.Add(h_mc7, "histo") print(h_mc7.GetEntries()) hs.Draw("nostack") hs.SetTitle( "Deposited energy in the pads of calorimeter;E, [MIP]; N_{hits}") c.SetGridx() c.SetGridy() c.BuildLegend() c.Update() input("wait")
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 __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 plot_calibrations(group_data, voltage, cal_pars_list, stacked=False): group_name = str(group_data[0].run_number) run = group_data[2] name = str(run.run_number) hists_and_lines = [] for cal_pars in cal_pars_list: pars = parameters.gain_pars[cal_pars] run.calibrate_energies(voltage, pars) hist = make_hist(name, run.calibrated_energies, 0, 3500) K_line = TLine(1460.820, 0, 1460.820, 1000000) K_line.SetLineColor(632) Tl_line = TLine(2614.511, 0, 2614.511, 1000000) Tl_line.SetLineColor(632) hists_and_lines.append([hist, K_line, Tl_line]) if stacked: print('Plotting stacked calibrated histograms.') run_canvas = TCanvas() run_canvas.SetLogy() colors = [808, 397, 436, 424, 628, 852, 800, 863, 403, 797] color_index = 0 hs = THStack('hs', 'Group %s Histograms' % group_name) for entry in hists_and_lines: title = str(run.run_number) entry[0].SetLineColor(colors[color_index]) color_index += 1 hs.Add(entry[0]) hs.Draw('nostack') K_line = TLine(1460.820, 0, 1460.820, 1000000) K_line.SetLineColor(632) K_line.Draw() Tl_line = TLine(2614.511, 0, 2614.511, 1000000) Tl_line.SetLineColor(632) Tl_line.Draw() run_canvas.BuildLegend() path = 'output/group_' + str(group_data[0].run_number) + '/' run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf[')) run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf')) run_canvas.Print((path + str(group_data[0].run_number) + '_stacked_calibrated_histogram.pdf]')) else: print('Plotting calibrated energy histogram.') run_canvas = TCanvas("run_canvas", "run canvas") run_canvas.Divide(3, int(len(cal_pars_list) / 2)) canvas_index = 1 for entry in hists_and_lines: pad = run_canvas.cd(canvas_index) pad.SetLogy() entry[0].Draw() entry[1].Draw() entry[2].Draw() pad.Update() canvas_index += 1 path = 'output/group_' + group_name + '/' run_canvas.Print((path + name + '_calibrated_histograms.pdf[')) run_canvas.Print((path + name + '_calibrated_histograms.pdf')) run_canvas.Print((path + name + '_calibrated_histograms.pdf]'))
def make_stack(tfile, stack_procs, chan, sys, distr): global mc_stack_n hs = THStack("mc_stack_%d" % mc_stack_n, "mc_stack_%d" % mc_stack_n) for proc in stack_procs.split(','): histo_name = std_histo_name(args.chan, proc, args.sys, args.distr) logging.debug(histo_name) if not tfile.Get(histo_name): logging.warning(histo_name + ' not in the file ' + args.in_file) continue histo = tfile.Get(histo_name) if args.scale_stack: histo.Scale(args.scale_stack) logging.debug(proc + ' ' + str(histo.Integral())) # histo styling col = plotting_root.nick_info[proc]['color'] histo.SetFillColor(col) #histo.SetLineColor( col ); # it's needed for shapes histo.SetMarkerStyle(20) #histo.SetLineStyle(proc_ocurance); histo.SetMarkerColor(col) hs.Add(histo, "HIST") mc_stack_n += 1 return hs
def stack_n_legend(used_histos, shift=0., exp_legend=False, sort_dy=False, leg=None): '''stack_n_legend(used_histos) used_histos = [(histo, nick of process, channel), ...] first check if there are different channels -- then add the channel name to the legend also the line style changes for different channels of the same process for histograms (not sure if it is a good hack) ''' channels = [c for _, _, c in used_histos] homogeneous_channels = all(c == channels[0] for c in channels) # build Stach and legend hs = THStack("mc_stack", "mc_stack") #leg = TLegend(0.7 - (0.15 if not homogeneous_channels else 0.), 0.4, 0.89, 0.89) if not leg: if exp_legend: leg = TLegend(0.8 - shift, 0.55, 1. - shift, 0.92) else: leg = TLegend(0.7 - shift, 0.55, 0.89 - shift, 0.92) leg.SetBorderSize(0) process_counter = {} # for distinguishing processes in different channels def sort_w_dy_option(histo_nick): order = nick_order.get(histo_nick, 1) if sort_dy and 'dy' in histo_nick: order = 0 return order #for histo, nick, channel in sorted(used_histos, key=lambda h_n: nick_order.get(h_n[1], 1)): for histo, nick, channel in sorted( used_histos, key=lambda h_n: sort_w_dy_option(h_n[1])): logging.debug("plotting stack_n_legend: %s %s" % (nick, channel)) proc_ocurance = process_counter.setdefault(nick, 1) process_counter[nick] += 1 col = nick_colour[nick] histo.SetFillColor(col) #histo.SetLineColor( col ); # it's needed for shapes histo.SetMarkerStyle(20) histo.SetLineStyle(proc_ocurance) histo.SetMarkerColor(col) #used_histos.append(histo) # hopefully root wont screw this up hs.Add(histo, "HIST") # to have legend in the same order for histo, nick, channel in sorted( used_histos, key=lambda h_n: -sort_w_dy_option(h_n[1])): if homogeneous_channels: leg.AddEntry(histo, nick_info[nick]['legend'], "F") else: leg.AddEntry(histo, "%s %s" % (nick, channel), "F") return hs, leg
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 backgroundStack( self ): #implement reordering here by total yield bkgStack = THStack() for p in reversed( self.__processes ): if not p.isSignal(): bkgStack.Add( p.nominal() ) return bkgStack
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 study_trigger(): # Import data and MC files: f_data = TFile.Open("../trees_5gev_e/.root", 'read') t_data = f_data.data f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read') t_mc = f_mc.lumical t_mc.AddFriend("lumical_tr_clusters=lumical", "../trees_5gev_e/.root") c = TCanvas() t_data.Draw("tr1_n_clusters>>h_data(6, 0, 6)") h_data = gROOT.FindObject("h_data") h_data.SetTitle("Data") h_data.SetLineWidth(2) h_data.SetLineColor(1) t_mc.Draw("tr1_n_hits>>h_mc(6, 0, 6)") h_mc = gROOT.FindObject("h_mc") h_mc.SetTitle("MC") h_mc.SetLineWidth(2) h_mc.SetLineColor(2) h_mc.Scale(t_data.GetEntries() / t_mc.GetEntries()) t_mc.Draw("tr1_n_clusters>>h_mc2(6, 0, 6)", "n_triggers == 3") h_mc2 = gROOT.FindObject("h_mc2") h_mc2.SetTitle("MC w/ trigger") h_mc2.SetLineWidth(2) h_mc2.SetLineColor(4) h_mc2.Scale(t_data.GetEntries() / t_mc.GetEntries()) hs = THStack("hs", "title") hs.Add(h_data, "histo") hs.Add(h_mc, "histo") hs.Add(h_mc2, "histo") hs.Draw("nostack") hs.SetTitle( "Number of clusters in the 1st tracker;N_{particles}; N_{events}") c.SetGridx() c.SetGridy() c.BuildLegend() c.Update() input("wait")
class FractionJetHistograms (Histograms) : '''eta distribution of the energy fraction per component''' def __init__ (self, name) : self.histos = [] for i in range (8) : # NB here we start from 0 on purpose, for simplicity self.histos.append (TH2F (name + '_' + str (len (self.histos)), '', 240, -6, 6, 100, 0, 1)) super (FractionJetHistograms, self).__init__ (name) # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... def fillJet (self, jet) : try: for i in range (1, 8) : self.histos[i].Fill (jet.eta (), jet.component (i).fraction ()) except: pass # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... def fillEvent (self, jets) : for jet in jets: self.fillJet (jet) # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... def summary (self) : '''to be run after the event loop, before saving''' self.summ = THStack (self.name + '_summ', 'total energy') self.mean = [] for i in range (1, 8) : # self.mean.append (self.histos[i].ProfileX ()) self.mean.append (self.fromProfileToHisto (self.histos[i].ProfileX (), 10 + i * 2)) self.summ.Add (self.mean[len (self.mean) - 1]) # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... def fromProfileToHisto (self, profile, color = 0) : thename = profile.GetName ().replace('pfx', 'ave') histo = TH1F (thename, '', profile.GetNbinsX (), profile.GetXaxis ().GetXmin (), profile.GetXaxis ().GetXmax ()) histo.SetFillColor (color) for iBin in range (1, profile.GetNbinsX () + 1) : histo.SetBinContent (iBin, profile.GetBinContent (iBin)) histo.SetBinError (iBin, profile.GetBinError (iBin)) return histo # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... def Write (self, dir) : '''overloads mother function, to save lists contents''' self.dir = dir.mkdir( self.name ) self.dir.cd () self.summ.Write () for i in range (1, 8) : self.histos[i].Write () self.mean[i-1].Write () dir.cd ()
def makeStack(mchists): """make stack plot""" stack = THStack("hs", "") index = 3 for hist in mchists: hist.SetLineColor(index) hist.SetFillColor(index) stack.Add(hist) index += 1 return stack
def myStack(colorlist_, backgroundlist_, legendname_): hs = THStack("hs", "") leg1 = myLegend() for j in range(len(colorlist_)): h = backgroundlist_[j] h.SetFillColor(colorlist_[j]) h.SetLineColor(colorlist_[j]) hs.Add(h, "") leg1.AddEntry(h, legendname_[j], "f") return [hs, leg1]
class TheStack: from ROOT import THStack theStack = THStack() theHistogram = None def __init__(self,processes,lumi,plot,zScaleFac): self.theStack = THStack() for process in processes: temphist = process.loadHistogram(plot,lumi,zScaleFac) self.theStack.Add(temphist.Clone()) if self.theHistogram == None: self.theHistogram = temphist.Clone() else: self.theHistogram.Add(temphist.Clone()) def Add(self,addstack): for h in addstack.theStack.GetHists(): self.theStack.Add(h.Clone()) self.theHistogram.Add(h.Clone())
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")
class TheStack: from ROOT import THStack theStack = THStack() theHistogram = None def __init__(self,processes,lumi,plot,zScaleFac,genMass=False,CIBins=False,cumulative=False): self.theStack = THStack() for process in processes: temphist = process.loadHistogram(plot,lumi,zScaleFac,genMass=genMass,CIBins=CIBins) if cumulative: temphist = makeHistoCumulative(temphist) self.theStack.Add(temphist.Clone()) if self.theHistogram == None: self.theHistogram = temphist.Clone() else: self.theHistogram.Add(temphist.Clone()) def Add(self,addstack): for h in addstack.theStack.GetHists(): self.theStack.Add(h.Clone()) self.theHistogram.Add(h.Clone())
def stack(wrps): """ Applies only to HistoWrappers. Returns StackWrapper. Checks lumi to be equal among all wrappers. >>> from ROOT import TH1I >>> h1 = TH1I("h1", "", 2, .5, 4.5) >>> h1.Fill(1,4) 1 >>> w1 = wrappers.HistoWrapper(h1, lumi=2.) >>> h2 = TH1I("h2", "", 2, .5, 4.5) >>> h2.Fill(1,3) 1 >>> h2.Fill(3,6) 2 >>> w2 = wrappers.HistoWrapper(h2, lumi=2.) >>> w3 = stack([w1, w2]) >>> w3.histo.Integral() 13.0 >>> w3.lumi 2.0 """ wrps = iterableize(wrps) stk_wrp = None lumi = 0. info = None sample = "" for wrp in wrps: if not isinstance(wrp, wrappers.HistoWrapper): # histo check raise WrongInputError( "stack accepts only HistoWrappers. wrp: " + str(wrp) ) if not stk_wrp: # stack init stk_wrp = THStack(wrp.name, wrp.title) lumi = wrp.lumi info = wrp.all_info() sample = wrp.sample elif lumi != wrp.lumi: # lumi check raise NoLumiMatchError( "stack needs lumis to match. (%f != %f)" % (lumi, wrp.lumi) ) if sample != wrp.sample: # add to stack sample = "" if wrp.legend: wrp.histo.SetTitle(wrp.legend) stk_wrp.Add(wrp.histo) if not info: raise TooFewWrpsError( "At least one Wrapper must be provided." ) if not sample: del info["sample"] return wrappers.StackWrapper(stk_wrp, **info)
def DrawStackHistograms(histograms, outname, blind=True, verbose=False): #hists_sorted = sorted(histograms, key=lambda h: h.Integral()) hs = THStack("h_stack", "") h_obs = None l = TLegend(0.77, 0.60, 0.90, 0.87) for hist in histograms: hname = hist.GetName() if "data_obs" in hname: if not blind: h_obs = hist SetHistogramStyle(h_obs, "Observed") l.AddEntry(h_obs, "Observed", "p") else: SetHistogramStyle(hist) label = GetLabelName(hist) hs.Add(hist) l.AddEntry(hist, label, "f") h_est = hs.GetStack().Last().Clone() if verbose: est_err = Double(0.) nbins_est = h_est.GetNbinsX() est_yields = h_est.IntegralAndError(1, nbins_est, est_err) print "predicted yields :", est_yields, "+/-", est_err if not blind: print "observed yields :", h_obs.Integral() # draw # SetCMSStyle() TODO canvas = TCanvas() gPad.SetLogy() #ymax_hs = hs.GetMaximum() #ymax = ymax_hs if h_obs is None else max(ymax_hs, h_obs.GetMaximum()) ymax = 10000 ymin = 0.1 hs.SetMaximum(ymax) hs.SetMinimum(ymin) hs.Draw("HIST") l.Draw("same") if not blind: h_obs.Draw("same") canvas.SaveAs(outname)
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")
class TreeStack(object): def __init__(self, name): '''Name is the name you want for your treestack.''' self.name = name self.trees = dict() self.styles = dict() self.treenames = [] self.hists = [] self.histsum = None self.stack = THStack('_'.join([self.name, 'stack']), 'title') def add(self, name, tree, style=None): '''Add a new tree with name "name". Your tree should have the method Project. You may implement tree weighting in this function. style should behave like in tools.style ''' self.trees[name] = tree self.styles[name] = style self.treenames.append(name) def hname(self, name): return '_'.join([self.name, name]) def project(self, var, cut, bins, xmin, xmax): '''Fill the histograms with all trees, using: var : variable to plot cut : cut to use These variables will be passed to the Project method of your trees. bins, xmin, xmax defins the histogram binning. ''' for name in self.treenames: tree = self.trees[name] hname = self.hname(name) hist = TH1F(hname, hname, bins, xmin, xmax) self.hists.append(hist) self.styles[name].formatHisto(hist) tree.Project(hname, var, cut) for hist in self.hists: if self.histsum is None: self.histsum = hist.Clone(self.hname('sum')) else: self.histsum.Add(hist) self.stack.Add(hist) def draw(self): '''Draw the stack. Call project first.''' self.stack.Draw()
def create_stacked_histo_array(mymatrix): #creating 1d array of stacked histograms for each analysis setup (e.g. number of rows in mymatrix) stack_hist_array = np.empty([mymatrix.shape[0], mymatrix.shape[1] - 1], dtype=object) mleg = ROOT.TLegend(0.65, 0.8, 0.75, 0.99) mleg.SetBorderSize(0) for i in range(mymatrix.shape[0]): #iterate over variations (rows) for j in range(mymatrix.shape[1] - 1): #iterate over signal files to draw hs = THStack(str(mymatrix[i][j].GetName()), "") #create stack histo for each variation hs.Add(mymatrix[i][mymatrix.shape[1] - 1]) #add background first hs.Add(mymatrix[i][j]) if j == 0: #only draw background once since it is independent of signal sample mleg.AddEntry(mymatrix[i][mymatrix.shape[1] - 1], mymatrix[i][mymatrix.shape[1] - 1].GetName(), "L") mleg.AddEntry(mymatrix[i][j], mymatrix[i][j].GetName(), "L") stack_hist_array[i][j] = hs del hs return stack_hist_array, mleg
class TheStack: from ROOT import THStack theStack = THStack() theHistogram = None def __init__(self,processes,lumi,plot,files,fromTree=False): self.theStack = THStack() for process in processes: temphist = process.loadHistogram(lumi,files,plot,fromTree) self.theStack.Add(temphist.Clone()) if self.theHistogram == None: self.theHistogram = temphist.Clone() else: self.theHistogram.Add(temphist.Clone())
class TheStack2D: from ROOT import THStack theStack = THStack() theHistogram = None def __init__(self,processes,lumi,plot,zScale): self.theStack = THStack() for process in processes: temphist = process.loadHistogramProjected(plot,lumi,zScale) self.theStack.Add(temphist.Clone()) if self.theHistogram == None: self.theHistogram = temphist.Clone() else: self.theHistogram.Add(temphist.Clone())
def plot_ripples_shutter(self, path): """ Plot ripples vs. shutter. That is one plot per pixel and one for the total. """ system('mkdir -p %s' % path) name = 'ripples_per_shutter_px%s_MPA%s' x_title = 'Shutter' y_title = 'Ripple count' # Get number of shutters no_shutters = len(self._MPAs[0].get_no_hits_shutter()) # Create THStack and its TLegend stack = THStack(name % ('all', 'all'), name % ('all', 'all')) leg = TLegend(.9, .5, 1., .9) # Plots for each pixel and each MPA for idx_mpa, MPA in enumerate(self._MPAs): # Histogram for all pixels on one MPA h_mpa = TH1F(name % ('all', idx_mpa), name % ('all', idx_mpa), no_shutters, .5, no_shutters + .5) for px in range(0, self._no_pxs_x * self._no_pxs_y): # Histogram for one pixel on one MPA h_mpa_px = TH1F(name % (px, idx_mpa), name % (px, idx_mpa), no_shutters, .5, no_shutters + .5) for shutter in range(0, no_shutters): h_mpa_px.Fill(shutter + 1, MPA.get_no_hits_shutter()[shutter][px]) h_mpa.Fill(shutter + 1, MPA.get_no_hits_shutter()[shutter][px]) self._save_histo(h_mpa_px, '%s/%s.pdf' % (path, name % (px, idx_mpa)), x_title, y_title) self._save_histo(h_mpa, '%s/%s.pdf' % (path, name % ('all', idx_mpa)), x_title, y_title) h_mpa.SetFillColor(self._get_fill_color(idx_mpa)) stack.Add(h_mpa) leg.AddEntry(h_mpa, 'MPA%s' % idx_mpa, 'f') self._save_histo(stack, '%s/%s.pdf' % (path, name % ('all', 'all')), x_title, y_title, leg)
def plot_cts_bx(self, path): """ Plots counts vs. bunch crossing. """ system('mkdir -p %s' % path) name = 'counts_per_bx_MPA%s' x_title = 'BX' y_title = 'Event count' # Get number of shutters no_shutters = len(self._MPAs[0].get_no_hits_shutter()) # Create THStack and its TLegend stack = THStack(name % ('all'), name % ('all')) leg = TLegend(.9, .5, 1., .9) # Get max of all MPA's max_bx = 0 for MPA in self._MPAs: max_bx = max(max_bx, MPA.get_max()) # Plots for each pixel and each MPA for idx_mpa, MPA in enumerate(self._MPAs): # Histogram for one MPA h_mpa = TH1F(name % (idx_mpa), name % (idx_mpa), 100, 0, 100) for shutter in range(0, no_shutters): for mem in range(0, self._no_mems): if MPA.get_no_hits_shutter()[shutter][mem] != 0: h_mpa.Fill(MPA.get_no_hits_shutter()[shutter][mem]) self._save_histo(h_mpa, '%s/%s.pdf' % (path, name % (idx_mpa)), x_title, y_title, logy=True) h_mpa.SetLineColor(self._get_fill_color(idx_mpa)) stack.Add(h_mpa) leg.AddEntry(h_mpa, 'MPA%s' % idx_mpa, 'l') self._save_histo(stack, '%s/%s.pdf' % (path, name % ('all')), x_title, y_title, leg, logy=True, draw_option='nostack')
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")
class TheStack2DRun2: from ROOT import THStack theStack = THStack() theHistogram = None def __init__(self,processes,lumi,plot,zScale,CIBins=False): self.theStack = THStack() for index, process in enumerate(processes[0]): temphist = process.loadHistogramProjected(plot,lumi[0],zScale[0]) temphist.Add(processes[1][index].loadHistogramProjected(plot,lumi[1],zScale[1])) temphist.Add(processes[2][index].loadHistogramProjected(plot,lumi[2],zScale[2])) self.theStack.Add(temphist.Clone()) if self.theHistogram == None: self.theHistogram = temphist.Clone() else: self.theHistogram.Add(temphist.Clone())