def makeTRTECCPlots(fp, fs, pulls): c1 = TCanvas("c1", "c1", 971, 300) c1.Divide(2, 1) c1.cd(1) h1 = (gDirectory.Get("trt_ec_residualR_Endcap_C")).Clone() h1.SetTitle(fs("TRT Endcap C Residual R; Residual; Events")) t = gaussfit(h1, True) h1.UseCurrentStyle() h1.Draw("HIST") t[0].Draw("SAME") c1.cd(2) h2 = (gDirectory.Get("trt_ec_pullR_notube_Endcap_C")).Clone() h2.SetTitle(fs("TRT Endcap C Pull; Pull; Events")) t = gaussfit(h2, True) h2.UseCurrentStyle() h2.Draw("HIST") t[0].SetRange(-2.5, 2.5) t[0].Draw("SAME") pulls["trtecC"] = t[1:] c1.SaveAs(fp("trtECC.pdf")) c1.SaveAs(fp("trtECC.png")) c1.SaveAs(fp("trtECC.gif")) c1.SaveAs(fp("trtECC.eps"))
def makeSCTECAPlots(fp, fs, pulls): c1 = TCanvas("c1", "c1", 971, 300) c1.Divide(2, 1) c1.cd(1) h1 = (gDirectory.Get("sct_eca_residualx")).Clone() h1.SetTitle(fs("SCT Endcap A Residual X; Residual; Events")) t = gaussfit(h1, True) h1.UseCurrentStyle() h1.Draw("HIST") t[0].Draw("SAME") c1.cd(2) h2 = (gDirectory.Get("sct_eca_pullx")).Clone() h2.SetTitle(fs("SCT Endcap A Pull X; Pull; Events")) t = gaussfit(h2, True) h2.UseCurrentStyle() h2.Draw("HIST") t[0].SetRange(-2.5, 2.5) t[0].Draw("SAME") pulls["sctecA"] = t[1:] c1.SaveAs(fp("sctECA.pdf")) c1.SaveAs(fp("sctECA.png")) c1.SaveAs(fp("sctECA.gif")) c1.SaveAs(fp("sctECA.eps"))
def plotStuff(plotList, plotstring, cutstring, plotfile, plotname, xlabel, ylabel, unitnorm): leg = TLegend(0.4, 0.75, 0.6, 0.9) isFirst = True for dataset in plotList: dataset[0].Draw(plotstring.format(dataset[1]), cutstring, "goff") hist = gDirectory.Get(dataset[1]) #hist.Sumw2() if unitnorm: hist.Scale(1.0 / hist.Integral()) else: hist.Scale(1.0 / dataset[2]) print "{0} {1} {2}".format(plotname, dataset[4], hist.Integral()) hist.SetLineColor(dataset[3]) leg.AddEntry(hist, dataset[4]) if isFirst: hist.GetXaxis().SetTitle(xlabel) hist.GetYaxis().SetTitle(ylabel) hist.Draw() else: hist.Draw("same") isFirst = False #leg.Draw() data1Hist = gDirectory.Get("data1") data2Hist = gDirectory.Get("data2") data3Hist = gDirectory.Get("data3") data1Hist.Divide(data3Hist) data2Hist.Divide(data3Hist) data1Hist.Draw() data2Hist.Draw("same") c.Print(plotfile, plotname)
def GetJonPlot(tree_gen, tree_fid, var, histbins, quantity='diff'): # # Quantity, or numerator # #jon_weight = '0.0000072*(event_type_truth<4)/20.277' jon_weight = 'weight_fiducial*(event_type_truth<4)/20.277' if quantity in ['fid', 'diff', 'eff']: #jon_weight += '*(118.<=dressed_lep4_m && dressed_lep4_m<=129.)' jon_weight += '*(118.<=bare_lep4_m && bare_lep4_m<=129.)' the_tree = tree_fid else: the_tree = tree_gen the_tree.Draw('%s>>h1%s' % (var, histbins), jon_weight, 'egoff') h1 = gDirectory.Get('h1') if quantity == 'eff': #jon_weight = jon_weight.replace('*(118.<=dressed_lep4_m && dressed_lep4_m<=129.)','') jon_weight = jon_weight.replace( '*(118.<=bare_lep4_m && bare_lep4_m<=129.)', '') tree_gen.Draw('%s>>Den%s' % (var, histbins), jon_weight, 'egoff') Den = gDirectory.Get('Den') h1.Divide(h1, Den, 1, 1, 'B') gROOT.ProcessLine('delete Den') if quantity == 'diff': ConvertNeventsToDSigma(h1) return h1
def get_nuis_corr(tfile, is_conditional, is_asimov, poi=1): f = ROOT.TFile.Open(tfile) mu = "1" if is_asimov: stub = "Asimov" f.cd("PlotsAfterFitToAsimov") mu = str(poi) else: stub = "Global" f.cd("PlotsAfterGlobalFit") mu = str(poi) if is_conditional: gDirectory.cd("conditionnal_MuIsEqualTo_" + mu) #if is_asimov: # gDirectory.cd("conditionnal_MuIsEqualTo_"+mu) #else: # gDirectory.cd("conditionnal_MuIsEqualTo_0") #p_nuis = gDirectory.Get("can_NuisPara_"+stub+"Fit_conditionnal_mu0") #p_corr = gDirectory.Get("can_CorrMatrix_"+stub+"Fit_conditionnal_mu0") p_nuis = gDirectory.Get("can_NuisPara_" + stub + "Fit_conditionnal_mu" + mu) p_corr = gDirectory.Get("can_CorrMatrix_" + stub + "Fit_conditionnal_mu" + mu) else: gDirectory.cd("unconditionnal") p_nuis = gDirectory.Get("can_NuisPara_" + stub + "Fit_unconditionnal_mu" + mu) p_corr = gDirectory.Get("can_CorrMatrix_" + stub + "Fit_unconditionnal_mu" + mu) return p_nuis, p_corr
def draw_canvas_1d(name): f_mc = TFile("plots/mc/%s_mcc7.root" % name) print(f_mc.ls()) print(name) h_mc = gDirectory.Get("h_%s_reco" % name) h_mc.SetName("h_%s_reco" % name) h_mc.SetLineColor(kRed + 1) h_mc.SetFillColor(kRed + 1) h_mc.SetFillStyle(0) h_mc.GetYaxis().SetTitle("Efficiency") h_mc.GetYaxis().SetRangeUser(0.61, 1.04) f = TFile("plots/data/e_%s_pandoraCosmic.root" % name) h = gDirectory.Get("h_%s" % name) h.SetMarkerStyle(20) h.SetLineColor(1) f_sys = TFile("plots/data/e_%s_sys_pandoraCosmic.root" % name) h_sys = gDirectory.Get("h_%s_sys" % name) h_ratio = h_sys.Clone() h_ratio.Divide(h_mc) x_minbin = h_mc.FindFirstBinAbove() low = h_mc.GetXaxis().GetBinLowEdge(x_minbin) x_maxbin = h_mc.FindLastBinAbove() high = h_mc.GetXaxis().GetBinUpEdge(x_maxbin) h_mc.GetXaxis().SetRangeUser(low, high) h_mc.GetYaxis().SetTitleSize(0.08) h_mc.GetYaxis().SetLabelSize(0.065) h_mc.GetYaxis().SetTitleOffset(0.59) h_ratio.GetXaxis().SetRangeUser(low, high) g_stat = histo2graph(h) g_sys = histo2graph(h_sys) g_sys.SetMarkerStyle(20) g_sys.SetLineWidth(2) g_stat.SetFillStyle(3001) g_stat.SetFillColor(kGray + 2) g_stat.SetLineWidth(2) g_stat.SetLineColor(kGray + 2) pt = TPaveText(0.09, 0.855, 0.32, 0.98, "ndc") pt.AddText("MicroBooNE") pt.SetFillColor(0) pt.SetBorderSize(0) pt.SetShadowColor(0) leg = TLegend(0.55, 0.09, 0.86, 0.4) leg.AddEntry(g_sys, "Data - stat. #oplus sys.", "ep") leg.AddEntry(g_stat, "Data - stat. only", "f") leg.AddEntry(h_mc, "Monte Carlo", "f") canvas = draw_ratio("c_%s" % name, [h_mc, g_stat, g_sys, pt, leg], [h_ratio], ["hist", "2", "p", "", ""], ["ep"]) canvas.SaveAs("plots/%s.pdf" % name) canvas.SaveAs("plots/%s.C" % name)
def getResolution ( fileName ): myfile = TFile( fileName ) mychain = gDirectory.Get( 'testTree' ) mychain.Draw('mainClustersEnergy>>tmpHist', '', 'goff') hist = gDirectory.Get('tmpHist') #print ( fileName ) #print ('nevent: %i ' % (entries)) return energyFit( hist )
def histdivider(tree, title, var, cut1, cut2): """ returns a histogram of the two histograms associated with the two variables with their own cut the returned hist will be hist1/hist2 """ tree.Project('hist{t}'.format(t=title), var, cut1) tree.Project('tmphist{t}'.format(t=title), var, cut2) divided_hist = gDirectory.Get('hist{t}'.format(t=title)) divided_hist.Divide(gDirectory.Get('tmphist{t}'.format(t=title))) divided_hist.SetTitle(title) divided_hist.SetStats(False) return divided_hist
def makeSCTBarrelPlots(fp, fs, pulls): c1 = TCanvas("c1", "c1", 971, 300) c1.Divide(2, 1) c1.cd(1) h1 = (gDirectory.Get("sct_b0_residualx")).Clone() h1.SetName("sct_b_residualx") h1.Add(gDirectory.Get("sct_b1_residualx")) h1.Add(gDirectory.Get("sct_b2_residualx")) h1.Add(gDirectory.Get("sct_b3_residualx")) h1.SetTitle(fs("SCT Barrel Residual X; Residual; Events")) t = gaussfit(h1, True) h1.UseCurrentStyle() h1.Draw("HIST") t[0].Draw("SAME") c1.cd(2) h2 = (gDirectory.Get("sct_b0_pullx")).Clone() h2.SetName("sct_b_pullx") h2.Add(gDirectory.Get("sct_b1_pullx")) h2.Add(gDirectory.Get("sct_b2_pullx")) h2.Add(gDirectory.Get("sct_b3_pullx")) h2.SetTitle(fs("SCT Barrel Pull X; Pull; Events")) t = gaussfit(h2, True) h2.UseCurrentStyle() h2.Draw("HIST") t[0].SetRange(-2.5, 2.5) t[0].Draw("SAME") pulls["sctbar"] = t[1:] c1.SaveAs(fp("sctBarrel.pdf")) c1.SaveAs(fp("sctBarrel.png")) c1.SaveAs(fp("sctBarrel.gif")) c1.SaveAs(fp("sctBarrel.eps"))
def draw_canvas_2d(name): f_mc = TFile("plots/mc/%s_mcc7.root" % name) h_mc = gDirectory.Get("h_%s_reco" % name) f = TFile("plots/data/e_%s_pandoraCosmic.root" % name) h = gDirectory.Get("h_%s" % name) h.Divide(h_mc) h.GetZaxis().SetRangeUser(0.5, 1.5) #h.GetZaxis().SetTitle("Data/Monte Carlo") #h.GetZaxis().RotateTitle() h.SetMarkerSize(2) x_minbin = h.FindFirstBinAbove(0, 1) low_x = h.GetXaxis().GetBinLowEdge(x_minbin) x_maxbin = h.FindLastBinAbove(0, 1) high_x = h.GetXaxis().GetBinUpEdge(x_maxbin) y_minbin = h.FindFirstBinAbove(0, 2) low_y = h.GetYaxis().GetBinLowEdge(y_minbin) y_maxbin = h.FindLastBinAbove(0, 2) high_y = h.GetYaxis().GetBinUpEdge(y_maxbin) h.GetXaxis().SetRangeUser(low_x, high_x) h.GetYaxis().SetRangeUser(low_y, high_y) c = TCanvas("c_%s" % name) h.SetMarkerSize(2.5) gPad.SetBottomMargin(0.17) gPad.SetLeftMargin(0.13) gPad.SetTopMargin(0.15) gPad.SetRightMargin(0.15) h.GetYaxis().SetTitleSize(0.07) h.GetXaxis().SetTitleSize(0.07) h.GetYaxis().SetTitleOffset(0.8) pt = TPaveText(0.13, 0.855, 0.42, 0.98, "ndc") pt.AddText("MicroBooNE") pt.SetFillColor(0) pt.SetBorderSize(0) pt.SetShadowColor(0) h.Draw("colz texte") pt.Draw() c.Update() c.SaveAs("plots/%s.pdf" % name) c.SaveAs("plots/%s.p" % name) return c
def calc_delta_stats_same_tracks(run_id, use_wrapping=True): """Calculates differences in orientation of fields when tracks are the same""" hit_trees = [] root_files = [] for is_parallel in [True, False]: if is_parallel: letter = 'P' else: letter = 'A' file_path = srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_files.append(TFile(file_path, "READ")) hit_trees.append(gDirectory.Get('hitTree')) gROOT.cd() delta_phi_list = [] for i in xrange(hit_trees[0].GetEntries()): hit_trees[0].GetEntry(i) hit_trees[1].GetEntry(i) delta_phi = hit_trees[0].phi - hit_trees[1].phi delta_phi_list.append(delta_phi) if use_wrapping: delta_phi_mean = srkmisc.reduce_periodics(delta_phi_list) else: delta_phi_mean = srkmisc.careful_mean(delta_phi_list) delta_phi_std = srkmisc.careful_std(delta_phi_list) root_files[0].Close() root_files[1].Close() return [delta_phi_mean, delta_phi_std]
def make_alpha_vs_phi_plot(run_id, is_parallel): if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() phi_list = [] alpha_list = [] radius = srkdata.get_data_for_rids_from_database([run_id], "ChamberRadius")[0][0] print radius for i in xrange(num_events): hit_tree.GetEntry(i) phi_list.append(hit_tree.phi) alpha = get_alpha_angle_2d(radius, hit_tree.pos0, hit_tree.vel0) alpha_list.append(alpha) root_file.Close() phi_mean = srkmisc.reduce_periodics(phi_list) delta_phi_list = map(lambda x: x - phi_mean, phi_list) plt.scatter(alpha_list, delta_phi_list)
def addRuns(self): # Read summary histogram hin = gDirectory.Get('readyMuDist') if hin == None: print 'No mu histogram found for run', run return hin.Print() # Check bin 1 bin1 = hin.GetBinContent(1) if bin1 > 100: print '==> Zero bin: %f' % bin1 if self.hout == None: print 'Creating new output histogram' self.out = TFile(self.outFile, 'recreate') self.hout = TH1D(hin) self.hout.SetName(self.houtName) else: self.hout.Add(hin) return
def get_result_data(leaf_names, run_id, is_parallel): """Get result data directly from root files based on leaf names""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( run_id) + "_" + letter + ".root" print "Opening ", file_path if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return {} root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() num_events = hit_tree.GetEntries() data = [] for leaf_name in leaf_names: temp_data = [] for i in xrange(num_events): hit_tree.GetEntry(i) temp_data.append( hit_tree.GetBranch(leaf_name).GetListOfLeaves()[0].GetValue()) data.append(temp_data) root_file.Close() return data
def splitTree(): dsNum, subNum = 0, 25 inPath = "/global/homes/w/wisecg/project/waveskim/waveSkimDS%d_%d.root" % (dsNum, subNum) outPath = "./cutSkimDS%d_%d.root" % (dsNum, subNum) inFile = TFile(inPath) bigTree = inFile.Get("skimTree") theCut = inFile.Get("theCut").GetTitle() bigTree.Draw(">>elist",theCut,"entrylist") elist = gDirectory.Get("elist") bigTree.SetEntryList(elist) nList = elist.GetN() outFile = TFile(outPath,"RECREATE") lilTree = TTree() lilTree.SetMaxTreeSize(150000000) lilTree = bigTree.CopyTree("") lilTree.Write("",TObject.kOverwrite) thisCut = TNamed("theCut",theCut) thisCut.Write()
def make_txt_hist_from_root_file(file_path_txt, rid, is_parallel, draw_string, hist_dim, cut_string="", option_string="", titles=("", "", "")): """Given a draw/cut string, take an SRK ROOT results file and create a histogram from it.""" if is_parallel: letter = 'P' else: letter = 'A' file_path = srkdata.srkglobal.results_dir + "Results_RID" + str( rid) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() histogram = TH1D("tempHist", "tempHist", hist_dim[0], hist_dim[1], hist_dim[2]) total_draw_string = draw_string + " >> tempHist" hit_tree.Draw(total_draw_string, cut_string, option_string) make_txt_from_hist(file_path_txt, histogram, titles) root_file.Close() return
def make_root_plot_from_results_file(rid, is_parallel, draw_string, cut_string="", option_string=""): """Makes a ROOT plot from results file based on a draw and cut string.""" # gStyle.SetOptStat("iMRKS") if is_parallel: letter = 'P' else: letter = 'A' file_path = srkglobal.results_dir + "Results_RID" + str( rid) + "_" + letter + ".root" if not srkmisc.file_exits_and_not_zombie(file_path): print file_path + " doesn't exist or is zombie." return root_file = TFile(file_path, "READ") hit_tree = gDirectory.Get('hitTree') gROOT.cd() c1 = rootnotes.canvas("Canvas", (1200, 800)) hit_tree.Draw(draw_string, cut_string, option_string) root_file.Close() return c1
def fillTree(self, name, event, specific = None): #determine if we need all event info or only part keys = event.keys() if specific is not None: keys = specific #if we haven't made the tree, create it and set it up if name not in self.myTrees.keys(): print 'creating tree %s'%name self.myTrees[name] = TTree(name,name) gDirectory.Add(self.myTrees[name]) self.myTrees[name] = gDirectory.Get(name) #create the struct we bind to our branches stct = self._makeStruct(name,keys,event) if len(stct) > 0: gROOT.ProcessLine('.L %s_vars.C'%(name)) else: gROOT.ProcessLine(stct) gROOT.ProcessLine('%s_vars %s_vars_holder;'%(name,name)) self.myStructs[name] = getattr(ROOT,"%s_vars"%(name))() #bind branches to the members of the struct we've created self._bindBranches(name,keys,event) self.myTrees[name].SetCacheSize() #we are now done setting up the tree (if needed) -> set values and fill if isinstance(event,dict): for key in keys: if hasattr(self.myStructs[name],key): setattr(self.myStructs[name],key,event[key]) else: self.myDicts[name][key] = event[key] self.myTrees[name].SetBranchAddress(key, self.myDicts[name][key]) self.myTrees[name].Fill()
def setEventList(cut=None): print 'now browsing the full tree... might take a while, but drawing will then be faster!' events.Draw('>>pyplus', cut) from ROOT import gDirectory pyplus = gDirectory.Get('pyplus') pyplus.SetReapplyCut(True) events.SetEventList(pyplus)
def setEventList(tree, cut=None): '''to undo, call tree.SetEventList(0)''' print 'now browsing the full tree... might take a while, but drawing will then be faster!' tree.Draw('>>pyplus', cut) pyplus = gDirectory.Get('pyplus') pyplus.SetReapplyCut(True) tree.SetEventList(pyplus)
def makeIBLPlots(fp, fs, pulls): c1 = TCanvas("c1", "c1", 971, 600) c1.Divide(2, 2) c1.cd(1) h1 = (gDirectory.Get("pix_b0_residualx")).Clone() h1.SetTitle(fs("IBL Residual X; Residual; Events")) t = gaussfit(h1, False) h1.UseCurrentStyle() h1.Draw("HIST") t[0].Draw("SAME") c1.cd(2) h2 = (gDirectory.Get("pix_b0_pullx")).Clone() h2.SetTitle(fs("IBL Pull X; Pull; Events")) t = gaussfit(h2, True) h2.UseCurrentStyle() h2.Draw("HIST") t[0].SetRange(-2.5, 2.5) t[0].Draw("SAME") pulls["iblx"] = t[1:] c1.cd(3) h3 = (gDirectory.Get("pix_b0_residualy")).Clone() h3.SetTitle(fs("IBL Residual Y; Residual; Events")) t = gaussfit(h3, False) h3.UseCurrentStyle() h3.Draw("HIST") t[0].Draw("SAME") c1.cd(4) h4 = (gDirectory.Get("pix_b0_pully")).Clone() h4.SetTitle(fs("IBL Pull Y; Pull; Events")) t = gaussfit(h4, True) h4.UseCurrentStyle() h4.Draw("HIST") t[0].SetRange(-2.5, 2.5) t[0].Draw("SAME") pulls["ibly"] = t[1:] c1.SaveAs(fp("IBL.pdf")) c1.SaveAs(fp("IBL.png")) c1.SaveAs(fp("IBL.gif")) c1.SaveAs(fp("IBL.eps"))
def getCovarianceElement(self, var1, var2): celement = 0.0 #Don't want to output the draws gROOT.SetBatch(True) self.rchain.Draw(var1+">>var1mean") v1h = gDirectory.Get("var1mean") var1mean = v1h.GetMean() self.rchain.Draw(var2+">>var2mean") v2h = gDirectory.Get("var2mean") var2mean = v2h.GetMean() for i in xrange(self.rchain.GetEntries()): self.rchain.GetEntry(i) v1 = float(getattr(self.rchain,var1)) v2 = float(getattr(self.rchain,var2)) celement = celement + ((v1 - var1mean)*(v2-var2mean)) Normalization = 1.0/(float(self.rchain.GetEntries())-1.0) return Normalization*celement
def retrieveHistogram(inputFile, h_Path, h_Name): h_file = TFile(inputFile) gDirectory.cd(h_Path) h = gDirectory.Get(h_Name) h.SetDirectory(0) return h
def ScaleToInt(histos, varControl): for sample in histos: histo = gDirectory.Get(histos[sample]) #histo=histos[sample] norm = histo.GetSumOfWeights() if (norm < 0.0001): norm = 1.0 if varControl is False: histo.Scale(1 / norm) if norm < 10: histo.Scale(0.1)
def findYrange(hdict, scaleFactor): yMax = 0 for samp in hdict: histo = gDirectory.Get(hdict[samp]) histo.Rebin(scaleFactor) ymaxBin = histo.GetMaximumBin() yMax = max(yMax, histo.GetBinContent(ymaxBin)) return yMax
def ReadRootFile(self, RootFileDir, bool=False): """HVMapNoise.ReadRootFile(string RootFileDir[, bool bool]) Reads in the path of a .root file of pedestal run noise and stores it in self.noise. If bool is true then data taken in peak mode is multiplied by 1.7""" #make varibles to keep track of dictionary keys RunT = RootFileDir.split('/')[-1].split('-')[1] SubD = RootFileDir.split('/')[-1].split('-')[2] #intialize varible to record the number of entries read from RootFile Ndet = 0 # Open the file: myfile = TFile(RootFileDir, 'r') # retrieve the ntuple of interest mychain = gDirectory.Get('tree') entries = mychain.GetEntriesFast() #Loop over the trees entries for jentry in xrange(entries): #get the tree from the chain ientry = mychain.LoadTree(jentry) #copy the entry in to memory and verify nb = mychain.GetEntry(jentry) #use the values directly from the tree detID = str(mychain.DETID) APVID = int(mychain.APVID) NoiseMean = mychain.NOISEMEAN #compensate for effects of detector DAQ mode on noise means if bool: if 'PEAK' in RootFileDir: NoiseMean = NoiseMean * 1.7 #Add to dictionary and check for detID/APVID uniqueness if RunT not in self.Noise.keys(): self.Noise.update({RunT: {SubD: {detID: {APVID: NoiseMean}}}}) Ndet = Ndet + 1 elif SubD not in self.Noise[RunT].keys(): self.Noise[RunT].update({SubD: {detID: {APVID: NoiseMean}}}) Ndet = Ndet + 1 elif detID not in self.Noise[RunT][SubD].keys(): self.Noise[RunT][SubD].update({detID: {APVID: NoiseMean}}) Ndet = Ndet + 1 else: if APVID not in self.Noise[RunT][SubD][detID].keys(): self.Noise[RunT][SubD][detID].update({APVID: NoiseMean}) else: print "Warning: in year: ", Year, ',', " detID: ", RunT, SubD, detID, " has found two noise mean entries for APVID: ", APVID, " could indicate file copy/naming error!" myfile.Close() print "Done reading in ", Ndet, " detIDs from", RootFileDir.split( '/')[-1]
def plotstuff(var, cut, maxsig, plotname): c.Clear() c.Divide(1, 2) c.cd(1) events.Draw(var, cut, "colz") hnew = gDirectory.Get("hnew") hnew.FitSlicesY() hnew.SetTitle(plotname) hnew.GetXaxis().SetTitle("momentum [GeV]") hnew.GetYaxis().SetTitle("DOCA [mm]") hnew_1 = gDirectory.Get("hnew_2") c.cd(2) hnew_1.Draw() hnew_1.Fit("fitfunc", "", "", 0.2, 0.75) hnew_1.GetYaxis().SetRangeUser(0, maxsig) hnew_1.GetXaxis().SetTitle("momentum [GeV]") hnew_1.GetYaxis().SetTitle("DOCA resolution [mm]") c.Print(remainder[0] + ".pdf", "Title:top_yz")
def drawAndPrint(var, altname=''): if len(altname) < 1: altname = var data.Draw(var + '>>' + altname + '(30)', var + ' != -9999.99', 'PE') h = gDirectory.Get(altname) h.SetMarkerStyle(20) if (altname[-5:] == '_bias') and (altname[0] == 'n'): print altname, 'mean:', h.GetMean() if (altname[-5:] == '_pull') and (opts.fitPull): fitfunc = 'gaus(0)/sqrt(TMath::TwoPi())/[2]' gfit = TF1('gfit', fitfunc, h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax()) gfit.SetParameters(1.0, h.GetMean(), h.GetRMS()) gfit.FixParameter(0, 1.0) data.UnbinnedFit('gfit', var, '', 'E') gfit2 = TF1('gfit2', fitfunc, h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax()) gfit2.SetParameter(0, 1.0) gfit2.FixParameter(1, gfit.GetParameter(1)) gfit2.FixParameter(2, gfit.GetParameter(2)) h.Fit('gfit2', 'LN0Q') gfit.FixParameter(0, gfit2.GetParameter(0)) L = TLatex() L.SetNDC() L.SetTextSize(0.04) L.SetTextAlign(12) h.Draw('PE') gfit.Draw('same') L.DrawLatex(0.12, 0.85, "<x>: %4.3f #pm %4.3f" % \ (gfit.GetParameter(1), gfit.GetParError(1))) L.DrawLatex(0.12, 0.8, "#sigma_{x}: %4.3f #pm %4.3f" % \ (gfit.GetParameter(2), gfit.GetParError(2))) c.Modified() sums = '' errs = '' errstr = '' trues = '' if ((altname[:4] == 'nsig') or (altname[:5] == 'nbkgd')) and \ (altname[-4:] != '_err') and (altname[-5:] != '_pull') and \ (altname[-5:] != '_bais'): mean = h.GetMean() rms = h.GetRMS() errstr = '%s mean: %5.3f rms: %5.3f fractional err: %6.4f' % ( altname, mean, rms, rms / mean) #print errstr #if (var == altname): sums = altname + '+' errs = (altname + '_err*') * 2 errs = errs[:-1] + '+' trues = altname + '_true+' c.Update() c.Print(opts.plotdir + '/' + altname + '.png') c.Print(opts.plotdir + '/' + altname + '.pdf') return errstr, sums, errs, trues
def findBeamCaloCoords(data): from ROOT import gDirectory data.Draw('maxEtaHB>>maxEtaHB(16,0.5,16.5)', 'triggerID==4', 'goff') temph = gDirectory.Get('maxEtaHB') ieta = findBeamCenter(temph) data.Draw('maxEtaEB>>maxEtaEB(50,0.5,50.5)', 'triggerID==4', 'goff') temph = gDirectory.Get('maxEtaEB') xtalieta = findBeamCenter(temph) data.Draw('maxPhiHB>>maxPhiHB(10,0.5,10.5)', 'triggerID==4', 'goff') temph = gDirectory.Get('maxPhiHB') iphi = findBeamCenter(temph) data.Draw('maxPhiEB>>maxPhiEB(21,0.5,21.5)', 'triggerID==4', 'goff') temph = gDirectory.Get('maxPhiEB') xtaliphi = findBeamCenter(temph) return (int(ieta), int(iphi), int(xtalieta), int(xtaliphi))
def buildArraysFromROOT(tree, allowedFeatures, cut, skipEvents, maxEvents, name): dataContainer = {} featureNames = [] eventCounter = -1 gROOT.Reset() # Get branch names for item in tree.GetListOfBranches(): featureName = item.GetName() if featureName in allowedFeatures: featureNames.append(featureName) dataContainer[featureName] = [] # Build the event list tcut = TCut(cut) tree.Draw(">>eventList", tcut) eventList = TEventList() eventList = gDirectory.Get("eventList") nSelectedEvents = eventList.GetN() # Event loop for i in range(0, nSelectedEvents): if (i < skipEvents): continue if (i % 100 == 0): sys.stdout.write("Reading %s: %d%% \r" % (tree.GetName(), 100 * i / (maxEvents + skipEvents))) sys.stdout.flush() if i >= (maxEvents + skipEvents): break selectedEvNum = eventList.GetEntry(i) tree.GetEntry(selectedEvNum) for feature in featureNames: dataContainer[feature].append(tree.__getattr__(feature)) sys.stdout.write("\n") # Make the numpy arrays outputArray = np.array([]) for feature in allowedFeatures: column = dataContainer[feature] feature_vector = np.asarray(column) feature_vector = feature_vector.reshape(feature_vector.size, 1) if outputArray.shape[0] == 0: outputArray = feature_vector else: outputArray = np.concatenate((outputArray, feature_vector), axis=1) imp = Imputer(missing_values=-999, strategy='mean', axis=0) imp.fit(outputArray) outputArray = imp.transform(outputArray) print name print "Events: ", outputArray.shape[0] print "Features: ", outputArray.shape[1] return outputArray