def finish(self): del self.fitter print 'finished writing tree' self.sTree.Write() ut.errorSummary() ut.writeHists(h,"recohists.root") if realPR: ut.writeHists(shipPatRec.h,"recohists_patrec.root")
def flukaRateIntegrated(save=False): fntuple = ROOT.TFile.Open('neutronsTI18.root') h['Fig12'] = ROOT.TGraph() h['neutronRate'] = ROOT.TGraph() h['N'] = ROOT.TGraph() n = 0 for nt in fntuple.nt: # nt.N = [cm/MeV] E = (nt.Eleft + nt.Eright) / 2. dE = nt.Eright - nt.Eleft h['Fig12'].SetPoint(n, ROOT.TMath.Log10(E), E * nt.N) h['neutronRate'].SetPoint(n, ROOT.TMath.Log10(E), dE * nt.N) h['N'].SetPoint(n, E, dE * nt.N) n += 1 S = 0 h['neutronRate<E'] = h['neutronRate'].Clone('S') for n in range(h['neutronRate'].GetN() - 1, -1, -1): S += h['neutronRate'].GetY()[n] h['neutronRate<E'].SetPoint(n, h['neutronRate'].GetX()[n], S) h['neutronRate<E%'] = h['neutronRate'].Clone('S%') for n in range(h['neutronRate<E'].GetN()): h['neutronRate<E%'].SetPoint( n, h['neutronRate<E'].GetX()[n], h['neutronRate<E'].GetY()[n] / h['neutronRate<E'].GetY()[0]) ut.bookHist(h, 'Nr', ';E [MeV];dn/dlogE [cm^{-2}y^{-1}] ', 100, -12., 2.) h['Nr'].SetMaximum(1.1) h['Nr'].SetMinimum(0.) h['Nr'].SetStats(0) h['Nr'].SetTitle('; log10(E [MeV]();N(E>x)/total') h['neutronRate<E%'].SetLineWidth(2) h['Nr'].Draw() h['neutronRate<E%'].Draw('same') if save: ut.writeHists(h, 'flukaNeutronRates')
def run1GeV(): tmp = "pythia8_Geant4_1.0_cXX.root" global weight weight = weightMbias1GeV for run in range(0,19000,1000): rc = processFile(tmp.replace('XX',str(run))) ut.writeHists(h,'pythia8_Geant4_1.0_c0-19000_nu.root')
def muonSpect(): inputFiles() for x in h["datasets"]: for ori in h["cuts"]: for p in ["P", "Pt"]: hn = x + p + ori print "work on histogram", hn if p == "P": ut.bookHist(h, hn, "muon momentum " + ori + " " + p, 80, 0.0, 400.0) h[hn].SetYTitle("[N/5GeV/c/spill]") h[hn].SetXTitle("P [GeV/c]") else: ut.bookHist(h, hn, "muon momentum " + ori + " " + p, 100, 0.0, 5.0) h[hn].SetYTitle("[N/50MeV/c/spill]") h[hn].SetXTitle("Pt [GeV/c]") h[hn].SetStats(0) h[hn].SetLineWidth(2) ROOT.gROOT.cd() sTree = h[x].FindObjectAny("pythia8-Geant4") if p == "P": sTree.Draw( "sqrt(px*px+py*py+pz*pz)>>" + hn, "w*(" + h["cuts"][ori] + "&&sqrt(px*px+py*py+pz*pz)>0.5)" ) else: sTree.Draw("sqrt(px*px+py*py)>>" + hn, "w*(" + h["cuts"][ori] + "&&sqrt(px*px+py*py+pz*pz)>0.5)") h.pop("datasets") h.pop("cuts") ut.writeHists(h, "muSpectrum.root")
def bckgOnly(): subdir = 'disV' tmp = "ship.10.0.muonDIS-TGeant4_Ana.pkl" flist = [] for r in ['10','20','40','30']: for i in range(10): theFile = subdir+r+str(i)+'/'+tmp if os.path.exists(theFile): flist.append(theFile) for f in flist: fp = open(f) weightsUsed = pickle.load(fp) bckg = pickle.load(fp) fp.close() if len(bckg)==0: continue inputFile = f.replace('Ana','rec').replace('pkl','root') ft = ROOT.TFile(inputFile) global sTree sTree = ft.cbmsim print "==> input file ",f nold = -1 for nb in bckg: if nb != nold: nold = nb myEventLoop(nb) ft.Close() makePlots() makeV0Plots() makePlotsForTP() ut.writeHists(h,"ship.10.0.muonDIS-TGeant4_Ana-bckgr.root")
def readHists(prods=['disV50','disV60','disV70','disV80','disCLBY0','disCLBY1','disCLBY2','disCLBY3']): first = True if not os.uname()[1].find('ubuntu')<0: path = '/media/Data/HNL/' sdir = {'disV':'muVetoDIS','disCLBY':'clbyDIS','disEM':'muVetoEM'} else: path = '/afs/cern.ch/project/lbcern/vol2/truf/' sdir = {'disV':'muVDIS','disCLBY':'clbyDIS','disEM':'muVetoEM'} sweights = {'disV':1E4,'disCLBY':5*1E3,'disEM':1E3} # known productions: # muDIS ship.10.0.muonDIS-TGeant4V10X_rec.root # clby ship.10.0.muonDIS-TGeant4_Ana_disCLBY30.root # nu in air: ship.10.0.Genie-TGeant4_neutrino_82X_Ana.root listOfFiles = [] tmp = "ship.10.0.muonDIS-TGeant4_Ana.root" for r in prods: for x in sdir: if x in r: subdir = path+sdir[x]+'/' for i in range(1,10): theFile = subdir+r+str(i)+'/'+tmp if os.path.exists(theFile): listOfFiles.append(theFile) for outFileH in listOfFiles: print 'read histograms from ',outFileH for x in sdir: if x in outFileH: sweight = sweights[x] ut.readHists(h,outFileH) outFileP = outFileH.replace('.root','.pkl') f = open(outFileP) if first: first = False weightsUsed = pickle.load(f) for wkey in weightsUsed: weightsUsed[wkey][1]=weightsUsed[wkey][1]*sweight else: temp = pickle.load(f) for wkey in temp: if not weightsUsed.has_key(wkey) : weightsUsed[wkey]=[0,0] weightsUsed[wkey][0]+= temp[wkey][0] weightsUsed[wkey][1]+= temp[wkey][1]*sweight makePlots() makeV0Plots() makePlotsForTP() print "Analysis of weights" # weightsUsed[wkey][0]+= Nexptected # sum of expected muon interactions # weightsUsed[wkey][1]+= 1. # counts how often a muon weight had been used print "weight sum of weights sum of entries mean" for wkey in weightsUsed: mean = weightsUsed[wkey][0]/weightsUsed[wkey][1] print wkey, weightsUsed[wkey], mean # print "corresponding pot: %10.2G"%(2E15/wkey/mean*1E4*60) # ??? discovered 5 August, why 2E15? should be 5E13!!! print "corresponding pot: %10.2G * number of iterations(2*30) * reuse of muon 1E4 * 2(like sign)"%(5E13/wkey/mean) print " == %10.2G"%(5E13/wkey/mean*60*2*2) # 60 == 30 x CERN/Yandex statistics, 2 iterations, 2 like sign # print "veto counters" for c in vetoDets: print c,h['IP0/mass-'+c].GetEntries() # save the summed histos fsum = "ship.10.0.muonDIS-TGeant4_Ana-Prods"+str(len(prods))+".root" ut.writeHists(h,fsum,plusCanvas=True)
def finish(self): del self.fitter print 'finished writing tree' self.sTree.Write() ut.errorSummary() ut.writeHists(h, "recohists.root") if realPR: shipPatRec.finalize()
def finish(self): del self.fitter print('finished writing tree') self.sTree.Write() ut.errorSummary() ut.writeHists(global_variables.h,"recohists.root") if global_variables.realPR: shipPatRec.finalize()
def run4Charm(): tmp = "pythia8_Geant4_charm_XX-YY_10.0.root" global weight weight = weightCharm for cycle in [0,1,2]: for run in range(0,100,20): crun = run+cycle*1000 fname = tmp.replace('XX',str(crun)).replace('YY',str(crun+19)) rc = processFile(fname,False) ut.writeHists(h,'pythia8_Geant4_charm_10.0_nu.root')
def save_hists(h, path): """ Save book of plots. Parameters ---------- h : dict Dictionary of plots. path : string Path where the plots will be saved. """ ut.writeHists(h, path)
def analyze(): ut.bookHist(h,'PinPout','pin pout',105,-0.5,10.,105,-0.5,10.) f=ROOT.TFile(outFile) sTree = f.cbmsim for n in range(sTree.GetEntries()): rc = sTree.GetEvent(n) mu = sTree.MCTrack[0] Pout = -0.49 for v in sTree.vetoPoint: if v.GetTrackID()==0: if v.LastPoint()[2]>119.9: Pout = v.LastMom().Mag() rc = h['PinPout'].Fill(mu.GetP(),Pout) ut.writeHists(h,'PinPout.root')
def addAllHistograms(): h={} ecut = '10.0' Nmax=45000 path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/" ut.bookCanvas(h,key='canvas',title='debug',nx=1600,ny=1200,cx=1,cy=1) h['canvas'].SetLogy(1) for i in range(0,Nmax,1000): fname = "pythia8_Geant4_"+ecut+"_c"+str(i)+".root" ut.readHists(h,path+fname) if i==0: h[1012].Draw() for x in h.keys(): if h[x].GetName().find('proj')>0: rc = h.pop(x) ut.writeHists(h,"pythia8_Geant4_"+ecut+"_c"+str(Nmax)+"-histos.root")
def addAllHistograms(): h={} ecut = '10.0' Nmax=45000 path = os.environ['EOSSHIP']+"/eos/experiment/ship/data/Mbias/background-prod-2018/" ut.bookCanvas(h,key='canvas',title='debug',nx=1600,ny=1200,cx=1,cy=1) h['canvas'].SetLogy(1) for i in range(0,Nmax,1000): fname = "pythia8_Geant4_"+ecut+"_c"+str(i)+".root" ut.readHists(h,path+fname) if i==0: h[1012].Draw() tmp = h.keys() for x in tmp: if h[x].GetName().find('proj')>0: rc = h.pop(x) ut.writeHists(h,"pythia8_Geant4_"+ecut+"_c"+str(Nmax)+"-histos.root")
def start(): bookHists() nEvents = sTree.GetEntries() # for x in sTree.GetListOfBranches(): sTree.SetBranchStatus(x.GetName(),0) for n in range(nEvents): myEventLoop(n) sTree.FitTracks.Delete() makePlots() # output histograms outFileH = inputFile.replace('rec','Ana') outFileP = outFileH.replace('.root','.pkl') ut.writeHists(h,outFileH) print "Analysis of weights" print "weight sum of weights sum of entries mean" for wkey in weightsUsed: print wkey, weightsUsed[wkey], weightsUsed[wkey][0]/weightsUsed[wkey][1] fpi=open(outFileP,'w') pickle.dump(weightsUsed,fpi) if not signal: pickle.dump(bckg,fpi) fpi.close()
def makeHistos(rfile): f=ROOT.TFile.Open(rfile) sTree = f.cbmsim nTot = 0 for k in f.GetListOfKeys(): if k.GetName() == 'FileHeader': tmp = k.GetTitle().split('=')[1] tmp2 = tmp.split('with')[0] if tmp2.find('E')<0: nTot += int(tmp2) else: nTot += float(tmp2) print("POT = ",nTot," number of events:",sTree.GetEntries()) # particle statistics h={} ut.bookHist(h,'pids','pid',19999,-9999.5,9999.5) ut.bookHist(h,'test','muon p/pt',100,0.,400.,100,0.,5.) diMuonDecays = [221, 223, 113, 331, 333] pDict = {} procDict = {} for n in range(sTree.GetEntries()): rc = sTree.GetEvent(n) for p in sTree.vetoPoint: t = sTree.MCTrack[p.GetTrackID()] pid = t.GetPdgCode() rc = h['pids'].Fill(pid) if abs(pid)==13: procID = t.GetProcName().Data() mother = t.GetMotherId() if not mother < 0: moPid = sTree.MCTrack[mother].GetPdgCode() name = pdg.GetParticle(moPid).GetName() name = procID+' '+name if name not in h: h[name]=h['test'].Clone(name) rc=h[name].Fill(t.GetP(),t.GetPt()) if procID not in h: h[procID]=h['test'].Clone(procID) rc=h[procID].Fill(t.GetP(),t.GetPt()) for x in h: h[x].Scale(1./nTot) tmp = rfile.split('/') hname = tmp[len(tmp)-1].replace('pythia8_Geant4','Histos') ut.writeHists(h,hname)
def makeHistos(rfile): f=ROOT.TFile.Open(rfile) sTree = f.cbmsim nTot = 0 for k in f.GetListOfKeys(): if k.GetName() == 'FileHeader': tmp = k.GetTitle().split('=')[1] tmp2 = tmp.split('with')[0] if tmp2.find('E')<0: nTot += int(tmp2) else: nTot += float(tmp2) print "POT = ",nTot," number of events:",sTree.GetEntries() # particle statistics h={} ut.bookHist(h,'pids','pid',19999,-9999.5,9999.5) ut.bookHist(h,'test','muon p/pt',100,0.,400.,100,0.,5.) diMuonDecays = [221, 223, 113, 331, 333] pDict = {} procDict = {} for n in range(sTree.GetEntries()): rc = sTree.GetEvent(n) for p in sTree.vetoPoint: t = sTree.MCTrack[p.GetTrackID()] pid = t.GetPdgCode() rc = h['pids'].Fill(pid) if abs(pid)==13: procID = t.GetProcName().Data() mother = t.GetMotherId() if not mother < 0: moPid = sTree.MCTrack[mother].GetPdgCode() name = pdg.GetParticle(moPid).GetName() name = procID+' '+name if not h.has_key(name): h[name]=h['test'].Clone(name) rc=h[name].Fill(t.GetP(),t.GetPt()) if not h.has_key(procID): h[procID]=h['test'].Clone(procID) rc=h[procID].Fill(t.GetP(),t.GetPt()) for x in h: h[x].Scale(1./nTot) tmp = rfile.split('/') hname = tmp[len(tmp)-1].replace('pythia8_Geant4','Histos') ut.writeHists(h,hname)
def executeOneFile(fn,output=None,pid=None): f = ROOT.TFile.Open(fn) sTree = f.cbmsim nEvents = sTree.GetEntries() if sTree.GetBranch("GeoTracks"): sTree.SetBranchStatus("GeoTracks",0) sTree.GetEntry(0) hitContainers = [sTree.vetoPoint,sTree.muonPoint,sTree.EcalPointLite,sTree.strawtubesPoint,sTree.ShipRpcPoint,sTree.TargetPoint] ntot = 0 for n in range(nEvents): rc = sTree.GetEntry(n) theMuon = sTree.MCTrack[0] if sTree.MCTrack.GetEntries() > 1: w = sTree.MCTrack[1].GetWeight() # also works for neutrinos else: print 'should not happen with new files',n,fn w = sTree.MCTrack[0].GetWeight() # also works for neutrinos if w==0 : w = 1. rc = h['weight'].Fill(w) rc = h['muonP'].Fill(theMuon.GetP()/u.GeV,w) ntot+=1 if ntot%10000 == 0 : print 'read event',f.GetName(),n hitmult = {} esum = 0 for mcp in sTree.MCTrack: if mcp.GetMotherId() == 0: # mother is original muon E = mcp.GetEnergy() if mcp.GetPdgCode() == 11: rc = h['deltaElec'].Fill(E,w) esum += E rc = h['secondaries'].Fill(E,w) rc = h['prop_deltaElec'].Fill(esum/sTree.MCTrack[0].GetP(),w) # until energy is really made persistent GetEnergy() for c in hitContainers: for ahit in c: if not ahit.GetEnergyLoss()>0: continue detID = ahit.GetDetectorID() if ahit.GetName() == 'strawtubesPoint': tmp = strawEncoding(detID) # detName = str(tmp[0]*10000000+tmp[1]*1000000+tmp[2]*100000+tmp[3]*10000) detName = "strawstation_"+str(tmp[0]) x = ahit.GetX() y = ahit.GetY() E = ahit.GetEnergyLoss() elif ahit.GetName() == 'ecalPoint': # not needed for lite collection: if abs(ahit.GetPdgCode())==12 or abs(ahit.GetPdgCode())==14 : continue detName = 'Ecal' ecal.GetCellCoordForPy(detID,pos) x = pos.X() y = pos.Y() E = ahit.GetEnergyLoss() else: if not logVols.has_key(detID): detName = c.GetName().replace('Points','') if not detName in histlistAll.values(): print detID,detName,c.GetName() else: detName = logVols[detID] x = ahit.GetX() y = ahit.GetY() z = ahit.GetZ() E = ahit.GetEnergyLoss() if not h.has_key(detName): bookHist(detName) mu='' pdgID = -2 if 'PdgCode' in dir(ahit): pdgID = ahit.PdgCode() trackID = ahit.GetTrackID() phit = -100. mom = ROOT.TVector3() if not trackID < 0: aTrack = sTree.MCTrack[trackID] pdgID = aTrack.GetPdgCode() aTrack.GetMomentum(mom) # ! this is not momentum of particle at Calorimeter place phit = mom.Mag()/u.GeV if abs(pdgID)==13: mu='_mu' if ahit.GetName().find('ecal')<0: rc = ahit.Momentum(mom) phit = mom.Mag()/u.GeV else: for ahit in sTree.EcalPoint: if ahit.GetTrackID() == trackID: rc = ahit.Momentum(mom) phit = mom.Mag()/u.GeV if phit>3 and abs(pdgID)==13: mu='_muV0' detName = detName + mu if detName.find('LS')<0: rc = h[detName].Fill(x/u.m,y/u.m,w) else: rc = h[detName].Fill(ahit.GetZ()/u.m,ROOT.TMath.ATan2(y,x)/ROOT.TMath.Pi(),w) rc = h[detName+'_E'].Fill(E/u.MeV,w) if not hitmult.has_key(detName): hitmult[detName] = {-1:0} if not hitmult[detName].has_key(trackID): hitmult[detName][trackID] = 0 hitmult[detName][trackID] +=1 hitmult[detName][-1] +=1 rc = h[detName+'_id'].Fill(pdgID,w) rc = h[detName+'_P'].Fill(phit,w) rc = h[detName+'_LP'].Fill(phit,w) if not trackID < 0: r = ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m rc = h['origin'].Fill(aTrack.GetStartZ()/u.m,r,w) rc = h[detName+'_origin'].Fill(aTrack.GetStartZ()/u.m,r,w) if abs(pdgID)== 13: rc = h[detName+'_originmu'].Fill(aTrack.GetStartZ()/u.m,r,w) rc = h['borigin'].Fill(aTrack.GetStartZ()/u.m,r,w) rc = aTrack.GetMomentum(mom) rc = h[detName+'_OP'].Fill(mom.Mag()/u.GeV,w) if trackID > 0: origin(sTree,trackID) rc = h['porigin'].Fill(aTrack.GetStartZ()/u.m,ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m,w) rc = h['mu-inter'].Fill(rz_inter[1]/u.m,rz_inter[0]/u.m,w) for detName in hitmult: rc = h[detName+'_evmul'].Fill(hitmult[detName][-1],w) for tr in hitmult[detName]: rc = h[detName+'_mul'].Fill(hitmult[detName][tr],w) if output: ut.writeHists(h,'tmpHists_'+str(pid)+'.root') output.put('ok') f.Close()
def analyse(tree, outputfile): """Analyse tree to find hit positions and create histograms. Parameters ---------- tree Tree or Chain of trees with the usual `cbmsim` format outputfile : str Filename for the file in which the histograms are saved, will be overwritten Returns ------- std::vector<double> Vector of hit x-positions [cm] """ # TODO handle addition of new output files! r.gROOT.SetBatch(True) maxpt = 6.5 maxp = 360. h = {} ut.bookHist(h, 'mu_pos', '#mu- hits;x[cm];y[cm]', 100, -1000, +1000, 100, -800, 1000) ut.bookHist(h, 'anti-mu_pos', '#mu+ hits;x[cm];y[cm]', 100, -1000, +1000, 100, -800, 1000) ut.bookHist(h, 'mu_w_pos', '#mu- hits;x[cm];y[cm]', 100, -1000, +1000, 100, -800, 1000) ut.bookHist(h, 'anti-mu_w_pos', '#mu+ hits;x[cm];y[cm]', 100, -1000, +1000, 100, -800, 1000) ut.bookHist(h, 'mu_p', '#mu+-;p[GeV];', 100, 0, maxp) ut.bookHist(h, 'mu_p_original', '#mu+-;p[GeV];', 100, 0, maxp) ut.bookHist(h, 'mu_pt_original', '#mu+-;p_t[GeV];', 100, 0, maxpt) ut.bookHist(h, 'mu_ppt_original', '#mu+-;p[GeV];p_t[GeV];', 100, 0, maxp, 100, 0, maxpt) ut.bookHist(h, 'smear', '#mu+- initial vertex;x[cm];y[cm]', 100, -10, +10, 100, -10, 10) xs = r.std.vector('double')() i, n = 0, tree.GetEntries() print '0/{}\r'.format(n), fout = r.TFile.Open('gallery.root', 'recreate') fout2 = r.TFile.Open('misis.root', 'recreate') fout2.cd() outtuple = Ntuple( ('px', 'py', 'pz', 'x', 'y', 'z', 'opx', 'opy', 'opz', 'w'), name='MISIS') histz = Hist(100, -8000, -3000, title='#mu z position at origin') mom = r.TVector3() for event in tree: i += 1 if i % 1000 == 0: print '{}/{}\r'.format(i, n), original_muon = event.MCTrack[1] h['smear'].Fill(original_muon.GetStartX(), original_muon.GetStartY()) for hit in event.vetoPoint: draw = False if hit: if not hit.GetEnergyLoss() > 0: continue pid = hit.PdgCode() if hit.GetZ() > 2597 and hit.GetZ() < 2599 and abs(pid) == 13: hit.Momentum(mom) P = mom.Mag() / u.GeV y = hit.GetY() x = hit.GetX() if pid == 13: h['mu_pos'].Fill(x, y) else: h['anti-mu_pos'].Fill(x, y) x *= pid / 13. if (P > 1 and abs(y) < 5 * u.m and (x < 2.6 * u.m and x > -3 * u.m)): xs.push_back(x) w = np.sqrt((560. - (x + 300.)) / 560.) h['mu_p'].Fill(P) original_muon = event.MCTrack[1] h['mu_p_original'].Fill(original_muon.GetP()) h['mu_pt_original'].Fill(original_muon.GetPt()) h['mu_ppt_original'].Fill(original_muon.GetP(), original_muon.GetPt()) if pid == 13: h['mu_w_pos'].Fill(x, y, w) else: h['anti-mu_w_pos'].Fill(-x, y, w) if (P > 1) and (x < 2.6 * u.m) and (abs(y) < 5 * u.m): draw = 4 if pid > 0 else 6 if draw: graph_x, graph_y = graph_tracks(event) graph_x.SetLineColor(draw) graph_y.SetLineColor(draw) c = Canvas(1600, 900, name='c{}'.format(i)) multigraph = r.TMultiGraph( 'tracks_{}'.format(i), 'Tracks in acceptance and/or on wrong side;z [cm];x/y [cm]') graph_x.SetLineStyle(1) graph_x.SetMarkerStyle(20) graph_x.SetTitle('x-projection') graph_x.SetFillStyle(0) graph_y.SetTitle('y-projection') graph_y.SetLineStyle(2) graph_y.SetMarkerStyle(20) graph_y.SetFillStyle(0) multigraph.Add(graph_x, 'lp') multigraph.Add(graph_y, 'lp') multigraph.Draw('Alp') c.BuildLegend() fout.cd() c.Write() fout2.cd() hitlist = {} for hit in event.vetoPoint: if abs(hit.PdgCode()) != 13: continue lp = hit.LastPoint() lm = hit.LastMom() if lp.z() < 2597: hitlist[lp.z()] = [lp.x(), lp.y(), lm.Px(), lm.Py(), lm.Pz()] zs = hitlist.keys() if len(zs) > 1: zs.sort() if not hitlist: continue last_hit = hitlist[zs[-1]] if last_hit[4] > 0: a = array('f', (last_hit[2], last_hit[3], last_hit[4], last_hit[0], last_hit[1], zs[-1], original_muon.GetPx(), original_muon.GetPy(), original_muon.GetPz(), original_muon.GetWeight())) outtuple.fill(a) histz.fill(original_muon.GetStartZ(), original_muon.GetWeight()) print 'Loop done' ut.writeHists(h, outputfile) fout2.cd() outtuple.Write() histz.Write() return xs
print(">>>> proton statistics, ntagged=", ntagged['p']) generators['p'].stat() print(">>>> neutron statistics, ntagged=", ntagged['n']) generators['n'].stat() timer.Stop() rtime = timer.RealTime() ctime = timer.CpuTime() print("run ", options.run, " PoT ", options.NPoT, " Real time ", rtime, " s, CPU time ", ctime, "s") signal.Write() for g in generators: sigma = generators[g].info.sigmaGen(processes[0]) h['xsec_' + g].SetBinContent(1, sigma) ut.writeHists(h, hname + '.root') def na50(online=True): for g in generators: if online: processes = generators[g].info.codesHard() name = generators[g].info.nameProc(processes[0]) sigma = generators[g].info.sigmaGen(processes[0]) else: name = '' sigma = h['xsec_' + g].GetBinContent(1) yax = h['M_' + g].GetYaxis() xax = h['M_' + g].GetXaxis() Mmin = xax.FindBin(2.9) Mmax = xax.FindBin(4.5)
for iEvent in range(firstEvent, SHiP.nEvents): if iEvent % 1000 == 0 or debug: print 'event ', iEvent ntracks = SHiP.findTracks(iEvent) for x in caloTasks: if x.GetName() == 'ecalFiller': x.Exec('start', SHiP.sTree.EcalPointLite) elif x.GetName() == 'ecalMatch': x.Exec('start', ecalReconstructed, SHiP.sTree.MCTrack) else: x.Exec('start') SHiP.EcalClusters.Fill() SHiP.EcalReconstructed.Fill() SHiP.Pid.execute() if vertexing: # now go for 2-track combinations SHiP.Vertexing.execute() if debug: print 'end of event after Fill' # memory monitoring # mem_monitor() # end loop over events print 'finished writing tree' SHiP.sTree.Write() ut.writeHists(h, "recohists.root") if realPR: ut.writeHists(shipPatRec.h, "recohists_patrec.root") ut.errorSummary()
ut.bookHist(h, 'Bx', 'Bx', 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) ut.bookHist(h, 'By', 'By', 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) ut.bookHist(h, 'Bz', 'Bz', 60, -113.86, 126.14, 21, -44.09, 79.81, 102, -253.77, 256.27) ut.bookHist(h, 'Byvsz', 'By vs z for x=1.4,y=1.6', 102, -253.77, 256.27) f = open('ExtGoliathFieldMap.txt', 'r') i = 0 for line in f: i += 1 if i < 6: continue x, y, z, Bx, By, Bz = line.split() x = float(x) / 10. y = float(y) / 10. z = float(z) / 10. Bx = Bx By = By Bz = Bz rc = h['Bx'].Fill(float(x), float(y), float(z), float(Bx)) rc = h['By'].Fill(float(x), float(y), float(z), float(By)) rc = h['Bz'].Fill(float(x), float(y), float(z), float(Bz)) if (round(x, 2) == 0.14) and (round(y, 2) == 0.16): rc = h['Byvsz'].Fill(float(z), float(By)) ut.writeHists(h, "GoliathFieldMap.root")
WireMeasurement = ROOT.genfit.WireMeasurement # for 'real' PatRec shipPatRec.initialize(fgeo) # main loop for iEvent in range(firstEvent, SHiP.nEvents): if debug: print 'event ',iEvent ntracks = SHiP.execute(iEvent) if vertexing: # now go for 2-track combinations if ntracks > 1: SHiP.find2TrackVertex() # make tracks and particles persistent SHiP.Particles.Fill() SHiP.fitTracks.Fill() SHiP.mcLink.Fill() SHiP.SHbranch.Fill() for x in caloTasks: x.Exec('start') SHiP.EcalClusters.Fill() if debug: print 'end of event after Fill' # end loop over events print 'finished writing tree' SHiP.sTree.Write() ut.writeHists(h,"recohists.root") if realPR: ut.writeHists(shipPatRec.h,"recohists_patrec.root")
h={} # new limits x: -1118.6, 1241.4 (59); y: -411.40, 768.60 (20); z: -2512.7, 2537.3 (101) # ut.bookHist(h,'Bx','Bx',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) ut.bookHist(h,'By','By',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) ut.bookHist(h,'Bz','Bz',60,-113.86,126.14,21,-44.09,79.81,102,-253.77,256.27) ut.bookHist(h,'Byvsz','By vs z for x=1.4,y=1.6',102,-253.77,256.27) f=open('ExtGoliathFieldMap.txt','r') i=0 for line in f: i+=1 if i<6: continue x,y,z,Bx,By,Bz = line.split() x=float(x)/10. y=float(y)/10. z=float(z)/10. Bx = Bx By = By Bz = Bz rc=h['Bx'].Fill(float(x),float(y),float(z),float(Bx)) rc=h['By'].Fill(float(x),float(y),float(z),float(By)) rc=h['Bz'].Fill(float(x),float(y),float(z),float(Bz)) if (round(x,2)==0.14) and (round(y,2)==0.16): rc=h['Byvsz'].Fill(float(z),float(By)) ut.writeHists(h,"GoliathFieldMap.root")
HNLMom = ROOT.TLorentzVector() HNL.Momentum(HNLMom) tr = ROOT.TVector3(0, 0, ShipGeo.target.z0) t = 0 for i in range(3): t += HNLMom(i) / HNLMom.P() * (tr(i) - HNLPos(i)) dist = 0 for i in range(3): dist += (tr(i) - HNLPos(i) - t * HNLMom(i) / HNLMom.P())**2 dist = ROOT.TMath.Sqrt(dist) h['IP0'].Fill(dist) h['IP0/mass'].Fill(HNLMom.M(), dist) h['HNL'].Fill(HNLMom.M()) def access2SmearedHits(): key = 0 for ahit in ev.SmearedHits.GetObject(): print ahit[0], ahit[1], ahit[2], ahit[3], ahit[4], ahit[5], ahit[6] # follow link to true MCHit mchit = TrackingHits[key] mctrack = MCTracks[mchit.GetTrackID()] print mchit.GetZ(), mctrack.GetP(), mctrack.GetPdgCode() key += 1 myEventLoop(nEvents) makePlots() # output histograms ut.writeHists(h, "ShipAna.root")
def absorptionLength(plotOnly=True): materials = { 'Boratedpolyethylene': ROOT.kGreen, 'BoronCarbide': ROOT.kBlue, 'Concrete': ROOT.kGray, 'EmulsionAg109': ROOT.kOrange, 'H2O': ROOT.kCyan } B10Parameter = {} B10Parameter['Boratedpolyethylene'] = 0.01 * 0.94 / (10. * 1.672E-24) B10Parameter['BoronCarbide'] = 0.125 * 1.360 / (10. * 1.672E-24) Xsec = 0.61E-24 h['Fabsorp'] = {} Fabsorp = h['Fabsorp'] for m in B10Parameter: Fabsorp[m] = ROOT.TF1('fabs' + m, '1./([0]/sqrt(10**x)*[1])', -10., 4.) Fabsorp[m].SetParameter(0, Xsec) Fabsorp[m].SetParameter(1, B10Parameter[m]) if not plotOnly: for material in materials: for Erange in [ '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4', '-4_-2' ]: fname = "thermNeutron_" + material + "_100.0_" + Erange + "_0.root" if not fname in os.listdir('.'): continue count(fname) h['Esecondary' + '_' + material + Erange] = h['Esecondary'].Clone('Esecondary' + '_' + material + Erange) h['electrons' + '_' + material + Erange] = h['electrons'].Clone('electrons' + '_' + material + Erange) h['photons' + '_' + material + Erange] = h['photons'].Clone('photons' + '_' + material + Erange) for x in ['Lab', 'Labz']: hname = x + '_' + material + Erange h[hname] = h[x].ProfileX(hname, 1, -1, 'g') hsum = x + '_' + material if not hsum in h: h[hsum] = h[hname].Clone(hsum) h[hsum].SetLineColor(materials[material]) else: h[hsum].Add(h[hname]) ROOT.gROOT.cd() ut.writeHists(h, 'thermalNeutrons-histograms.root', plusCanvas=True) else: ut.readHists(h, 'thermalNeutrons-histograms.root') # make stats about secondary neutrons: for material in materials: for Erange in [ '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4', '-4_-2' ]: histo = h['Esecondary' + '_' + material + Erange] print("secondary neutrons for %s %s %5.2F%%" % (material, Erange, 100. * histo.GetEntries() / h['Labz' + '_' + material + Erange].GetEntries())) for X in ['electrons', 'photons']: for material in materials: h[X + '_' + material] = h[X].Clone(X + '_' + material) for Erange in [ '-14_-12', '-12_-10', '-10_-8', '-8_-7', '-7_-6', '-6_-4', '-4_-2' ]: h[X + '_' + material].Add(h[X + '_' + material + Erange]) norm = h[X + '_' + material].ProjectionX('norm', 1, 101) for p in [1, 2, 5, 10]: h[X + str(p) + 'Percent_' + material] = h[X + '_' + material].ProjectionX( X + str(p) + 'Percent_' + material, 1, p) h[X + str(p) + 'Percent_' + material].Divide(norm) ut.bookCanvas(h, 'T' + X, '', 1200, 800, 1, 1) h['T' + X].cd() material = 'EmulsionAg109' h[X + '1Percent_' + material].SetLineColor(ROOT.kRed) h[X + '2Percent_' + material].SetLineColor(ROOT.kOrange) h[X + '5Percent_' + material].SetLineColor(ROOT.kBlue) h[X + '10Percent_' + material].SetLineColor(ROOT.kGreen) h[X + '1Percent_' + material].SetTitle('') h[X + '1Percent_' + material].GetYaxis().SetTitle('fraction of events with < N_{' + X + '}') h[X + '1Percent_' + material].GetXaxis().SetRangeUser(-12., 1) h[X + '1Percent_' + material].SetStats(0) h[X + '1Percent_' + material].Draw('hist') h['leg' + X] = ROOT.TLegend(0.63, 0.25, 0.88, 0.40) for p in [1, 2, 5, 10]: h[X + str(p) + 'Percent_' + material].Draw('histsame') rc = h['leg' + X].AddEntry(h[X + str(p) + 'Percent_' + material], 'N_{' + X + '}<' + str(p), 'PL') h['leg' + X].Draw('same') myPrint(h['T' + X], 'fracEveWith' + X) # fntuple = ROOT.TFile.Open('neutronsTI18.root') nt = fntuple.nt ROOT.gROOT.cd() tcanv = 'TFig12' if tcanv in h: h.pop(tcanv) ut.bookCanvas(h, tcanv, '', 1200, 800, 1, 1) # figure 12 of technical proposal nt.Draw('log10(N*Eleft):log10(Eleft)>>rates', '', 'box') h['rates'] = ROOT.gROOT.FindObjectAny('rates').Clone('rates') for x in ['Lab', 'Labz']: tcanv = 'abs' + x if tcanv in h: h.pop(tcanv) ut.bookCanvas(h, tcanv, '', 1200, 800, 1, 1) h['abs' + x].cd() h['abs' + x].SetLogy() hsum = x + '_Concrete' h[hsum].GetXaxis().SetRangeUser(-12., 1) h[hsum].SetMaximum(30.) h[hsum].SetMinimum(0.004) h[hsum].GetXaxis().SetTitle('logE[MeV]') h[hsum].GetYaxis().SetTitle('absorption Length [cm]') h[hsum].SetLineWidth(2) h[hsum].Draw('hist') h['leg' + x] = ROOT.TLegend(0.6, 0.2, 0.86, 0.36) for material in materials: hsum = x + '_' + material h[hsum].SetStats(0) h[hsum].SetLineWidth(2) h[hsum].Draw('histsame') if material in Fabsorp: Fabsorp[material].Draw('same') rc = h['leg' + x].AddEntry(h[hsum], material, 'PL') h['leg' + x].Draw('same') myPrint(h['abs' + x], 'AbsLength' + x) # folding with neutron rate h['Fig12'] = ROOT.TGraph() h['dE'] = ROOT.TGraph() h['neutronRate'] = ROOT.TGraph() h['dangerZone'] = ROOT.TGraph() h['dangerZone'].SetPoint(0, -5.6, 0.) h['dangerZone'].SetPoint(1, -5.6, 1.E7) h['dangerZone'].SetPoint(2, -5.1, 1.E7) h['dangerZone'].SetPoint(3, -5.1, 0.) h['dangerZone'].SetFillStyle(1001) h['dangerZone'].SetFillColor(ROOT.kYellow) n = 0 RateIntegrated = 0 RateIntegratedW = 0 for nt in fntuple.nt: E = (nt.Eleft + nt.Eright) / 2. dE = nt.Eright - nt.Eleft h['Fig12'].SetPoint(n, ROOT.TMath.Log10(E), ROOT.TMath.Log10(nt.N * E)) h['neutronRate'].SetPoint(n, E, nt.N) h['dE'].SetPoint(n, E, dE) RateIntegrated += nt.N RateIntegratedW += nt.N * dE n += 1 h['TFig12'].cd() h['Fig12'].Draw('same') # ut.bookHist(h, 'Nr', ';E [MeV];dn/dlogE [cm^{-2}y^{-1}] ', 100, -12., 1.) h['Nr'].SetMaximum(2.E8) h['Nr'].SetMinimum(1.E-4) h['Nr'].SetStats(0) intRates = {} thick = { 0.0: ROOT.kBlue, 0.5: ROOT.kOrange, 1: ROOT.kRed, 2: ROOT.kRed + 2, 5: ROOT.kRed - 7, 10: ROOT.kGreen } for material in ['Boratedpolyethylene', 'BoronCarbide']: intRates[material] = {} tcanv = 'ratesWith_' + material if tcanv in h: h.pop(tcanv) ut.bookCanvas(h, tcanv, material, 1200, 800, 1, 1) h[tcanv].SetLogy(1) h[tcanv].cd() h['ratesWith_' + material].cd() h['Nr'].Draw() h['dangerZone'].Draw('sameF') h['legthick' + material] = ROOT.TLegend(0.6, 0.2, 0.86, 0.36) for d in thick: # try different thicknesses intRates[material][d] = 0 absorbLength = h['Labz_' + material] gname = 'neutronRate_' + material + '_' + str(d) h[gname] = ROOT.TGraph() h[gname].SetLineWidth(2) h[gname].SetLineColor(thick[d]) for n in range(h['Fig12'].GetN()): logE = h['Fig12'].GetX()[n] R = ROOT.TMath.Power(10., h['Fig12'].GetY()[n]) dE = h['dE'].GetPointY(n) E = ROOT.TMath.Power(10., logE) absorpt = 0 if d == 0.0: h[gname].SetPoint(n, logE, R) intRates[material][d] += dE * R / E else: L = absorbLength.GetBinContent(absorbLength.FindBin(logE)) Rnew = 0 if L > 0: absorpt = ROOT.TMath.Exp(-d / L) Rnew = R * absorpt h[gname].SetPoint(n, logE, Rnew) # E = (nt.Eleft+nt.Eright)/2. h['Fig12'].SetPoint(n,ROOT.TMath.Log10(E),ROOT.TMath.Log10(nt.N*E)) intRates[material][d] += dE * Rnew / E h[gname].Draw('same') rc = h['legthick' + material].AddEntry(h[gname], 'thickness %3.1Fcm' % (d), 'PL') reduction = intRates[material][d] / intRates[material][0] print( 'integrated rate with %s d=%3.1Fcm: %6.4G reduction factor=%6.2G' % (material, d, intRates[material][d], reduction)) # make integrated rates: h['IUp-neutronRate_' + material + str(d)] = ROOT.TGraph() h['IUp-neutronRateW_' + material + str(d)] = ROOT.TGraph() h['IDown-neutronRate_' + material + str(d)] = ROOT.TGraph() up = h['IUp-neutronRate_' + material + str(d)] down = h['IDown-neutronRate_' + material + str(d)] N = h[gname].GetN() S = 0 for n in range(N): logE = h[gname].GetX()[n] dE = h['dE'].GetPointY(n) Rnew = h[gname].GetY()[n] E = ROOT.TMath.Power(10., logE) S += dE * Rnew / E up.SetPoint(n, logE, S) # with damage function W = 1 - h['electrons1Percent_EmulsionAg109'].GetBinContent(n) h['IUp-neutronRateW_' + material + str(d)].SetPoint( n, logE, W * S) S = up.GetY()[N - 1] for n in range(N): logE = up.GetX()[n] S -= up.GetY()[n] down.SetPoint(n, logE, S) # for Elimit in [100., 1., 0.1, 0.01]: #MeV g = h['IUp-neutronRate_' + material + str(d)] gW = h['IUp-neutronRateW_' + material + str(d)] N = g.GetN() for n in range(N - 1, 1, -1): if ROOT.TMath.Power(10, g.GetX()[n]) < Elimit: break reduction = g.GetY()[n] / h['IUp-neutronRate_' + material + str(0.0)].GetY()[N - 1] reductionW = gW.GetY()[n] / h['IUp-neutronRate_' + material + str(0.0)].GetY()[N - 1] print( 'integrated rate E < %5.3F with %s d=%3.1Fcm: %6.4G reduction factor=%6.2G | %6.4G reduction factor=%6.2G' % (Elimit, material, d, g.GetY()[n], reduction, gW.GetY()[n], reductionW)) h['legthick' + material].Draw('same') myPrint(h['ratesWith_' + material], 'reducedRates_' + material)
HNL = LV[t1]+LV[t2] tr = ROOT.TVector3(0,0,ShipGeo.target.z0) t = 0 for i in range(3): t += HNL(i)/HNL.P()*(tr(i)-HNLPos(i)) dist = 0 for i in range(3): dist += (tr(i)-HNLPos(i)-t*HNL(i)/HNL.P())**2 dist = ROOT.TMath.Sqrt(dist) h['IP0'].Fill(dist) h['IP0/mass'].Fill(HNL.M(),dist) h['HNL'].Fill(HNL.M()) # try to make it persistent vx = ROOT.TLorentzVector(HNLPos,0.) # time not set particle = ROOT.TParticle(9900014,0,-1,-1,t1,t2,HNL,vx) def access2SmearedHits(): key = 0 for ahit in ev.SmearedHits.GetObject(): print ahit[0],ahit[1],ahit[2],ahit[3],ahit[4],ahit[5],ahit[6] # follow link to true MCHit mchit = TrackingHits[key] mctrack = MCTracks[mchit.GetTrackID()] print mchit.GetZ(),mctrack.GetP(),mctrack.GetPdgCode() key+=1 myEventLoop(nEvents) makePlots() # output histograms ut.writeHists(h,"ShipAna.root")
def processOneFile(fn,output): f = ROOT.TFile(fn) ntot = 0 if not f or not f.FindObjectAny('cbmsim'): print 'problem with file:',fn return sTree = f.cbmsim nEvents = sTree.GetEntries() if sTree.GetBranch("GeoTracks"): sTree.SetBranchStatus("GeoTracks",0) if sTree.GetBranch("FitTracks"): sTree.SetBranchStatus("FitTracks",0) sTree.GetEntry(0) hitContainers = [sTree.vetoPoint,sTree.muonPoint,sTree.EcalPointLite,sTree.strawtubesPoint,sTree.ShipRpcPoint,sTree.TargetPoint] for n in range(nEvents): rc = sTree.GetEntry(n) theMuon = sTree.MCTrack[1] # [0] contains pythiaid,parentid # [1] contains tof,w w = theMuon.GetWeight() if w==0 : w = 1. rc = h['weight'].Fill(w) rc = h['muonP'].Fill(theMuon.GetP()/u.GeV,w) ntot+=1 if ntot%10000 == 0 : print 'read event',f.GetName(),n hitmult = {} esum = 0 for mcp in sTree.MCTrack: if mcp.GetMotherId() == 0: # mother is original muon E = mcp.GetEnergy() if mcp.GetPdgCode() == 11: rc = h['deltaElec'].Fill(E,w) esum += E rc = h['secondaries'].Fill(E,w) rc = h['prop_deltaElec'].Fill(esum/sTree.MCTrack[0].GetP(),w) # until energy is really made persistent GetEnergy() for c in hitContainers: for ahit in c: if not ahit.GetEnergyLoss()>0: continue detID = ahit.GetDetectorID() if ahit.GetName() == 'strawtubesPoint': tmp = strawEncoding(detID) # detName = str(tmp[0]*10000000+tmp[1]*1000000+tmp[2]*100000+tmp[3]*10000) detName = "strawstation_"+str(tmp[0]) x = ahit.GetX() y = ahit.GetY() E = ahit.GetEnergyLoss() elif ahit.GetName() == 'ShipRpcPoint': detName = 'Rpc' x = ahit.GetX() y = ahit.GetY() z = ahit.GetZ() E = ahit.GetEnergyLoss() elif ahit.GetName() == 'TargetPoint': detName = 'Emulsion' x = ahit.GetX() y = ahit.GetY() z = ahit.GetZ() E = ahit.GetEnergyLoss() elif ahit.GetName() == 'ecalPoint': # not needed for lite collection: if abs(ahit.GetPdgCode())==12 or abs(ahit.GetPdgCode())==14 : continue detName = 'Ecal' ecal.GetCellCoordForPy(detID,pos) x = pos.X() y = pos.Y() E = ahit.GetEnergyLoss() else: if logVols.has_key(detID): detName = logVols[detID] else: detName = str(detID) if not detName.find('LiSc')<0: detName = 'LiSc' x = ahit.GetX() y = ahit.GetY() z = ahit.GetZ() E = ahit.GetEnergyLoss() if not h.has_key(detName): bookHist(detName) mu='' pdgID = -2 if 'PdgCode' in dir(ahit): pdgID = ahit.PdgCode() trackID = ahit.GetTrackID() if not trackID < 0: aTrack = sTree.MCTrack[trackID] pdgID = aTrack.GetPdgCode() if abs(pdgID)==13: mu='_mu' rc = ahit.Momentum(mom) phit = mom.Mag()/u.GeV if phit>3 and abs(pdgID)==13: mu='_muV0' detName = detName + mu if detName.find('LiSc')<0: rc = h[detName].Fill(x/u.m,y/u.m,w) else: rc = h[detName].Fill(ahit.GetZ()/u.m,ROOT.TMath.ATan2(y,x)/ROOT.TMath.Pi(),w) rc = h[detName+'_E'].Fill(E/u.MeV,w) if not hitmult.has_key(detName): hitmult[detName] = {-1:0} if not hitmult[detName].has_key(trackID): hitmult[detName][trackID] = 0 hitmult[detName][trackID] +=1 hitmult[detName][-1] +=1 rc = h[detName+'_id'].Fill(pdgID,w) rc = h[detName+'_P'].Fill(phit,w) rc = h[detName+'_LP'].Fill(phit,w) if not trackID < 0: r = ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m z = aTrack.GetStartZ()/u.m rc = h['origin'].Fill(z,r,w) rc = h[detName+'_origin'].Fill(z,r,w) rc = h['borigin'].Fill(z,r,w) rc = aTrack.GetMomentum(mom) rc = h[detName+'_OP'].Fill(mom.Mag()/u.GeV,w) if trackID > 0: origin(sTree,trackID) rc = h['porigin'].Fill(aTrack.GetStartZ()/u.m,ROOT.TMath.Sqrt(aTrack.GetStartX()**2+aTrack.GetStartY()**2)/u.m,w) rc = h['mu-inter'].Fill(rz_inter[1]/u.m,rz_inter[0]/u.m,w) for detName in hitmult: rc = h[detName+'_evmul'].Fill(hitmult[detName][-1],w) for tr in hitmult[detName]: rc = h[detName+'_mul'].Fill(hitmult[detName][tr],w) f.Close() ut.writeHists(h,fn.replace(".root","-hists.root") ) output.put(ntot)
def coldBox(plotOnly=True, pas=''): if 1 > 0: tmp = options.inputFile.split('/') gFile = "geofile-" + (tmp[len(tmp) - 1].split('_coldbox')[0] + '_coldbox.root').replace('histos-', '') g = ROOT.TFile(gFile) sGeo = g.FAIRGeom ROOT.gROOT.cd() vbox = sGeo.FindVolumeFast('vbox') sbox = sGeo.FindVolumeFast('sensBox') dX, dY, dZ = vbox.GetShape().GetDX(), vbox.GetShape().GetDY( ), vbox.GetShape().GetDZ() nav = sGeo.GetCurrentNavigator() boundaries = {} # find y boundaries start = array('d', [0, 200, 0]) direction = array('d', [0, -1, 0]) startnode = sGeo.InitTrack(start, direction) length = c_double(200.) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['topIn'] = nav.GetCurrentPoint()[1] node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['topSens'] = nav.GetCurrentPoint()[1] start = array('d', [0, -200, 0]) direction = array('d', [0, 1, 0]) startnode = sGeo.InitTrack(start, direction) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['botSens'] = nav.GetCurrentPoint()[1] # find x boundaries start = array('d', [-200, 0, 0]) direction = array('d', [1, 0, 0]) startnode = sGeo.InitTrack(start, direction) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['leftIn'] = nav.GetCurrentPoint()[0] node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['leftSens'] = nav.GetCurrentPoint()[0] start = array('d', [200, 0, 0]) direction = array('d', [-1, 0, 0]) startnode = sGeo.InitTrack(start, direction) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['rightIn'] = nav.GetCurrentPoint()[0] node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['rightSens'] = nav.GetCurrentPoint()[0] # find z boundaries start = array('d', [0, 0, -200]) direction = array('d', [0, 0, 1]) startnode = sGeo.InitTrack(start, direction) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['backIn'] = nav.GetCurrentPoint()[2] node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['backSens'] = nav.GetCurrentPoint()[2] start = array('d', [0, 0, 200]) direction = array('d', [0, 0, -1]) startnode = sGeo.InitTrack(start, direction) node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['frontIn'] = nav.GetCurrentPoint()[2] node = sGeo.FindNextBoundaryAndStep(length, ROOT.kFALSE) boundaries['frontSens'] = nav.GetCurrentPoint()[2] Rin = { '': '', 'topIn': 'Y', 'leftIn': 'X', 'rightIn': 'X', 'frontIn': 'Z', 'backIn': 'Z' } Rsens = { '': '', 'topSens': 'Y', 'botSens': 'Y', 'leftSens': 'X', 'rightSens': 'X', 'frontSens': 'Z', 'backSens': 'Z' } epsi = 0.1 # side with holes is the front # if not plotOnly: # example file "root://eospublic.cern.ch:1094//eos/experiment/sndlhc/MonteCarlo/ThermalNeutrons//thermNeutron_Borated30polyethylene_10.0_coldbox_0-20M.root" f = ROOT.TFile.Open(options.inputFile) ROOT.gROOT.cd() ut.bookHist(h, 'start', 'start neutron;x [cm] ;y [cm] ;z [cm]', 100, -200, 200, 100, -200, 200, 100, -200, 200) ut.bookHist(h, 'startR', 'start neutron;R', 100, 0, 200) for o in ['_seco', '_prim']: for T in ['', 'cold', 'hot']: ut.bookHist(h, 'entry' + T + o, 'entry neutron;x [cm] ;y [cm] ;z [cm]', 100, -100, 100, 100, -100, 100, 100, -100, 100) ut.bookHist(h, 'exit' + T + '-original' + o, 'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]', 100, -100, 100, 100, -100, 100, 100, -100, 100) ut.bookHist(h, 'exit' + T + o, 'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]', 100, -100, 100, 100, -100, 100, 100, -100, 100) for r in Rin: ut.bookHist(h, 'EkinE' + r + o, 'log10(Ekin)', 100, -13., 0, 100, -200., 200.) ut.bookHist(h, 'Ekin' + r + o, 'log10(Ekin)', 100, -13., 0, 100, -200., 200.) for r in Rsens: ut.bookHist(h, 'DF' + r + o, 'travel distance', 100, 0., 200.) ut.bookHist(h, 'EkinF' + r + o, 'log10(Ekin) vs distance', 100, -13., 0, 100, -200., 200.) ut.bookHist(h, 'EkinF-original' + r + o, 'log10(Ekin) vs distance', 100, -13., 0, 100, -200., 200.) ut.bookHist(h, 'checkBox' + r + o, 'enter coldbox neutron;x [cm] ;y [cm] ;z [cm]', 100, -100, 100, 100, -100, 100, 100, -100, 100) ut.bookHist(h, 'EkinG', 'log10(Ekin)', 100, -13., 0.) ut.bookHist(h, 'EkinW', 'log10(Ekin)', 100, -13., 0.) ut.bookHist(h, 'EkinWlin', 'Ekin', 100, 1E-9, 100 * 1E-9) ut.bookHist(h, 'multS', 'mult veto points shielding', 100, -0.5, 99.5) ut.bookHist(h, 'multC', 'mult veto points inside', 100, -0.5, 99.5) ut.bookHist(h, 'multN', 'mult neutrons', 100, -0.5, 99.5) flukaRateIntegrated() Nsim = f.cbmsim.GetEntries() for sTree in f.cbmsim: rc = h['multN'].Fill(sTree.MCTrack.GetEntries()) neutron = sTree.MCTrack[0] start = ROOT.TVector3(neutron.GetStartX(), neutron.GetStartY(), neutron.GetStartZ()) if start.y() < boundaries['botSens']: continue P = ROOT.TVector3(neutron.GetPx(), neutron.GetPy(), neutron.GetPz()) Ekin = ROOT.TMath.Sqrt(P.Mag2() + neutronMass**2) - neutronMass W = h['Fig12'].Eval(ROOT.TMath.Log10(Ekin * 1000)) / Nsim rc = h['start'].Fill(start.Z(), start.X(), start.Y(), W) rc = h['EkinW'].Fill(ROOT.TMath.Log10(Ekin), W) rc = h['EkinWlin'].Fill(Ekin, W) rc = h['EkinG'].Fill(ROOT.TMath.Log10(Ekin)) rc = h['startR'].Fill(start.Mag(), W) nC, nS = 0, 0 for p in sTree.vetoPoint: if p.PdgCode() != 2112: continue if p.GetDetectorID() == 13: nC += 1 else: nS += 1 rc = h['multC'].Fill(nC) rc = h['multS'].Fill(nS) trajectory = {} for p in sTree.vetoPoint: if p.PdgCode() != 2112: continue trackID = p.GetTrackID() if not trackID in trajectory: trajectory[trackID] = [] trajectory[trackID].append(p) for trackID in trajectory: firstSens = True for p in trajectory[trackID]: origin = '_seco' if trackID == 0: origin = '_prim' lastPoint = p.LastPoint() mPoint = ROOT.TVector3(p.GetX(), p.GetY(), p.GetZ()) firstPoint = 2 * mPoint - lastPoint D = lastPoint - firstPoint TD = firstPoint - start firstMom = ROOT.TVector3(p.GetPx(), p.GetPy(), p.GetPz()) Ekin_entry = ROOT.TMath.Sqrt(firstMom.Mag2() + neutronMass**2) - neutronMass if p.GetDetectorID( ) == 13 and firstSens: # first point inside coldbox firstSens = False rc = h['exit' + origin].Fill(firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) if Ekin * 1E9 < 10: rc = h['exitcold-original' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) # 10eV else: rc = h['exithot-original' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) if Ekin_entry * 1E9 < 10: rc = h['exitcold' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) # 10eV else: rc = h['exithot' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) rc = h['DF' + origin].Fill(TD.Mag(), W) rc = h['EkinF' + origin].Fill( ROOT.TMath.Log10(Ekin_entry), D.Mag(), W) rc = h['EkinF-original' + origin].Fill( ROOT.TMath.Log10(Ekin), D.Mag(), W) # find location Rsens = ['','topSens','botSens','leftSens','rightSens','frontSens','backSens'] found = False for r in Rsens: if r == '': continue X = eval('firstPoint.' + Rsens[r] + '()') if abs(X - boundaries[r]) < epsi: # if r=='botSens' and p!=trajectory[trackID][0]: continue # to enter from bottom is without crossing shield. It is more complicated! found = True break if not found: txt = '' for r in Rsens: if r == '': continue X = eval('firstPoint.' + Rsens[r] + '()') txt += " " + r + " " + str(X) print("this should no happen", txt, boundaries) for P in trajectory[trackID]: print(P.GetDetectorID(), P.LastPoint().X(), P.LastPoint().Y(), P.LastPoint().Z()) rc = h['DF' + r + origin].Fill(TD.Mag(), W) rc = h['EkinF' + r + origin].Fill( ROOT.TMath.Log10(Ekin_entry), D.Mag(), W) rc = h['EkinF-original' + r + origin].Fill( ROOT.TMath.Log10(Ekin), D.Mag(), W) rc = h['checkBox' + r + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) if p.GetDetectorID() == 1: # inside shielding # check that first point is further out. if firstPoint.Mag() < lastPoint.Mag(): continue rc = h['Ekin' + origin].Fill(ROOT.TMath.Log10(Ekin), D.Mag(), W) rc = h['EkinE' + origin].Fill( ROOT.TMath.Log10(Ekin_entry), D.Mag(), W) rc = h['entry' + origin].Fill(firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) if Ekin * 1E9 < 10: rc = h['entrycold' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) # 10eV else: rc = h['entryhot' + origin].Fill( firstPoint.X(), firstPoint.Y(), firstPoint.Z(), W) # find location for r in Rin: if r == '': continue X = eval('firstPoint.' + Rin[r] + '()') if abs(X - boundaries[r]) < epsi: break rc = h['Ekin' + r + origin].Fill( ROOT.TMath.Log10(Ekin), X, W) rc = h['EkinE' + r + origin].Fill( ROOT.TMath.Log10(Ekin_entry), X, W) tmp = options.inputFile.split('/') outFile = 'histos-' + tmp[len(tmp) - 1] # make sum of seco and prim hkeys = list(h.keys()) for x in hkeys: if x.find('_seco') > 0: hname = x.replace('_seco', '') h[hname] = h[x].Clone(hname) h[hname].Add(h[x.replace('_seco', '_prim')]) # ut.writeHists(h, outFile) print('finished making histograms ', 'histos-noConc-' + options.inputFile) else: ut.readHists(h, options.inputFile) if pas != '': ut.readHists( hnorm, 'histos-thermNeutron_vacuums_0.0001_coldbox_pass1.root') else: ut.readHists(hnorm, options.inputFile) tmp = options.inputFile.split('_') material = tmp[1] + "_coldbox/" thickness = "_" + tmp[2] binning = {} for c in ['entry', 'exit']: binning[c] = {} for p in ['x', 'y', 'z']: tmp = h[c].Project3D(p) for imin in range(1, tmp.GetNbinsX() + 1): if tmp.GetBinContent(imin) > 0: break for imax in range(tmp.GetNbinsX(), 0, -1): if tmp.GetBinContent(imax) > 0: break binning[c][p] = {'min': imin, 'max': imax} # ytop = { 'axis': 'Y', 'proj': 'xz', 'entry': binning['entry']['y']['max'], 'exit': h['exit'].GetYaxis().FindBin(boundaries['topSens']), 'xdist': dZ, 'ydist': dX } ybot = { 'axis': 'Y', 'proj': 'xz', 'entry': binning['entry']['y']['min'], 'exit': h['exit'].GetYaxis().FindBin(boundaries['botSens']), 'xdist': dZ, 'ydist': dX } xLeft = { 'axis': 'X', 'proj': 'yz', 'entry': binning['entry']['x']['min'], 'exit': h['exit'].GetXaxis().FindBin(boundaries['leftSens']), 'xdist': dZ, 'ydist': dY } xRight = { 'axis': 'X', 'proj': 'yz', 'entry': binning['entry']['x']['max'], 'exit': h['exit'].GetXaxis().FindBin(boundaries['rightSens']), 'xdist': dZ, 'ydist': dY } zMin = { 'axis': 'Z', 'proj': 'yx', 'entry': binning['entry']['z']['min'], 'exit': h['exit'].GetZaxis().FindBin(boundaries['backSens']), 'xdist': dX, 'ydist': dY } zMax = { 'axis': 'Z', 'proj': 'yx', 'entry': binning['entry']['z']['max'], 'exit': h['exit'].GetXaxis().FindBin(boundaries['frontSens']), 'xdist': dX, 'ydist': dY } print('boundaries', boundaries) # make projections projections = { 'Top': ytop, 'Bot': ybot, 'Right': xRight, 'Left': xLeft, 'Front': zMax, 'Back': zMin } h['fluences'] = {} for o in ['', '_prim']: for T in ['', 'cold', 'hot']: for Z in ['entry', 'exit', 'exit-original']: tmp = Z.split('-') c = tmp[0] x = '' if len(tmp) > 1: x = '-' + tmp[1] case = c + T + x + o ut.bookCanvas(h, 't' + case, case, 1200, 1800, 2, 3) k = 1 for p in projections: h['t' + case].cd(k) tmp = h[case] axis = eval('tmp.Get' + projections[p]['axis'] + 'axis()') if Z == 'entry': axis.SetRange(projections[p][c] - 1, projections[p][c] + 1) else: axis.SetRange(projections[p][c], projections[p][c]) if p == 'xBot': xax = tmp.GetXaxis() xax.SetRange( xax.FindBin(boundaries['leftSens']) + 1, xax.FindBin(boundaries['rightSens']) - 1) zax = tmp.GetZaxis() zax.SetRange( zax.FindBin(boundaries['backSens']) + 1, zax.FindBin(boundaries['frontSens']) - 1) h[case + p] = tmp.Project3D(projections[p]['proj']) h[case + p].SetName(case + p) tmp.GetXaxis().SetRange(0, 0) tmp.GetYaxis().SetRange(0, 0) tmp.GetZaxis().SetRange(0, 0) h[case + p].SetStats(0) h[case + p].SetMinimum(0) h[case + p].SetTitle(p) h[case + p].Draw('colz') # check uniformity: h['X-' + case + p] = h[case + p].ProjectionX('X-' + case + p) h['Y-' + case + p] = h[case + p].ProjectionY('Y-' + case + p) k += 1 sqcm = projections[p]['xdist'] * projections[p]['ydist'] entries = h[case + p].GetSumOfWeights() X = entries / sqcm if X > 100: txt = "%5.1F/cm^{2}" % (X) else: txt = "%5.2F/cm^{2}" % (X) h['fluences'][case + p] = X L = ROOT.TLatex() rc = L.DrawLatexNDC(0.2, 0.85, txt) h['X-' + case + p].Scale(1. / projections[p]['ydist']) h['Y-' + case + p].Scale(1. / projections[p]['xdist']) myPrint(h['t' + case], material + 't' + case + thickness) # make cross checks ut.bookCanvas(h, 'crosschecks', 'cross checks', 900, 600, 1, 1) tc = h['crosschecks'].cd() tc.SetLogy(1) tc.SetGridx() tc.SetGridy() h['EkinW'].SetStats(0) h['EkinW'].SetStats(0) h['EkinW'].SetLineWidth(3) h['EkinW'].SetTitle(';log(E) [GeV];dn/dlogE [cm^{-2}y^{-1}] ') h['EkinW'].SetMaximum(1E8) h['EkinW'].SetMinimum(1E2) h['EkinW'].Draw() myPrint(h['crosschecks'], material + 'kinEnergy' + thickness) tc.SetLogy(0) k = -10 for p in projections: for l in ['X-', 'Y-']: case = l + 'entry' + p h[case].SetLineColor(ROOT.kRed + k) h[case].SetStats(0) if k < -9: h[case].SetTitle('; x,y,z [cm]; N/L [cm^{-1}]') tpl = ut.findMaximumAndMinimum(h[case]) h[case].SetMaximum(tpl[1] * 1.5) h[case].Draw() else: h[case].Draw('same') k += 1 myPrint(h['crosschecks'], material + 'irradiationXYZ' + thickness) # tc.SetLogy(1) # Ekin Rin = {'':'','topIn':'Y','leftIn':'X','rightIn':'X','frontIn':'Z','backIn':'Z'} # EkinF Rsens = {'':'','topSens':'Y','botSens':'Y','leftSens':'X','rightSens':'X','frontSens':'Z','backSens':'Z'} ut.bookCanvas(h, 'trej', 'rejections', 1200, 1800, 2, 3) k = 0 for r in ['', 'top', 'bot', 'right', 'left', 'front', 'back']: rej = 'rej' + r rejo = 'rejo' + r if r == '': norm = hnorm['Ekin'].ProjectionX('norm') h[rej] = h['EkinF'].ProjectionX(rej) h[rejo] = h['EkinF-original'].ProjectionX(rejo) else: k += 1 if r == 'bot': norm = hnorm['EkintopIn'].ProjectionX('norm') else: norm = hnorm['Ekin' + r + 'In'].ProjectionX('norm') h[rej] = h['EkinF' + r + 'Sens'].ProjectionX(rej) h[rejo] = h['EkinF-original' + r + 'Sens'].ProjectionX(rejo) h[rej].Divide(norm) h[rejo].Divide(norm) h[rej].SetStats(0) h[rejo].SetStats(0) h[rej].SetTitle(';log10(Ekin) GeV; rejection') h[rej].SetLineColor(ROOT.kBlue) h[rej].SetLineWidth(2) h[rejo].SetLineWidth(2) h[rejo].SetLineColor(ROOT.kGreen) h[rej].GetXaxis().SetRangeUser(-13., -1.) h[rej].SetMaximum(1.2) h[rej].SetMinimum(1.E-4) if k == 0: tc = h['crosschecks'].cd() else: tc = h['trej'].cd(k) tc.SetGridx() tc.SetGridy() h[rej].SetMinimum(1.E-6) h[rej].SetTitle(r[0].upper() + r[1:]) tc.SetLogy() h[rej].Draw('hist') h[rejo].Draw('histsame') h['legR' + r] = ROOT.TLegend(0.11, 0.74, 0.72, 0.82) rc = h['legR' + r].AddEntry( h[rejo], 'reduction as function of original E_{kin} when entering shield', 'PL') rc = h['legR' + r].AddEntry( h[rej], 'reduction as function of E_{kin} when leaving shield', 'PL') h['legR' + r].Draw('same') if k == 0: myPrint(h['crosschecks'], material + 'rejections' + thickness) myPrint(h['trej'], material + 'Listrejections' + thickness + pas) # h['dangerZone'] = ROOT.TGraph() h['dangerZone'].SetPoint(0, -8.6, 0.) h['dangerZone'].SetPoint(1, -8.6, 1.) h['dangerZone'].SetPoint(2, -8.1, 1.) h['dangerZone'].SetPoint(3, -8.1, 0.) h['dangerZone'].SetFillStyle(1001) h['dangerZone'].SetFillColor(ROOT.kYellow) for r in ['rej', 'rejo']: ut.bookCanvas(h, r + 'ection2', 'rejectionRate', 900, 600, 1, 1) h[r + 'TopLeftRightBack'] = h[r + 'top'].Clone(r + 'TopLeftRightBack') h[r + 'TopLeftRightBack'].Add(h[r + 'left']) h[r + 'TopLeftRightBack'].Add(h[r + 'right']) h[r + 'TopLeftRightBack'].Add(h[r + 'back']) h[r + 'TopLeftRightBack'].Scale(1. / 4.) h[r + 'TopLeftRightBack'].SetTitle('') if r == 'rej': h[r + 'TopLeftRightBack'].GetXaxis().SetTitle( 'outgoing ' + h[r + 'TopLeftRightBack'].GetXaxis().GetTitle()) if r == 'rejo': h[r + 'TopLeftRightBack'].GetXaxis().SetTitle( 'incoming ' + h[r + 'TopLeftRightBack'].GetXaxis().GetTitle()) h[r + 'TopLeftRightBack'].SetLineColor(ROOT.kGreen) h[r + 'bot'].SetLineColor(ROOT.kGray) h[r + 'front'].SetLineColor(ROOT.kRed) h[r + 'TopLeftRightBack'].SetMaximum(1.2) h[r + 'TopLeftRightBack'].SetMinimum(1.E-6) tc = h[r + 'ection2'].cd() tc.SetGridx() tc.SetGridy() tc.SetLogy() h[r + 'TopLeftRightBack'].Draw() h['dangerZone'].Draw('sameF') h[r + 'TopLeftRightBack'].Draw('same') h[r + 'bot'].Draw('same') h[r + 'front'].Draw('same') h[r + 'legR2'] = ROOT.TLegend(0.55, 0.30, 0.86, 0.45) rc = h[r + 'legR2'].AddEntry(h[r + 'TopLeftRightBack'], 'av. rejection top/left/right/back', 'PL') rc = h[r + 'legR2'].AddEntry(h[r + 'bot'], 'rejction bottom, only concrete', 'PL') rc = h[r + 'legR2'].AddEntry(h[r + 'front'], 'rejction front, with holes', 'PL') h[r + 'legR2'].Draw('same') myPrint(h[r + 'ection2'], material + 'Sum ' + r + 'ections' + thickness + pas) if pas == '': ut.writeHists(h, options.inputFile.replace('.root', '_pass1.root')) # statistics: for o in ['', '-original']: for T in ['cold', 'hot']: norm = 0 exit = 0 concrete = 0 holes = 0 for p in projections: if p != 'Bot' and norm != 'Front': norm += h['fluences']['entry' + T + p] exit += h['fluences']['exit' + T + o + p] if p == 'Bot': concrete = h['fluences']['exit' + T + o + p] elif p == 'Front': holes = h['fluences']['exit' + T + o + p] norm = norm / float(4) exit = exit / float(4) #! do not need average, need total. # incoming = 6 * average ! print( '%s %s region: %5.2F concrete: %5.2F holes: %5.2F x permille total: %5.2F x permille' % (o, T, exit / norm * 1000, concrete / norm * 1000, holes / norm * 1000, (4 * exit + concrete + holes) / (6 * norm) * 1000))
def save_hists(h, path): ut.writeHists(h, path)
def finish(self): del self.fitter print 'finished writing tree' self.sTree.Write() ut.errorSummary() ut.writeHists(h, "recohists.root")
if HNLMom.M() > 0.1: if not n == lastEvent["Mass"]: weight_mass += ((0.01)**hitSegments)*wg #Mass cut lastEvent["Mass"] = n if dist < 30*u.m: weight_IP += ((0.01)**hitSegments)*wg print "totalweight = ",totalweight print "weight_2Track = ", weight_2Track, " (", events_2Track,")" print "weight_noTagger = ", weight_noTagger, " (", events_noTagger,")" print "weight_DOCA = ", weight_DOCA print "weight_POCA = ", weight_POCA, " (", events_POCA,")" print "" print "weight_mass = ", weight_mass print "weight_Tag1 = ", weight_Tag1 print "weight_Tag099 = ", weight_Tag099 print "weight_Tag09 = ", weight_Tag09 print "weight_Seg095 = ", weight_Seg095 print "weight_Seg099 = ", weight_Seg099 print "weight_IP = ", weight_IP print print cat # myEventLoop(nEvents) writename = "shipAna_" +outfile+ ".root" print "End Loop, Write Histograms: ", writename ut.writeHists(h,writename) print
def run4Charm1GeV(): fname = "pythia8_Geant4_charm_0-19_1.0.root" # renamed pythia8_Geant4_charm_XX-YY_10.0.root global weight weight = weightCharm1GeV rc = processFile(fname,False) ut.writeHists(h,'pythia8_Geant4_charm_1.0_nu.root')
ecalCl2Ph = ROOT.TFormula("ecalCl2Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y") ecalCl2Ph.SetParameters(0.000948095, 5.67471, 0.00339177, -0.000122629, -0.000169109, 8.33448e-06) ecalClusterCalib.SetCalibration(2, ecalCl2Ph) caloTasks.append(ecalClusterCalib) ecalReco = ROOT.ecalReco('ecalReco', 0) caloTasks.append(ecalReco) # Match reco to MC ecalMatch = ROOT.ecalMatch('ecalMatch', 0) caloTasks.append(ecalMatch) ecalCalib = ecalClusterCalib.InitPython() ecalReconstructed = ecalReco.InitPython(sTree.EcalClusters, ecalStructure, ecalCalib) ecalMatch.InitPython(ecalStructure, ecalReconstructed, sTree.MCTrack) nEvents = min(sTree.GetEntries(), nEvents) for n in range(nEvents): myEventLoop(n) sTree.FitTracks.Delete() makePlots() # output histograms hfile = inputFile.split(',')[0].replace('_rec', '_ana') if hfile[0:4] == "/eos" or not inputFile.find(',') < 0: # do not write to eos, write to local directory tmp = hfile.split('/') hfile = tmp[len(tmp) - 1] ROOT.gROOT.cd() ut.writeHists(h, hfile)
if not theTrack.checkConsistency(): print 'Problem with track after fit, not consistent', atrack, theTrack continue fitStatus = theTrack.getFitStatus() nmeas = fitStatus.getNdf() chi2 = fitStatus.getChi2() / nmeas h['chi2'].Fill(chi2) # make track persistent nTrack = self.fGenFitArray.GetEntries() if not debug: theTrack.prune( "CFL" ) # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280 self.fGenFitArray[nTrack] = theTrack self.fitTrack2MC.push_back(atrack) if debug: print 'save track', theTrack, chi2, nM, fitStatus.isFitConverged( ) self.fitTracks.Fill() self.mcLink.Fill() return nTrack + 1 def finish(self): del self.fitter print 'finished writing tree' self.sTree.Write() ut.errorSummary() ut.writeHists(h, "recohists.root") if realPR: ut.writeHists(shipPatRec.h, "recohists_patrec.root")
ecalClusterCalib.SetStraightCalibration(2, ecalCl2PhS) ecalCl2Ph=ROOT.TFormula("ecalCl2Ph", "[0]+x*([1]+x*([2]+x*[3]))+[4]*x*y+[5]*x*y*y") ecalCl2Ph.SetParameters(0.000948095, 5.67471, 0.00339177, -0.000122629, -0.000169109, 8.33448e-06) ecalClusterCalib.SetCalibration(2, ecalCl2Ph) caloTasks.append(ecalClusterCalib) ecalReco=ROOT.ecalReco('ecalReco',0) caloTasks.append(ecalReco) # Match reco to MC ecalMatch=ROOT.ecalMatch('ecalMatch',0) caloTasks.append(ecalMatch) ecalCalib = ecalClusterCalib.InitPython() ecalReconstructed = ecalReco.InitPython(sTree.EcalClusters, ecalStructure, ecalCalib) ecalMatch.InitPython(ecalStructure, ecalReconstructed, sTree.MCTrack) nEvents = min(sTree.GetEntries(),nEvents) for n in range(nEvents): myEventLoop(n) sTree.FitTracks.Delete() makePlots() # output histograms hfile = inputFile.split(',')[0].replace('_rec','_ana') if hfile[0:4] == "/eos" or not inputFile.find(',')<0: # do not write to eos, write to local directory tmp = hfile.split('/') hfile = tmp[len(tmp)-1] ROOT.gROOT.cd() ut.writeHists(h,hfile)
def persistency(): printAndCopy(prefix) ut.writeHists(h, prefix + ".root", plusCanvas=True)
def persistency(): printAndCopy(prefix) ut.writeHists(h,prefix+".root",plusCanvas=True)
h['Chi2'].Fill(mu_chi2) h['Chi2'].Fill(pi_chi2) h['HNL_mom_diff'].Fill(mom_diff) h['Pion_mom'].Fill(piP) h['Muon_mom'].Fill(muP) mu_t1, mu_t2 = time_res(muPartkey, muV) if mu_t1 != None: h['Time'].Fill(mu_t1) h['Time3'].Fill(mu_t2) pi_t1, pi_t2 = time_res(piPartkey, piV) if pi_t1 != None: h['Time2'].Fill(pi_t1) h['Time4'].Fill(pi_t2) print('\n' + str(pi_decaycheck) + ' pi --> mu decays before detection\n') finState2MuPi() makePlots() hfile = inputFile.split(',')[0].replace('_rec', '_NStesting') #create outputFile if hfile[0:4] == "/eos" or not inputFile.find(',') < 0: # do not write to eos, write to local directory tmp = hfile.split('/') hfile = tmp[len(tmp) - 1] #occurs only for cern users ROOT.gROOT.cd() ut.writeHists(h, hfile) #write histograms to outputFile lineLogFile.close() #close lineTestLogFile particleDataFile.close() #close File