def fit_distribution(run_num, attr1='FitResult_Energy', attr2='FitResult_XtalNum==0', draw=False): """give an output file number from fitter, fit peak to find mean and variance with their errors""" #in_file = TFile("/home/newg2/Workspace/L1Tests/crunchedFiles/gm2uw_%05i_analysis.root" % run_num) in_file = TFile( "/Users/kimsiang/Work/UWCENPA/gm2/SLAC2016/Data/gm2uw_run%05i_analysis.root" % run_num) tree = in_file.Get("slacAnalyzer/eventTree") tree.Draw("%s>>h1(200)" % attr1, attr2, "goff") hist = gROOT.FindObject("h1") mean = hist.GetMean() std = hist.GetRMS() low = mean - 3 * std high = mean + 3 * std tree.Draw("%s>>h2(100,%s,%s)" % (attr1, str(low), str(high)), attr2, "goff") hist = gROOT.FindObject("h2") hist.Fit("gaus", "0q") func = hist.GetFunction("gaus") out = (func.GetParameter(1), func.GetParameter(2), func.GetParError(1), func.GetParError(2)) if draw: gStyle.SetOptFit(1) hist.Draw() hist.GetFunction("gaus").Draw("same") raw_input('any key to continue') in_file.Close() return out
def plot_inpix(inputfilename=None, histofilename="EfficiencyHistos.root", basecut="nTelTracks == 1", matchcut="hasHit == 0", usize=0.0, vsize=0.0, ubins=10, vbins=10): if inputfilename == None: return None total_cut = TCut(basecut) pass_cut = TCut(basecut) + TCut(matchcut) rawfile = gROOT.FindObject(inputfilename) if rawfile: rawfile.Close() rawfile = TFile(inputfilename, 'READ') histofile = gROOT.FindObject(histofilename) if histofile: histofile.Close() histofile = TFile( histofilename, 'RECREATE', 'Efficiency histos created from input file ' + inputfilename) # Get access to tracks tree = rawfile.Get("Track") h_track_total = TH2F("h_track_total", "", ubins, -usize, +usize, vbins, -vsize, vsize) tree.Draw(" v_fit:u_fit >> +h_track_total", total_cut, "goff") h_track_total.GetXaxis().SetTitle("u_fit [mm]") h_track_total.GetYaxis().SetTitle("v_fit [mm]") h_track_total.GetZaxis().SetTitle("tracks") h_track_total.SetStats(0) h_track_pass = TH2F("h_track_pass", "", ubins, -usize, usize, vbins, -vsize, +usize) tree.Draw(" v_fit:u_fit >> +h_track_pass", pass_cut, "goff") h_track_pass.GetXaxis().SetTitle("u_fit [mm]") h_track_pass.GetYaxis().SetTitle("v_fit [mm]") h_track_pass.GetZaxis().SetTitle("tracks") h_track_pass.SetStats(0) h_efficiency = h_track_pass h_efficiency.SetName("h_efficiency") h_efficiency.Divide(h_track_total) h_efficiency.SetTitle("") h_efficiency.SetXTitle("u_fit [mm]") h_efficiency.SetYTitle("v_fit [mm]") h_efficiency.SetZTitle("efficiency") h_efficiency.SetStats(0) # write the tree into the output file and close the file histofile.Write() histofile.Close() rawfile.Close()
def clear_hist(sample): for s in attr: if gROOT.FindObject( sample+s ) != None: hh = gROOT.FindObject( sample+s ) #to find the histogram hh.Delete() #to delete the histogram if gROOT.FindObject( sample+s+'CHS' ) != None: hhchs = gROOT.FindObject( sample+s+'CHS' ) #to find the histogram hhchs.Delete() #to delete the histogram
def plot(inputfilename = None, histofilename = "OccupancyHistos.root", ucells=0,vcells=0): if inputfilename == None: return None rawfile = gROOT.FindObject( inputfilename ) if rawfile: rawfile.Close() rawfile = TFile( inputfilename, 'READ' ) histofile = gROOT.FindObject( histofilename ) if histofile: histofile.Close() histofile = TFile( histofilename, 'RECREATE', 'Occupancy histos created from input file ' + inputfilename ) # Get access to hits tree = rawfile.Get("Hit") # Only count hits not matched to a track basecut = TCut("hasTrack == -1") # Number of events events = rawfile.Get("Event").GetEntries() # Compute occupancy for v cells h_occupancy_v = TH1F("h_occupancy_v","",vcells,0,vcells) tree.Draw("cellV_hit >> +h_occupancy_v", basecut , "goff") h_occupancy_v.Scale(1.0/(ucells*events ) ) h_occupancy_v.SetTitle("") h_occupancy_v.GetXaxis().SetTitle("cellV [cellID]") h_occupancy_v.GetYaxis().SetTitle("occupancy") # Compute occupancy for u cells h_occupancy_u = TH1F("h_occupancy_u","",ucells,0,ucells) tree.Draw("cellU_hit >> +h_occupancy_u", basecut , "goff") h_occupancy_u.Scale(1.0/(vcells*events ) ) h_occupancy_u.SetTitle("") h_occupancy_u.GetXaxis().SetTitle("cellU [cellID]") h_occupancy_u.GetYaxis().SetTitle("occupancy") # Compute occupancy for u:v cells h_occupancy = TH2F("h_occupancy","",ucells,0,ucells,vcells,0,vcells) tree.Draw("cellV_hit:cellU_hit >> +h_occupancy", basecut , "goff") h_occupancy.Scale(1.0/( 1.0*events ) ) h_occupancy.SetTitle("") h_occupancy.GetXaxis().SetTitle("cellU [cellID]") h_occupancy.GetYaxis().SetTitle("cellV [cellID]") h_occupancy.GetYaxis().SetTitle("occupancy") # write the tree into the output file and close the file histofile.Write() histofile.Close() rawfile.Close()
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 test2ObjectDestructionCallback(self): """Test ROOT notification on object destruction""" # create ROOT traced object a = TH1F('memtest_th1f', 'title', 100, -1., 1.) # locate it self.assertEqual(a, gROOT.FindObject('memtest_th1f')) # destroy it del a # should no longer be accessible self.assert_(not gROOT.FindObject('memtest_th1f'))
def MakeHisto(self): file_handle = TFile.Open(self.filepath) tree = file_handle.Get(self.tree) if not tree: logging.error("Could not open tree '%s' from file '%s'" % (self.tree, self.filename)) if self.weight and self.weight != '': tree.Draw( self.variable + '>>' + self.name + '(' + str(self.bins) + ',' + str(self.xmin) + ',' + str(self.xmax) + ')', self.weight + '*(' + self.cut + ')', "goff") else: tree.Draw( self.variable + '>>' + self.name + '(' + str(self.bins) + ',' + str(self.xmin) + ',' + str(self.xmax) + ')', self.cut, "goff") histo = gROOT.FindObject(self.name) histo.SetTitle(self.title + ' (%s sample)' % self.filename + ';' + self.xlabel + ';' + self.ylabel + ' / %0.2f' % (histo.GetBinWidth(1))) self.histo = copy.deepcopy(histo) file_handle.Close() # Overflow # self.histo.SetBinContent( 1, self.histo.GetBinContent(0) + self.histo.GetBinContent(1)) self.histo.SetBinContent( self.histo.GetNbinsX(), self.histo.GetBinContent(self.histo.GetNbinsX()) + self.histo.GetBinContent(self.histo.GetNbinsX() + 1))
def Hist_create(hist_name): x_index = [] x_count = [] x_index_out = [] hist_o = gROOT.FindObject(hist_name) if "TH1" in hist_o.ClassName(): print "" cal_ans = raw_input("Calibrate? [y / n] ") Get_Data(hist_name, x_index, x_count) if cal_ans == "y": Calibrate(x_index, x_index_out) print "" print "Drawing graph..." plt.plot(x_index_out, x_count, "m") plt.show() else: print "Drawing graph..." print "" #val = Get_Data(hist_name, x_index, x_count) Draw_Hist(x_index, x_count) if "TH2" in hist_o.ClassName(): #print "YES" #val_x = 0 #val_y = 0 y_index = [] z_count = [] Get_Data_2D(hist_name, x_index, y_index, z_count) #, val_x, val_y) Draw_2D(x_index, y_index, z_count)
def contourPlot(tree, pmin, pmax, bestFit=(10.1, 1.5)): n = tree.Draw("r_" + to_do_first + ":r_"+to_do, "%f <= quantileExpected && quantileExpected <= %f && quantileExpected != 1" % (pmin,pmax), "") print "Drawing for r_%s:%s, %f <= quantileExpected && quantileExpected <= %f && quantileExpected != 1 yielded %d points" % (to_do_first, to_do,pmin, pmax, n) gr = gROOT.FindObject("Graph").Clone() xi = gr.GetX() yi = gr.GetY() npoints = gr.GetN() for i in range(npoints): xi[i] -= bestFit[0] yi[i] -= bestFit[1] def compArg(i, j): return 1 if TGraph.CompareArg(gr, i, j) else -1 sorted_points = sorted(range(npoints), cmp=compArg) sorted_graph = TGraph(npoints+1) for n,i in enumerate(sorted_points): sorted_graph.SetPoint(n, xi[i], yi[i]) sorted_graph.SetPoint(npoints, xi[sorted_points[0]], yi[sorted_points[0]]) xi_sorted = sorted_graph.GetX() yi_sorted = sorted_graph.GetY() for i in range(npoints+1): xi_sorted[i] += bestFit[0] yi_sorted[i] += bestFit[1] return sorted_graph
def study_geo_cuts(): # 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_tr_clusters=lumical", "../trees/lucas_5gev_e_tr_clusters.root") c = TCanvas("tr1_mc_hit_map") t_data.Draw("cal_hit_pad:cal_hit_sector>>h_data(4, 0, 4, 64, 0, 64)", "cal_hit_layer == 6", "colz") h_data = gROOT.FindObject("h_data") h_data.SetTitle("Data: hit map in tracker 2; sector, [0-3]; pad, [0-63]") h_data.SetStats(0) # t_mc.Draw("tr1_pad:tr1_sector>>h_mc(4, 0, 4, 64, 0, 64)", "", "colz") # h_mc = gROOT.FindObject("h_mc") # h_mc.SetTitle("MC: hit map in tracker 1; sector, [0-3]; pad, [0-63]") # h_mc.SetStats(0) c.SetLogz() c.Update() input("wait")
def MakeHisto(self): file_handle = TFile.Open(self.filepath) tree = file_handle.Get(self.tree) if not tree: logging.error("Could not open tree '%s' from file '%s'"%(self.tree,self.filename)) first_arg = self.variable+'>>'+self.name+'('+str(self.bins)+','+str(self.xmin)+','+str(self.xmax)+')' if self.weight and self.weight != '' and self.cut != '': second_arg = self.weight + "* (" + self.cut + ")" elif self.weight and self.weight != '': second_arg = self.weight elif self.cut != '': second_arg = self.cut else: second_arg = '' tree.Draw(first_arg,second_arg,"goff") histo = gROOT.FindObject(self.name) try: histo.ClassName() except ReferenceError: raise RuntimeError('Could not produce histogram %s'%self.name) histo.SetTitle(self.title+';'+self.xlabel+';'+self.filename+' '+self.ylabel+' / %0.2f'%(histo.GetBinWidth(1))) self.histo = copy.deepcopy(histo) file_handle.Close() # Overflow # self.histo.SetBinContent(1,self.histo.GetBinContent(0)+self.histo.GetBinContent(1)) self.histo.SetBinContent(self.histo.GetNbinsX(),self.histo.GetBinContent(self.histo.GetNbinsX())+self.histo.GetBinContent(self.histo.GetNbinsX()+1))
def B_Sub_Work(hist_name, it, b_num, count): hist_o = gROOT.FindObject(hist_name) s = TSpectrum() B_hist = s.Background(hist_o, it, "same") b_x = [] b_count = [] nb_x = [] nb_count = [] b_x_max = B_hist.GetNbinsX() i = 0 while i < b_x_max: #Iterates over all the bins getting their content b_count.append(B_hist.GetBinContent(i)) b_x.append(i) i += 1 nb_x_max = hist_o.GetNbinsX() j = 0 while j < nb_x_max: #Iterates over all the bins getting their content nb_count.append(hist_o.GetBinContent(j)) nb_x.append(j) j += 1 k = 0 while k < len(b_x): count.append(nb_count[k] - b_count[k]) b_num.append(k) k += 1
def def_matrix(): edata_events = experimental_events()[1] f1 = TFile("histograms/mc.root") ntuple = gROOT.FindObject('Tree') i = 0 j = 0 NtrueMC = array('d') while i < N: cut1 = "m3pimc > " + str(list[i]) + " && m3pimc < " + str(list[i + 1]) Nev0 = float(ntuple.GetEntries(cut1)) NtrueMC.append(Nev0) while j < N: if abs(i - j) < 14: cut2 = "m3pi > " + str(list[j]) + " && m3pi < " + str( list[j + 1]) Nev = ntuple.GetEntries(cut2 + " && " + cut1) MAT[i][j] = Nev / edata_events[i] #/Nev0 j = j + 1 i = i + 1 j = 0 print(MAT) #plt.imshow(MAT) #plt.colorbar() #plt.show() np.savetxt('Matrix2.txt', MAT, fmt='%.1f') np.savetxt('NtrueMC.txt', NtrueMC, fmt='%.1f') input("wait") return 1
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")
def BestFit(tree): n = tree.Draw("limit>>h1", "quantileExpected==-1", "") h1 = gROOT.FindObject("h1").Clone() if h1.GetEntries() > 1: print("ERROR Best Fit hist has more than 1 entries ") sys.exit() bestFit = h1.GetMean() print("BestFit from data_file: %s" % bestFit) return bestFit
def test07ObjectValidity(self): """Test object validity checking""" t1 = TObject() self.assert_(t1) self.assert_(not not t1) t2 = gROOT.FindObject("Nah, I don't exist") self.assert_(not t2)
def get_canvas(cname="c1"): """Return the canvas named CNAME. Create it if it doesn't exist. """ global _canvas _canvas = gROOT.FindObject(cname) if not _canvas: _canvas = TCanvas(cname, cname, 700, 600) _canvas.SetLeftMargin(0.15) _canvas.SetBottomMargin(0.15) _canvas.SetLogy(0) return _canvas
def Get_Data(hist, index_out, count_out): hist_o = gROOT.FindObject(hist) x_max = hist_o.GetNbinsX() #print x_max #val = hist_o.GetBinContent(x_max) i = 0 while i < x_max: #Iterates over all the bins getting their content count_out.append(hist_o.GetBinContent(i)) index_out.append(i) i += 1
def getRunHisto(self, f): print("Extracting run hist from file %s" % f) try: root_file = TFile.Open(f) tree = root_file.Get("Runs") tree.Draw("run>>h(" + str(self.run_stop - self.run_start) + "," + str(self.run_start) + "," + str(self.run_stop) + ")") h = copy.deepcopy(gROOT.FindObject("h")) root_file.Close() return h except Exception as e: print("Exception %s for file %s" % (e, f))
def MakeHisto(self): file_handle = TFile.Open(self.filepath) tree = file_handle.Get(self.tree) if not tree: logging.error("Could not open tree '%s' from file '%s'" % (self.tree, self.filename)) first_arg = self.variabley + ':' + self.variablex + '>>' + self.name + '(' + str( self.binsx) + ',' + str(self.xmin) + ',' + str( self.xmax) + ',' + str(self.binsy) + ',' + str( self.ymin) + ',' + str(self.ymax) + ')' if self.weight and self.weight != '' and self.cut != '': second_arg = self.weight + "* (" + self.cut + ")" elif self.weight and self.weight != '': second_arg = self.weight elif self.cut != '': second_arg = self.cut else: second_arg = '' tree.Draw(first_arg, second_arg, "goff " + self.option) self.histo = copy.deepcopy(gROOT.FindObject(self.name)) if self.normalizeX: for x in range(0, self.histo.GetNbinsX() + 1): sum_y = 0 for y in range(0, self.histo.GetNbinsY() + 1): sum_y += self.histo.GetBinContent(x, y) if sum_y == 0: continue for y in range(0, self.histo.GetNbinsY() + 1): self.histo.SetBinContent( x, y, self.histo.GetBinContent(x, y) / sum_y) self.title += ' [Normalized]' if self.normalizeY: for y in range(0, self.histo.GetNbinsY() + 1): sum_x = 0 for x in range(0, self.histo.GetNbinsX() + 1): sum_x += self.histo.GetBinContent(x, y) if sum_x == 0: continue for x in range(0, self.histo.GetNbinsX() + 1): self.histo.SetBinContent( x, y, self.histo.GetBinContent(x, y) / sum_x) self.title += ' [Normalized]' self.histo.SetTitle(self.title + ';' + self.xlabel + ';' + self.ylabel + ';' + self.zlabel + ' / %0.2f / %0.2f' % (self.histo.GetXaxis().GetBinWidth(1), self.histo.GetYaxis().GetBinWidth(1))) self.histo.SetMinimum(0) file_handle.Close()
def ToyFit(tree, data_obs): x = tree.Draw("limit>>h2") h2 = gROOT.FindObject("h2").Clone() nentries = h2.GetEntries() h2.Scale(1. / h2.Integral()) cdf = h2.GetCumulative() CL99 = cdf.GetBinCenter(cdf.FindFirstBinAbove(0.99)) CL95 = cdf.GetBinCenter(cdf.FindFirstBinAbove(0.95)) CL90 = cdf.GetBinCenter(cdf.FindFirstBinAbove(0.90)) p_value = 1 - cdf.GetBinContent(cdf.FindBin(data_obs)) print( " CL90: {}\n CL95: {}\n CL99: {}\n obs: {} \n p_value: {}\n sample size {} \n toy_file {}" .format(CL90, CL95, CL99, data_obs, p_value, nentries, toy_file)) return CL90, CL95, CL99, p_value, h2
def main(m1, m2): f1 = TFile("histograms/mc.root") h1 = TH1D("h1", "h1", 40, -0.04, 0.04) h2 = TH1D("h2", "h2", 40, -0.04, 0.04) ntuple = gROOT.FindObject('Tree') cut1 = TCut("abs(m3pimc - " + str(m1) + ") < 0.05") ntuple.Draw("m3pimc-m3pi >> h1", cut1) cut2 = TCut("abs(m3pimc - " + str(m2) + ") < 0.05") ntuple.Draw("m3pimc-m3pi >> h2", cut2) h2.Scale(h1.GetEntries() / h2.GetEntries()) h2.SetLineColor(2) h1.Draw() h2.Draw("same") input()
def main(): Quit = False print "" print "DanWare - V.1.9" print "---------------" print "" print "Ha ha get it - DanWare - like radware.. Get it?" print "" print "The point of this is to see if I can make a grutinizer-esque program" print "in python. I will attempt to use PyROOT to do this." print "" print "--------------------------------------" print "" print "Enter 'h' for help." while True: File_1 = Read_File() if File_1 == "q": break if File_1 == "c": continue while True: print "File Content: " print "" File_1.ls() print "" print "Which histogram do you want to look at? (1D only) " hist_name = raw_input("Hist name = ") print "" if hist_name == "q": break hist_o = gROOT.FindObject(hist_name) if "TDirectoryFile" in hist_o.ClassName(): hist_o.cd() continue Hist_create(hist_name) break if hist_name == "q": continue print "" print "Quit?" q_answer = raw_input("[y / n] = ") if q_answer == "y": break print "" print "Exiting..." print ""
def save_targetpos(treefilename=None,dbfilename=None): """ Updates the alignment DB with the expected target position from the vertex fit :@filename: Name of file with MSCTree which includes the vertex parameters :@dbfilename Name of the db root file :author: [email protected] """ if treefilename == None: return None if dbfilename == None: return None gROOT.SetBatch(1) rawfile = gROOT.FindObject( treefilename ) # if tree file is open, close it if rawfile: rawfile.Close() # Open tree file in read mode rawfile = TFile( treefilename, 'READ' ) tree=rawfile.Get('MSCTree') # Calculate mean value of the vertex z position count=0 mean=0 for event in tree: mean += getCurrentValue(event,"vertex_z") count +=1 if count == 0: raise ValueError('Tree is empty!') # Round mean value to first decimal (100 microns) mean=round(mean/count,1) print "New target position is" print mean Modify_AlignmentDBFile(dbfilename=dbfilename, planenumber=3, mode='z', value=mean)
def Get_Data_2D(hist, index_x, index_y, count_y): #, val_x, val_y): hist_o = gROOT.FindObject(hist) x_max = hist_o.GetNbinsX() y_max = hist_o.GetNbinsY() #val_x = hist_o.GetBinContent(x_max) #val_y = hist_o.GetBinContent(y_max) i = 0 while i < x_max: #Iterates over all the bins getting their content j = 0 while j < y_max: #Iterates over all the bins getting their content z = hist_o.GetBinContent(i, j) index_x.append(i) #print z count_y.append(z) #print index_x[i], index_y[j], hist_o.GetBinContent(i,j) index_y.append(j) #print index_x[i], index_y[j], hist_o.GetBinContent(i,j) j += 1 i += 1
def Background_Sub(hist_name): #c_list = ['b','r','g','c','m','k'] #print "" #print "Which histogram do you want to look at? (1D only) " #hist_name = raw_input("Hist name = ") print "" iterations = raw_input("How many iterations do you want? ") if iterations == "": iterations = 20 else: iterations = int(iterations) print "" opt = raw_input("Subtraction intensity? [b / m / h / i] ") if opt == "": opt = "b" print "" cal_ans = raw_input("Calibrate? [y / n] ") print "" x_index = [] x_index_in = [] x_count = [] hist_o = gROOT.FindObject(hist_name) if "TH1" in hist_o.ClassName(): print "Drawing graph..." print "" #val = Get_Data(hist_name, x_index, x_count) #Get_Data(hist_name, x_index_in, x_count) B_Sub_Work(hist_name, iterations, x_index_in, x_count, opt) if cal_ans == "y": Calibrate(x_index_in, x_index) plt.plot(x_index, x_count) #, c_list[i % 6]) else: plt.plot(x_index_in, x_count) #, c_list[i % 6]) #if "TH2" in hist_o.ClassName(): else: print "BROKEN!!!" print "" plt.show()
def drawlik(input, gr = TGraph(), color = 8, second = False, Folder = "") : print ("reading " + Folder+"/"+input) tf2 = TFile.Open(Folder+"/"+input, "READ") tree2 = tf2.Get("limit") bu = "P" if second : bu = "P same" tree2.Draw("2*deltaNLL:kappa_t>>hist(50,-3,3)","2*deltaNLL<50", bu) canv.Update(); canv.Modified(); gr = gROOT.FindObject("Graph").Clone() gr.Sort() tf2.Close() gROOT.Reset() #hist = gDirectory.Get("hist") gr.GetXaxis().SetTitleFont(43) gr.GetYaxis().SetTitleFont(43) gr.GetXaxis().SetTitleSize(28) gr.GetYaxis().SetTitleSize(28) gr.GetXaxis().SetTitleOffset(0.8) gr.GetYaxis().SetTitleOffset(0.7) gr.GetXaxis().SetTitle("#kappa_t") gr.GetYaxis().SetTitle("-2#Delta lnL") #gr2.SetMarkerStyle(34) return gr
gROOT.Reset() # Create a new canvas, and customize it. c1 = TCanvas('c1', 'Dynamic Filling Example', 200, 10, 700, 500) c1.SetFillColor(42) c1.GetFrame().SetFillColor(21) c1.GetFrame().SetBorderSize(6) c1.GetFrame().SetBorderMode(-1) # Create a new ROOT binary machine independent file. # Note that this file may contain any kind of ROOT objects, histograms, # pictures, graphics objects, detector geometries, tracks, events, etc.. # This file is now becoming the current directory. hfile = gROOT.FindObject('hsimple.root') if hfile: hfile.Close() hfile = TFile('hsimple.root', 'RECREATE', 'Demo ROOT file with histograms') # Create some histograms, a profile histogram and an ntuple hpx = TH1F('hpx', 'This is the px distribution', 100, -4, 4) hpxpy = TH2F('hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4) hprof = TProfile('hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20) ntuple = TNtuple('ntuple', 'Demo ntuple', 'px:py:pz:random:i') # Set canvas/frame attributes. hpx.SetFillColor(48) gBenchmark.Start('hsimple')
def generator(nuslice_tree, rootfile, pset): n_bins = pset.n_bins drift_distance = pset.DriftDistance bin_width = drift_distance/n_bins half_bin_width = bin_width/2. xvals = np.arange(half_bin_width, drift_distance, bin_width) xerrs = np.array([half_bin_width] * len(xvals)) dist_to_anode_bins = n_bins dist_to_anode_low = 0. dist_to_anode_up = drift_distance profile_bins = n_bins profile_option = 's' # errors are the standard deviation dy_spreads = [None] * n_bins dy_means = [None] * n_bins dy_hist = TH2D("dy_hist", "#Delta y", dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up, pset.dy_bins, pset.dy_low, pset.dy_up) dy_hist.GetXaxis().SetTitle("distance from anode (cm)") dy_hist.GetYaxis().SetTitle("y_flash - y_TPC (cm)") dy_prof = TProfile("dy_prof", "Profile of dy_spreads in #Delta y", profile_bins, dist_to_anode_low, dist_to_anode_up, pset.dy_low*2, pset.dy_up*2, profile_option) dy_prof.GetXaxis().SetTitle("distance from anode (cm)") dy_prof.GetYaxis().SetTitle("y_flash - y_TPC (cm)") dy_h1 = TH1D("dy_h1", "", profile_bins, dist_to_anode_low, dist_to_anode_up) dy_h1.GetXaxis().SetTitle("distance from anode (cm)") dy_h1.GetYaxis().SetTitle("y_flash - y_TPC (cm)") dz_spreads = [None] * n_bins dz_means = [None] * n_bins dz_hist = TH2D("dz_hist", "#Delta z", dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up, pset.dz_bins, pset.dz_low, pset.dz_up) dz_hist.GetXaxis().SetTitle("distance from anode (cm)") dz_hist.GetYaxis().SetTitle("z_flash - z_TPC (cm)") dz_prof = TProfile("dz_prof", "Profile of dz_spreads in #Delta z", profile_bins, dist_to_anode_low, dist_to_anode_up, pset.dz_low*2.5, pset.dz_up*2.5, profile_option) dz_prof.GetXaxis().SetTitle("distance from anode (cm)") dz_prof.GetYaxis().SetTitle("z_flash - z_TPC (cm)") dz_h1 = TH1D("dz_h1", "", profile_bins, dist_to_anode_low, dist_to_anode_up) dz_h1.GetXaxis().SetTitle("distance from anode (cm)") dz_h1.GetYaxis().SetTitle("z_flash - z_TPC (cm)") rr_spreads = [None] * n_bins rr_means = [None] * n_bins rr_hist = TH2D("rr_hist", "PE Spread", dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up, pset.rr_bins, pset.rr_low, pset.rr_up) rr_hist.GetXaxis().SetTitle("distance from anode (cm)") rr_hist.GetYaxis().SetTitle("RMS flash (cm)") rr_prof = TProfile("rr_prof", "Profile of PE Spread", profile_bins, dist_to_anode_low, dist_to_anode_up, pset.rr_low, pset.rr_up, profile_option) rr_prof.GetXaxis().SetTitle("distance from anode (cm)") rr_prof.GetYaxis().SetTitle("RMS flash (cm)") rr_h1 = TH1D("rr_h1", "", profile_bins, dist_to_anode_low, dist_to_anode_up) rr_h1.GetXaxis().SetTitle("distance from anode (cm)") rr_h1.GetYaxis().SetTitle("RMS flash (cm)") if detector == "sbnd": pe_spreads = [None] * n_bins pe_means = [None] * n_bins pe_hist = TH2D("pe_hist", "Uncoated/Coated Ratio", dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up, pset.pe_bins, pset.pe_low, pset.pe_up) pe_hist.GetXaxis().SetTitle("distance from anode (cm)") pe_hist.GetYaxis().SetTitle("ratio_{uncoated/coated}") pe_prof = TProfile("pe_prof", "Profile of Uncoated/Coated Ratio", profile_bins, dist_to_anode_low, dist_to_anode_up, pset.pe_low, pset.pe_up, profile_option) pe_prof.GetXaxis().SetTitle("distance from anode (cm)") pe_prof.GetYaxis().SetTitle("ratio_{uncoated/coated}") pe_h1 = TH1D("pe_h1", "", profile_bins, dist_to_anode_low, dist_to_anode_up) pe_h1.GetXaxis().SetTitle("distance from anode (cm)") pe_h1.GetYaxis().SetTitle("ratio_{uncoated/coated}") match_score_scatter = TH2D("match_score_scatter", "Scatter plot of match scores", dist_to_anode_bins, dist_to_anode_low, dist_to_anode_up, pset.score_hist_bins, pset.score_hist_low, pset.score_hist_up*(3./5.)) match_score_scatter.GetXaxis().SetTitle("distance from anode (cm)") match_score_scatter.GetYaxis().SetTitle("match score (arbitrary)") match_score_hist = TH1D("match_score", "Match Score", pset.score_hist_bins, pset.score_hist_low, pset.score_hist_up) match_score_hist.GetXaxis().SetTitle("match score (arbitrary)") for e in nuslice_tree: slice = e.charge_x dy_hist.Fill(slice, e.flash_y - e.charge_y) dy_prof.Fill(slice, e.flash_y - e.charge_y) dz_hist.Fill(slice, e.flash_z - e.charge_z) dz_prof.Fill(slice, e.flash_z - e.charge_z) rr_hist.Fill(slice, e.flash_r) rr_prof.Fill(slice, e.flash_r) if detector == "sbnd": pe_hist.Fill(slice, e.flash_ratio) pe_prof.Fill(slice, e.flash_ratio) # fill histograms for match score calculation from profile histograms for ib in list(range(0, profile_bins)): ibp = ib + 1 dy_h1.SetBinContent(ibp, dy_prof.GetBinContent(ibp)) dy_h1.SetBinError(ibp, dy_prof.GetBinError(ibp)) dy_means[int(ib)] = dy_prof.GetBinContent(ibp) dy_spreads[int(ib)] = dy_prof.GetBinError(ibp) dz_h1.SetBinContent(ibp, dz_prof.GetBinContent(ibp)) dz_h1.SetBinError(ibp, dz_prof.GetBinError(ibp)) dz_means[int(ib)] = dz_prof.GetBinContent(ibp) dz_spreads[int(ib)] = dz_prof.GetBinError(ibp) rr_h1.SetBinContent(ibp, rr_prof.GetBinContent(ibp)) rr_h1.SetBinError(ibp, rr_prof.GetBinError(ibp)) rr_means[int(ib)] = rr_prof.GetBinContent(ibp) rr_spreads[int(ib)] = rr_prof.GetBinError(ibp) if detector == "sbnd": pe_h1.SetBinContent(ibp, pe_prof.GetBinContent(ibp)) pe_h1.SetBinError(ibp, pe_prof.GetBinError(ibp)) pe_means[int(ib)] = pe_prof.GetBinContent(ibp) pe_spreads[int(ib)] = pe_prof.GetBinError(ibp) for e in nuslice_tree: slice = e.charge_x # calculate match score isl = int(slice/bin_width) score = 0. if dy_spreads[isl] <= 1.e-8: print("Warning zero spread.\n", f"slice: {slice}. isl: {isl}. dy_spreads[isl]: {dy_spreads[isl]} ") dy_spreads[isl] = dy_spreads[isl+1] if dz_spreads[isl] <= 1.e-8: print("Warning zero spread.\n", f"slice: {slice}. isl: {isl}. dz_spreads[isl]: {dz_spreads[isl]} ") dz_spreads[isl] = dz_spreads[isl+1] if rr_spreads[isl] <= 1.e-8: print("Warning zero spread.\n", f"slice: {slice}. isl: {isl}. rr_spreads[isl]: {rr_spreads[isl]} ") rr_spreads[isl] = rr_spreads[isl+1] if detector == "sbnd" and pe_spreads[isl] <= 1.e-8: print("Warning zero spread.\n", f"slice: {slice}. isl: {isl}. pe_spreads[isl]: {pe_spreads[isl]} ") pe_spreads[isl] = pe_spreads[isl+1] score += abs(abs(e.flash_y-e.charge_y) - dy_means[isl])/dy_spreads[isl] score += abs(abs(e.flash_z-e.charge_z) - dz_means[isl])/dz_spreads[isl] score += abs(e.flash_r-rr_means[isl])/rr_spreads[isl] if detector == "sbnd" and pset.UseUncoatedPMT: score += abs(e.flash_ratio-pe_means[isl])/pe_spreads[isl] match_score_scatter.Fill(slice, score) match_score_hist.Fill(score) metrics_filename = 'fm_metrics_' + detector + '.root' hfile = gROOT.FindObject(metrics_filename) if hfile: hfile.Close() hfile = TFile(metrics_filename, 'RECREATE', 'Simple flash matching metrics for ' + detector.upper()) dy_hist.Write() dy_prof.Write() dy_h1.Write() dz_hist.Write() dz_prof.Write() dz_h1.Write() rr_hist.Write() rr_prof.Write() rr_h1.Write() if detector == "sbnd": pe_hist.Write() pe_prof.Write() pe_h1.Write() match_score_scatter.Write() match_score_hist.Write() hfile.Close() canv = TCanvas("canv") dy_hist.Draw() crosses = TGraphErrors(n_bins, array('f', xvals), array('f', dy_means), array('f', xerrs), array('f', dy_spreads)) crosses.SetLineColor(9) crosses.SetLineWidth(3) crosses.Draw("Psame") canv.Print("dy.pdf") canv.Update() dz_hist.Draw() crosses = TGraphErrors(n_bins, array('f', xvals), array('f', dz_means), array('f', xerrs), array('f', dz_spreads)) crosses.SetLineColor(9) crosses.SetLineWidth(3) crosses.Draw("Psame") canv.Print("dz.pdf") canv.Update() rr_hist.Draw() crosses = TGraphErrors(n_bins, array('f', xvals), array('f', rr_means), array('f', xerrs), array('f', rr_spreads)) crosses.SetLineColor(9) crosses.SetLineWidth(3) crosses.Draw("Psame") canv.Print("rr.pdf") canv.Update() if detector == "sbnd": pe_hist.Draw() crosses = TGraphErrors(n_bins, array('f', xvals), array('f', pe_means), array('f', xerrs), array('f', pe_spreads)) crosses.SetLineColor(9) crosses.SetLineWidth(3) crosses.Draw("Psame") canv.Print("pe.pdf") canv.Update() match_score_scatter.Draw() canv.Print("match_score_scatter.pdf") canv.Update() match_score_hist.Draw() canv.Print("match_score.pdf") canv.Update() sleep(20)
# see begin_html <a href="hsimple.C.html">An example creating/filling/saving histograms/ntuples on file</a> end_html # example = TFile('py-hsimple.root') example.ls() # Draw a global picture title title = TPaveLabel(0.1, 0.94, 0.9, 0.98, 'Drawing options for one dimensional histograms') title.SetFillColor(16) title.SetTextFont(52) title.Draw() # # Draw histogram hpx in first pad with the default option. pad1.cd() pad1.GetFrame().SetFillColor(18) hpx = gROOT.FindObject('hpx') hpx.SetFillColor(45) hpx.DrawCopy() label1 = TPaveLabel(-3.5, 700, -1, 800, 'Default option') label1.SetFillColor(42) label1.Draw() # # Draw hpx as a lego. Clicking on the lego area will show # a "transparent cube" to guide you rotating the lego in real time. pad2.cd() hpx.DrawCopy('lego1') label2 = TPaveLabel(-0.72, 0.74, -0.22, 0.88, 'option Lego1') label2.SetFillColor(42) label2.Draw() label2a = TPaveLabel(-0.93, -1.08, 0.25, -0.92, 'Click on lego to rotate') label2a.SetFillColor(42)