def findAntiprotonsInFile(filename, name): event = 0 results = [] histogram = TH2D("", "", 256, 0, 256, 256, 0, 256) pixels = 0 timeDelay = 0 numberOfLines = 0 timeAntiproton = 0 for line in open(filename): numberOfLines += 1 columns = line.split() if columns[0] == "new": isAntiproton = False if pixels > 70: print "test one antiproton" isAntiproton = evaluateHistogram(histogram, name, event) event += 1 if isAntiproton: timeDelay = timeAntiproton * 1.0 / pixels - float(columns[2]) results.append(timeDelay) histogram = TH2D("", "", 256, 0, 256, 256, 0, 256) timeAntiproton = 0 pixels = 0 else: pixels += 1 timeAntiproton += float(columns[3]) histogram.SetBinContent(int(columns[0]), int(columns[1]), float(columns[2])) if numberOfLines < 800: return "noFile" else: return results
def rmsvstime(sector, aoh, ch): gStyle.SetOptStat(0) logfile = open('rmsvstime.log', 'w') c2 = TCanvas("c2", "rmsvstime", 200, 10, 800, 600) t0 = time.time() tmax = 5. h = TH2D('hd', "", 2, 0, tmax, 2, 0, 1024) h.Draw() gm = TGraph(100) gr = TGraph(100) gm.SetMarkerSize(0.4) gm.SetMarkerColor(1) gr.SetMarkerSize(0.4) gr.SetMarkerColor(2) i = 0 while c2: gm.Draw('P') gr.Draw('P') c2.Update() t = time.time() - t0 response = sector.aoh[aoh].fed.query("rms %d" % sector.aoh[aoh].fedchannels[ch]) #response="24 %f %f dummy"%(300+100*math.sin(t*0.1),5.+0.1*math.cos(t*0.2)); time.sleep(random.uniform(0.1,0.5)) channel, mean, rms, name = response.split() logfile.write("%8.2f %s %s\n" % (t, mean, rms)) gm.SetPoint(i, t, float(mean)) gr.SetPoint(i, t, float(rms) * 100.) i += 1 if t > tmax: tmax = tmax * 2 h = TH2D('hd', "", 2, 0, tmax, 2, 0, 1024) h.Draw()
def findAntiprotonsInFile(filename, name): results = [] histogram = TH2D("", "", 256, 0, 256, 256, 0, 256) pixels = 0 timeDelay = 0 numberOfLines = 0 timeAntiproton = 0 print "processing file", filename for line in open(filename): numberOfLines += 1 columns = line.split() if columns[0] == "new": isAntiproton = False if pixels > 10: isAntiproton = evaluateHistogram(histogram) if isAntiproton: timeDelay = timeAntiproton * 1.0 / pixels - float(columns[2]) results.append(timeDelay) histogram = TH2D("", "", 256, 0, 256, 256, 0, 256) timeAntiproton = 0 pixels = 0 else: pixels += 1 timeAntiproton += float(columns[3]) histogram.SetBinContent(int(columns[0]), int(columns[1]), float(columns[2])) print "number of lines", numberOfLines if numberOfLines < 800: return "noFile" else: return results
def bookHist(h, key=None, title='', nbinsx=100, xmin=0, xmax=0, nbinsy=0, ymin=0, ymax=0, nbinsz=0, zmin=0, zmax=0): if key == None: print 'missing key' return rkey = str( key) # in case somebody wants to use integers, or floats as keys if h.has_key(key): h[key].Reset() elif hasattr(nbinsx, 'itemsize'): if xmin == 0: h[key] = TH1D(rkey, title, len(nbinsx) - 1, nbinsx) else: h[key] = TH2D(rkey, title, len(nbinsx) - 1, nbinsx, xmin, xmax, nbinsy) elif nbinsz > 0: h[key] = TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax, nbinsz, zmin, zmax) elif nbinsy > 0: h[key] = TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax) else: h[key] = TH1D(rkey, title, nbinsx, xmin, xmax) h[key].SetDirectory(gROOT)
def plotEtaPhiForAllL1(self): canvas = TCanvas("cEtaPhi", "Eta Phi", 1200, 1200) canvas.Divide(2, 1) graphAll = self.fileHandler.getGraph('graphs/L1MuonPresent') graphWithHo = self.fileHandler.getGraph('graphs/L1Muon3x3') halfPhiBinwidth = L1_PHI_BIN / 2. halfEtaBinwidth = L1_ETA_BIN / 2. histAll = TH2D('hEtaPhiAll', "#eta#phi for all L1", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 289, -math.pi - halfPhiBinwidth, math.pi + halfPhiBinwidth) histWithHo = TH2D('hEtaPhiWithHO', "#eta#phi L1 + HO (3x3)", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 289, -math.pi - halfPhiBinwidth, math.pi + halfPhiBinwidth) x = Double(0) y = Double(0) for i in range(0, graphAll.GetN()): graphAll.GetPoint(i, x, y) histAll.Fill(x, y) for i in range(0, graphWithHo.GetN()): graphWithHo.GetPoint(i, x, y) histWithHo.Fill(x, y) canvas.cd(1) histAll.SetStats(0) histAll.GetXaxis().SetRangeUser(-1, 1) histAll.SetTitle(histAll.GetTitle() + ';#eta;#phi;Entries') setupAxes(histAll) histAll.Draw('colz') label1 = self.drawLabel() canvas.Update() setupPalette(histAll) canvas.cd(2) histWithHo.SetStats(0) histWithHo.GetXaxis().SetRangeUser(-1, 1) histWithHo.SetTitle(histWithHo.GetTitle() + ';#eta;#phi;Entries') setupAxes(histWithHo) histWithHo.Draw('colz') label2 = self.drawLabel() canvas.Update() setupPalette(histWithHo) canvas.Update() canvas.SaveAs('plots/etaPhiForAllL1.pdf') return canvas, histAll, histWithHo, label1, label2
def plot_2D(xvar, yvar, title, xtitle, ytitle, xnbin, xlow, xhigh, ynbin, ylow, yhigh, region, cutter): if cutter == "": weight = "event_weight" else: weight = "(" + cutter + ")*event_weight" can = TCanvas("can", "can", 1000, 900) can.cd() # gPad.SetLogy(1) # gPad.SetLogz(1) gStyle.SetOptStat(0) backs = TH2D('a', "DiPhoton;" + xtitle + ";" + ytitle, xnbin, xlow, xhigh, ynbin, ylow, yhigh) diphob = TH1F('b', "DiPhoton;" + xtitle + ";", xnbin, xlow, xhigh) Variables = {} for tre in ListBacks: histName = xvar + yvar + tre Variables[tre] = TH2F(histName, ";" + xtitle + ";" + ytitle, xnbin, xlow, xhigh, ynbin, ylow, yhigh) treepj[tre].Draw(yvar + ":" + xvar + ">>" + histName, weight) Variables[tre].Sumw2() Variables[tre].Scale(lumi * crossx[tre] * kFact[tre] / Nevents[tre]) if tre.startswith("GJets"): backs.Add(Variables[tre]) if tre.startswith("QCD"): backs.Add(Variables[tre]) if tre.startswith("DiPhoton"): backs.Add(Variables[tre]) backs.Draw("COLZ") can.SaveAs("plots/Background" + region + "-" + xvar + "-" + yvar + ".pdf") Variables['Data'] = TH2D('Data', "Data/Background;" + xtitle + ";" + ytitle, xnbin, xlow, xhigh, ynbin, ylow, yhigh) treepj['Data'].Draw(yvar + ":" + xvar + ">>Data", cutter) Pull = TH2D('Pull', title + ";" + xtitle + ";" + ytitle, xnbin, xlow, xhigh, ynbin, ylow, yhigh) Pull = Variables['data'].Clone() Pull.Divide(backs) Pull.SetMaximum(2.0) Pull.SetMinimum(0.0) for i in range(xnbin): i += 1 for j in range(ynbin): j += 1 if Variables['data'].GetBinContent(i, j) != 0: Pull.SetBinContent(i, j, Pull.GetBinContent(i, j)) # print "x: "+str(i)+" y: "+str(j)+" Data: "+str(Variables['data'].GetBinContent(i,j))+" Backgrounds: "+str(backs.GetBinContent(i,j))+" Data/Backgrounds: "+str(Pull.GetBinContent(i,j)) else: Pull.SetBinContent(i, j, 0) can4 = TCanvas("can4", "can", 1000, 900) Pull.Draw("COLZ") can4.SaveAs("plots/Pull2D-" + region + "-" + xvar + "-" + yvar + ".pdf")
def plotClusters(filepath): print "filepath", filepath histogram = TH2D("clusterNumber1", "clusterNumber1", 256, 0, 256, 256, 0, 256) histogramTotal = TH2D("total", "total", 256, 0, 256, 256, 0, 256) histogramTime = TH1D("default", "default", 1, 0, 1) outputRootFile = filepath.replace("clustering", "histograms").replace(".dat", ".root") myFile = TFile(outputRootFile, "RECREATE") clusterNumber = 0 hasStarted = False average = 0 modeTime = 0 totalTime = 0 numberOfPixels = 0 fileS.write("new\n") print "working with file ", filepath for line in open(filepath): print line columns = line.split() if columns[0] == "new": if hasStarted == False: modeTime = float(columns[2]) histogramTime = TH1D("ToA", "ToA", 200, -1000, 1000) #if hasStarted and histogram.GetEntries()>10 and histogram.GetEntries()<1000: if hasStarted and histogram.GetEntries( ) > 0 and histogram.GetEntries() < 1000: average = totalTime / (1.0 * numberOfPixels) delay = average - modeTime fileS.write(str(histogram.GetEntries()) + "\n") if delay > 1000: histogram.SetTitle("delayed " + str(delay)) histogram.Write() print " er vi her" clusterNumber = clusterNumber + 1 totalTime = 0 numberOfPixels = 0 #modeTime=float(columns[2]) histogram = TH2D("clusterNumber " + str(clusterNumber), "clusterNumber ", 256, 0, 256, 256, 0, 256) else: print "er vi her da" numberOfPixels = numberOfPixels + 1 totalTime = float(columns[3]) + totalTime histogram.Fill(int(columns[0]), int(columns[1]), float(columns[2])) histogramTotal.Fill(int(columns[0]), int(columns[1]), float(columns[2])) histogramTime.Fill(float(columns[3]) - modeTime) hasStarted = True histogramTotal.Write() histogramTime.Write() del histogramTime myFile.Write()
def plotEtaPhiForTightL1(self): canvas = TCanvas("cEtaPhi","Eta Phi",1200,1200) canvas.Divide(2,1) graphAll = self.fileHandler.getGraph('graphs/patTightToL1Muons') graphWithHo = self.fileHandler.getGraph('graphs/patTightToL1Muons3x3') halfPhiBinwidth = L1_PHI_BIN/2. l1BinOffset = L1_PHI_BIN*3/4. histAll = TH2D('hEtaPhiAll',"#eta#phi for tight L1",30,-15*L1_ETA_BIN ,15*L1_ETA_BIN, 144, -math.pi,math.pi) histWithHo = TH2D('hEtaPhiWithHO',"#eta#phi tight L1 + HO (3x3)",30,-15*L1_ETA_BIN,15*L1_ETA_BIN, 144, -math.pi,math.pi) x = Double(0) y = Double(0) for i in range(0,graphAll.GetN()): graphAll.GetPoint(i,x,y) histAll.Fill(x,y) for i in range(0,graphWithHo.GetN()): graphWithHo.GetPoint(i,x,y) histWithHo.Fill(x,y) canvas.cd(1) histAll.SetStats(0) histAll.GetXaxis().SetRangeUser(-1,1) histAll.SetTitle(histAll.GetTitle() + ';#eta_{L1};#phi_{L1};Entries') histAll.Draw('colz') canvas.Update() setupAxes(histAll) setupPalette(histAll) label1 = self.drawLabel() canvas.Update() canvas.cd(2) histWithHo.SetStats(0) histWithHo.GetXaxis().SetRangeUser(-1,1) histWithHo.SetTitle(histWithHo.GetTitle() + ';#eta_{L1};#phi_{L1};Entries') histWithHo.Draw('colz') label2 = self.drawLabel() canvas.Update() setupAxes(histWithHo) setupPalette(histWithHo) canvas.Update() self.storeCanvas(canvas, 'etaPhiForTightL1') return canvas,histAll,histWithHo,label1,label2
def two_dimensional_weight(mcfile, fixdata, var2weight1, var2weight2, nbins, xmin, xmax, ymin, ymax, weightfile, weightplot, denominator_weight=None, numerator_weight="sig_sw"): #global settings lhcbStyle.lhcbStyle.SetPadTopMargin(0.08) lhcbStyle.lhcbStyle.SetPadRightMargin(0.15) weightvar = var2weight1 + ":" + var2weight2 cut = "1" #obtain mc histo f1 = TFile(mcfile) t1 = f1.Get("DecayTree") h1 = TH2D("h1", "h1", nbins, xmin, xmax, nbins, ymin, ymax) h1.Sumw2() print(denominator_weight) if denominator_weight is None: t1.Project("h1", weightvar, cut) else: t1.Project("h1", weightvar, "({0})*{1}".format(cut, denominator_weight)) h1.Scale(1. / h1.Integral()) #obtain data histo f2 = TFile(fixdata) t2 = f2.Get("DecayTree") h2 = TH2D("h2", "h2", nbins, xmin, xmax, nbins, ymin, ymax) h2.Sumw2() t2.Project("h2", weightvar, "({0})*{1}".format(cut, numerator_weight)) h2.Scale(1. / h2.Integral()) #calculate weights fw = TFile(weightfile, "RECREATE") hw = TH2D("hw", "hw", nbins, xmin, xmax, nbins, ymin, ymax) hw.Divide(h2, h1, 1, 1, "B") #weight plot save c1 = TCanvas("c1", "c1") hw.Draw("COL Z TEXT") hw.SetXTitle(var2weight1) hw.SetYTitle(var2weight2) c1.SaveAs(weightplot) #save weight to root file hw.Write()
def plotTightL1EtaPhiRatio(self): gL1Tight = self.fileHandler.getGraph('graphs/patTightToL1Muons') gL1Tight3x3 = self.fileHandler.getGraph('graphs/patTightToL1Muons3x3') halfPhiBinwidth = L1_PHI_BIN / 2. hL1Tight = TH2D('hL1Tight', 'L1Tight', 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 144, -math.pi, math.pi) hL1Tight3x3 = TH2D('hL1Tight3x3', 'L1Tight3x3', 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 144, -math.pi, math.pi) hL1Tight = fillGraphIn2DHist(gL1Tight, hL1Tight) hL1Tight3x3 = fillGraphIn2DHist(gL1Tight3x3, hL1Tight3x3) c1 = TCanvas("available tight L1 for matching") hClone = hL1Tight.Clone('hClone') hClone.Draw('colz') hRatio = hL1Tight3x3.Clone('asdfasdf') hRatio.Divide(hL1Tight) c = TCanvas('2dMap') hRatio.SetTitle( 'Local Efficiency per tight L1 coordinate (3x3 Matching);#eta_{L1};#phi_{L1};#epsilon' ) hRatio.GetXaxis().SetRangeUser(-0.8, .8) hRatio.Draw('colz') hRatio.SetStats(0) c.Update() setupAxes(hRatio) setupPalette(hRatio) label = self.drawLabel() c.Update() self.storeCanvas(c, 'localTightL1Efficiency') c2 = TCanvas('projections') c2.Divide(2, 1) c2.cd(1) hEta = hRatio.ProjectionX() hEta.Scale(1 / float(144)) #72 phi bins hEta.Draw() c2.cd(2) hPhi = hRatio.ProjectionY() hPhi.Scale(1 / float(16)) #16 eta bins, cutoff due to |eta| < 0.8 hPhi.Draw() return c, hRatio, label, c2, hEta, hPhi, c1, hClone
def __plot_2d(self): global unique_cnt uid = next(unique_cnt) header = self.__parser.get_header_info() hdata = self.__parser.get_histogram_data()['DATA'] name = header['H_NAME'] + ' ' + str(uid) name = name[1:] nxbins = header['XBINS'] nybins = header['YBINS'] nzbins = header['ZBINS'] xl = header['XRAN'][0] xu = header['XRAN'][1] yl = header['YRAN'][0] yu = header['YRAN'][1] zl = header['ZRAN'][0] zu = header['ZRAN'][1] n_of_histo = nzbins self.__histo = TH2D(name, name, int(nzbins), float(zl), float(zu), int(nybins), float(yl), float(yu)) self.__histo.SetXTitle("Z [cm]") self.__histo.GetXaxis().CenterTitle(kTRUE) self.__histo.GetXaxis().SetTitleOffset(1.1) self.__histo.GetXaxis().SetTitleSize(0.04) self.__histo.GetXaxis().SetLabelSize(0.03) self.__histo.GetXaxis().SetTickLength(0.02) self.__histo.GetXaxis().SetNdivisions(20510) self.__histo.SetYTitle("Y [cm]") self.__histo.GetYaxis().CenterTitle(kTRUE) self.__histo.GetYaxis().SetTitleOffset(1.2) self.__histo.GetYaxis().SetTitleSize(0.04) self.__histo.GetYaxis().SetLabelSize(0.03) self.__histo.GetYaxis().SetTickLength(0.02) self.__histo.GetYaxis().SetNdivisions(20510) self.__histo.SetLineColor(kRed) self.__histo.SetMinimum(1e-9) self.__histo.GetZaxis().SetTitle("a.u.") nxbins = header['XBINS'] ResX = (header['XRAN'][1] - header['XRAN'][0]) / nxbins ResY = (yu - yl) / nybins ResZ = (zu - zl) / nzbins FirstX = header['XRAN'][0] + ResX / 2. FirstY = yl + ResY / 2. FirstZ = zl + ResZ / 2. N = nxbins * nybins * nzbins zPos = [None] * N xPos = [None] * N yPos = [None] * N # -> fill the histo now! pos_cnt = 0 for zentry in range(nzbins): zPos[zentry] = FirstZ + float(zentry) * ResZ for yentry in range(nybins): for xentry in range(nxbins): data_point = hdata[pos_cnt] xPos[xentry] = FirstX + float(xentry) * ResX yPos[yentry] = FirstY + float(yentry) * ResY self.__histo.Fill(zPos[zentry], yPos[yentry], data_point) pos_cnt += 1
def plotEtaPhiForDeltaPhiOne(self): canvas = TCanvas("cEtaPhiDeltaPhiOne", "Eta Phi For DPhi 1", 1200, 1200) graph = self.fileHandler.getGraph('graphs/averageEnergyDeltaPhi1') halfbinwidth = L1_PHI_BIN / 2. hist = TH2D('hEtaPhiDeltaPhi1', "#eta#phi of #Delta#phi=1 evts.", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 289, -math.pi - halfbinwidth, math.pi + halfbinwidth) x = Double(0) y = Double(0) for i in range(0, graph.GetN()): graph.GetPoint(i, x, y) hist.Fill(x, y) hist.SetStats(0) hist.GetXaxis().SetRangeUser(-1, 1) hist.SetTitle(hist.GetTitle() + ';#eta;#phi;Entries') setupAxes(hist) hist.Draw('colz') canvas.Update() setupPalette(hist) label = self.drawLabel() canvas.Update() self.storeCanvas(canvas, 'etaPhiForDeltaPhiOne') canvas.SaveAs('plots/etaPhiForDeltaPhiOne.pdf') return canvas, hist, label
def butterPlots2D(dsList): basicCut = "trapENFCal > 0.8 && gain==0 && mH==1 && isGood && !muVeto && !wfDCBits && !isLNFill1 && !isLNFill2 && trapETailMin < 0 && channel!=596 && channel!=676 && channel!=676 && channel!=612 && channel!=1104 && channel!=1200 && channel!=1334 && channel!=1336" bcrCut = " && tOffset < 10 && waveS5/TMath::Power(trapENFCal,1/4) < 1200 && (waveS3-waveS2)/trapENFCal > 100 && (waveS3-waveS2)/trapENFCal < 300" # bcrCut += " && (waveS3-waveS4)/trapENFCal < 100 && (waveS3-waveS4)/trapENFCal > 0" # this doesn't do much ds3noisyRunCut = " && !(channel==692 && (run==16974 || run==16975 || run==16976 || run==16977 || run==16979))" bn, lo, hi = 100, 0, 20 c = TCanvas("", "", 800, 600) for dsNum in dsList: print "Plotting DS-%d ..." % dsNum ch = TChain("skimTree") ch.Add(str("~/project/wavelet-skim/waveletSkimDS%d*" % dsNum)) h1 = TH2D("h1", "h1", 100, 0, 20, 100, 0, 22000) ch.Project("h1", "butterTime:trapENFCal", basicCut + bcrCut + ds3noisyRunCut) h1.GetXaxis().SetTitle("Energy (keV)") h1.GetYaxis().SetTitle("Deriv.MaxTime") h1.GetYaxis().SetTitleOffset(1.5) h1.Draw() c.SetLeftMargin(0.15) c.Print("./plots/butterTime_DS%d.pdf" % dsNum)
def h2_generated(ptbins, ctbins, name='Generated'): th2 = TH2D(name, ';#it{p}_{T} (GeV/#it{c});c#it{t} (cm); Generated', len(ptbins) - 1, np.array(ptbins, 'double'), len(ctbins) - 1, np.array(ctbins, 'double')) th2.SetDirectory(0) return th2
def plot_ratio_data(df1, df2, data, c=None): from ROOT import TH2D if c is None: from ROOT import TCanvas c = TCanvas() plot = PlotData() plot.canvas = c nktbins = 5 ncentbins = 2 h = TH2D('hist', 'Hist; kT (GeV); Centrality', nktbins, -0.5, nktbins+0.5, ncentbins, -0.5, ncentbins+0.5) h.SetStats(0) cents = [] kts = [] ratios = [] for cent, cdf in df1.groupby('cent'): cents.append(cent) for kt, ktdf in cdf.groupby('kt'): pass # h.FillRandom() # h2 = h.Clone('h2') # h2.Fill # h.Divide(h2) np.frombuffer(h.GetArray(), count=h.GetNcells())[:] = data.flatten() h.SetBinContent(0,0) h.Draw('COLZ') plot.h = h return plot
def hist2D(self, var1, nBins1, a1, b1, var2, nBins2, a2, b2, **kwargs): name = kwargs.get( 'name', makeHistName(self.label + "_merged", "%s_vs_%s" % (var1, var2))) title = kwargs.get('title', self.label) blind = kwargs.get('blind', self.blind) kwargs['scale'] = self.scale * kwargs.get('scale', 1.0) # pass scale down verbosity = kwargs.get('verbosity', 0) printVerbose( ">>>\n>>> Samples - %s, %s vs. %s: %s" % (color(name, color="grey"), var1, var2, self.filenameshort), verbosity) printVerbose(">>> scale: %.4f" % (kwargs['scale']), verbosity) hist2D = TH2D(name, title, nBins2, a2, b2, nBins1, a1, b1) for sample in self.samples: if 'name' in kwargs: # prevent memory leaks kwargs['name'] = makeHistName( sample.label, name.replace(self.label + '_', '')) hist2D.Add( sample.hist2D(var1, nBins1, a1, b1, var2, nBins2, a2, b2, **kwargs)) return hist2D
def makeCoordinatePlot(self, source): c = TCanvas(source, source, 1200, 1200) graphDt = self.fileHandler.getGraph('graphs/L1MuonPresent_' + source) histAll = TH2D('hEtaPhi' + source, ";#eta_{L1};#phi_{L1};#", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 144, -math.pi, math.pi) fillGraphIn2DHist(graphDt, histAll) ### ''' Temporary stuff to check the eta coordinates in the graphs ''' x = Double(0) y = Double(0) listeDt = [] for i in range(0, graphDt.GetN()): graphDt.GetPoint(i, x, y) listeDt.append(float(x)) histAll.SetStats(0) histAll.Draw('colz') c.Update() setupAxes(histAll) label = self.drawLabel() c.Update() return c, histAll, label
def doPlotEtaPtOfSuccessfulMatches(): file = TFile.Open('L1MuonHistogram.root') #Prepare canvas canvas = TCanvas("canvasPtEtaHoMatch", "PtEtaHoMatch", 1200, 1200) canvas.cd().Draw() #prepare histogram hist = file.Get("hoMuonAnalyzer/etaPhi/3D/NoTrgTdmiAboveThr_EtaPhiPt") stack = THStack(hist, "zx", "2dStack", "", -1, -1, -1, -1, "zx", "") #Create new histogram and add the histograms from the stack histNew = TH2D("histPtEtaHoMatch", "p_{T} vs. #eta distribution;#eta;p_{T} / 5 GeV;#", 40, -1.6, 1.6, 40, 0, 200) histNew.GetYaxis().SetTitleOffset(1.2) for i in stack.GetHists(): histNew.Add(i) gStyle.SetPalette(1) histNew.SetStats(0) histNew.Draw('COLZ') canvas.Update() palette = histNew.FindObject("palette") palette.SetX1NDC(0.9) palette.SetX2NDC(0.92) #add label label = PlotStyle.getLabelCmsPrivateSimulation() label.Draw() canvas.Update() canvas.SaveAs('plots/NoL1HoMatchPtEta.pdf') canvas.SaveAs('plots/NoL1HoMatchPtEta.png') return canvas, hist, stack, histNew, label, palette, file
def genPartPlots(tree, name, cut): plots = [] # Kinetic energy plots.append( TH1D(name + 'Ekin', 'Kinetic Energy of ' + name + ' (MeV)', 200, 0, 50)) tree.Draw('PartEk >> ' + name + 'Ekin', cut) # Time offset plots.append( TH1D(name + 'Time', 'Time Offset of ' + name + ' (ns)', 200, 0, 50)) tree.Draw('PartDt >> ' + name + 'Time', cut) # Origin plots.append( TH1D(name + 'Orig', 'Particle Origin of ' + name + ' (mm)', 200, -200000, 0)) tree.Draw('PartZ >> ' + name + 'Orig', cut) # Radial distribution plots.append( TH1D(name + 'Rad', 'Radial Distribution of ' + name + ' (mm)', 200, 0, 4000)) tree.Draw('sqrt(PartX*PartX+PartY*PartY) >> ' + name + 'Rad', cut) # xy distribution plots.append( TH2D(name + 'XY', 'XY Distribution of ' + name + ' (mm)', 200, -4000, 4000, 200, -4000, 4000)) tree.Draw('PartX:PartY >> ' + name + 'XY', cut) return plots
def model_hist(xvar, yvar, modfuncs, nbins=95, crange=(-10.0, 10.0)): """Construct histogram of model functions, based on bin integrals. xvar, yvar: Coordinate variables. modfuncs: Model functions used in fit. nbins: Number of bins in histograms. crange: Range of coordinates. """ hists = [ TH2D('hmodel{0}{1}'.format(c, i), 'hmodel{0}{1}'.format(c, i), nbins, crange[0], crange[1], nbins, crange[0], crange[1]) for (i, c) in ic ] for xbin in range(nbins): xlo = hists[0].GetXaxis().GetBinLowEdge(xbin + 1) xup = hists[0].GetXaxis().GetBinUpEdge(xbin + 1) for ybin in range(nbins): ylo = hists[0].GetXaxis().GetBinLowEdge(ybin + 1) yup = hists[0].GetXaxis().GetBinUpEdge(ybin + 1) name = 'bin_{0}_{1}'.format(xbin, ybin) xvar.setRange(name, xlo, xup) yvar.setRange(name, ylo, yup) for hist, modfunc in zip(hists, modfuncs): integral = modfunc.createIntegral( RooArgSet(xvar, yvar), RooFit.NormSet(RooArgSet(xvar, yvar)), RooFit.Range(name)).getVal() hist.SetBinContent(xbin + 1, ybin + 1, integral) return hists
def merge_sf(filename, histname_barrel, histname_endcap): file = ensureTFile(filename) hist_barrel = file.Get(histname_barrel) hist_endcap = file.Get(histname_endcap) nxbin = hist_barrel.GetXaxis().GetNbins() nybin = hist_barrel.GetYaxis().GetNbins() new_histname = "%s" % histname_barrel[:-7] if '2017' in filename: ptmax = 1000 else: ptmax = 2000 new_hist = TH2D(new_histname,"SF for barrel and endcap",nxbin,-2.5,2.5,nybin,0,ptmax) for pt in np.arange(0,ptmax,10): for eta in np.arange(-2.5,2.5,0.1): if abs(eta)>1.5: etabin = hist_endcap.GetXaxis().FindBin(eta) ptbin = hist_endcap.GetYaxis().FindBin(pt) value = hist_endcap.GetBinContent(etabin,ptbin) else: etabin = hist_barrel.GetXaxis().FindBin(eta) ptbin = hist_barrel.GetYaxis().FindBin(pt) value = hist_barrel.GetBinContent(etabin,ptbin) etabin_new = new_hist.GetXaxis().FindBin(eta) ptbin_new = new_hist.GetYaxis().FindBin(pt) new_hist.SetBinContent(etabin_new,ptbin_new,value) new_hist.Write() file.Close
def __plot_3d(self): #definite_integral=0. header = self.__parser.get_header_info() hdata = self.__parser.get_histogram_data() nrbins = header['RBINS'] nzbins = header['ZBINS'] rl = header['RRAN'][0] ru = header['RRAN'][1] pl = header['PRAN'][0] pu = header['PRAN'][1] zl = header['ZRAN'][0] zu = header['ZRAN'][1] n_of_histo = len(hdata['DATA']) / nrbins ## ------ TH2D::TH2D(const char* name, const char* title, int nbinsx, double xlow, double xup, int nbinsy, double ylow, double yup) self.__histo = TH2D(header['H_NAME'], header['H_NAME'], len(hdata['DATA']), float(zl), float(zu), len(hdata['DATA']), float(pl), float(pu)) self.__histo.SetXTitle("R [cm]") self.__histo.GetXaxis().CenterTitle(kTRUE) self.__histo.GetXaxis().SetTitleOffset(1.1) self.__histo.GetXaxis().SetTitleSize(0.04) self.__histo.GetXaxis().SetLabelSize(0.03) self.__histo.GetXaxis().SetTickLength(0.02) self.__histo.GetXaxis().SetNdivisions(20510) self.__histo.SetYTitle("N") self.__histo.GetYaxis().CenterTitle(kTRUE) self.__histo.GetYaxis().SetTitleOffset(1.2) self.__histo.GetYaxis().SetTitleSize(0.04) self.__histo.GetYaxis().SetLabelSize(0.03) self.__histo.GetYaxis().SetTickLength(0.02) self.__histo.GetYaxis().SetNdivisions(20510) self.__histo.SetLineColor(kRed) #self.__histo.SetMinimum(1e-9); self.__histo.GetZaxis().SetTitle("Z [cm]") # -> fill the histo now! self.__histo = [None] * n_of_histo for it in xrange(len(self.__histo)): self.__histo[it] = TH1F(header['H_NAME'], header['H_NAME'], int(nrbins), float(rl), float(ru)) for indx, data_point in enumerate(hdata['DATA']): self.__histo[int(indx / nrbins)].SetBinContent( indx % nrbins + 1, data_point) for indx, error_point in enumerate(hdata['ERRORS']): error_point *= self.__histo[int( indx / nrbins)].GetBinContent(indx % nrbins + 1) * 0.01 / 2 self.__histo[int(indx / nrbins)].SetBinError( indx % nrbins + 1, error_point) min_val = min(hdata['DATA']) max_val = max(hdata['DATA']) for l in xrange(n_of_histo): self.__histo[l].SetMarkerStyle(20) self.__histo[l].SetMarkerSize(0.6)
def MakeDataFrameFlat(channel, data, var_name1, var_name2, label, Target): data_copy = data.copy( deep=True ) ## Making a deep copy of data ( => separate data and index from data) data_copy_small = data.loc[( data_copy[target] == Target)] ## choose b/w signal and background FileName = "{}/{}_{}_{}_{}.root".format(channel, "Histo2D", var_name1, var_name2, label) file = TFile.Open(FileName) canvas = file.Get("c1") ## Extracting the canvas stored in the root file histo2D = TH2D() histo2D = canvas.GetPrimitive("histo2D") #print("No. of entries ", histo2D.GetEntries()) list_sf_values = [] ## Creating empty lists for index, row in data_copy_small.iterrows(): #print("(X,Y) Values: ", row[var_name1], row[var_name2]) SF = getSF_from_TH2(histo2D, row[var_name1], row[var_name2]) Value = 0. if (SF == 0.): Value = 1.0 ## Such events will have unit weights else: Value = 1.0 / SF #print("Scale Factor: ", Value) list_sf_values.append(Value) nparray_sf_values = np.array( list_sf_values) ## converting list to numpy array data_copy_small[ "Kin_weight"] = nparray_sf_values ## Adding numpy array as new column to dataframe #print data_copy_small return data_copy_small
def produce2DPlots(processes, selections, variables2D, colors, intLumi, pdir, lt, rt, logZ, hfile): print '' print 'Preparing 2D plots ...' gROOT.SetBatch(True) intLumiab = intLumi/1e+06 ff = "eps" logstr = '' if logZ: logstr = 'log' else: logstr = 'lin' nsel = 0 for s in selections: selstr = 'sel{}'.format(int(nsel)) nsel += 1 for v in variables2D.keys() : i = 0 for p in processes: filename = '{}_{}_{}_{}'.format(p, v, selstr, logstr) filename = formatted(filename) hname = '{}_{}_{}'.format(p, selstr, v) h = hfile.Get(hname) hh = TH2D.Clone(h) hh.Scale(intLumi) draw2D(filename, lt, rt, ff, pdir, logZ, hh) print 'DONE.'
def make_plot(self, events): f_det = TFile( '{}/text_gen.{}{}.root'.format( self.data_dir, self.file_basename, '.exclude_noise' if self.exclude_noise else ''), 'RECREATE') multiple_particle_event_count = 0 h_count = TH1D('h_count', 'h_count', 100, -0.5, 99.5) h_timing = TH1D('h_timing', 'h_timing', 5000, 0., 50.e3) # ns h_xy = TH2D('h_xy', 'h_xy', 600, -150, 150, 600, -150, 150) # cm h_z = TH1D('h_z', 'h_z', 500, -1, 1) # cm for i, event in enumerate(events): h_count.Fill(len(event)) if len(event) > 1: multiple_particle_event_count += 1 for particle in event: h_timing.Fill(particle[-1]) is_noise = particle[0] if is_noise: continue x = particle[-4] y = particle[-3] z = particle[-2] h_xy.Fill(x, y) h_z.Fill(z) print('len(events) = {}'.format(len(events))) print('multiple_particle_event_count = {}'.format( multiple_particle_event_count)) h_count.Write('h_particle_count_per_event') h_timing.Write('h_timing') h_xy.Write('h_xy') h_z.Write('h_z') f_det.Close()
def createPlots(plotopts, rootopts): from ROOT import TH1D, TProfile, TH2D, TProfile2D plots = {} #creating histos for plotopt in plotopts: plots[plotopt] = {} for rootopt in rootopts: if (plotopt.profile): if (plotopt.i2d): plot = TProfile2D( str(hash(plotopt)) + str(hash(rootopt)), plotopt.display_name, plotopt.nbins[0], 0, 0, plotopt.nbins[1], 0, 0) else: plot = TProfile( str(hash(plotopt)) + str(hash(rootopt)), plotopt.display_name, plotopt.nbins, 0, 0) else: if (plotopt.i2d): plot = TH2D( str(hash(plotopt)) + str(hash(rootopt)), plotopt.display_name, plotopt.nbins[0], 0, 0, plotopt.nbins[1], 0, 0) else: plot = TH1D( str(hash(plotopt)) + str(hash(rootopt)), plotopt.display_name, plotopt.nbins, 0, 0) plot.SetBuffer(1000000) plots[plotopt][rootopt] = plot return plots
def makeCorrPlots(self, xs, sigcut='', bgcut=''): # format of xs is [ [var,title,(optional nbins, binlo, binhi)] ] nX = len(xs) h2 = TH2D('hcorr', 'hcorr', nX, 0, nX, nX, 0, nX) h2.GetZaxis().SetTitle('Correlation') # label X and Y in opposite order for iB in xrange(1, nX + 1): h2.GetXaxis().SetBinLabel(iB, xs[iB - 1][1]) h2.GetYaxis().SetBinLabel(nX - iB + 1, xs[iB - 1][1]) h2bg = h2.Clone('hcorrbg') for iX in xrange(nX): for iY in xrange(iX, nX): x = xs[iX] y = xs[iY] if not (x == y): xbins = None if len(x) < 3 else x[2] ybins = None if len(y) < 3 else y[2] PInfo("SquarePlotter.makeCorrPlots", "%s vs %s" % (x[0], y[0])) corrsig = getPearson(self.tsig, x[0], y[0], sigcut, xbins, ybins) corrbg = getPearson(self.tbg, x[0], y[0], bgcut, xbins, ybins) else: corrsig = 1 corrbg = 1 h2.SetBinContent(iX + 1, nX - iY, corrsig) h2bg.SetBinContent(iX + 1, nX - iY, corrbg) return h2, h2bg
def DoPatternRecognition(self, i, tolerance, scale=1): trackDistX = [] clusterDistX = [] trackDistY = [] clusterDistY = [] tmp_track_X = [] tmp_track_Y = [] for ind in range(i, i + scaler): for track in self.AllTracks[ind]: tmp_track_X.append(track.trackX[3]) tmp_track_Y.append(track.trackY[3]) allTrack_tmp = [] allCluster_tmp = [] for tracks in self.AllTracks[i:i + scale]: for track in tracks: allTrack_tmp.append(track) allCluster_tmp = self.AllClusters[i] pattern = TH2D("", "", 14000, -npix_Y * pitchY / 2, npix_Y * pitchY / 2, len(allCluster_tmp) + len(allTrack_tmp), 0, len(allCluster_tmp) + len(allTrack_tmp)) count = 0 for index, cluster in enumerate(allCluster_tmp): pass
def plotPtAndPhiOfWrongBxId(self): #Prepare canvas canvas = TCanvas("canvasPtPhiBxWrong","PtPhiBxWrong",1200,1200) canvas.cd().Draw() #prepare histogram hist = self.fileHandler.getHistogram("etaPhi/3D/BxWrongGen_EtaPhiPt") stack = THStack(hist,"zy","2dStack","",-1,-1,-1,-1,"zy","") #Create new histogram and add the histograms from the stack histNew = TH2D("histPtPhiBxWrong","p_{T} vs. #phi distribution for wrong BX ID;#phi;p_{T} / 5 GeV;#",80,-3.2,3.2,40,0,200) histNew.GetYaxis().SetTitleOffset(1.2) for i in stack.GetHists(): histNew.Add(i) gStyle.SetPalette(1) histNew.SetStats(0) setupAxes(histNew) histNew.Draw('COLZ') canvas.Update() palette = histNew.FindObject("palette") palette.SetX1NDC(0.9) palette.SetX2NDC(0.92) #add label label = getLabelCmsPrivateSimulation() label.Draw() canvas.Update() self.storeCanvas(canvas,"bxWrongPtPhi") return canvas,hist,stack,histNew,label
def bookHist(h, key=None, title='', nbinsx=100, xmin=0, xmax=1, nbinsy=0, ymin=0, ymax=1, nbinsz=0, zmin=0, zmax=1): if key == None: print('missing key') return rkey = str( key) # in case somebody wants to use integers, or floats as keys if key in h: h[key].Reset() elif nbinsz > 0: h[key] = TH3D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax, nbinsz, zmin, zmax) elif nbinsy > 0: h[key] = TH2D(rkey, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax) else: h[key] = TH1D(rkey, title, nbinsx, xmin, xmax) h[key].SetDirectory(gROOT)