model.metadata.create_all() sm = orm.sessionmaker(bind=engine, autoflush=True, autocommit=False, expire_on_commit=True) session = orm.scoped_session(sm) #print "hererere??" import sys for AgetID in range(4): #print "alalal" for ChannelID in range(68): tb0 = tree.GetBranch("asic_{}_{:02d}".format(AgetID,ChannelID)) tbjcStruct = ROOT.tbjcStruct() tb0.SetAddress(ROOT.AddressOf(tbjcStruct,'uval')) PadNum = FindPadNum(AgetID,ChannelID) if not PadNum: continue #try: # PadNum = FindPadNum(AgetID,ChannelID) #except: # print AgetID,ChannelID # sys.exit(1) TB = 512 #for i in xrange(tb0.GetEntries()): for i in xrange(100): if i % 100 == 0:
def createRootMap(inFileName, outFileName): print 'Create ROOT map {0} from {1}'.format(outFileName, inFileName) # Define ROOT file and its TTree theFile = ROOT.TFile.Open(outFileName, 'recreate') rangeTree = ROOT.TTree('Range', 'Range') rangeTree.SetDirectory(theFile) rStruct = ROOT.rangeStruct() rangeTree.Branch('xMin', ROOT.AddressOf(rStruct, 'xMin'), 'xMin/D') rangeTree.Branch('xMax', ROOT.AddressOf(rStruct, 'xMax'), 'xMax/D') rangeTree.Branch('dx', ROOT.AddressOf(rStruct, 'dx'), 'dx/D') rangeTree.Branch('yMin', ROOT.AddressOf(rStruct, 'yMin'), 'yMin/D') rangeTree.Branch('yMax', ROOT.AddressOf(rStruct, 'yMax'), 'yMax/D') rangeTree.Branch('dy', ROOT.AddressOf(rStruct, 'dy'), 'dy/D') rangeTree.Branch('zMin', ROOT.AddressOf(rStruct, 'zMin'), 'zMin/D') rangeTree.Branch('zMax', ROOT.AddressOf(rStruct, 'zMax'), 'zMax/D') rangeTree.Branch('dz', ROOT.AddressOf(rStruct, 'dz'), 'dz/D') dataTree = ROOT.TTree('Data', 'Data') dataTree.SetDirectory(theFile) dStruct = ROOT.dataStruct() dataTree.Branch('x', ROOT.AddressOf(dStruct, 'x'), 'x/D') dataTree.Branch('y', ROOT.AddressOf(dStruct, 'y'), 'y/D') dataTree.Branch('z', ROOT.AddressOf(dStruct, 'z'), 'z/D') dataTree.Branch('Bx', ROOT.AddressOf(dStruct, 'Bx'), 'Bx/D') dataTree.Branch('By', ROOT.AddressOf(dStruct, 'By'), 'By/D') dataTree.Branch('Bz', ROOT.AddressOf(dStruct, 'Bz'), 'Bz/D') # Open text file and process the information iLine = 0 # Number of bins initialised by reading first line Nx = 0 Ny = 0 Nz = 0 Nzy = 0 with open(inFileName, 'r') as f: for line in f: iLine += 1 sLine = line.split() # First line contains ranges if iLine == 1: rStruct.xMin = float(sLine[1]) rStruct.xMax = float(sLine[2]) rStruct.dx = float(sLine[3]) rStruct.yMin = float(sLine[4]) rStruct.yMax = float(sLine[5]) rStruct.dy = float(sLine[6]) rStruct.zMin = float(sLine[7]) rStruct.zMax = float(sLine[8]) rStruct.dz = float(sLine[9]) Nx = int(((rStruct.xMax - rStruct.xMin) / rStruct.dx) + 1.0) Ny = int(((rStruct.yMax - rStruct.yMin) / rStruct.dy) + 1.0) Nz = int(((rStruct.zMax - rStruct.zMin) / rStruct.dz) + 1.0) Nzy = Nz * Ny print 'Nx = {0}, Ny = {1}, Nz = {2}'.format(Nx, Ny, Nz) rangeTree.Fill() elif iLine > 2: # B field components dStruct.Bx = float(sLine[0]) dStruct.By = float(sLine[1]) dStruct.Bz = float(sLine[2]) # Also store bin centre coordinates. # Map is ordered in ascending z, y, then x iBin = iLine - 3 zBin = iBin % Nz yBin = int((iBin / Nz)) % Ny xBin = int(iBin / Nzy) dStruct.x = rStruct.dx * (xBin + 0.5) + rStruct.xMin dStruct.y = rStruct.dy * (yBin + 0.5) + rStruct.yMin dStruct.z = rStruct.dz * (zBin + 0.5) + rStruct.zMin dataTree.Fill() theFile.cd() rangeTree.Write() dataTree.Write() theFile.Close()
def Plot(files, label, obs): radmasses = [] for f in files: radmasses.append(float(f.replace("Xvv.mX", "").split("_")[0]) / 1000.) #print radmasses efficiencies = {} for mass in radmasses: efficiencies[mass] = number_of_mc_events * 0.005 / 19800.0 # W-tagging scale factor if "qW" in label.split("_")[0] or "qZ" in label.split("_")[0]: efficiencies[mass] *= 0.89 else: efficiencies[mass] *= 0.89 * 0.89 fChain = [] for onefile in files: #print onefile fileIN = rt.TFile.Open(onefile) fChain.append(fileIN.Get("limit;1")) rt.gROOT.ProcessLine("struct limit_t {Double_t limit;};") from ROOT import limit_t limit_branch = limit_t() for j in range(0, len(fChain)): chain = fChain[j] chain.SetBranchAddress("limit", rt.AddressOf(limit_branch, 'limit')) rad = [] for j in range(0, len(fChain)): chain = fChain[j] thisrad = [] for i in range(0, 6): chain.GetTree().GetEntry(i) thisrad.append(limit_branch.limit) #print "limit = %f" %limit_branch.limit #print thisrad rad.append(thisrad) # we do a plot r*MR mg = rt.TMultiGraph() mg.SetTitle("X -> ZZ") c1 = rt.TCanvas("c1", "A Simple Graph Example", 200, 10, 600, 600) x = [] yobs = [] y2up = [] y1up = [] y1down = [] y2down = [] ymean = [] for i in range(0, len(fChain)): y2up.append(rad[i][0] * efficiencies[radmasses[j]]) y1up.append(rad[i][1] * efficiencies[radmasses[j]]) ymean.append(rad[i][2] * efficiencies[radmasses[j]]) y1down.append(rad[i][3] * efficiencies[radmasses[j]]) y2down.append(rad[i][4] * efficiencies[radmasses[j]]) yobs.append(rad[i][5] * efficiencies[radmasses[j]]) grobs = rt.TGraphErrors(1) grobs.SetMarkerStyle(rt.kFullDotLarge) grobs.SetLineColor(rt.kRed) grobs.SetLineWidth(3) gr2up = rt.TGraphErrors(1) gr2up.SetMarkerColor(0) gr1up = rt.TGraphErrors(1) gr1up.SetMarkerColor(0) grmean = rt.TGraphErrors(1) grmean.SetLineColor(1) grmean.SetLineWidth(2) grmean.SetLineStyle(3) gr1down = rt.TGraphErrors(1) gr1down.SetMarkerColor(0) gr2down = rt.TGraphErrors(1) gr2down.SetMarkerColor(0) for j in range(0, len(fChain)): grobs.SetPoint(j, radmasses[j], yobs[j]) gr2up.SetPoint(j, radmasses[j], y2up[j]) gr1up.SetPoint(j, radmasses[j], y1up[j]) grmean.SetPoint(j, radmasses[j], ymean[j]) gr1down.SetPoint(j, radmasses[j], y1down[j]) gr2down.SetPoint(j, radmasses[j], y2down[j]) #print " observed %f %f" %(radmasses[j],yobs[j]) mg.Add(gr2up) #.Draw("same") mg.Add(gr1up) #.Draw("same") mg.Add(grmean, "L") #.Draw("same,AC*") mg.Add(gr1down) #.Draw("same,AC*") mg.Add(gr2down) #.Draw("same,AC*") if obs: mg.Add(grobs, "L,P") #.Draw("AC*") c1.SetLogy(1) mg.SetTitle("") mg.Draw("AP") mg.GetXaxis().SetTitle("Resonance mass (TeV)") if withAcceptance: mg.GetYaxis().SetTitle("#sigma #times BR(X #rightarrow " + label.split("_")[0] + ") #times A (pb)") else: mg.GetYaxis().SetTitle("#sigma #times BR(X #rightarrow " + label.split("_")[0] + ") (pb)") mg.GetYaxis().SetTitleSize(0.06) mg.GetXaxis().SetTitleSize(0.06) mg.GetXaxis().SetLabelSize(0.045) mg.GetYaxis().SetLabelSize(0.045) mg.GetYaxis().SetRangeUser(0.001, 4) mg.GetYaxis().SetTitleOffset(1.4) mg.GetYaxis().CenterTitle(True) mg.GetXaxis().SetTitleOffset(1.1) mg.GetXaxis().CenterTitle(True) mg.GetXaxis().SetNdivisions(508) if "qW" in label.split("_")[0] or "qZ" in label.split("_")[0]: mg.GetXaxis().SetLimits(0.9, 4.1) elif "WZ" in label.split("_")[0]: mg.GetXaxis().SetLimits(0.9, 2.1) else: mg.GetXaxis().SetLimits(0.9, 3.1) # histo to shade n = len(fChain) grgreen = rt.TGraph(2 * n) for i in range(0, n): grgreen.SetPoint(i, radmasses[i], y2up[i]) grgreen.SetPoint(n + i, radmasses[n - i - 1], y2down[n - i - 1]) grgreen.SetFillColor(rt.kGreen) grgreen.Draw("f") gryellow = rt.TGraph(2 * n) for i in range(0, n): gryellow.SetPoint(i, radmasses[i], y1up[i]) gryellow.SetPoint(n + i, radmasses[n - i - 1], y1down[n - i - 1]) gryellow.SetFillColor(rt.kYellow) gryellow.Draw("f,same") grmean.Draw("L") if obs: grobs.Draw("L,P,E") gtheory = rt.TGraphErrors(1) gtheory.SetLineColor(rt.kBlue) gtheory.SetLineWidth(3) ftheory = open("signalcrosssections.txt") j = 0 glogtheory = rt.TGraphErrors(1) for lines in ftheory.readlines(): for line in lines.split("\r"): if label.split("_")[0] in line: split = line.split(":") gtheory.SetPoint(j, float(split[0][-4:]) / 1000., float(split[1])) glogtheory.SetPoint(j, float(split[0][-4:]) / 1000., log(float(split[1]))) j += 1 mg.Add(gtheory, "L") gtheory.Draw("L") if "qW" in label.split("_")[0]: ltheory = "q* #rightarrow qW" if "qZ" in label.split("_")[0]: ltheory = "q* #rightarrow qZ" if "WW" in label.split("_")[0]: ltheory = "G_{RS} #rightarrow WW" if "ZZ" in label.split("_")[0]: ltheory = "G_{RS} #rightarrow ZZ" if "WZ" in label.split("_")[0]: ltheory = "W' #rightarrow WZ" crossing = 0 for mass in range(int(radmasses[0] * 1000.), int(radmasses[-1] * 1000.)): if exp(glogtheory.Eval(mass / 1000.)) > grmean.Eval( mass / 1000.) and crossing >= 0: print label, "exp crossing", mass crossing = -1 if exp(glogtheory.Eval(mass / 1000.)) < grmean.Eval( mass / 1000.) and crossing <= 0: print label, "exp crossing", mass crossing = 1 crossing = 0 for mass in range(int(radmasses[0] * 1000.), int(radmasses[-1] * 1000.)): if exp(glogtheory.Eval(mass / 1000.)) > grobs.Eval( mass / 1000.) and crossing >= 0: print label, "obs crossing", mass crossing = -1 if exp(glogtheory.Eval(mass / 1000.)) < grobs.Eval( mass / 1000.) and crossing <= 0: print label, "obs crossing", mass crossing = 1 leg = rt.TLegend(0.60, 0.65, 0.95, 0.89) leg.SetFillColor(rt.kWhite) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetBorderSize(0) if obs: leg.AddEntry(grobs, "Observed", "L,P") leg.AddEntry(grmean, "Expected", "L") leg.AddEntry(gryellow, "#pm 1 #sigma Expected", "f") leg.AddEntry(grgreen, "#pm 2 #sigma Expected", "f") leg.AddEntry(gtheory, ltheory, "L") #leg.SetHeader("X #rightarrow %s" %label.split("_")[0]) leg.Draw() banner = TLatex(0.22, 0.93, "CMS Preliminary, 19.8 fb^{-1}, #sqrt{s} = 8TeV") banner.SetNDC() banner.SetTextSize(0.045) banner.Draw() if withAcceptance: c1.SaveAs("brazilianFlag_acc_%s.root" % label) c1.SaveAs("brazilianFlag_acc_%s.pdf" % label) else: c1.SaveAs("brazilianFlag_%s.root" % label) c1.SaveAs("brazilianFlag_%s.pdf" % label)
def ReturnPaths(self, tree, index): ds = self.dataStruct ds.geiger_id = ROOT.std.vector('int')() ds.true_id = ROOT.std.vector('int')() ds.tracker_module = ROOT.std.vector('int')() ds.tracker_side = ROOT.std.vector('int')() ds.tracker_layer = ROOT.std.vector('int')() ds.tracker_column = ROOT.std.vector('int')() ds.x = ROOT.std.vector('double')() ds.y = ROOT.std.vector('double')() ds.z = ROOT.std.vector('double')() ds.ex = ROOT.std.vector('double')() ds.ey = ROOT.std.vector('double')() ds.ez = ROOT.std.vector('double')() N = tree.GetEntries() tree.SetBranchAddress('evtId', ROOT.AddressOf(ds, "evtId")) tree.SetBranchAddress('clId', ROOT.AddressOf(ds, "clId")) tree.SetBranchAddress('pathId', ROOT.AddressOf(ds, "pathId")) tree.SetBranchAddress('geiger_id', ROOT.AddressOf(ds, "geiger_id")) tree.SetBranchAddress('true_id', ROOT.AddressOf(ds, "true_id")) tree.SetBranchAddress('tracker_module', ROOT.AddressOf(ds, "tracker_module")) tree.SetBranchAddress('tracker_side', ROOT.AddressOf(ds, "tracker_side")) tree.SetBranchAddress('tracker_layer', ROOT.AddressOf(ds, "tracker_layer")) tree.SetBranchAddress('tracker_column', ROOT.AddressOf(ds, "tracker_column")) tree.SetBranchAddress('x', ROOT.AddressOf(ds, "x")) tree.SetBranchAddress('y', ROOT.AddressOf(ds, "y")) tree.SetBranchAddress('z', ROOT.AddressOf(ds, "z")) tree.SetBranchAddress('ex', ROOT.AddressOf(ds, "ex")) tree.SetBranchAddress('ey', ROOT.AddressOf(ds, "ey")) tree.SetBranchAddress('ez', ROOT.AddressOf(ds, "ez")) cldict = {} # First, find out the tree indices which correspond to our # event id index. Set the status of all other branches to "off" tree.SetBranchStatus("*", 0) tree.SetBranchStatus("evtId", 1) # Find the entries that correspond to our eventId listOfEntries = [] for i in range(N): tree.GetEntry(i) # self.dataStruct is filled if (ds.evtId == index): listOfEntries.append(i) # Re-enable all branches, looping over only those entries # that match our event index tree.SetBranchStatus("*", 1) clid = set() candidates = {} for i in range(len(listOfEntries)): tree.GetEntry(listOfEntries[i]) # self.dataStruct is filled clid.add(ds.clId) path = [] for xc, yc, zc, ex, ey, ez, gid, tid, tm, ts, tl, tc in zip( ds.x, ds.y, ds.z, ds.ex, ds.ey, ds.ez, ds.geiger_id, ds.true_id, ds.tracker_module, ds.tracker_side, ds.tracker_layer, ds.tracker_column): minfo = (gid, tid, tm, ts, tl, tc) path.append((xc, yc, zc, ex, ey, ez, minfo)) candidates[(ds.clId, ds.pathId)] = path result = [] for entry in clid: # unique clId numbers cp = ClusterPaths(entry) # cand = {} for tup, p in candidates.iteritems(): if tup[0] == entry: cp.add_path(tup[1], p) # cand[tup[1]] = p # cldict[entry] = cand result.append(cp) # return cldict return result # return list of ClusterPaths object
def setAddress(obj, flag): for branch in dir(obj): if branch.startswith('__'): continue tree.Branch(branch, rt.AddressOf(obj, branch), '%s/%s' % (branch, flag))
# Get the geometry. tFile.Get("EDepSimGeometry") # Get the event tree. events = tFile.Get("EDepSimEvents") # Example of looping over the events. for entry in events: print "Have event", entry.Event.EventId print "Have primaries", entry.Event.Primaries.size() print "Have primaries", entry.Event.Primaries[0].GeneratorName # Set the branch address. event = ROOT.TG4Event() events.SetBranchAddress("Event", ROOT.AddressOf(event)) # Get event zero. events.GetEntry(0) print "event number", event.EventId print "number of trajectories", event.Trajectories.size() for traj in event.Trajectories: print " Track Id: ", traj.TrackId print " Parent Id:", traj.ParentId print " Particle: ", traj.Name print " PDG Code: ", traj.PDGCode print " Points: ", traj.Points.size() print "number of segment detectors", event.SegmentDetectors.size() for det in event.SegmentDetectors:
#vname["wc"] = ["xA", "yA", "xB", "yB", "xC", "yC", "xD", "yD", "xE", "yE"] vname["wc"] = ["xA", "yA", "xB", "yB", "xC", "yC"] MAXDIGIS = 300 MAXTS = 10 # Treat pulse and pulse_adc like 1D array of length MAXDIGIS*MAXTS ROOT.gROOT.ProcessLine( "struct hbhe_struct {Int_t numChs; Int_t numTS; Int_t iphi[%(dg)d]; Int_t ieta[%(dg)d]; Int_t depth[%(dg)d]; Float_t pulse[%(dg)d * %(ts)d]; UChar_t pulse_adc[%(dg)d * %(ts)d]; Float_t ped[%(dg)d]; Float_t ped_adc[%(dg)d];};" % { "dg": MAXDIGIS, "ts": MAXTS }) shbhe = ROOT.hbhe_struct() for ivname in vname["hbhe"]: ntp["hbhe"].SetBranchAddress(ivname, ROOT.AddressOf(shbhe, ivname)) ROOT.gROOT.ProcessLine( "struct hf_struct {Int_t numChs; Int_t numTS; Int_t iphi[%(dg)d]; Int_t ieta[%(dg)d]; Int_t depth[%(dg)d]; Float_t pulse[%(dg)d * %(ts)d]; UChar_t pulse_adc[%(dg)d * %(ts)d]; Float_t ped[%(dg)d]; Float_t ped_adc[%(dg)d];};" % { "dg": MAXDIGIS, "ts": MAXTS }) shf = ROOT.hf_struct() for ivname in vname["hf"]: ntp["hf"].SetBranchAddress(ivname, ROOT.AddressOf(shf, ivname)) ROOT.gROOT.ProcessLine( "struct qie11_struct {Int_t numChs; Int_t numTS; Int_t iphi[%(dg)d]; Int_t ieta[%(dg)d]; Int_t depth[%(dg)d]; Float_t pulse[%(dg)d * %(ts)d]; Float_t ped[%(dg)d]; UChar_t pulse_adc[%(dg)d * %(ts)d]; Float_t ped_adc[%(dg)d]; bool capid_error[%(dg)d]; bool link_error[%(dg)d]; bool soi[%(dg)d * %(ts)d];};" % { "dg": MAXDIGIS,
def loop(events, dspt, tgeo, tout): event = ROOT.TG4Event() events.SetBranchAddress("Event", ROOT.AddressOf(event)) N = events.GetEntries() print "Starting loop over %d entries" % N ient = 0 for evt in dspt: if ient % 1000 == 0: print "Event %d of %d..." % (ient, N) if ient > nmax: break events.GetEntry(ient) # Loop over the primary vertices in the event for ivtx, vertex in enumerate(event.Primaries): # Reset the variables ResetVariables() t_ievt[0] = ient t_Ev[0] = evt.StdHepP4[ 3] # neutrino is first 4-vector, so 3 is always Ev # Get the reaction code t_Reac = vertex.GetReaction() # Set the vertex location for i in range(3): t_vtx[i] = vertex.GetPosition()[i] # Reset lepton trajectory ileptraj = -1 # Number of final state particle nfsp = 0 # Loop over the particles at the vertex for ipart, particle in enumerate(vertex.Particles): e = particle.GetMomentum()[3] p = (particle.GetMomentum()[0]**2 + particle.GetMomentum()[1]**2 + particle.GetMomentum()[2]**2)**0.5 m = (e**2 - p**2)**0.5 pdg = particle.GetPDGCode() t_fsPdg[nfsp] = pdg t_fsPx[nfsp] = particle.GetMomentum()[0] t_fsPy[nfsp] = particle.GetMomentum()[1] t_fsPz[nfsp] = particle.GetMomentum()[2] t_fsE[nfsp] = e nfsp += 1 # Look for the lepton (dicey, need match?) if abs(pdg) in [11, 12, 13, 14]: ileptraj = particle.GetTrackId() t_lepPdg[0] = pdg # set the muon momentum for output for i in range(3): t_p3lep[i] = particle.GetMomentum()[i] t_lepKE[0] = e - m t_lepE[0] = e assert ileptraj != -1, "There isn't a lepton!" t_nFS[0] = nfsp # Only interested in muons if abs(t_lepPdg[0]) != 13: continue # If there is a muon, determine how to reconstruct its momentum and charge exit = False inTMS = False leptraj = event.Trajectories[ileptraj] # Can loop over each trajectory #for traj in event.Trajectories: # Now find which volume the first hit of the lepton trajectory is startpt = leptraj.Points[0].GetPosition() startnode = tgeo.FindNode(startpt.X(), startpt.Y(), startpt.Z()) vertexname = startnode.GetName() if ("volTPCActive_" in vertexname or "volPixelPlane_" in vertexname or "volLAr_" in vertexname or "volArCLight_PV" in vertexname): t_muonStart[0] = 1 elif ("TMS" in vertexname or "modulelayer" in vertexname): t_muonStart[0] = 2 else: t_muonStart[0] = 0 # Now loop over the particles for p in leptraj.Points: pt = p.GetPosition() node = tgeo.FindNode(pt.X(), pt.Y(), pt.Z()) if node == None: continue volName = node.GetName() pPos = ROOT.TVector3(pt.X(), pt.Y(), pt.Z()) # Update the exit point if ("volTPCActive_" in volName or "volPixelPlane_" in volName or "volLAr_" in volName or "volArCLight_PV" in volName): t_muonExitPt[0] = pt.X() t_muonExitPt[1] = pt.Y() t_muonExitPt[2] = pt.Z() t_muonExitMom[0] = p.GetMomentum().x() t_muonExitMom[1] = p.GetMomentum().y() t_muonExitMom[2] = p.GetMomentum().z() t_muonExitKE[0] = (p.GetMomentum().Mag2() + muon_mass * 2)**0.5 - muon_mass else: exit = True # Check if it is in the TMS if ("TMS_" in volName or "modulelayer" in volName) and not inTMS: t_TMSKE[0] = (p.GetMomentum().Mag2() + muon_mass * 2)**0.5 - muon_mass inTMS = True # Get the endpoint endpt = leptraj.Points[-1].GetPosition() t_GlobalDeath[0] = endpt.X() t_GlobalDeath[1] = endpt.Y() t_GlobalDeath[2] = endpt.Z() node = tgeo.FindNode(endpt.X(), endpt.Y(), endpt.Z()) if node == None: continue endVolName = node.GetName() if "TPCActive" in endVolName: t_muonReco[0] = 1 # contained # Updated name in new geom elif "TMS" in endVolName: t_muonReco[0] = 2 # Scintillator stopper else: t_muonReco[0] = 0 # endpoint not in active material # look for muon hits in the ArgonCube arhits = [] for key in event.SegmentDetectors: # Updated name in new geom if key.first == "TPCActive_shape": arhits += key.second ar_muon_hits = [] for idx, hit in enumerate(arhits): tid = hit.Contrib[0] traj = event.Trajectories[tid] if traj.GetParentId() == -1 and abs(traj.GetPDGCode()) == 13: ar_muon_hits.append(hit) for idx, hit in enumerate(ar_muon_hits): hStart = ROOT.TVector3(hit.GetStart()[0], hit.GetStart()[1], hit.GetStart()[2]) xpt.push_back(hStart.x()) ypt.push_back(hStart.y()) zpt.push_back(hStart.z()) deposit.push_back(hit.GetEnergyDeposit()) #------------------------------------------------------- # look for muon hits in the scintillator hits = [] for key in event.SegmentDetectors: if key.first == "volTMS": hits += key.second muon_hits = [] for idx, hit in enumerate(hits): tid = hit.Contrib[0] traj = event.Trajectories[tid] # Check they are fundamental if traj.GetParentId() == -1 and abs(traj.GetPDGCode()) == 13: muon_hits.append(hit) if muon_hits: hMuonStart = muon_hits[0].GetStart() t_TMSBirth[0] = hMuonStart[0] t_TMSBirth[1] = hMuonStart[1] t_TMSBirth[2] = hMuonStart[2] for idx, hit in enumerate(muon_hits): hStart = ROOT.TVector3(hit.GetStart()[0], hit.GetStart()[1], hit.GetStart()[2]) hStop = ROOT.TVector3(hit.GetStop()[0], hit.GetStop()[1], hit.GetStop()[2]) Time = hit.GetStart()[3] xpt.push_back(hStart.x()) ypt.push_back(hStart.y()) zpt.push_back(hStart.z()) deposit.push_back(hit.GetEnergyDeposit()) hit = muon_hits[-1] hFinal = ROOT.TVector3(hit.GetStart()[0], hit.GetStart()[1], hit.GetStart()[2]) t_TMSDeath[0] = hFinal.x() t_TMSDeath[1] = hFinal.y() t_TMSDeath[2] = hFinal.z() else: t_TMSBirth[0] = -999.99 t_TMSBirth[1] = -999.99 t_TMSBirth[2] = -999.99 t_TMSDeath[0] = -999.99 t_TMSDeath[1] = -999.99 t_TMSDeath[2] = -999.99 tout.Fill() ient += 1
def _setup_structure(self): ''' set up structure of flsim output ''' self.datastruct.truetracker_nohits = 0 self.datastruct.truetracker_id = ROOT.std.vector('int')() self.datastruct.truetracker_module = ROOT.std.vector('int')() self.datastruct.truetracker_side = ROOT.std.vector('int')() self.datastruct.truetracker_layer = ROOT.std.vector('int')() self.datastruct.truetracker_column = ROOT.std.vector('int')() self.datastruct.truetracker_trackid = ROOT.std.vector('int')() self.datastruct.truetracker_parenttrackid = ROOT.std.vector('int')() self.datastruct.truetracker_time = ROOT.std.vector('double')() self.datastruct.truetracker_xstart = ROOT.std.vector('double')() self.datastruct.truetracker_ystart = ROOT.std.vector('double')() self.datastruct.truetracker_zstart = ROOT.std.vector('double')() self.datastruct.truetracker_xstop = ROOT.std.vector('double')() self.datastruct.truetracker_ystop = ROOT.std.vector('double')() self.datastruct.truetracker_zstop = ROOT.std.vector('double')() self.datastruct.truecalo_nohits = 0 self.datastruct.truecalo_id = ROOT.std.vector('int')() self.datastruct.truecalo_type = ROOT.std.vector('int')() self.datastruct.truecalo_module = ROOT.std.vector('int')() self.datastruct.truecalo_side = ROOT.std.vector('int')() self.datastruct.truecalo_column = ROOT.std.vector('int')() self.datastruct.truecalo_row = ROOT.std.vector('int')() self.datastruct.truecalo_wall = ROOT.std.vector('int')() self.datastruct.truecalo_time = ROOT.std.vector('double')() self.datastruct.truecalo_x = ROOT.std.vector('double')() self.datastruct.truecalo_y = ROOT.std.vector('double')() self.datastruct.truecalo_z = ROOT.std.vector('double')() self.datastruct.truecalo_energy = ROOT.std.vector('double')() self.datastruct.tracker_nohits = 0 self.datastruct.tracker_id = ROOT.std.vector('int')() self.datastruct.tracker_truehitid = ROOT.std.vector('int')() self.datastruct.tracker_module = ROOT.std.vector('int')() self.datastruct.tracker_side = ROOT.std.vector('int')() self.datastruct.tracker_layer = ROOT.std.vector('int')() self.datastruct.tracker_column = ROOT.std.vector('int')() self.datastruct.tracker_x = ROOT.std.vector('double')() self.datastruct.tracker_y = ROOT.std.vector('double')() self.datastruct.tracker_z = ROOT.std.vector('double')() self.datastruct.tracker_sigmaz = ROOT.std.vector('double')() self.datastruct.tracker_r = ROOT.std.vector('double')() self.datastruct.tracker_sigmar = ROOT.std.vector('double')() self.datastruct.calo_nohits = 0 self.datastruct.calo_id = ROOT.std.vector('int')() self.datastruct.calo_type = ROOT.std.vector('int')() self.datastruct.calo_module = ROOT.std.vector('int')() self.datastruct.calo_side = ROOT.std.vector('int')() self.datastruct.calo_column = ROOT.std.vector('int')() self.datastruct.calo_row = ROOT.std.vector('int')() self.datastruct.calo_wall = ROOT.std.vector('int')() self.datastruct.calo_time = ROOT.std.vector('double')() self.datastruct.calo_sigmatime = ROOT.std.vector('double')() self.datastruct.calo_energy = ROOT.std.vector('double')() self.datastruct.calo_sigmaenergy = ROOT.std.vector('double')() self.datastruct_truth.trueparticle_noparticles = 0 self.datastruct_truth.trueparticle_id = ROOT.std.vector('int')() self.datastruct_truth.trueparticle_type = ROOT.std.vector('int')() self.datastruct_truth.trueparticle_px = ROOT.std.vector('double')() self.datastruct_truth.trueparticle_py = ROOT.std.vector('double')() self.datastruct_truth.trueparticle_pz = ROOT.std.vector('double')() self.datastruct_truth.trueparticle_time = ROOT.std.vector('double')() self.datastruct_truth.trueparticle_kinenergy = ROOT.std.vector( 'double')() self.datastruct_truth.truevertex_x = 0.0 self.datastruct_truth.truevertex_y = 0.0 self.datastruct_truth.truevertex_z = 0.0 self.datastruct_truth.truevertex_time = 0.0 self.tree.SetBranchAddress( 'truetracker.nohits', ROOT.AddressOf(self.datastruct, "truetracker_nohits")) self.tree.SetBranchAddress( 'truetracker.id', ROOT.AddressOf(self.datastruct, "truetracker_id")) self.tree.SetBranchAddress( 'truetracker.module', ROOT.AddressOf(self.datastruct, "truetracker_module")) self.tree.SetBranchAddress( 'truetracker.side', ROOT.AddressOf(self.datastruct, "truetracker_side")) self.tree.SetBranchAddress( 'truetracker.layer', ROOT.AddressOf(self.datastruct, "truetracker_layer")) self.tree.SetBranchAddress( 'truetracker.column', ROOT.AddressOf(self.datastruct, "truetracker_column")) self.tree.SetBranchAddress( 'truetracker.time', ROOT.AddressOf(self.datastruct, "truetracker_time")) self.tree.SetBranchAddress( 'truetracker.xstart', ROOT.AddressOf(self.datastruct, "truetracker_xstart")) self.tree.SetBranchAddress( 'truetracker.ystart', ROOT.AddressOf(self.datastruct, "truetracker_ystart")) self.tree.SetBranchAddress( 'truetracker.zstart', ROOT.AddressOf(self.datastruct, "truetracker_zstart")) self.tree.SetBranchAddress( 'truetracker.xstop', ROOT.AddressOf(self.datastruct, "truetracker_xstop")) self.tree.SetBranchAddress( 'truetracker.ystop', ROOT.AddressOf(self.datastruct, "truetracker_ystop")) self.tree.SetBranchAddress( 'truetracker.zstop', ROOT.AddressOf(self.datastruct, "truetracker_zstop")) self.tree.SetBranchAddress( 'truetracker.trackid', ROOT.AddressOf(self.datastruct, "truetracker_trackid")) self.tree.SetBranchAddress( 'truetracker.parenttrackid', ROOT.AddressOf(self.datastruct, "truetracker_parenttrackid")) self.tree.SetBranchAddress( 'tracker.nohits', ROOT.AddressOf(self.datastruct, "tracker_nohits")) self.tree.SetBranchAddress( 'tracker.id', ROOT.AddressOf(self.datastruct, "tracker_id")) self.tree.SetBranchAddress( 'tracker.truehitid', ROOT.AddressOf(self.datastruct, "tracker_truehitid")) self.tree.SetBranchAddress( 'tracker.module', ROOT.AddressOf(self.datastruct, "tracker_module")) self.tree.SetBranchAddress( 'tracker.side', ROOT.AddressOf(self.datastruct, "tracker_side")) self.tree.SetBranchAddress( 'tracker.layer', ROOT.AddressOf(self.datastruct, "tracker_layer")) self.tree.SetBranchAddress( 'tracker.column', ROOT.AddressOf(self.datastruct, "tracker_column")) self.tree.SetBranchAddress( 'tracker.x', ROOT.AddressOf(self.datastruct, "tracker_x")) self.tree.SetBranchAddress( 'tracker.y', ROOT.AddressOf(self.datastruct, "tracker_y")) self.tree.SetBranchAddress( 'tracker.z', ROOT.AddressOf(self.datastruct, "tracker_z")) self.tree.SetBranchAddress( 'tracker.sigmaz', ROOT.AddressOf(self.datastruct, "tracker_sigmaz")) self.tree.SetBranchAddress( 'tracker.r', ROOT.AddressOf(self.datastruct, "tracker_r")) self.tree.SetBranchAddress( 'tracker.sigmar', ROOT.AddressOf(self.datastruct, "tracker_sigmar")) self.tree.SetBranchAddress( 'truecalo.nohits', ROOT.AddressOf(self.datastruct, "truecalo_nohits")) self.tree.SetBranchAddress( 'truecalo.id', ROOT.AddressOf(self.datastruct, "truecalo_id")) self.tree.SetBranchAddress( 'truecalo.type', ROOT.AddressOf(self.datastruct, "truecalo_type")) self.tree.SetBranchAddress( 'truecalo.module', ROOT.AddressOf(self.datastruct, "truecalo_module")) self.tree.SetBranchAddress( 'truecalo.side', ROOT.AddressOf(self.datastruct, "truecalo_side")) self.tree.SetBranchAddress( 'truecalo.column', ROOT.AddressOf(self.datastruct, "truecalo_column")) self.tree.SetBranchAddress( 'truecalo.row', ROOT.AddressOf(self.datastruct, "truecalo_row")) self.tree.SetBranchAddress( 'truecalo.wall', ROOT.AddressOf(self.datastruct, "truecalo_wall")) self.tree.SetBranchAddress( 'truecalo.time', ROOT.AddressOf(self.datastruct, "truecalo_time")) self.tree.SetBranchAddress( 'truecalo.x', ROOT.AddressOf(self.datastruct, "truecalo_x")) self.tree.SetBranchAddress( 'truecalo.y', ROOT.AddressOf(self.datastruct, "truecalo_y")) self.tree.SetBranchAddress( 'truecalo.z', ROOT.AddressOf(self.datastruct, "truecalo_z")) self.tree.SetBranchAddress( 'truecalo.energy', ROOT.AddressOf(self.datastruct, "truecalo_energy")) self.tree.SetBranchAddress( 'calo.nohits', ROOT.AddressOf(self.datastruct, "calo_nohits")) self.tree.SetBranchAddress('calo.id', ROOT.AddressOf(self.datastruct, "calo_id")) self.tree.SetBranchAddress( 'calo.type', ROOT.AddressOf(self.datastruct, "calo_type")) self.tree.SetBranchAddress( 'calo.module', ROOT.AddressOf(self.datastruct, "calo_module")) self.tree.SetBranchAddress( 'calo.side', ROOT.AddressOf(self.datastruct, "calo_side")) self.tree.SetBranchAddress( 'calo.column', ROOT.AddressOf(self.datastruct, "calo_column")) self.tree.SetBranchAddress('calo.row', ROOT.AddressOf(self.datastruct, "calo_row")) self.tree.SetBranchAddress( 'calo.wall', ROOT.AddressOf(self.datastruct, "calo_wall")) self.tree.SetBranchAddress( 'calo.time', ROOT.AddressOf(self.datastruct, "calo_time")) self.tree.SetBranchAddress( 'calo.sigmatime', ROOT.AddressOf(self.datastruct, "calo_sigmatime")) self.tree.SetBranchAddress( 'calo.energy', ROOT.AddressOf(self.datastruct, "calo_energy")) self.tree.SetBranchAddress( 'calo.sigmaenergy', ROOT.AddressOf(self.datastruct, "calo_sigmaenergy")) self.tree.SetBranchAddress( 'truevertex.x', ROOT.AddressOf(self.datastruct_truth, "truevertex_x")) self.tree.SetBranchAddress( 'truevertex.y', ROOT.AddressOf(self.datastruct_truth, "truevertex_y")) self.tree.SetBranchAddress( 'truevertex.z', ROOT.AddressOf(self.datastruct_truth, "truevertex_z")) self.tree.SetBranchAddress( 'truevertex.time', ROOT.AddressOf(self.datastruct_truth, "truevertex_time")) self.tree.SetBranchAddress( 'trueparticle.noparticles', ROOT.AddressOf(self.datastruct_truth, "trueparticle_noparticles")) self.tree.SetBranchAddress( 'trueparticle.id', ROOT.AddressOf(self.datastruct_truth, "trueparticle_id")) self.tree.SetBranchAddress( 'trueparticle.type', ROOT.AddressOf(self.datastruct_truth, "trueparticle_type")) self.tree.SetBranchAddress( 'trueparticle.px', ROOT.AddressOf(self.datastruct_truth, "trueparticle_px")) self.tree.SetBranchAddress( 'trueparticle.py', ROOT.AddressOf(self.datastruct_truth, "trueparticle_py")) self.tree.SetBranchAddress( 'trueparticle.pz', ROOT.AddressOf(self.datastruct_truth, "trueparticle_pz")) self.tree.SetBranchAddress( 'trueparticle.time', ROOT.AddressOf(self.datastruct_truth, "trueparticle_time")) self.tree.SetBranchAddress( 'trueparticle.kinenergy', ROOT.AddressOf(self.datastruct_truth, "trueparticle_kinenergy")) self.tree.SetBranchStatus("*", 0) # activate only the wanted branches self.tree.SetBranchStatus("truetracker.nohits", 1) self.tree.SetBranchStatus("truetracker.id", 1) self.tree.SetBranchStatus("truetracker.module", 1) self.tree.SetBranchStatus("truetracker.side", 1) self.tree.SetBranchStatus("truetracker.layer", 1) self.tree.SetBranchStatus("truetracker.column", 1) self.tree.SetBranchStatus("truetracker.time", 1) self.tree.SetBranchStatus("truetracker.xstart", 1) self.tree.SetBranchStatus("truetracker.ystart", 1) self.tree.SetBranchStatus("truetracker.zstart", 1) self.tree.SetBranchStatus("truetracker.xstop", 1) self.tree.SetBranchStatus("truetracker.ystop", 1) self.tree.SetBranchStatus("truetracker.zstop", 1) self.tree.SetBranchStatus("truetracker.trackid", 1) self.tree.SetBranchStatus("truetracker.parenttrackid", 1) self.tree.SetBranchStatus("tracker.nohits", 1) self.tree.SetBranchStatus("tracker.id", 1) self.tree.SetBranchStatus("tracker.module", 1) self.tree.SetBranchStatus("tracker.side", 1) self.tree.SetBranchStatus("tracker.layer", 1) self.tree.SetBranchStatus("tracker.column", 1) self.tree.SetBranchStatus("tracker.x", 1) self.tree.SetBranchStatus("tracker.y", 1) self.tree.SetBranchStatus("tracker.z", 1) self.tree.SetBranchStatus("tracker.sigmaz", 1) self.tree.SetBranchStatus("tracker.r", 1) self.tree.SetBranchStatus("tracker.sigmar", 1) self.tree.SetBranchStatus("tracker.truehitid", 1) self.tree.SetBranchStatus("truecalo.nohits", 1) self.tree.SetBranchStatus("truecalo.id", 1) self.tree.SetBranchStatus("truecalo.type", 1) self.tree.SetBranchStatus("truecalo.x", 1) self.tree.SetBranchStatus("truecalo.y", 1) self.tree.SetBranchStatus("truecalo.z", 1) self.tree.SetBranchStatus("truecalo.time", 1) self.tree.SetBranchStatus("truecalo.energy", 1) self.tree.SetBranchStatus("truecalo.module", 1) self.tree.SetBranchStatus("truecalo.side", 1) self.tree.SetBranchStatus("truecalo.wall", 1) self.tree.SetBranchStatus("truecalo.column", 1) self.tree.SetBranchStatus("truecalo.row", 1) self.tree.SetBranchStatus("calo.nohits", 1) self.tree.SetBranchStatus("calo.id", 1) self.tree.SetBranchStatus("calo.module", 1) self.tree.SetBranchStatus("calo.side", 1) self.tree.SetBranchStatus("calo.column", 1) self.tree.SetBranchStatus("calo.row", 1) self.tree.SetBranchStatus("calo.wall", 1) self.tree.SetBranchStatus("calo.time", 1) self.tree.SetBranchStatus("calo.sigmatime", 1) self.tree.SetBranchStatus("calo.energy", 1) self.tree.SetBranchStatus("calo.sigmaenergy", 1) self.tree.SetBranchStatus("calo.type", 1) self.tree.SetBranchStatus("truevertex.x", 1) self.tree.SetBranchStatus("truevertex.y", 1) self.tree.SetBranchStatus("truevertex.z", 1) self.tree.SetBranchStatus("truevertex.time", 1) self.tree.SetBranchStatus("trueparticle.noparticles", 1) self.tree.SetBranchStatus("trueparticle.id", 1) self.tree.SetBranchStatus("trueparticle.type", 1) self.tree.SetBranchStatus("trueparticle.px", 1) self.tree.SetBranchStatus("trueparticle.py", 1) self.tree.SetBranchStatus("trueparticle.pz", 1) self.tree.SetBranchStatus("trueparticle.time", 1) self.tree.SetBranchStatus("trueparticle.kinenergy", 1)
else: timestr = time.localtime() date = str(timestr[0]) + "_" + str(timestr[1]) + "_" + str( timestr[2]) + "_" + str(timestr[3]) + "_" + str( timestr[4]) os.system("mkdir " + outputDir + mode + "/" + lepton_mode + "/" + bin + "_" + date + "/") workingDir = outputDir + mode + "/" + lepton_mode + "/" + bin + "_" + date + "/" print "\n", bold, "ERROR directory", outputDir + mode + "/" + lepton_mode + "/" + bin + "/", "already existing", print "created directory", outputDir + mode + "/" + lepton_mode + "/" + bin + "_" + date + "/", "instead!", reset tree = ROOT.TTree( "Events", "Events", 1) #Construct the Events TTreefor the target file for var in variables: tree.Branch(var, ROOT.AddressOf(struct, var), var + '/F') if loadArrays: for arr in arrays: tree.Branch(arr, ROOT.AddressOf(struct, arr), arr + '[20]/F') root_file = workingDir + "histo_" + sample + "_" + analyzer_type + "_" + commoncf_string + ".root" if os.path.isfile(root_file): print bold, "ERROR", root_file, "already there! Adding Time!!!", reset timestr = time.localtime() root_file = workingDir + timestr[4] + timestr[ 5] + "histo_" + sample + "_" + analyzer_type + "_" + commoncf_string + ".root" #=======================================================================CREATED FILES AND DIRS if small: if number_events > 200: number_events = 2
def loop(events, tgeo, tout): offset = [0., 5.5, 411.] collarLo = [-320., -120., 30.] collarHi = [320., 120., 470.] # Initialize geometric efficiency module. geoEff = pyGeoEff.geoEff(args.seed) # Multiple of 64 doesn't waste bits geoEff.setNthrows(4992) # Use neutrino decay position, rather than fixed neutrino direction as symmetry axis geoEff.setUseFixedBeamDir(False) # Decay position in detector coordinates. Rough estimate from neutrino direction in mcc11v4 -- might want to update. In cm. geoEff.setDecayPos(-args.offaxis * 100, -5155, -55400) # 30 cm veto geoEff.setVetoSizes([30]) # 20, 30 and 40 MeV threshold geoEff.setVetoEnergyThresholds([20, 30, 40]) # Active detector dimensions geoEff.setActiveX(collarLo[0] - 30, collarHi[0] + 30) geoEff.setActiveY(collarLo[1] - 30, collarHi[1] + 30) geoEff.setActiveZ(collarLo[2] - 30, collarHi[2] + 30) # Range for translation throws. Use full active volume but fix X. geoEff.setRangeX(-1, -1) geoEff.setRandomizeX(False) geoEff.setRangeY(collarLo[1] - 30, collarHi[1] + 30) geoEff.setRangeZ(collarLo[2] - 30, collarHi[2] + 30) # Set offset between MC coordinate system and volumes defined above. geoEff.setOffsetX(offset[0]) geoEff.setOffsetY(offset[1]) geoEff.setOffsetZ(offset[2]) event = ROOT.TG4Event() events.SetBranchAddress("Event", ROOT.AddressOf(event)) N = events.GetEntries() print "Starting loop over %d entries" % N ient = 0 # This is unnecessary iwritten = 0 for ient in range(N): if ient % 100 == 0: print "Event %d of %d..." % (ient, N) events.GetEntry(ient) for ivtx, vertex in enumerate(event.Primaries): ## initialize output variables t_ievt[0] = ient t_vtx[0] = 0.0 t_vtx[1] = 0.0 t_vtx[2] = 0.0 t_p3lep[0] = 0.0 t_p3lep[1] = 0.0 t_p3lep[2] = 0.0 t_lepDeath[0] = 0.0 t_lepDeath[1] = 0.0 t_lepDeath[2] = 0.0 t_lepPdg[0] = 0 t_lepKE[0] = 0. t_muonExitPt[0] = 0.0 t_muonExitPt[1] = 0.0 t_muonExitPt[2] = 0.0 t_muonExitMom[0] = 0.0 t_muonExitMom[1] = 0.0 t_muonExitMom[2] = 0.0 t_muonReco[0] = -1 t_muon_endVolName.replace(0, ROOT.std.string.npos, "") t_muGArLen[0] = 0.0 t_hadTot[0] = 0. t_hadP[0] = 0. t_hadN[0] = 0. t_hadPip[0] = 0. t_hadPim[0] = 0. t_hadPi0[0] = 0. t_hadOther[0] = 0. t_hadCollar[0] = 0. t_nFS[0] = 0 ## done # now ID numucc reaction = vertex.Reaction # set the vertex location for output for i in range(3): t_vtx[i] = vertex.Position[i] / 10. - offset[i] # cm # fiducial vertex pre-cut if abs(t_vtx[0]) > 310. or abs( t_vtx[1]) > 110. or t_vtx[2] < 40. or t_vtx[2] > 360.: continue geoEff.setVertex(vertex.Position[0] / 10., vertex.Position[1] / 10., vertex.Position[2] / 10.) # Renew throws every 100th event written to the output file. if (iwritten % 100) == 0: geoEff.throwTransforms() t_geoEffThrowsY.clear() for i in geoEff.getCurrentThrowTranslationsY(): t_geoEffThrowsY.push_back(i) t_geoEffThrowsZ.clear() for i in geoEff.getCurrentThrowTranslationsZ(): t_geoEffThrowsZ.push_back(i) t_geoEffThrowsPhi.clear() for i in geoEff.getCurrentThrowRotations(): t_geoEffThrowsPhi.push_back(i) tGeoEfficiencyThrowsOut.Fill() ileptraj = -1 nfsp = 0 nHadrons = 0 # get the lepton kinematics from the edepsim file fsParticleIdx = {} for ipart, particle in enumerate(vertex.Particles): e = particle.Momentum[3] p = (particle.Momentum[0]**2 + particle.Momentum[1]**2 + particle.Momentum[2]**2)**0.5 m = (e**2 - p**2)**0.5 t_fsPdg[nfsp] = particle.PDGCode t_fsPx[nfsp] = particle.Momentum[0] t_fsPy[nfsp] = particle.Momentum[1] t_fsPz[nfsp] = particle.Momentum[2] t_fsE[nfsp] = e fsParticleIdx[particle.TrackId] = nfsp nfsp += 1 pdg = particle.PDGCode if abs(pdg) in [11, 12, 13, 14]: ileptraj = particle.TrackId t_lepPdg[0] = pdg # set the muon momentum for output for i in range(3): t_p3lep[i] = particle.Momentum[i] t_lepKE[0] = e - m assert ileptraj != -1, "There isn't a lepton??" t_nFS[0] = nfsp # If there is a muon, determine how to reconstruct its momentum and charge if abs(t_lepPdg[0]) == 13: leptraj = event.Trajectories[ileptraj] for p in leptraj.Points: pt = p.Position node = tgeo.FindNode(pt.X(), pt.Y(), pt.Z()) volName = node.GetName() active = False if "LAr" in volName or "PixelPlane" in volName or "sPlane" in volName: # in active volume, update exit points t_muonExitPt[0] = pt.X() / 10. - offset[0] t_muonExitPt[1] = pt.Y() / 10. - offset[1] t_muonExitPt[2] = pt.Z() / 10. - offset[2] t_muonExitMom[0] = p.Momentum.x() t_muonExitMom[1] = p.Momentum.y() t_muonExitMom[2] = p.Momentum.z() else: t_muonExitPt[0] = pt.X() / 10. - offset[0] t_muonExitPt[1] = pt.Y() / 10. - offset[1] t_muonExitPt[2] = pt.Z() / 10. - offset[2] break endpt = leptraj.Points[-1].Position node = tgeo.FindNode(endpt.X(), endpt.Y(), endpt.Z()) t_lepDeath[0] = endpt.X() / 10. - offset[0] t_lepDeath[1] = endpt.Y() / 10. - offset[1] t_lepDeath[2] = endpt.Z() / 10. - offset[2] endVolName = node.GetName() t_muon_endVolName.replace(0, ROOT.std.string.npos, endVolName) if "LArActive" in endVolName: t_muonReco[0] = 1 # contained elif "ECal" in endVolName: t_muonReco[0] = 2 # ECAL stopper else: t_muonReco[ 0] = 0 # endpoint not in active material, but might still be reconstructed by curvature if GAr length > 0 # look for muon hits in the gas TPC hits = [] for key in event.SegmentDetectors: if key.first in ["TPC_Drift1", "TPC_Drift2"]: hits += key.second tot_length = 0.0 for hit in hits: if hit.PrimaryId == ileptraj: # hit is due to the muon # TG4HitSegment::TrackLength includes all delta-rays, which spiral in gas TPC and give ridiculously long tracks hStart = ROOT.TVector3(hit.Start[0] / 10. - offset[0], hit.Start[1] / 10. - offset[1], hit.Start[2] / 10. - offset[2]) hStop = ROOT.TVector3(hit.Stop[0] / 10. - offset[0], hit.Stop[1] / 10. - offset[1], hit.Stop[2] / 10. - offset[2]) tot_length += (hStop - hStart).Mag() # look for muon hits in the ECAL ehits = [] for key in event.SegmentDetectors: if key.first in ["BarrelECal_vol", "EndcapECal_vol"]: ehits += key.second etot_length = 0.0 for hit in ehits: if hit.PrimaryId == ileptraj: # hit is due to the muon # TG4HitSegment::TrackLength includes all delta-rays, which spiral in gas TPC and give ridiculously long tracks hStart = ROOT.TVector3(hit.Start[0] / 10. - offset[0], hit.Start[1] / 10. - offset[1], hit.Start[2] / 10. - offset[2]) hStop = ROOT.TVector3(hit.Stop[0] / 10. - offset[0], hit.Stop[1] / 10. - offset[1], hit.Stop[2] / 10. - offset[2]) etot_length += (hStop - hStart).Mag() t_muGArLen[0] = tot_length t_muECalLen[0] = etot_length # hadronic containment -- find hits in ArgonCube hits = [] for key in event.SegmentDetectors: if key.first == "ArgonCube": hits += key.second # Truth-matching energy -- make dictionary of trajectory --> primary pdg traj_to_pdg = {} # For pi0s, stop at the photons to determine the visible energy due to gamma1/gamma2 tid_to_gamma = {} gamma_tids = [] for traj in event.Trajectories: mom = traj.ParentId tid = traj.TrackId if event.Trajectories[ mom].PDGCode == 111 and event.Trajectories[ tid].PDGCode == 22 and event.Trajectories[ mom].ParentId == -1: gamma_tids.append(tid) while mom != -1: tid = mom mom = event.Trajectories[mom].ParentId if mom in gamma_tids: tid_to_gamma[tid] = mom traj_to_pdg[traj] = event.Trajectories[tid].PDGCode collar_energy = 0. total_energy = 0. geoEff_EDepPosition = [] geoEff_EDepEnergy = [] track_length = [0. for i in range(nfsp)] dEdX = [[] for i in range(nfsp)] this_step = [[0., 0.] for i in range(nfsp)] end_point = [None for i in range(nfsp)] int_energy = [0. for i in range(nfsp)] trk_calo = [0. for i in range(nfsp)] gamma_energy = {} for g in gamma_tids: gamma_energy[g] = 0. for hit in hits: hStart = ROOT.TVector3(hit.Start[0] / 10. - offset[0], hit.Start[1] / 10. - offset[1], hit.Start[2] / 10. - offset[2]) hStop = ROOT.TVector3(hit.Stop[0] / 10. - offset[0], hit.Stop[1] / 10. - offset[1], hit.Stop[2] / 10. - offset[2]) # Don't use edep-sim's PrimaryId, which thinks you want to associate absoltely everything with the primary # Instead, get the actual contributors (usually only one) and take the biggest tid = hit.Contrib[0] traj = event.Trajectories[tid] if traj.ParentId == -1: # primary particle idx = fsParticleIdx[hit.PrimaryId] trk_calo[idx] += hit.EnergyDeposit end_point[idx] = hStop dx = (hStop - hStart).Mag() track_length[idx] += dx this_step[idx][1] += dx this_step[idx][0] += hit.EnergyDeposit if this_step[idx][1] > 0.5: dEdX[idx].append((this_step[idx][0], this_step[idx][1], hStart)) # MeV/cm this_step[idx] = [0., 0.] else: # non-primary energy for k, ep in enumerate(end_point): if ep is None: continue if (hStart - ep).Mag() < 10.: int_energy[k] += hit.EnergyDeposit if tid in tid_to_gamma: gamma_energy[tid_to_gamma[tid]] += hit.EnergyDeposit if hit.PrimaryId != ileptraj: # here we do want to associate stuff to the lepton hStart = ROOT.TVector3(hit.Start[0] / 10. - offset[0], hit.Start[1] / 10. - offset[1], hit.Start[2] / 10. - offset[2]) total_energy += hit.EnergyDeposit # check if hit is in collar region if hStart.x() < collarLo[0] or hStart.x( ) > collarHi[0] or hStart.y() < collarLo[1] or hStart.y( ) > collarHi[1] or hStart.z() < collarLo[2] or hStart.z( ) > collarHi[2]: collar_energy += hit.EnergyDeposit # Set up arrays for geometric efficiency for dim in range(3): geoEff_EDepPosition.append( (hit.Start[dim] + hit.Stop[dim]) / 2. / 10.) geoEff_EDepEnergy.append(hit.EnergyDeposit) # Determine primary particle pdg = traj_to_pdg[traj] if pdg in [11, -11, 13, -13]: continue # lepton elif pdg == 2212: t_hadP[0] += hit.EnergyDeposit elif pdg == 2112: t_hadN[0] += hit.EnergyDeposit elif pdg == 211: t_hadPip[0] += hit.EnergyDeposit elif pdg == -211: t_hadPim[0] += hit.EnergyDeposit elif pdg == 111: t_hadPi0[0] += hit.EnergyDeposit else: t_hadOther[0] += hit.EnergyDeposit t_hadTot[0] = total_energy t_hadCollar[0] = collar_energy geoEff.setHitSegEdeps(geoEff_EDepEnergy) geoEff.setHitSegPoss(geoEff_EDepPosition) geoEffThrowResultsList = geoEff.getHadronContainmentThrows() t_geoEffThrowResults.clear() for i in range(len(geoEffThrowResultsList)): iVec = ROOT.std.vector('vector< uint64_t >')() for j in range(len(geoEffThrowResultsList[i])): jVec = ROOT.std.vector('uint64_t')() for k in range(len(geoEffThrowResultsList[i][j])): jVec.push_back(geoEffThrowResultsList[i][j][k]) iVec.push_back(jVec) t_geoEffThrowResults.push_back(iVec) for i in range(nfsp): t_fsTrkLen[i] = track_length[i] # Average of anything in the last 3cm of track t_fsTrkEnddEdX[i] = 0. t_fsTrkFrontdEdX[i] = 0. totlen = 0. j = len(dEdX[i]) - 1 while j >= 0: totlen += dEdX[i][j][1] t_fsTrkEnddEdX[i] += dEdX[i][j][0] j -= 1 if totlen > 3.: break if totlen > 0.: t_fsTrkEnddEdX[i] /= totlen totlen = 0. for k in range(j + 1): totlen += dEdX[i][k][1] t_fsTrkFrontdEdX[i] += dEdX[i][k][0] if totlen > 0.: t_fsTrkFrontdEdX[i] /= totlen t_fsTrkEndpointBall[i] = int_energy[i] t_fsTrkCalo[i] = trk_calo[i] t_fsGamma1[i] = 0. t_fsGamma2[i] = 0. # Photons for t in gamma_tids: mom = event.Trajectories[t].ParentId if t_fsGamma1[mom] == 0.: t_fsGamma1[mom] = gamma_energy[t] elif t_fsGamma2[mom] == 0.: t_fsGamma2[mom] = gamma_energy[t] else: print "Pi0 has more than two photons wtf" tout.Fill() iwritten += 1 ient += 1 # This is unnecessary
def main(): # Parse all command line arguments using the argparse module. parser = argparse.ArgumentParser( description='PyRoot analysis demostrating the us of a DST.') parser.add_argument("dst_file", help="ROOT DST file to process") parser.add_argument("-o", "--output", help="Name of output pdf file") parser.add_argument("-m", "--mc", help="is MonteCarlo") args = parser.parse_args() # If an output file name was not specified, set a default name and warn # the user if args.output: output_file = args.output else: output_file = "analysis_output.root" print "[ HPS ANALYSIS ]: An output file name was not specified. Setting the name to " print output_file print "[ HPS ANALYSIS ]: Output file is " + output_file isMC = False if args.mc: print "[ HPS ANALYSIS ]: Setting to run as MC" isMC = True # Load the HpsEvent library. In this example, this is done by finding the # path to the HpsEvent shared library via the environmental variable # HPS_DST_PATH. The HPS_DST_PATH environmental variable points to the # location of the build directory containing all binaries and libraries. # In general, the location of the library can be anywhere a user wants it # to be as long as the proper path is specified. if os.getenv('HPS_DST_PATH') is None: print "[ HPS ANALYSIS ]: Error! Environmental variable HPS_DST_HOME is not set." print "\n[ HPS ANALYSIS ]: Exiting ..." sys.exit(2) hps_dst_path = os.environ['HPS_DST_PATH'] hps_dst_path += "/build/lib/libHpsEvent.so" print "Loading HpsEvent Library from " + hps_dst_path # Load the library in ROOT import ROOT ROOT.gSystem.Load(hps_dst_path) # import the modules used by HpsEvent i.e. HpsEvent, # SvtTrack, EcalCluster ... from ROOT import HpsEvent, SvtTrack, GblTrack, EcalCluster, EcalHit, TChain, TTree, HpsParticle ################################# # Event Selection ################################ ebeam = 1.05 #clean up event first nTrkMax = 5 nPosMax = 2 # vertex quality cuts for vertexing v0Chi2 = 10.0 v0PzMax = 1.2 v0PzMin = 0.8 v0PyMax = 0.2 #absolute value v0PxMax = 0.2 #absolute value v0VyMax = 1.0 # mm from target v0VxMax = 2.0 # mm from target # track quality cuts trkChi2 = 20.0 # trkChi2=100.0 beamCut = 0.8 isoCut = 1.0 minPCut = 0.25 trkPyMax = 0.2 trkPxMax = 0.2 slopeCut = 0.0 z0Cut = 0.5 ############## # ESum slices; upper limits nSlicesESum = 5 esumMin = 0.55 esumMax = 1.2 sliceSizeESum = 0.1 #100MeV starting at esumMin ############## trackKiller = False tkEnergy = 0.3 tkEff = 0.75 ############## requireECalMatch = True useGBL = True # Open the ROOT file # root_file = ROOT.TFile(str(args.dst_file)) # Get the TTree "HPS_EVENT" containing the HpsEvent branch and all # other colletions # tree = root_file.Get("HPS_Event") #use a TChain print "[ HPS ANALYSIS ]: Reading in root chain from " + args.dst_file tree = ROOT.TChain("HPS_Event") tree.Add(str(args.dst_file) + "*") # Create an HpsEvent object in order to read the TClonesArray # collections hps_event = HpsEvent() b_hps_event = tree.SetBranchAddress("Event", ROOT.AddressOf(hps_event)) # Get the HpsEvent branch from the TTree # b_hps_event = tree.GetBranch("Event") # b_hps_event.SetAddress(ROOT.AddressOf(hps_event)) #--- Analysis ---# #----------------# #counters nEvents = 0 nPassBasicCuts = 0 nPassESumCuts = 0 nPassV0Cuts = 0 nPassTrkCuts = 0 nPassIsoCuts = 0 nPassNCand = 0 nPassECalMatch = 0 myhist = myHistograms() for entry in xrange(0, tree.GetEntries()): # Print the event number every 500 events if (entry + 1) % 10000 == 0: print "Event " + str(entry + 1) tree.GetEntry(entry) if not hps_event.isPair1Trigger() and not isMC: continue nEvents += 1 # Loop over all tracks in the event npositrons = 0 n_tracks = 0 for track_n in xrange(0, hps_event.getNumberOfTracks()): track = hps_event.getTrack(track_n) if track is None: continue # if not (useGBL ^ track.type<32) : continue n_tracks += 1 if track.getCharge() > 0: npositrons += 1 # print "nTracks = "+str(n_tracks)+"; nPositrons = "+str(npositrons) if n_tracks > nTrkMax: continue if n_tracks < 2: continue if npositrons < 1 or npositrons > nPosMax: continue nPassBasicCuts += 1 # print "passed basic cuts" candidateList = [] bestCandidate = -99 nCandidate = 0 # loop over all v0 candidates... for bsc_index in xrange( 0, hps_event.getNumberOfParticles(HpsParticle.BSC_V0_CANDIDATE)): particle = hps_event.getParticle(HpsParticle.BSC_V0_CANDIDATE, bsc_index) if useGBL and particle.getType() < 32: continue if not useGBL and particle.getType() > 31: continue # Only look at particles that have two daugther particles... daughter_particles = particle.getParticles() if daughter_particles.GetSize() != 2: continue # Only look at particles that are composed of e+e- pairs if daughter_particles.At(0).getCharge() * daughter_particles.At( 1).getCharge() > 0: continue # print "Passed daughter number cuts" electron = daughter_particles.At(0) positron = daughter_particles.At(1) if daughter_particles.At(0).getCharge() > 0: electron = daughter_particles.At(1) positron = daughter_particles.At(0) pEle = electron.getMomentum() pPos = positron.getMomentum() v0Sum = pMag(pSum(pEle, pPos)) if v0Sum > v0PzMax: continue if v0Sum < v0PzMin: continue nPassESumCuts += 1 vchi2 = particle.getVertexFitChi2() vposition = particle.getVertexPosition() vmomentum = particle.getMomentum() if vchi2 > v0Chi2: continue if abs(vposition[0]) > v0VxMax: continue if abs(vposition[1]) > v0VyMax: continue nPassV0Cuts += 1 # print "Passed v0 cuts" if pMag(pEle) > beamCut or pMag(pPos) > beamCut: continue if pMag(pEle) < minPCut or pMag(pPos) < minPCut: continue if pEle[1] * pPos[1] > 0: continue # print particle.getTracks().At(0).GetEntries() # eleTrk=GblTrack(particle.getTracks().At(0)) # posTrk=GblTrack(particle.getTracks().At(1)) # if eleTrk.getCharge()>0 : # eleTrk=GblTrack(particle.getTracks().At(1)) # posTrk=GblTrack(particle.getTracks().At(0)) eleTrk = electron.getTracks().At(0) posTrk = positron.getTracks().At(0) if eleTrk.getChi2() > trkChi2 or posTrk.getChi2() > trkChi2: continue if abs(eleTrk.getZ0()) > z0Cut or abs(posTrk.getZ0()) > z0Cut: continue # if abs(eleTrk.getTanLambda())<slopeCut or abs(posTrk.getTanLambda())<slopeCut : # continue if isMC and trackKiller: if pMag(pEle) < tkEnergy and random.random() > tkEff: continue nPassTrkCuts += 1 if requireECalMatch: if positron.getClusters().GetEntries() == 0: continue if electron.getClusters().GetEntries() == 0: continue nPassECalMatch += 1 if abs(eleTrk.getIsolation(0)) < isoCut or abs( eleTrk.getIsolation(1)) < isoCut: continue if abs(posTrk.getIsolation(0)) < isoCut or abs( posTrk.getIsolation(1)) < isoCut: continue nPassIsoCuts += 1 #Passed the cuts..append the candidate index candidateList.append(bsc_index) ######################### # found some candidates...lets fill plots... ######################### for index in range(0, len(candidateList)): particle = hps_event.getParticle(HpsParticle.BSC_V0_CANDIDATE, candidateList[index]) ucparticle = hps_event.getParticle(HpsParticle.UC_V0_CANDIDATE, candidateList[index]) myhist.fillCandidateHistograms(particle, ucparticle) if nPassIsoCuts > 0: myhist.saveHistograms(output_file) print "\t\t\tTrident Selection Summary" print "******************************************************************************************" print "Number of Events:\t\t", nEvents, "\t\t\t", float( nEvents) / nEvents, "\t\t\t", float(nEvents) / nEvents print "N(particle) Cuts:\t\t", nPassBasicCuts, "\t\t\t", float( nPassBasicCuts) / nEvents, "\t\t\t", float(nPassBasicCuts) / nEvents print "ESum Cuts:\t\t", nPassESumCuts, "\t\t\t", float( nPassESumCuts) / nPassBasicCuts, "\t\t\t", float( nPassESumCuts) / nEvents print "V0 Vertex Cuts:\t\t", nPassV0Cuts, "\t\t\t", float( nPassV0Cuts) / nPassESumCuts, "\t\t\t", float(nPassV0Cuts) / nEvents print "Tracking Cuts:\t\t", nPassTrkCuts, "\t\t\t", float( nPassTrkCuts) / nPassV0Cuts, "\t\t\t", float(nPassTrkCuts) / nEvents print "ECal Match Cuts:\t\t", nPassECalMatch, "\t\t\t", float( nPassECalMatch) / nPassTrkCuts, "\t\t\t", float( nPassECalMatch) / nEvents print "Isolation Cuts:\t\t", nPassIsoCuts, "\t\t\t", float( nPassIsoCuts) / nPassECalMatch, "\t\t\t", float(nPassIsoCuts) / nEvents
def main(): global beamEnergy # Parse all command line arguments using the argparse module. parser = argparse.ArgumentParser(description='PyRoot analysis demostrating the us of a DST.') parser.add_argument("dst_file", help="ROOT DST file to process") parser.add_argument("-o", "--output", help="Name of output pdf file") parser.add_argument("-m", "--mc", help="is MonteCarlo") parser.add_argument("-p", "--pulser", help="is Pulser") parser.add_argument("-e","--energy",help="beam energy") args = parser.parse_args() # If an output file name was not specified, set a default name and warn # the user if args.output: output_file = args.output else: output_file = "analysis_output.root" print "[ HPS ANALYSIS ]: An output file name was not specified. Setting the name to " print output_file print "[ HPS ANALYSIS ]: Output file is "+output_file isMC=False if args.mc: print "[ HPS ANALYSIS ]: Setting to run as MC" isMC=True isPulser=False if args.pulser: print "[ HPS ANALYSIS ]: Setting to run from a pulser file" isPulser=True if args.energy : print 'Setting beam energy to '+args.energy beamEnergy=float(args.energy) myhist=myHistograms(beamEnergy) ################################# # Event Selection ################################ #clean up event first #### nominal selection requireECalFiducial = False requireECalSuperFiducial = False # this is included as separate histograms now...leave false! positronMomentumFromPositionCut = False # this is included as separate histograms now...leave false! requireTopBottomCut = True requireLeftRightCut = True if isMC : smearEnergy=False smearRes=0.05 myhist.setSmearEnergy(smearEnergy,smearRes) L1Ele = True # require L1 hit for Ele L1Pos = False # require L1 hit for Pos L6Ele = False # require L1 hit for Ele L6Pos = False # require L1 hit for Pos trackKiller=True killInMomentum=False killInClusterPosition=False killInTrackSlope = True # effFileName='/u/br/mgraham/hps-analysis/TrackEfficiency/cop180_EfficiencyResults.root' # effDataName='h_Ecl_hps_005772_eleEff' # effMCName='h_Ecl_tritrig-NOSUMCUT_HPS-EngRun2015-Nominal-v5-0_eleEff' effFileName='/u/br/mgraham/hps-analysis/TrackEfficiency/cop180_midESum_TwoD-EfficiencyResults.root' effDataName='h_XvsY_hps_005772_eleEff' effMCName='h_XvsY_tritrig-NOSUMCUT_HPS-EngRun2015-Nominal-v5-0_eleEff' if isMC and trackKiller and killInClusterPosition : effFile=ROOT.TFile(effFileName) print 'Getting data efficiency from '+effFileName # effData=getEffTH1(effFile,effDataName) # effMC=getEffTH1(effFile,effMCName) effData=getEffTH2(effFile,effDataName) effMC=getEffTH2(effFile,effMCName) effData.Print("v") effMC.Print("v") effData.Divide(effMC) # this will be the killing factor effData.Print("V") if isMC and trackKiller and killInTrackSlope: # effSlopeFileName='/u/br/mgraham/hps-analysis/WABs/EmGamma-L1HitEfficiencyResults.root' effSlopeFileName='/u/home/mgraham/HPS-CODE/ANALYSIS/users/mgraham/TridentWABs2016/EmGamma-L1HitEfficiencyResults-2016.root' effRatioName='p2slopehps_007963.1GamEm_L1HitInefficiency' effSlopeFile=ROOT.TFile(effSlopeFileName) effSlopeFile.ls() effSlopeData=getEffTH1(effSlopeFile,effRatioName) effSlopeData.Print("v") print 'L1 Hit Efficiency vs Slope: MC' fixTH1EffBins(effSlopeData) # Open the ROOT file # root_file = ROOT.TFile(str(args.dst_file)) # Get the TTree "HPS_EVENT" containing the HpsEvent branch and all # other colletions # tree = root_file.Get("HPS_Event") #use a TChain print "[ HPS ANALYSIS ]: Reading in root chain from "+args.dst_file tree=ROOT.TChain("HPS_Event") tree.Add(str(args.dst_file)+"*") # Create an HpsEvent object in order to read the TClonesArray # collections hps_event = HpsEvent() b_hps_event = tree.SetBranchAddress("Event", ROOT.AddressOf(hps_event)) #--- Analysis ---# #----------------# #counters nEvents=0 nPassBasicCuts=0 # //================ Time coincidence ====================================== coincide_pars_mean = [0.289337, -2.81998, 9.03475, -12.93, 8.71476, -2.26969] coincide_pars_sigm = [4.3987, -24.2371, 68.9567, -98.2586, 67.562, -17.8987] formula_pol5 = "[0] + x*( [1] + x*( [2] + x*( [3] + x*( [4] + x*( [5] ) ) ) ) ) " f_coincide_clust_mean = ROOT.TF1("f_coincide_clust_mean", formula_pol5, 0., 1.4) f_coincide_clust_sigm = ROOT.TF1("f_coincide_clust_sigm", formula_pol5, 0., 1.4) f_coincide_clust_mean.SetParameters(np.array(coincide_pars_mean)) f_coincide_clust_sigm.SetParameters(np.array(coincide_pars_sigm)) # //The cut is === mean - 3sigma < dt < mean + 3sigma === clTimeMin = 30 clTimeMax = 50 if beamEnergy == 2.3 : clTimeMin = 40 clTimeMax = 65 energyRatio=beamEnergy/1.05 #ratio of beam energies references to 1.05 GeV (2015 run) print("Total number of events in tree = "+str(tree.GetEntries())) seedCnt=0 # Loop over all events in the file for entry in xrange(0, tree.GetEntries()) : # Print the event number every 500 events if (entry+1)%100 == 0 : print "Event " + str(entry+1) tree.GetEntry(entry) if not hps_event.isPair1Trigger() and not isMC and not isPulser: continue nEvents+=1 nPassBasicCuts+=1 # print "passed basic cuts" pairList=[] bestCandidate=-99 pairsFound=0 for i in range(0,hps_event.getNumberOfEcalClusters()) : cl1=hps_event.getEcalCluster(i) cl1Position=cl1.getPosition() cl_xi=cl1Position[0] cl_yi=cl1Position[1] cl_zi=cl1Position[2] cl_ti=cl1.getClusterTime() cl_Ei=cl1.getEnergy() myhist.h_clTime1vsclE.Fill(cl_Ei,cl_ti) cl_di = math.sqrt( (cl_xi - phot_nom_x)*(cl_xi - phot_nom_x) + cl_yi*cl_yi ) # print 'looking at clusters' #if(!fid_ECal(cl_xi,cl_yi)) # continue if requireECalFiducial and not myhist.inFiducialRegion(cl_xi, cl_yi) : continue if requireECalSuperFiducial and not myhist.inSuperFiducialRegion(cl_xi, cl_yi) : continue if not (cl_ti > clTimeMin and cl_ti < clTimeMax ): continue if positronMomentumFromPositionCut and not myhist.momFromPositionEclUpperCut(cl_Ei,myhist.momFromECalPosition(cl_xi,cl_zi,beamAngle,myhist.BEff)) : continue # print 'Found first good cluster' for j in range(i+1,hps_event.getNumberOfEcalClusters()) : cl2=hps_event.getEcalCluster(j) cl2Position=cl2.getPosition() cl_xj=cl2Position[0] cl_yj=cl2Position[1] cl_zj=cl2Position[2] cl_tj=cl2.getClusterTime() cl_Ej=cl2.getEnergy() cl_dj =math.sqrt( (cl_xj - phot_nom_x)*(cl_xj - phot_nom_x) + cl_yj*cl_yj ) Esum = cl_Ei + cl_Ej if requireECalFiducial and not myhist.inFiducialRegion(cl_xj,cl_yj): continue if requireECalSuperFiducial and not myhist.inSuperFiducialRegion(cl_xj,cl_yj): continue if not (cl_tj > clTimeMin and cl_tj < clTimeMax ): continue if positronMomentumFromPositionCut and not myhist.momFromPositionEclUpperCut(cl_Ej,myhist.momFromECalPosition(cl_xj,cl_zj,beamAngle,myhist.BEff)) : continue # print 'Passed the probable positron cut' myhist.h_clTime1vsclTime2.Fill(cl_ti,cl_tj) dt = cl_ti - cl_tj # delt_t_mean = f_coincide_clust_mean.Eval(Esum) # delt_t_sigm = f_coincide_clust_sigm.Eval(Esum) # divide by 2 since these parameters were extracted from 1.05GeV Data (this is kludgy!) delt_t_mean = f_coincide_clust_mean.Eval(Esum/energyRatio) delt_t_sigm = f_coincide_clust_sigm.Eval(Esum/energyRatio) if not (dt < delt_t_mean + 3*delt_t_sigm and dt > delt_t_mean - 3*delt_t_sigm) : continue # //make sure they are top/bottom # print 'Passed the timing cut' # print str(cl_yi)+" " + str(cl_yj) if requireTopBottomCut and cl_yi*cl_yj>0 : continue if requireLeftRightCut and cl_xi*cl_xj>0 : continue # print 'Found a pair!!!!' clpair=[cl1,cl2] pairList.append(clpair) pairsFound+=len(pairList) # if len(pairList) >0 : print "found this many pairs "+str(len(pairList)) fspList=[] for i in xrange(0, hps_event.getNumberOfParticles(HpsParticle.FINAL_STATE_PARTICLE)): fspList.append( hps_event.getParticle(HpsParticle.FINAL_STATE_PARTICLE,i)) ######################### # found some candidates...lets fill plots... ######################### removeL1HitEle=False removeL1HitPos=False for pair in pairList : if pair[0].getPosition()[1] >0 : clTop=pair[0] clBottom=pair[1] else : clTop=pair[1] clBottom=pair[0] clTopPosition=clTop.getPosition() clBottomPosition=clBottom.getPosition() topX=clTopPosition[0] topY=clTopPosition[1] topZ=clTopPosition[2] botX=clBottomPosition[0] botY=clBottomPosition[1] botZ=clBottomPosition[2] topE=clTop.getEnergy() botE=clBottom.getEnergy() Esum=topE+botE Ediff=abs(topE-botE) cl_impact_angleTop = math.atan2(topY, topX - phot_nom_x)*radian cl_impact_angleBottom = math.atan2(botY,botX - phot_nom_x)*radian if cl_impact_angleTop < 0. : cl_impact_angleTop = cl_impact_angleTop + 360. if cl_impact_angleBottom < 0. : cl_impact_angleBottom = cl_impact_angleBottom + 360. coplanarity= cl_impact_angleBottom - cl_impact_angleTop myhist.h_coplan_Esum1.Fill(Esum,coplanarity) # cl_d_top= math.sqrt( (topX - phot_nom_x)*(topX - phot_nom_x) + topY*topY )- (60. + 100*(topE - 0.85)*(topE - 0.85) ) # cl_d_bottom= math.sqrt( (botX - phot_nom_x)*(botX - phot_nom_x) + botY*botY )- (60. + 100*(botE - 0.85)*(botE - 0.85) ) #do track matching trTop=ecalMatchTrack(fspList,clTop) trBottom=ecalMatchTrack(fspList,clBottom) #initial PDG assignments trEle=trTop trPos=trBottom clEle=clTop clPos=clBottom if topX > 0 : #assign the ele & pos with respect to the side of ECAL the cluster is on trEle=trBottom clEle=clBottom trPos=trTop clPos=clTop if trEle is not None and trEle.getPDG() == -11 :# whoops, it's a positron trEle=trBottom trPos=trTop clEle=clBottom clPos=clTop # if trPos is not None and trPos.getPDG() == 11 : # whoops, it's an electron # trEle=trBottom # trPos=trTop # clEle=clBottom # clPos=clTop #for ++ or -- events, this will get flipped twice...live with it... if topY*botY >0 : print "both clusters in same half?? How could this happen?"+str(topY)+" vs "+str(botY) if trackKiller and isMC: if killInMomentum : p=clEle.getEnergy() bin=effData.FindBin(p) tkEff=effData.GetBinContent(bin) print str(p)+ ' '+str(bin)+' '+str(tkEff) if random.random()>tkEff : #high ratio of efficiencies, this hardly kills...low, kills a lot print "REJECTING THIS ELECTRON TRACK!!! "+str(p) trEle=None #### same thing for positron side p=clPos.getEnergy() bin=effData.FindBin(p) tkEff=effData.GetBinContent(bin) print str(p)+' '+str(bin)+' '+str(tkEff) if random.random()>tkEff : #high ratio of efficiencies, this hardly kills...low, kills a lot print "REJECTING THIS ELECTRON TRACK!!! "+str(p) trPos=None if killInClusterPosition: clX=clEle.getPosition()[0] clY=clEle.getPosition()[1] bin=effData.FindBin(clX,clY) tkEff=effData.GetBinContent(bin) if random.random()>tkEff and tkEff!=0.0: print str(clX)+ ' '+str(clY)+' '+str(bin)+' '+str(tkEff) print "REJECTING THIS ELECTRON TRACK!!! "+str(clX) trEle=None clX=clPos.getPosition()[0] clY=clPos.getPosition()[1] bin=effData.FindBin(-clX+80,clY) # flip sign +80mm for positron side (this isn't strictly correct)!!! tkEff=effData.GetBinContent(bin) if random.random()>tkEff and tkEff!=0.0 : print str(clX)+ ' '+str(clY)+' '+str(bin)+' '+str(tkEff) print "REJECTING THIS POSITRON TRACK!!! "+str(clX) trPos=None if killInTrackSlope: if trEle is not None and len(trEle.getTracks())>0: # print("found an electron...kill it!!!") trk=trEle.getTracks()[0] nHits=len(trk.getSvtHits()) slp=trk.getTanLambda() rndm=random.random() ibin=effSlopeData.FindBin(slp) eff=1-effSlopeData.GetBinContent(ibin) #the slope "efficiency" is actually an inefficiency # print(str(rndm)+" "+str(eff)) if rndm>eff: if nHits==5: print('Removing this electron due to L1 inefficiency') trEle=None else : print(' Removing this electron L1 hit due to inefficiency') removeL1HitEle=True if trPos is not None and len(trPos.getTracks())>0: # print("found an positron...kill it!!!") trk=trPos.getTracks()[0] nHits=len(trk.getSvtHits()) slp=trk.getTanLambda() rndm=random.random() ibin=effSlopeData.FindBin(slp) eff=1-effSlopeData.GetBinContent(ibin) #the slope "efficiency" is actually an inefficiency # print(str(rndm)+" "+str(eff)) if rndm>eff: if nHits==5: print('Removing this positron due to L1 inefficiency') trPos=None else : print('Removing this positron L1 hit due to inefficiency') removeL1HitPos=True #require layer 1 if L1Ele and (not myhist.hasL1Hit(trEle) or removeL1HitEle): trEle=None if L1Pos and (not myhist.hasL1Hit(trPos) or removeL1HitPos): trPos=None #require layer 6 if L6Ele and not myhist.hasLXHit(trEle,6): trEle=None if L6Pos and not myhist.hasLXHit(trPos,6): trPos=None myhist.fillBand("_copAll_",trEle,clEle,trPos,clPos) if abs(coplanarity-180)<10 : # some debugging here... # for events where there is a positron track and no electron track # check to see if there maybe is a track that's could be associated with this clus if trEle is None and trPos is not None and trPos.getCharge()>0 : nMatchEle=0; print 'found positron but not electron! ele energy = '+str(clEle.getEnergy())+'; ele clX = '+str(clEle.getPosition()[0])+'; ele clY = '+str(clEle.getPosition()[1]) #loop through the electrons in event and check to see if on is in the same half for fsp_n in xrange(0, hps_event.getNumberOfParticles(HpsParticle.FINAL_STATE_PARTICLE)) : fsp = hps_event.getParticle(HpsParticle.FINAL_STATE_PARTICLE,fsp_n) if fsp.getType() !=0 : if fsp.getType() > 32 : continue track=fsp.getTracks()[0] slope=track.getTanLambda() if fsp.getCharge()<0 and slope*clEle.getPosition()[1]>0 and pMag(fsp.getMomentum())<0.8 : nMatchEle=nMatchEle+1 print 'found and electron in right half!!' print 'track p = '+str(pMag(fsp.getMomentum())) trkAtEcal=track.getPositionAtEcal() delX=trkAtEcal[0]-clEle.getPosition()[0] delY=trkAtEcal[1]-clEle.getPosition()[1] print 'trk-clEle delX = '+str(delX)+'; delY = '+str(delY) myhist.h_misEle_delXvsdelY.Fill(delX,delY) myhist.h_misEle_trkPvsclE.Fill(pMag(fsp.getMomentum()),clEle.getEnergy()) if len(fsp.getClusters())>0 : clThisE=fsp.getClusters()[0] print '...this track matched to cluster with ele energy = '+str(clThisE.getEnergy())+'; ele clX = '+str(clThisE.getPosition()[0])+'; ele clY = '+str(clThisE.getPosition()[1]) ######################## myhist.h_misEle_eleTrks.Fill(nMatchEle) myhist.fillBand("_cop180_",trEle,clEle,trPos,clPos) if Esum>myhist.midESumLow and Esum<myhist.midESumHigh : myhist.fillBand("_cop180_midESum_",trEle,clEle,trPos,clPos) if myhist.inSuperFiducialRegion(topX,topY) and myhist.inSuperFiducialRegion(botX,botY): myhist.fillBand("_cop180_midESum_SuperFid",trEle,clEle,trPos,clPos) if not myhist.inSuperFiducialRegion(topX,topY) and not myhist.inSuperFiducialRegion(botX,botY): myhist.fillBand("_cop180_midESum_AntiSuperFid",trEle,clEle,trPos,clPos) if myhist.inSuperFiducialRegion(topX,topY) and myhist.inSuperFiducialRegion(botX,botY): myhist.fillBand("_cop180_SuperFid",trEle,clEle,trPos,clPos) if not myhist.inPhotonHole(topX,topY) and not myhist.inPhotonHole(botX,botY) : myhist.fillBand("_cop180_SuperFid_CutPhotons",trEle,clEle,trPos,clPos) if not myhist.inSuperFiducialRegion(topX,topY) and not myhist.inSuperFiducialRegion(botX,botY): myhist.fillBand("_cop180_AntiSuperFid",trEle,clEle,trPos,clPos) if Ediff<0.2 and len(pairList)==1: myhist.fillBand("_cop180_Holly_",trEle,clEle,trPos,clPos) if not myhist.inPhotonHole(topX,topY) and not myhist.inPhotonHole(botX,botY) : myhist.fillBand("_cop180_CutPhotons",trEle,clEle,trPos,clPos) elif abs(coplanarity-160)<10 : myhist.fillBand("_cop160_",trEle,clEle,trPos,clPos) if Esum>myhist.midESumLow and Esum<myhist.midESumHigh : myhist.fillBand("_cop160_midESum_",trEle,clEle,trPos,clPos) if myhist.inSuperFiducialRegion(topX,topY) and myhist.inSuperFiducialRegion(botX,botY): myhist.fillBand("_cop160_SuperFid",trEle,clEle,trPos,clPos) # if myhist.momFromPositionEclUpperCut(topE,myhist.momFromECalPosition(topX,topZ,beamAngle,myhist.BEff)) and myhist.momFromPositionEclUpperCut(botE,myhist.momFromECalPosition(botX,botZ,beamAngle,myhist.BEff)): if not myhist.inPhotonHole(topX,topY) and not myhist.inPhotonHole(botX,botY) : myhist.fillBand("_cop160_SuperFid_CutPhotons",trEle,clEle,trPos,clPos) # if myhist.momFromPositionEclUpperCut(topE,myhist.momFromECalPosition(topX,topZ,beamAngle,myhist.BEff)) and myhist.momFromPositionEclUpperCut(botE,myhist.momFromECalPosition(botX,botZ,beamAngle,myhist.BEff)): if not myhist.inPhotonHole(topX,topY) and not myhist.inPhotonHole(botX,botY) : myhist.fillBand("_cop160_CutPhotons",trEle,clEle,trPos,clPos) # particle = hps_event.getParticle(HpsParticle.TC_V0_CANDIDATE, candidateList[index]) # myhist.fillCandidateHistograms(particle) # if(nPassTrkCuts>0): print "******************************************************************************************" myhist.saveHistograms(output_file) # sys.exit(0) print "*** Returning ****" return
def writeXsecTree(box, model, directory, mg, mchi, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2): outputFileName = "%s/xsecUL_mg_%s_mchi_%s_%s.root" % (directory, mg, mchi, box) print "INFO: xsec UL values being written to %s" % outputFileName fileOut = rt.TFile.Open(outputFileName, "recreate") xsecTree = rt.TTree("xsecTree", "xsecTree") myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi; Double_t x; Double_t y;" ixsecUL = 0 myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 0) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 1) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 2) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 3) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 4) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 5) ixsecUL += 6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s, "mg"), 'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s, "mchi"), 'mchi/D') xsecTree.Branch("x", rt.AddressOf(s, "x"), 'x/D') xsecTree.Branch("y", rt.AddressOf(s, "y"), 'y/D') s.mg = mg s.mchi = mchi if 'T1x' in model: s.x = float(model[model.find('x') + 1:model.find('y')].replace( 'p', '.')) s.y = float(model[model.find('y') + 1:].replace('p', '.')) elif model == 'T1bbbb': s.x = 1 s.y = 0 elif model == 'T1tttt': s.x = 0 s.y = 1 else: s.x = -1 s.y = -1 ixsecUL = 0 xsecTree.Branch("xsecULObs_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 0)), 'xsecUL%i/D' % (ixsecUL + 0)) xsecTree.Branch("xsecULExpPlus2_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 1)), 'xsecUL%i/D' % (ixsecUL + 1)) xsecTree.Branch("xsecULExpPlus_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 2)), 'xsecUL%i/D' % (ixsecUL + 2)) xsecTree.Branch("xsecULExp_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 3)), 'xsecUL%i/D' % (ixsecUL + 3)) xsecTree.Branch("xsecULExpMinus_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 4)), 'xsecUL%i/D' % (ixsecUL + 4)) xsecTree.Branch("xsecULExpMinus2_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 5)), 'xsecUL%i/D' % (ixsecUL + 5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]' % (ixsecUL + 0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]' % (ixsecUL + 1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]' % (ixsecUL + 2) exec 's.xsecUL%i = xsecULExp[ixsecUL]' % (ixsecUL + 3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]' % (ixsecUL + 4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]' % (ixsecUL + 5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() return outputFileName
# For events in the train set, we set the discriminator to -1 # to avoid accidentally reusing the training set in the analysis. out_signal_name = os.path.basename(signal_file_name_test).replace('.root', '_BDT.root') out_signal = root.TFile(out_signal_name, 'RECREATE') out_signal_tree = signalTree_test.CloneTree(0) out_bkg_name = os.path.basename(bkg_file_name_test).replace('.root', '_BDT.root') out_bkg = root.TFile(out_bkg_name, 'RECREATE') out_bkg_tree = bkgTree_test.CloneTree(0) # This is the boilerplate code for writing something # to a ROOT tree from Python. root.gROOT.ProcessLine("struct MyStruct{float disc;};") from ROOT import MyStruct s = MyStruct() disc_branch_sig = out_signal_tree.Branch('disc', root.AddressOf(s, 'disc'), 'disc/F'); disc_branch_bkg = out_bkg_tree.Branch('disc', root.AddressOf(s, 'disc'), 'disc/F'); print "Writing new ROOT signal file with discriminator appended" fill_discriminator(signalTree_test, out_signal_tree, disc_lookup_signal, s) print "Writing new ROOT background file with discriminator appended" fill_discriminator(bkgTree_test, out_bkg_tree, disc_lookup_bkg, s) # Cristian's code uses GetCurrentFile() for this part. # I will do that too just in case (paranoia). out_signal.cd() out_signal_tree.GetCurrentFile().Write() signalNevents_test.Write() out_signal_tree.GetCurrentFile().Close() out_bkg.cd()
def get_event(self, index): """Return the event at position index """ event = {} self.datastruct.dirx = ROOT.std.vector('double')() self.datastruct.diry = ROOT.std.vector('double')() self.datastruct.dirz = ROOT.std.vector('double')() self.datastruct.pointx = ROOT.std.vector('double')() self.datastruct.pointy = ROOT.std.vector('double')() self.datastruct.pointz = ROOT.std.vector('double')() self.datastruct.breakpointx = ROOT.std.vector('double')() self.datastruct.breakpointy = ROOT.std.vector('double')() self.datastruct.bpangle = ROOT.std.vector('double')() self.datastruct.radius = ROOT.std.vector('double')() self.datastruct.wirex = ROOT.std.vector('double')() self.datastruct.wirey = ROOT.std.vector('double')() self.datastruct.wirez = ROOT.std.vector('double')() self.datastruct.grid_id = ROOT.std.vector('int')() self.datastruct.grid_side = ROOT.std.vector('int')() self.datastruct.grid_layer = ROOT.std.vector('int')() self.datastruct.grid_column = ROOT.std.vector('int')() self.datastruct.break_layer = ROOT.std.vector('int')() self.datastruct.charge = ROOT.std.vector('int')() self.datastruct.calo_id = ROOT.std.vector('int')() self.datastruct.calo_type = ROOT.std.vector('int')() self.datastruct.calo_side = ROOT.std.vector('int')() self.datastruct.calo_wall = ROOT.std.vector('int')() self.datastruct.calo_row = ROOT.std.vector('int')() self.datastruct.calo_column = ROOT.std.vector('int')() self.tree.SetBranchAddress('dirx', ROOT.AddressOf(self.datastruct, "dirx")) self.tree.SetBranchAddress('diry', ROOT.AddressOf(self.datastruct, "diry")) self.tree.SetBranchAddress('dirz', ROOT.AddressOf(self.datastruct, "dirz")) self.tree.SetBranchAddress('pointx', ROOT.AddressOf(self.datastruct, "pointx")) self.tree.SetBranchAddress('pointy', ROOT.AddressOf(self.datastruct, "pointy")) self.tree.SetBranchAddress('pointz', ROOT.AddressOf(self.datastruct, "pointz")) self.tree.SetBranchAddress( 'breakpointx', ROOT.AddressOf(self.datastruct, "breakpointx")) self.tree.SetBranchAddress( 'breakpointy', ROOT.AddressOf(self.datastruct, "breakpointy")) self.tree.SetBranchAddress('bpangle', ROOT.AddressOf(self.datastruct, "bpangle")) self.tree.SetBranchAddress('radius', ROOT.AddressOf(self.datastruct, "radius")) self.tree.SetBranchAddress('wirex', ROOT.AddressOf(self.datastruct, "wirex")) self.tree.SetBranchAddress('wirey', ROOT.AddressOf(self.datastruct, "wirey")) self.tree.SetBranchAddress('wirez', ROOT.AddressOf(self.datastruct, "wirez")) self.tree.SetBranchAddress('grid_id', ROOT.AddressOf(self.datastruct, "grid_id")) self.tree.SetBranchAddress( 'grid_side', ROOT.AddressOf(self.datastruct, "grid_side")) self.tree.SetBranchAddress( 'grid_layer', ROOT.AddressOf(self.datastruct, "grid_layer")) self.tree.SetBranchAddress( 'grid_column', ROOT.AddressOf(self.datastruct, "grid_column")) self.tree.SetBranchAddress( 'break_layer', ROOT.AddressOf(self.datastruct, "break_layer")) self.tree.SetBranchAddress('charge', ROOT.AddressOf(self.datastruct, "charge")) self.tree.SetBranchAddress('calo_id', ROOT.AddressOf(self.datastruct, "calo_id")) self.tree.SetBranchAddress( 'calo_type', ROOT.AddressOf(self.datastruct, "calo_type")) self.tree.SetBranchAddress( 'calo_side', ROOT.AddressOf(self.datastruct, "calo_side")) self.tree.SetBranchAddress( 'calo_wall', ROOT.AddressOf(self.datastruct, "calo_wall")) self.tree.SetBranchAddress('calo_row', ROOT.AddressOf(self.datastruct, "calo_row")) self.tree.SetBranchAddress( 'calo_column', ROOT.AddressOf(self.datastruct, "calo_column")) self.tree.GetEntry(index) # now self.datastruct is filled event["raw"] = {} event["raw"]["gg"] = self.__build_observed_gg() event["raw"]["calo_hits"] = self.__build_calohits() event["raw"]["truthsim"] = self.__build_truth() return event
# HISTOS # ########## h_PU_lumiPOG = f_lumiPOG_PU.Get("h_PU_LumiPOG") h_nPV = TH1F('h_nPV', 'nPV', 100, 0, 100) h_nPV_True = TH1F('h_nPV_True', 'nPV True', 100, 0, 100) ########### # MC LOOP # ########### chains = {} chains['Evt'] = [] # Event info chains['Evt'].append(ROOT.TChain('l1EventTree/L1EventTree')) chains['Evt'][0].Add(f_Run3MC) Evt_br = ROOT.L1Analysis.L1AnalysisEventDataFormat() chains['Evt'][0].SetBranchAddress('Event', ROOT.AddressOf(Evt_br)) print("\nEntering loop over events for chain") for jEvt in range(chains['Evt'][0].GetEntries()): chains['Evt'][0].GetEntry(jEvt) h_nPV.Fill(int(Evt_br.nPV)) h_nPV_True.Fill(int(Evt_br.nPV_True)) h_PU_lumiPOG.Scale(h_nPV_True.Integral() / h_PU_lumiPOG.Integral()) # Save histograms in a root file print("Saving histograms into root file ...") outfile_histos = TFile.Open( outputDir + "/" + "h_PUreweighting_LumiPOG_PU_gaussianStartOfTheFill.root", "RECREATE") outfile_histos.cd()
def init_branches(self): """ Connect the branches of the Trees with the corresponding members in the L1Data container. """ if not self.tree_main: L1Ana.log.fatal( "There is no main L1Tree -- aborting initialization of branches" ) exit(0) self.nentries = self.tree_main.GetEntries() if self.nevents < 0 or self.nevents > self.nentries: self.nevents = self.nentries L1Ana.log.info( "Approximate number of entries: {n}, running over: {n2}".format( n=self.nentries, n2=self.nevents)) self.data.event = root.L1Analysis.L1AnalysisEventDataFormat() self.data.simulation = root.L1Analysis.L1AnalysisSimulationDataFormat() self.data.gct = root.L1Analysis.L1AnalysisGCTDataFormat() self.data.gmt = root.L1Analysis.L1AnalysisGMTDataFormat() self.data.gt = root.L1Analysis.L1AnalysisGTDataFormat() self.data.rct = root.L1Analysis.L1AnalysisRCTDataFormat() self.data.dttf = root.L1Analysis.L1AnalysisDTTFDataFormat() self.data.csctf = root.L1Analysis.L1AnalysisCSCTFDataFormat() L1Ana.log.info("Setting branch addresses for main L1Tree.") self.tree_main.SetBranchAddress("Event", root.AddressOf(self.data.event)) self.tree_main.SetBranchAddress("GCT", root.AddressOf(self.data.gct)) self.tree_main.SetBranchAddress("GMT", root.AddressOf(self.data.gmt)) self.tree_main.SetBranchAddress("GT", root.AddressOf(self.data.gt)) self.tree_main.SetBranchAddress("RCT", root.AddressOf(self.data.rct)) self.tree_main.SetBranchAddress("CSCTF", root.AddressOf(self.data.csctf)) self.tree_main.SetBranchAddress("DTTF", root.AddressOf(self.data.dttf)) if self.tree_main.GetBranch("Simulation"): self.tree_main.SetBranchAddress( "Simulation", root.AddressOf(self.data.simulation)) else: L1Ana.log.warning("Simulation branch not present...") if self.tree_main.GetBranch("Generator"): self.tree_main.SetBranchAddress("Generator", root.AddressOf(self.data.gen)) else: L1Ana.log.warning("Generator branch not present...") if self.do_reco: L1Ana.log.info("Setting branch addresses for RecoTree.") self.data.recoMet = root.L1Analysis.L1AnalysisRecoMetDataFormat() self.data.recoJet = root.L1Analysis.L1AnalysisRecoJetDataFormat() self.data.recoBasicCluster = root.L1Analysis.L1AnalysisRecoClusterDataFormat( ) self.data.recoSuperCluster = root.L1Analysis.L1AnalysisRecoClusterDataFormat( ) self.data.recoVertex = root.L1Analysis.L1AnalysisRecoVertexDataFormat( ) self.data.recoTrack = root.L1Analysis.L1AnalysisRecoTrackDataFormat( ) self.tree_reco.SetBranchAddress("Jet", root.AddressOf(self.data.recoJet)) self.tree_reco.SetBranchAddress( "BasicClusters", root.AddressOf(self.data.recoBasicCluster)) self.tree_reco.SetBranchAddress( "SuperClusters", root.AddressOf(self.data.recoSuperCluster)) self.tree_reco.SetBranchAddress("Met", root.AddressOf(self.data.recoMet)) self.tree_reco.SetBranchAddress( "Tracks", root.AddressOf(self.data.recoTrack)) self.tree_reco.SetBranchAddress( "Vertices", root.AddressOf(self.data.recoVertex)) if self.do_muon: L1Ana.log.info("Setting branch addresses for MuonRecoTree.") self.data.recoMuon = root.L1Analysis.L1AnalysisRecoMuonDataFormat() self.data.recoRpcHit = root.L1Analysis.L1AnalysisRecoRpcHitDataFormat( ) self.tree_muon.SetBranchAddress("Muon", root.AddressOf(self.data.recoMuon)) if self.tree_muon.GetBranch("RpcHit"): self.tree_muon.SetBranchAddress( "RpcHit", root.AddressOf(self.data.recoRpcHit)) else: L1Ana.log.warning("RpcHit branch not present...") if self.do_l1menu: L1Ana.log.info("Setting branch addresses for L1Menu.") self.data.l1menu = root.L1Analysis.L1AnalysisL1MenuDataFormat() self.tree_menu.SetBranchAddress("L1Menu", root.AddressOf(self.data.l1menu)) if self.do_l1extra: L1Ana.log.info("Setting branch addresses for L1Extra.") self.data.l1extra = root.L1Analysis.L1AnalysisL1ExtraDataFormat() self.tree_extra.SetBranchAddress( "L1Extra", root.AddressOf(self.data.l1emuextra)) if self.do_l1emuextra: L1Ana.log.info("Setting branch addresses for L1EmuExtra.") self.data.l1emuextra = root.L1Analysis.L1AnalysisL1ExtraDataFormat( ) self.tree_emu_extra.SetBranchAddress( "L1Extra", root.AddressOf(self.data.l1emuextra))
def main(): """ Converts SSW binary to the ROOT format as a TTree object """ allowed_splitlevels = (1, 99) parser = argparse.ArgumentParser(description=main.__doc__, epilog='Homepage: https://github.com/kbat/mc-tools') parser.add_argument('-splitlevel', dest='splitlevel', type=int, help='split level (see TTree::Branch documentation)', required=False, default=1, choices=allowed_splitlevels) parser.add_argument('wssa', type=str, help='ssw output file name') arguments = parser.parse_args() fin_name = arguments.wssa fout_name = fin_name + ".root" hits = ROOT.hit_t() ssw = SSW(fin_name) fout = ROOT.TFile(fout_name, "recreate", ssw.getTitle()) T = ROOT.TTree("T", ssw.probs) # T.SetMaxTreeSize((Long64_t)1e+18) if arguments.splitlevel==99: T.Branch("hits", hits, "history:id:weight:energy:time:x:y:z:wx:wy:k") elif arguments.splitlevel == 1: T.Branch("history", ROOT.AddressOf(hits, 'history'), "history") T.Branch("id", ROOT.AddressOf(hits, 'id'), "id") T.Branch("weight", ROOT.AddressOf(hits, 'weight'), "weight") T.Branch("energy", ROOT.AddressOf(hits, 'energy'), "energy") T.Branch("time", ROOT.AddressOf(hits, 'time'), "time") T.Branch("x", ROOT.AddressOf(hits, 'x'), "x") T.Branch("y", ROOT.AddressOf(hits, 'y'), "y") T.Branch("z", ROOT.AddressOf(hits, 'z'), "z") T.Branch("wx", ROOT.AddressOf(hits, 'wx'), "wx") T.Branch("wy", ROOT.AddressOf(hits, 'wy'), "wy") T.Branch("k", ROOT.AddressOf(hits, 'k'), "k") for i in range(ssw.nevt): ssb = ssw.readHit() hits.history = ssb[0] # >0 = with collision, <0 = without collision hits.id = ssb[1] # surface + particle type + multigroup problem info hits.weight = ssb[2] hits.energy = ssb[3] # [MeV] hits.time = ssb[4] # [shakes] hits.x = ssb[5] # [cm] hits.y = ssb[6] # [cm] hits.z = ssb[7] # [cm] hits.wx = ssb[8] hits.wy = ssb[9] hits.k = ssb[10] # cosine of angle between track and normal to surface jsu (in MCNPX it is called cs) T.Fill() ssw.file.close() sinfo = ROOT.TObjString("%d" % ssw.N); # number of incident particles for correct normalisation T.GetUserInfo().Add(sinfo); # T.Print() T.SetAlias("theta", "TMath::RadToDeg()*(TMath::ATan2(x,y) > 0 ? TMath::ATan2(x,y) : 2*TMath::Pi()+TMath::ATan2(x,y))"); T.SetAlias("i","TMath::Nint(TMath::Abs(id/1E+6))");# tmp variable T.SetAlias("JGP","-TMath::Nint(i/200.0)"); # energy group T.SetAlias("JC","TMath::Nint(i/100.0) + 2*JGP"); # T.SetAlias("IPT","i-100*JC+200*JGP"); # particle type: 1=neutron, 2=photon, 3=electron T.SetAlias("wz", "TMath::Sqrt(TMath::Max(0, 1-wx*wx-wy*wy)) * id/TMath::Abs(id)") # z-direction cosine T.SetAlias("surface", "TMath::Abs(id) % 1000000") # surface crossed T.Write() fout.Purge() fout.Close()
def loop( events, tgeo, tout, nfiles, okruns, GeoNow, doDetSim ): if len(okruns) == 0: print "There are no runs in this TTree...skipping!" return print "Inside event loop with %d files and first run %d" % (nfiles, okruns[0]) #==================================================================================================================================================== 1.1 Geo설정 1~10============= #GeoNow=5; # updated geometry with less steel # cm # geometry 1 and 3 if GeoNow=="Geo1" or GeoNow=="Geo3": offset = [ 0., 0., -50. ] fvLo = [ -90., -90., -90. ] fvHi = [ 90., 90., 90. ] collarLo = [ -90., -90., -90. ] collarHi = [ 90., 90., 90. ] size3DST = [200., 200., 200.] minEndInCM = [-100, -100, -100 ] maxEndInCM = [100, 100, 100] # geometry 2 if GeoNow=="Geo2": offset = [ 0., 0., -50. ] fvLo = [ -140., -90., -90. ] fvHi = [ 140., 90., 90. ] collarLo = [ -140., -140., -90. ] collarHi = [ 140., 140., 90. ] size3DST = [300., 200., 200.] minEndInCM = [-150, -100, -100 ] maxEndInCM = [150, 100, 100] # geometry 4 and 5 if GeoNow=="Geo4": offset = [ 0., 0., -50. ] fvLo = [ -2000., -2000., -2000. ] fvHi = [ 2000., 2000., 2000. ] collarLo = [ -2000., -2000., -2000. ] collarHi = [ 2000., 2000., 2000. ] size3DST = [200., 200., 200.] minEndInCM = [-100, -100, -100 ] maxEndInCM = [100, 100, 100] if GeoNow=="Geo5" or GeoNow=="Geo6" or GeoNow=="Geo7": offset = [ 0., 0., 550.-50. ] fvLo = [ -2000., -2000., -2000. ] fvHi = [ 2000., 2000., 2000. ] collarLo = [ -2000., -2000., -2000. ] collarHi = [ 2000., 2000., 2000. ] size3DST = [200., 200., 200.] minEndInCM = [-100, -100, -100 ] maxEndInCM = [100, 100, 100] if GeoNow=="Geo8": offset = [ 0., 0., -50. ] fvLo = [ -50., -50., -50. ] fvHi = [ 50., 50., 50. ] collarLo = [ -50., -50., -50. ] collarHi = [ 50., 50., 50. ] size3DST = [120., 120., 120.] minEndInCM = [-100, -100, -100 ] maxEndInCM = [100, 100, 100] if GeoNow=="Geo9": offset = [ 0., 0., 550.-50. ] fvLo = [ -2000., -2000., -2000. ] fvHi = [ 2000., 2000., 2000. ] collarLo = [ -2000., -2000., -2000. ] collarHi = [ 2000., 2000., 2000. ] size3DST = [120., 120., 120.] minEndInCM = [-100, -100, -100 ] maxEndInCM = [100, 100, 100] if GeoNow=="Geo10" or GeoNow=="Geo12": offset = [ 0., 0., 550.-50. ] fvLo = [ -2000., -2000., -2000. ] fvHi = [ 2000., 2000., 2000. ] collarLo = [ -2000., -2000., -2000. ] collarHi = [ 2000., 2000., 2000. ] size3DST = [240., 240., 200.] #minEndInCM = [-100, -100, -100 ] #maxEndInCM = [100, 100, 100] if GeoNow=="Geo11": offset = [ 0., 0., 550.-50. ] fvLo = [ -2000., -2000., -2000. ] fvHi = [ 2000., 2000., 2000. ] collarLo = [ -2000., -2000., -2000. ] collarHi = [ 2000., 2000., 2000. ] size3DST = [120., 120., 120.] if GeoNow == "Geo2": sideExitParameter=150. elif GeoNow=="Geo8" or GeoNow=="Geo9" or GeoNow=="Geo11": sideExitParameter=60. elif GeoNow=="Geo10" or GeoNow=="Geo12": sideExitParameter=120. else: sideExitParameter=100. print 'GeoNow is ', GeoNow #================================================================================================================================================================1.2 Event얼만큼 일어났는 지===== event = ROOT.TG4Event() events.SetBranchAddress("Event",ROOT.AddressOf(event)) print "Set branch address" N = events.GetEntries() evt_per_file = N/nfiles if N % nfiles: print "Files don't all have the same number of events!!!" print "\n\n\n\n\n\n\n\n\n\n\n" print "Starting loop over %d entries" % N for ient in range(N): if ient % 100 == 0: print "Event %d of %d..." % (ient,N) #========================================================================================================================================================1.3 입자별로 변수 생성=========== events.GetEntry(ient) for ivtx,vertex in enumerate(event.Primaries): ## initialize output variables fileidx = ient/evt_per_file t_ifileNo[0] = okruns[fileidx] t_ievt[0] = ient%evt_per_file; t_vtx[0]=0.0; t_vtx[1]=0.0; t_vtx[2]=0.0; #랩톤 변수 생성 t_p3lep[0]=0.0; t_p3lep[1]=0.0; t_p3lep[2]=0.0; t_lepDeath[0]=0.0; t_lepDeath[1]=0.0; t_lepDeath[2]=0.0; t_lepPdg[0] = 0 t_lepKE[0] = 0. #파이온 변수 생성 t_p3pi[0]=0.0; t_p3pi[1]=0.0; t_p3pi[2]=0.0; t_piDeath[0]=0.0; t_piDeath[1]=0.0; t_piDeath[2]=0.0; t_piPdg[0] = 0 t_piKE[0] = 0. #프로톤 변수 생성 t_p3proton[0]=0.0; t_p3proton[1]=0.0; t_p3proton[2]=0.0; t_protonDeath[0]=0.0; t_protonDeath[1]=0.0; t_protonDeath[2]=0.0; t_protonPdg[0] = 0 t_protonKE[0] = 0. #뮤온 변수 생성 t_muonExitPt[0] = 0.0; t_muonExitPt[1] = 0.0; t_muonExitPt[2] = 0.0; t_muonExitMom[0] = 0.0; t_muonExitMom[1] = 0.0; t_muonExitMom[2] = 0.0; t_muonReco[0] = -1; t_muGArLen[0]=0.0; #하드론 변수 생성 t_hadTot[0] = 0.; t_hadTot_ECAL[0] = 0.; t_hadTot_3DST[0] = 0.; t_hadTot_TPC[0] = 0.; t_hadTot_allECAL[0] = 0.; t_hadTot_leak[0] = 0.; t_hadCollar[0] = 0.; t_vtxTime[0] = 0.; t_nFS[0] = 0 #neutron에 대해서 특별히 리스트 변수 생성 for inii in range(1000): t_neutronHitX[inii]=0.; t_neutronHitY[inii]=0.; t_neutronHitZ[inii]=0.; t_neutronHitT[inii]=0.; t_neutronHitSmearT[inii]=0.; t_neutronHitE[inii]=0.; t_neutronRecoE[inii]=0.; t_neutronHitS[inii]=0.; t_neutronTrueE[inii]=0.; t_neutronParentId[inii]=0.; t_neutronParentPDG[inii]=0.; ## done #==================================================================================================================================1.4 뉴트리노 버텍스랑 FV 컷 위치 지정=========== # now ID numucc reaction=vertex.Reaction # set the vertex location for output # Neutrino vertax위치 지정하기 for i in range(3): t_vtx[i] = vertex.Position[i] / 10. - offset[i] # cm #print t_vtx[i] # fiducial vertex cut # FV컷 지정하기---------------------------------------------------------------> 이게 뭐임? fvCut = False for i in range(3): if t_vtx[i] < fvLo[i] or t_vtx[i] > fvHi[i]: fvCut = True vtxv = ROOT.TVector3( t_vtx[0], t_vtx[1], t_vtx[2] ) if fvCut: continue #==================================================================================================================================1.5 입자별로 물리량 할당======================= ileptraj = -1 #i 랩톤 트레젝토리 ipi0traj = -1 #i 파이온0 트레젝토리 ipitraj = -1 #i 파이온 트레젝토리 nfsp = 0 # number of final state particles # get the lepton kinematics from the edepsim file fsParticleIdx = {} for ipart,particle in enumerate(vertex.Particles): e = particle.Momentum[3] #토탈 에너지 p = (particle.Momentum[0]**2 + particle.Momentum[1]**2 + particle.Momentum[2]**2)**0.5 #3차원 운동량->운동에너지 m = (e**2 - p**2)**0.5 #정지 에너지 print "fs pdg list ",particle.PDGCode t_fsPdg[nfsp] = particle.PDGCode #final state particle 종류 t_fsPx[nfsp] = particle.Momentum[0] #final state particle x방향 운동량 t_fsPy[nfsp] = particle.Momentum[1] #final state particle x방향 운동량 t_fsPz[nfsp] = particle.Momentum[2] #final state particle x방향 운동량 t_fsE[nfsp] = e #final state particle x방향 운동량 fsParticleIdx[particle.TrackId] = nfsp nfsp += 1 if abs(particle.PDGCode) in [11,12,13,14]: #전자, 전자중성미자, 뮤온, 뮤온중성미자 ileptraj = particle.TrackId #랩톤 궤적 t_lepPdg[0] = particle.PDGCode #랩톤 종류 # set the muon momentum for output for i in range(3): t_p3lep[i] = particle.Momentum[i] #랩톤 운동량 t_lepKE[0] = e - m #랩톤 운동에너지 = 토탈에너지 - 정지에너지 if abs(particle.PDGCode) in [211]: #파이온 ipitraj = particle.TrackId t_piPdg[0] = particle.PDGCode # set the pion momentum for output for i in range(3): t_p3pi[i] = particle.Momentum[i] t_piKE[0] = e - m if abs(particle.PDGCode) in [111]: #파이온0 ipi0traj = particle.TrackId if abs(particle.PDGCode) in [2212]: #프로톤 iprotontraj = particle.TrackId t_protonPdg[0] = particle.PDGCode # set the proton momentum for output for i in range(3): t_p3proton[i] = particle.Momentum[i] t_protonKE[0] = e - m assert ileptraj != -1, "There isn't a lepton??" t_nFS[0] = nfsp #============================================================================================================================================================================= # If there is a muon, determine how to reconstruct its momentum and charge t_muexit[0] = 0 exitKE = 0. exitP = None endVolIdx = -1 # where does the muon die #뮤온이 밖으로 빠져나왔는 지 아닌 지, 어디에서 멈췄는 지 확인하기 if abs(t_lepPdg[0]) == 13: #뮤온 leptraj = event.Trajectories[ileptraj] for p in leptraj.Points: pt = p.Position node = tgeo.FindNode( pt.X(), pt.Y(), pt.Z() ) volName = node.GetName() active = False for v in lar_active_vols: if v in volName: active = True break if active: t_muonExitPt[0] = pt.X() / 10. - offset[0] t_muonExitPt[1] = pt.Y() / 10. - offset[1] t_muonExitPt[2] = pt.Z() / 10. - offset[2] continue # first hit outside 3DST -- determine exit t_muonExitPt[0] = pt.X() / 10. - offset[0] t_muonExitPt[1] = pt.Y() / 10. - offset[1] t_muonExitPt[2] = pt.Z() / 10. - offset[2] t_muonExitMom[0] = p.Momentum.x() t_muonExitMom[1] = p.Momentum.y() t_muonExitMom[2] = p.Momentum.z() if abs(pt.X() / 10. - offset[0]) > sideExitParameter: t_muexit[0] = 1 # side exit elif abs(pt.Y() / 10. - offset[1]) > 100.: t_muexit[0] = 2 # top/bottom exit elif pt.Z() / 10. - offset[2] < -100.: t_muexit[0] = 3 # upstream exit elif pt.Z() / 10. - offset[2] > 100.: t_muexit[0] = 4 # downstream exit else: print "Hit in %s at position (%1.1f, %1.1f, %1.1f) unknown exit!" % (volName, pt.X()/10.-offset[0], pt.Y()/10.-offset[1], pt.Z()/10.-offset[2]) exitP = p.Momentum exitKE = (exitP.x()**2 + exitP.y()**2 + exitP.z()**2 + 105.3**2)**0.5 - 105.3 break endpt = leptraj.Points[-1].Position node = tgeo.FindNode( endpt.X(), endpt.Y(), endpt.Z() ) t_lepDeath[0] = endpt.X()/10. - offset[0] t_lepDeath[1] = endpt.Y()/10. - offset[1] t_lepDeath[2] = endpt.Z()/10. - offset[2] endVolName = node.GetName() #print endVolName #print t_muexit[0] # dipole+HPGTPC if "volWorld" in endVolName or "volDetEnclosure" in endVolName: endVolIdx = 0 # outside detector components elif "volCube" in endVolName or "volcube" in endVolName: endVolIdx = 1 # 3DST elif "volTPC" in endVolName or "volTPCTop" in endVolName: endVolIdx = 2 # TPC elif "volECALStripx" in endVolName or "volECALStripy" in endVolName or "volRadiatorPlate" in endVolName: endVolIdx = 3 # ECAL elif "volMagnet" in endVolName: endVolIdx = 4 # Magnet # look for muon hits in the gas TPC hits = [] for key in event.SegmentDetectors: if key.first in ["volTPC", "volTPCTop"]: hits += key.second tot_length = 0.0 for hit in hits: if hit.PrimaryId == ileptraj: # hit is due to the muon # TG4HitSegment::TrackLength includes all delta-rays, which spiral in gas TPC and give ridiculously long tracks hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit.Stop[0]/10.-offset[0], hit.Stop[1]/10.-offset[1], hit.Stop[2]/10.-offset[2] ) tot_length += (hStop-hStart).Mag() t_muGArLen[0] = tot_length # muon reconstruction method # 1 = contained if endVolIdx == 1: t_muonReco[0] = 1 # 2 = gas TPC match #elif tot_length > 0.: elif endVolIdx == 2: t_muonReco[0] = 2 # 3 = ECAL stopping elif endVolIdx == 3: t_muonReco[0] = 3 # 4 = magnet/coil stopper elif endVolIdx == 4: t_muonReco[0] = 4 #====================================================================================================================================================================================== # If there is a pion, determine how to reconstruct its momentum and charge t_piexit[0] = 0 exitKE = 0. exitP = None endVolIdx = -1 # where does the pion die if abs(t_piPdg[0]) == 211: #파이온이 밖으로 빠져 나왔는 지 아닌 지 어디에서 멈췄는 지 확인하기 pitraj = event.Trajectories[ipitraj] for p in pitraj.Points: pt = p.Position node = tgeo.FindNode( pt.X(), pt.Y(), pt.Z() ) volName = node.GetName() active = False for v in lar_active_vols: if v in volName: active = True break if active: t_pionExitPt[0] = pt.X() / 10. - offset[0] t_pionExitPt[1] = pt.Y() / 10. - offset[1] t_pionExitPt[2] = pt.Z() / 10. - offset[2] continue # first hit outside 3DST -- determine exit t_pionExitPt[0] = pt.X() / 10. - offset[0] t_pionExitPt[1] = pt.Y() / 10. - offset[1] t_pionExitPt[2] = pt.Z() / 10. - offset[2] t_pionExitMom[0] = p.Momentum.x() t_pionExitMom[1] = p.Momentum.y() t_pionExitMom[2] = p.Momentum.z() if abs(pt.X() / 10. - offset[0]) > 150.: t_piexit[0] = 1 # side exit elif abs(pt.Y() / 10. - offset[1]) > 100.: t_piexit[0] = 2 # top/bottom exit elif pt.Z() / 10. - offset[2] < -100.: t_piexit[0] = 3 # upstream exit elif pt.Z() / 10. - offset[2] > 100.: t_piexit[0] = 4 # downstream exit else: print "Hit in %s at position (%1.1f, %1.1f, %1.1f) unknown exit!" % (volName, pt.X()/10.-offset[0], pt.Y()/10.-offset[1], pt.Z()/10.-offset[2]) exitP = p.Momentum exitKE = (exitP.x()**2 + exitP.y()**2 + exitP.z()**2 + 105.3**2)**0.5 - 105.3 break endpt = pitraj.Points[-1].Position node = tgeo.FindNode( endpt.X(), endpt.Y(), endpt.Z() ) t_piDeath[0] = endpt.X()/10. - offset[0] t_piDeath[1] = endpt.Y()/10. - offset[1] t_piDeath[2] = endpt.Z()/10. - offset[2] endVolName = node.GetName() #print endVolName #print t_piexit[0] # dipole+HPGTPC if "volWorld" in endVolName or "volDetEnclosure" in endVolName: endVolIdx = 0 # outside detector components elif "volCube" in endVolName or "volcube" in endVolName: endVolIdx = 1 # 3DST elif "volTPC" in endVolName or "volTPCTop" in endVolName: endVolIdx = 2 # TPC elif "volECALStripx" in endVolName or "volECALStripy" in endVolName or "volRadiatorPlate" in endVolName: endVolIdx = 3 # ECAL elif "volMagnet" in endVolName: endVolIdx = 4 # Magnet # look for pion hits in the gas TPC hits = [] for key in event.SegmentDetectors: if key.first in ["volTPC", "volTPCTop"]: hits += key.second tot_length = 0.0 for hit in hits: if hit.PrimaryId == ipitraj: # hit is due to the pion # TG4HitSegment::TrackLength includes all delta-rays, which spiral in gas TPC and give ridiculously long tracks hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit.Stop[0]/10.-offset[0], hit.Stop[1]/10.-offset[1], hit.Stop[2]/10.-offset[2] ) tot_length += (hStop-hStart).Mag() t_piGArLen[0] = tot_length # pion reconstruction method # 1 = contained if endVolIdx == 1: t_pionReco[0] = 1 # 2 = gas TPC match #elif tot_length > 0.: elif endVolIdx == 2: t_pionReco[0] = 2 # 3 = ECAL stopping elif endVolIdx == 3: t_pionReco[0] = 3 # 4 = magnet/coil stopper elif endVolIdx == 4: t_pionReco[0] = 4 #================================================================================================================================================================================== # If there is a proton, determine how to reconstruct its momentum and charge t_protonexit[0] = 0 exitKE = 0. exitP = None endVolIdx = -1 # where does the proton die if abs(t_protonPdg[0]) == 2212: protontraj = event.Trajectories[iprotontraj] for p in protontraj.Points: pt = p.Position node = tgeo.FindNode( pt.X(), pt.Y(), pt.Z() ) volName = node.GetName() active = False for v in lar_active_vols: if v in volName: active = True break if active: t_protonExitPt[0] = pt.X() / 10. - offset[0] t_protonExitPt[1] = pt.Y() / 10. - offset[1] t_protonExitPt[2] = pt.Z() / 10. - offset[2] continue # first hit outside 3DST -- determine exit t_protonExitPt[0] = pt.X() / 10. - offset[0] t_protonExitPt[1] = pt.Y() / 10. - offset[1] t_protonExitPt[2] = pt.Z() / 10. - offset[2] t_protonExitMom[0] = p.Momentum.x() t_protonExitMom[1] = p.Momentum.y() t_protonExitMom[2] = p.Momentum.z() if abs(pt.X() / 10. - offset[0]) > 150.: t_protonexit[0] = 1 # side exit elif abs(pt.Y() / 10. - offset[1]) > 100.: t_protonexit[0] = 2 # top/bottom exit elif pt.Z() / 10. - offset[2] < -100.: t_protonexit[0] = 3 # upstream exit elif pt.Z() / 10. - offset[2] > 100.: t_protonexit[0] = 4 # downstream exit else: print "Hit in %s at position (%1.1f, %1.1f, %1.1f) unknown exit!" % (volName, pt.X()/10.-offset[0], pt.Y()/10.-offset[1], pt.Z()/10.-offset[2]) exitP = p.Momentum exitKE = (exitP.x()**2 + exitP.y()**2 + exitP.z()**2 + 105.3**2)**0.5 - 105.3 break endpt = protontraj.Points[-1].Position node = tgeo.FindNode( endpt.X(), endpt.Y(), endpt.Z() ) t_protonDeath[0] = endpt.X()/10. - offset[0] t_protonDeath[1] = endpt.Y()/10. - offset[1] t_protonDeath[2] = endpt.Z()/10. - offset[2] endVolName = node.GetName() #print endVolName #print t_protonexit[0] # dipole+HPGTPC if "volWorld" in endVolName or "volDetEnclosure" in endVolName: endVolIdx = 0 # outside detector components elif "volCube" in endVolName or "volcube" in endVolName: endVolIdx = 1 # 3DST elif "volTPC" in endVolName or "volTPCTop" in endVolName: endVolIdx = 2 # TPC elif "volECALStripx" in endVolName or "volECALStripy" in endVolName or "volRadiatorPlate" in endVolName: endVolIdx = 3 # ECAL elif "volMagnet" in endVolName: endVolIdx = 4 # Magnet # look for proton hits in the gas TPC hits = [] for key in event.SegmentDetectors: if key.first in ["volTPC", "volTPCTop"]: hits += key.second tot_length = 0.0 for hit in hits: if hit.PrimaryId == iprotontraj: # hit is due to the proton # TG4HitSegment::TrackLength includes all delta-rays, which sprotonral in gas TPC and give ridiculously long tracks hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit.Stop[0]/10.-offset[0], hit.Stop[1]/10.-offset[1], hit.Stop[2]/10.-offset[2] ) tot_length += (hStop-hStart).Mag() t_protonGArLen[0] = tot_length # proton reconstruction method # 1 = contained if endVolIdx == 1: t_protonReco[0] = 1 # 2 = gas TPC match #elif tot_length > 0.: elif endVolIdx == 2: t_protonReco[0] = 2 # 3 = ECAL stopprotonng elif endVolIdx == 3: t_protonReco[0] = 3 # 4 = magnet/coil stopper elif endVolIdx == 4: t_protonReco[0] = 4 #================================================================================================================================================================================== # hadronic containment -- find hits in TPC hitsTPC = [] for key in event.SegmentDetectors: if "volTPC" in key.first: hitsTPC += key.second total_energy_TPC = 0. track_length_TPC = [0. for i in range(nfsp)] for hit in hitsTPC: hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit.Stop[0]/10.-offset[0], hit.Stop[1]/10.-offset[1], hit.Stop[2]/10.-offset[2] ) if event.Trajectories[hit.PrimaryId].ParentId == -1: track_length_TPC[fsParticleIdx[hit.PrimaryId]] += (hStop-hStart).Mag() if hit.PrimaryId != ileptraj: hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) total_energy_TPC += hit.EnergyDeposit t_hadTot_TPC[0] = total_energy_TPC #print total_energy_TPC # hits in ECAL without radiator hitsECAL = [] for key2 in event.SegmentDetectors: if "volECAL" in key2.first: hitsECAL += key2.second total_energy_ECAL = 0. track_length_ECAL = [0. for i in range(nfsp)] for hit2 in hitsECAL: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit2.Stop[0]/10.-offset[0], hit2.Stop[1]/10.-offset[1], hit2.Stop[2]/10.-offset[2] ) if event.Trajectories[hit2.PrimaryId].ParentId == -1: track_length_ECAL[fsParticleIdx[hit2.PrimaryId]] += (hStop-hStart).Mag() if hit2.PrimaryId != ileptraj: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) total_energy_ECAL += hit2.EnergyDeposit t_hadTot_ECAL[0] = total_energy_ECAL #print total_energy_ECAL # hits in ECAL with radiator hitsECAL = [] for key2 in event.SegmentDetectors: if "volECAL" in key2.first or "volRadiator" in key2.first: hitsECAL += key2.second total_energy_ECAL = 0. track_length_ECAL = [0. for i in range(nfsp)] for hit2 in hitsECAL: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit2.Stop[0]/10.-offset[0], hit2.Stop[1]/10.-offset[1], hit2.Stop[2]/10.-offset[2] ) if event.Trajectories[hit2.PrimaryId].ParentId == -1: track_length_ECAL[fsParticleIdx[hit2.PrimaryId]] += (hStop-hStart).Mag() if hit2.PrimaryId != ileptraj: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) total_energy_ECAL += hit2.EnergyDeposit t_hadTot_allECAL[0] = total_energy_ECAL # hits outside sensitive detectors hitsLeak = [] for key2 in event.SegmentDetectors: if "volECAL" in key2.first or "volRadiator" in key2.first or "volTPC" in key2.first or "volCube" in key2.first or "volcube" in key2.first: print "contained in sensitive detector" else: hitsLeak += key2.second total_energy_Leak = 0. track_length_Leak = [0. for i in range(nfsp)] for hit2 in hitsLeak: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit2.Stop[0]/10.-offset[0], hit2.Stop[1]/10.-offset[1], hit2.Stop[2]/10.-offset[2] ) if event.Trajectories[hit2.PrimaryId].ParentId == -1: track_length_Leak[fsParticleIdx[hit2.PrimaryId]] += (hStop-hStart).Mag() if hit2.PrimaryId != ileptraj: hStart = ROOT.TVector3( hit2.Start[0]/10.-offset[0], hit2.Start[1]/10.-offset[1], hit2.Start[2]/10.-offset[2] ) total_energy_Leak += hit2.EnergyDeposit t_hadTot_leak[0] = total_energy_Leak # event vtx time t_vtxTime[0] = random.uniform(0.0,10000.) # Get neutron trajectory information PDG neutron 2112 proton 2212 nTraj = [] icounter = 0 for ctraj in event.Trajectories: if event.Trajectories[ctraj.TrackId].PDGCode == 2112: #print "a FS neutron with kinetic energy ", event.Trajectories[ctraj.TrackId].InitialMomentum.Energy()-939.565 #t_neutronTrueE[icounter]= event.Trajectories[ctraj.TrackId].InitialMomentum.Energy()-939.565 #print "Parent PDG ", event.Trajectories[ctraj.ParentId].PDGCode #print event.Trajectories[ctraj.TrackId].InitialMomentum.Energy()-939.565 #print event.Trajectories[ctraj.TrackId].InitialMomentum.T() icounter = icounter+1 #print ctraj.ParentId #print ctraj.TrackId #print ctraj.Name parentDaughterMap = dict() neutronMap = dict() for ctraj in event.Trajectories: if event.Trajectories[ctraj.ParentId].PDGCode == 2112: #print "a neutron hit" #print "parent is neutron, then neutron's parent is : ", event.Trajectories[event.Trajectories[ctraj.ParentId].TrackId].PDGCode #print ctraj.ParentId #print ctraj.TrackId #print ctraj.Name nTraj.append(ctraj.TrackId) parentDaughterMap[ctraj.TrackId] = ctraj.ParentId for ctraj4 in event.Trajectories: if ctraj4.TrackId == ctraj.ParentId: neutronMap[ctraj.TrackId] = ctraj4.ParentId if ctraj4.ParentId == -1: print "neutron induced ID ",ctraj.TrackId, " neutron parent Id ", ctraj4.ParentId print "neutron induced PDG ",event.Trajectories[ctraj.TrackId].PDGCode, " parent of parent PDG ", event.Trajectories[ctraj4.ParentId].PDGCode #if ctraj.PDGCode == 2112: #print ctraj.Name #nTraj.append(ctraj.TrackId) print "----------------- ",ient """ nTraj_1daughter = [] for cctraj in event.Trajectories: #print cctraj.ParentId for iloop in nTraj: if cctraj.ParentId == iloop: #print cctraj.Name nTraj_1daughter.append(cctraj.TrackId) nTraj_2daughter = [] for cctraj in event.Trajectories: for iloop in nTraj_1daughter: if cctraj.ParentId == iloop: #print cctraj.Name nTraj_2daughter.append(cctraj.TrackId) nTraj_3daughter = [] for cctraj in event.Trajectories: for iloop in nTraj_2daughter: if cctraj.ParentId == iloop: #print cctraj.Name nTraj_3daughter.append(cctraj.TrackId) """ # neutron hit number looper that will be used soon iN = 0; # hits in 3DST hits = [] cubeInven = [] for key3 in event.SegmentDetectors: if "volCube" in key3.first or "volcube" in key3.first or "vol" in key3.first: hits += key3.second collar_energy = 0. total_energy_3DST = 0. track_length = [0. for i in range(nfsp)] for hit in hits: hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) hStop = ROOT.TVector3( hit.Stop[0]/10.-offset[0], hit.Stop[1]/10.-offset[1], hit.Stop[2]/10.-offset[2] ) if event.Trajectories[hit.PrimaryId].ParentId == -1: track_length[fsParticleIdx[hit.PrimaryId]] += (hStop-hStart).Mag() if hit.PrimaryId != ileptraj: hStart = ROOT.TVector3( hit.Start[0]/10.-offset[0], hit.Start[1]/10.-offset[1], hit.Start[2]/10.-offset[2] ) total_energy_3DST += hit.EnergyDeposit # check if hit is in collar region if hStart.x() < collarLo[0] or hStart.x() > collarHi[0] or hStart.y() < collarLo[1] or hStart.y() > collarHi[1] or hStart.z() < collarLo[2] or hStart.z() > collarHi[2]: collar_energy += hit.EnergyDeposit if hit.PrimaryId == ipi0traj: print '---------------!!!!!!!!!!!!!!!!!' #print 'random time stamp ',random.uniform(0.0,10000.) #print 'hit time is ',hit.Start.T() #print 'generated time is ',hit.Start.T()+random.uniform(0.0,10000.) #print hit.Contrib[0] #Neutron PDG code 2112, neutron should not give energy deposit itself for iloop in nTraj: #print "checking" #print iloop # if hit.Contrib[0] == iloop: # thisMatch = False # cubeInfo = getCube(minEndInCM, maxEndInCM, (hStart.x()+hStop.x())/2., (hStart.y()+hStop.y())/2., (hStart.z()+hStop.z())/2.) # for cubeloop in len(cubeInven): # if cubeInfo == cubeInven[cubeloop]: # thisMatch = True # if thisMatch == False: # cubeInven.append(cubeInfo) # iN += 1; if hit.Contrib[0] == iloop and iN < 999: #print hStart.x() #print 'energy deposit by ',event.Trajectories[hit.PrimaryId].Name #print iN, "--- neutron induced ID ",iloop, " neutron parent Id ", neutronMap.get(iloop) #print "--- neutron induced PDG ",event.Trajectories[iloop].PDGCode, " parent of parent PDG ", event.Trajectories[neutronMap.get(iloop)].PDGCode if doDetSim == False: t_neutronHitX[iN] = hStart.x() t_neutronHitY[iN] = hStart.y() t_neutronHitZ[iN] = hStart.z() else: #detResSim dist = math.sqrt( math.sqrt( math.pow(t_vtx[0]-hStart.x(),2) + math.pow(t_vtx[1]-hStart.y(),2) + math.pow(t_vtx[2]-hStart.z(),2) )) calVec=detResSim( hStart.x(), hStart.y() , hStart.z(), hit.Start.T(), hit.EnergyDeposit, size3DST[0], size3DST[1], size3DST[2], dist ) #print 'checking location x y z and time and recoE and distance',' ',calVec[0],' ',calVec[1],' ',calVec[2],' ',calVec[3],' ',calVec[4],' ',dist t_neutronHitX[iN] = calVec[0] t_neutronHitY[iN] = calVec[1] t_neutronHitZ[iN] = calVec[2] t_neutronHitSmearT[iN] = calVec[3]+t_vtxTime[0] t_neutronRecoE[iN] = calVec[4] t_neutronTrueE[iN]= event.Trajectories[iloop].InitialMomentum.Energy()-939.565 t_neutronHitT[iN] = hit.Start.T()+t_vtxTime[0] t_neutronHitE[iN] = hit.EnergyDeposit t_neutronHitS[iN] = event.Trajectories[hit.PrimaryId].PDGCode if (neutronMap.get(iloop) > -1000000): t_neutronParentId[iN] = neutronMap.get(iloop) t_neutronParentPDG[iN] = event.Trajectories[neutronMap.get(iloop)].PDGCode parID = parentDaughterMap.get(hit.PrimaryId) #print type(parID),' ',hit.PrimaryId,' ',parentDaughterMap.get(hit.PrimaryId) #print 'checking',event.Trajectories[parID].PDGCode #print event.Trajectories[hit.PrimaryId].InitialMomentum.Energy() iN += 1; """ for iloop in nTraj_1daughter: if hit.Contrib[0] == iloop: #print hStart.x() t_neutronHitX[iN] = hStart.x() t_neutronHitY[iN] = hStart.y() t_neutronHitZ[iN] = hStart.z() t_neutronHitE[iN] = hit.EnergyDeposit t_neutronHitS[iN] = event.Trajectories[hit.PrimaryId].PDGCode iN += 1; for iloop in nTraj_2daughter: if hit.Contrib[0] == iloop: #print hStart.x() t_neutronHitX[iN] = hStart.x() t_neutronHitY[iN] = hStart.y() t_neutronHitZ[iN] = hStart.z() t_neutronHitE[iN] = hit.EnergyDeposit t_neutronHitS[iN] = event.Trajectories[hit.PrimaryId].PDGCode iN += 1; for iloop in nTraj_3daughter: if hit.Contrib[0] == iloop: #print hStart.x() t_neutronHitX[iN] = hStart.x() t_neutronHitY[iN] = hStart.y() t_neutronHitZ[iN] = hStart.z() t_neutronHitE[iN] = hit.EnergyDeposit t_neutronHitS[iN] = event.Trajectories[hit.PrimaryId].PDGCode iN += 1; """ parentDaughterMap.clear() t_hadTot_3DST[0] = total_energy_3DST #print total_energy_3DST t_hadTot[0] = total_energy_3DST + total_energy_ECAL + total_energy_TPC t_hadCollar[0] = collar_energy for i in range(nfsp): t_fsTrkLen[i] = track_length[i] tout.Fill()
def Plot(files, label, obs): radmasses = [] for f in files: # radmasses.append(float(f.replace("CMS_jj_","").split("_")[0])/1000.) radmasses = [750, 1000, 2000, 3000] #,3.5,4.,4.5] print radmasses efficiencies = {} for mass in radmasses: efficiencies[mass] = 1000. # to convert from pb to fb fChain = [] for onefile in files: print onefile fileIN = rt.TFile.Open(onefile) fChain.append(fileIN.Get("limit;1")) rt.gROOT.ProcessLine("struct limit_t {Double_t limit;};") from ROOT import limit_t limit_branch = limit_t() for j in range(0, len(fChain)): chain = fChain[j] chain.SetBranchAddress("limit", rt.AddressOf(limit_branch, 'limit')) rad = [] for j in range(0, len(fChain)): chain = fChain[j] thisrad = [] for i in range(0, 6): chain.GetTree().GetEntry(i) thisrad.append(limit_branch.limit) #print "limit = %f" %limit_branch.limit #print thisrad rad.append(thisrad) # we do a plot r*MR mg = rt.TMultiGraph() mg.SetTitle("X -> ZZ") c1 = rt.TCanvas("c1", "A Simple Graph Example", 200, 10, 600, 600) c1.SetGridx(1) c1.SetGridy(1) x = [] yobs = [] y2up = [] y1up = [] y1down = [] y2down = [] ymean = [] for i in range(0, len(fChain)): y2up.append(rad[i][0] * efficiencies[radmasses[j]]) y1up.append(rad[i][1] * efficiencies[radmasses[j]]) ymean.append(rad[i][2] * efficiencies[radmasses[j]]) y1down.append(rad[i][3] * efficiencies[radmasses[j]]) y2down.append(rad[i][4] * efficiencies[radmasses[j]]) yobs.append(rad[i][5] * efficiencies[radmasses[j]]) grobs = rt.TGraphErrors(1) grobs.SetMarkerStyle(rt.kFullDotLarge) grobs.SetLineColor(rt.kRed) grobs.SetLineWidth(3) gr2up = rt.TGraphErrors(1) gr2up.SetMarkerColor(0) gr1up = rt.TGraphErrors(1) gr1up.SetMarkerColor(0) grmean = rt.TGraphErrors(1) grmean.SetLineColor(1) grmean.SetLineWidth(2) grmean.SetLineStyle(3) gr1down = rt.TGraphErrors(1) gr1down.SetMarkerColor(0) gr2down = rt.TGraphErrors(1) gr2down.SetMarkerColor(0) for j in range(0, len(fChain)): grobs.SetPoint(j, radmasses[j], yobs[j]) gr2up.SetPoint(j, radmasses[j], y2up[j]) gr1up.SetPoint(j, radmasses[j], y1up[j]) grmean.SetPoint(j, radmasses[j], ymean[j]) print(ymean[j]) gr1down.SetPoint(j, radmasses[j], y1down[j]) gr2down.SetPoint(j, radmasses[j], y2down[j]) #print " observed %f %f" %(radmasses[j],yobs[j]) mg.Add(gr2up) #.Draw("same") mg.Add(gr1up) #.Draw("same") mg.Add(grmean, "L") #.Draw("same,AC*") mg.Add(gr1down) #.Draw("same,AC*") mg.Add(gr2down) #.Draw("same,AC*") if obs: mg.Add(grobs, "L") #.Draw("AC*") c1.SetLogy(1) mg.SetTitle("") mg.Draw("AP") mg.GetXaxis().SetTitle("Resonance mass (GeV)") resonance = "G" #resonance="G_{Bulk}" if withAcceptance: mg.GetYaxis().SetTitle( "#sigma #times B(" + resonance + " #rightarrow " + label.split("_")[0].replace("RS1", "").replace("Bulk", "") + ") #times A (fb)") else: mg.GetYaxis().SetTitle("#sigma #times B(" + resonance + " #rightarrow Z#gamma) (fb)") mg.GetYaxis().SetLabelFont(42) mg.GetXaxis().SetLabelFont(42) mg.GetYaxis().SetTitleFont(42) mg.GetXaxis().SetTitleFont(42) mg.GetYaxis().SetTitleSize(0.035) mg.GetXaxis().SetTitleSize(0.035) mg.GetXaxis().SetLabelSize(0.045) mg.GetYaxis().SetLabelSize(0.045) mg.GetYaxis().SetRangeUser(0.5, 500) mg.GetYaxis().SetTitleOffset(1.4) mg.GetYaxis().CenterTitle(True) mg.GetXaxis().SetTitleOffset(1.1) mg.GetXaxis().CenterTitle(True) mg.GetXaxis().SetNdivisions(508) if "qW" in label.split("_")[0] or "qZ" in label.split("_")[0]: mg.GetXaxis().SetLimits(750, 3000) else: mg.GetXaxis().SetLimits(750, 3000) # histo to shade n = len(fChain) grgreen = rt.TGraph(2 * n) for i in range(0, n): grgreen.SetPoint(i, radmasses[i], y2up[i]) grgreen.SetPoint(n + i, radmasses[n - i - 1], y2down[n - i - 1]) grgreen.SetFillColor(rt.kGreen) grgreen.Draw("f") gryellow = rt.TGraph(2 * n) for i in range(0, n): gryellow.SetPoint(i, radmasses[i], y1up[i]) gryellow.SetPoint(n + i, radmasses[n - i - 1], y1down[n - i - 1]) gryellow.SetFillColor(rt.kYellow) gryellow.Draw("f,same") grmean.Draw("L") if obs: grobs.Draw("L") gtheory = rt.TGraphErrors(1) gtheory.SetLineColor(rt.kRed) gtheory.SetLineWidth(4) #ftheory=open("signal_cross_section_RS1Graviton.txt") #ftheory=open("bulk_graviton_exo15002.txt") #ij=0 #glogtheory = rt.TGraphErrors(1) #for lines in ftheory.readlines(): # for line in lines.split("\r"): # split=line.split(":") #print(split[1][0:]) # gtheory.SetPoint(ij, float(split[0][-4:])/1000., float(split[1])) # glogtheory.SetPoint(ij, float(split[0][-4:])/1000., log(float(split[1]))) # ij+=1 #mg.Add(gtheory,"L") #gtheory.Draw("L") #ltheory="G_{RS1} #rightarrow HH (k/#bar{M}_{Pl}=0.1)" #ltheory ="G_{Bulk} (ktild = 0.5)" # crossing=0 # for mass in range(int(radmasses[0]*1000.),int(radmasses[-1]*1000.)): # if exp(glogtheory.Eval(mass/1000.))>grmean.Eval(mass/1000.) and crossing>=0: # print label,"exp crossing",mass # crossing=-1 # if exp(glogtheory.Eval(mass/1000.))<grmean.Eval(mass/1000.) and crossing<=0: # print label,"exp crossing",mass # crossing=1 # crossing=0 # for mass in range(int(radmasses[0]*1000.),int(radmasses[-1]*1000.)): # if exp(glogtheory.Eval(mass/1000.))>grobs.Eval(mass/1000.) and crossing>=0: # print label,"obs crossing",mass # crossing=-1 # if exp(glogtheory.Eval(mass/1000.))<grobs.Eval(mass/1000.) and crossing<=0: #print label,"obs crossing",mass #crossing=1 if "WW" in label.split("_")[0] or "ZZ" in label.split("_")[0]: leg = rt.TLegend(0.53, 0.65, 0.95, 0.89) leg2 = rt.TLegend(0.33, 0.55, 0.95, 0.89) else: leg = rt.TLegend(0.59, 0.65, 0.95, 0.89) leg2 = rt.TLegend(0.49, 0.55, 0.95, 0.89) leg.SetFillColor(rt.kWhite) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetTextFont(42) leg.SetBorderSize(0) leg2.SetFillColor(rt.kWhite) leg2.SetFillStyle(0) leg2.SetTextSize(0.04) leg2.SetBorderSize(0) if obs: leg.AddEntry(grobs, "Observed", "L") leg.AddEntry(gryellow, "Expected (68%)", "f") leg.AddEntry(grgreen, "Expected (95%)", "f") #leg.AddEntry(gtheory, ltheory, "L") if obs: leg2.AddEntry(grobs, " ", "") #leg2.AddEntry(grmean, " ", "L") #leg2.AddEntry(grmean, " ", "L") #leg2.AddEntry(gtheory, " ", "") leg.Draw() #leg2.Draw("same") CMS_lumi.CMS_lumi(c1, iPeriod, iPos) c1.cd() c1.Update() if withAcceptance: c1.SaveAs("brazilianFlag_acc_%s_13TeV.root" % label) c1.SaveAs("brazilianFlag_acc_%s_13TeV.pdf" % label) else: c1.SaveAs("brazilianFlag_%s_13TeV.root" % label) c1.SaveAs("brazilianFlag_%s_13TeV.pdf" % label)
def getTree(myTree, paramNames, nBins, box, z): rando = random.randint(1, 999999) # first structure stringMyStruct1 = "void tempMacro_%d(){struct MyStruct1{" % (rando) stringMyStruct1 += "float toy_num; float nll_%s; float n2llr_%s; float chi2_%s;" % ( box, box, box) for k in range(1, len(z)): ibtag = z[k - 1] stringMyStruct1 += "float nll_%ibtag_%s; float n2llr_%ibtag_%s; float chi2_%ibtag_%s;" % ( ibtag, box, ibtag, box, ibtag, box) stringMyStruct1 += "int covQual_%s; int migrad_%s; int hesse_%s; int minos_%s;" % ( box, box, box, box) for paramName in paramNames: stringMyStruct1 = stringMyStruct1 + "float %s; float %s_error;" % ( paramName, paramName) if paramName == 'r': stringMyStruct1 = stringMyStruct1 + "float r_errorlo; float r_errorhi;" for iBinX in range(0, nBins): stringMyStruct1 = stringMyStruct1 + "float b%i;" % (iBinX) tempMacro = open("tempMacro_%d.C" % rando, "w") tempMacro.write(stringMyStruct1 + "};}") tempMacro.close() rt.gROOT.Macro("tempMacro_%d.C" % rando) #rt.gROOT.ProcessLine(".x tempMacro_%d.C"%rando) #rt.gROOT.ProcessLine(stringMyStruct1+"};") from ROOT import MyStruct1 # fills the bins list and associate the bins to the corresponding variables in the structure s1 = MyStruct1() myTree.Branch('toy_num', rt.AddressOf(s1, 'toy_num'), 'toy_num/F') myTree.Branch('nll_%s' % box, rt.AddressOf(s1, 'nll_%s' % box), 'nll_%s/F' % box) myTree.Branch('n2llr_%s' % box, rt.AddressOf(s1, 'n2llr_%s' % box), 'n2llr_%s/F' % box) myTree.Branch('chi2_%s' % box, rt.AddressOf(s1, 'chi2_%s' % box), 'chi2_%s/F' % box) for k in range(1, len(z)): ibtag = z[k - 1] myTree.Branch('nll_%ibtag_%s' % (ibtag, box), rt.AddressOf(s1, 'nll_%ibtag_%s' % (ibtag, box)), 'nll_%ibtag_%s/F' % (ibtag, box)) myTree.Branch('n2llr_%ibtag_%s' % (ibtag, box), rt.AddressOf(s1, 'n2llr_%ibtag_%s' % (ibtag, box)), 'n2llr_%ibtag_%s/F' % (ibtag, box)) myTree.Branch('chi2_%ibtag_%s' % (ibtag, box), rt.AddressOf(s1, 'chi2_%ibtag_%s' % (ibtag, box)), 'chi2_%ibtag_%s/F' % (ibtag, box)) myTree.Branch('covQual_%s' % box, rt.AddressOf(s1, 'covQual_%s' % box), 'covQual_%s/I' % box) myTree.Branch('migrad_%s' % box, rt.AddressOf(s1, 'migrad_%s' % box), 'migrad_%s/I' % box) myTree.Branch('hesse_%s' % box, rt.AddressOf(s1, 'hesse_%s' % box), 'hesse_%s/I' % box) myTree.Branch('minos_%s' % box, rt.AddressOf(s1, 'minos_%s' % box), 'minos_%s/I' % box) for paramName in paramNames: myTree.Branch(paramName, rt.AddressOf(s1, paramName), '%s/F' % paramName) myTree.Branch('%s_error' % paramName, rt.AddressOf(s1, '%s_error' % paramName), '%s_error/F' % paramName) if paramName == 'r': myTree.Branch('r_errorlo', rt.AddressOf(s1, 'r_errorlo'), 'r_errorlo/F') myTree.Branch('r_errorhi', rt.AddressOf(s1, 'r_errorhi'), 'r_errorhi/F') for ix in range(0, nBins): myTree.Branch("b%i" % (ix), rt.AddressOf(s1, "b%i" % (ix)), 'b%i/F' % ix) os.system("rm tempMacro_%d.C" % rando) return s1
def Plot(files, label, obs): radmasses = [] for f in files: radmasses.append(float(f.replace("CMS_jj_","").split("_")[0])/1000.) #print radmasses efficiencies={} for mass in radmasses: efficiencies[mass]=0.01*1000. # assume 10/fb signal cross section fChain = [] for onefile in files: print onefile fileIN = rt.TFile.Open(onefile) fChain.append(fileIN.Get("limit;1")) print fileIN rt.gROOT.ProcessLine("struct limit_t {Double_t limit;};") from ROOT import limit_t limit_branch = limit_t() for j in range(0,len(fChain)): chain = fChain[j] chain.SetBranchAddress("limit", rt.AddressOf(limit_branch,'limit')) rad = [] for j in range(0,len(fChain)): chain = fChain[j] thisrad = [] for i in range(0,6): chain.GetTree().GetEntry(i) thisrad.append(limit_branch.limit) #print "limit = %f" %limit_branch.limit #print thisrad rad.append(thisrad) # we do a plot r*MR mg = rt.TMultiGraph() mg.SetTitle("X -> ZZ") c1 = rt.TCanvas("c1","A Simple Graph Example",200,10,600,600) x = [] yobs = [] y2up = [] y1up = [] y1down = [] y2down = [] ymean = [] for i in range(0,len(fChain)): y2up.append(rad[i][0]*efficiencies[radmasses[j]]) y1up.append(rad[i][1]*efficiencies[radmasses[j]]) ymean.append(rad[i][2]*efficiencies[radmasses[j]]) y1down.append(rad[i][3]*efficiencies[radmasses[j]]) y2down.append(rad[i][4]*efficiencies[radmasses[j]]) yobs.append(rad[i][5]*efficiencies[radmasses[j]]) grobs = rt.TGraphErrors(1) grobs.SetMarkerStyle(rt.kFullDotLarge) grobs.SetLineColor(rt.kBlack) grobs.SetLineWidth(3) gr2up = rt.TGraphErrors(1) gr2up.SetMarkerColor(0) gr1up = rt.TGraphErrors(1) gr1up.SetMarkerColor(0) grmean = rt.TGraphErrors(1) grmean.SetLineColor(1) grmean.SetLineWidth(2) grmean.SetLineStyle(3) gr1down = rt.TGraphErrors(1) gr1down.SetMarkerColor(0) gr2down = rt.TGraphErrors(1) gr2down.SetMarkerColor(0) for j in range(0,len(fChain)): grobs.SetPoint(j, radmasses[j], yobs[j]) gr2up.SetPoint(j, radmasses[j], y2up[j]) gr1up.SetPoint(j, radmasses[j], y1up[j]) grmean.SetPoint(j, radmasses[j], ymean[j]) gr1down.SetPoint(j, radmasses[j], y1down[j]) gr2down.SetPoint(j, radmasses[j], y2down[j]) #print " observed %f %f" %(radmasses[j],yobs[j]) mg.Add(gr2up)#.Draw("same") mg.Add(gr1up)#.Draw("same") mg.Add(grmean,"L")#.Draw("same,AC*") mg.Add(gr1down)#.Draw("same,AC*") mg.Add(gr2down)#.Draw("same,AC*") if obs: mg.Add(grobs,"L")#.Draw("AC*") c1.SetLogy(1) mg.SetTitle("") mg.Draw("AP") mg.GetXaxis().SetTitle("Resonance mass (TeV)") if "HH" in label.split("_")[0]: resonance="Radion" if withAcceptance: mg.GetYaxis().SetTitle("#sigma #times B("+resonance+" #rightarrow HH #rightarrow bbbb #times A (fb)") else: mg.GetYaxis().SetTitle("#sigma #times B("+resonance+" #rightarrow HH #rightarrow bbbb) (fb)") mg.GetYaxis().SetTitleSize(0.06) mg.GetXaxis().SetTitleSize(0.06) mg.GetXaxis().SetLabelSize(0.045) mg.GetYaxis().SetLabelSize(0.045) mg.GetYaxis().SetRangeUser(0.1,1000) mg.GetYaxis().SetTitleOffset(1.4) mg.GetYaxis().CenterTitle(True) mg.GetXaxis().SetTitleOffset(1.1) mg.GetXaxis().CenterTitle(True) mg.GetXaxis().SetNdivisions(508) mg.GetXaxis().SetLimits(0.9,3.2) # histo to shade n=len(fChain) grgreen = rt.TGraph(2*n) for i in range(0,n): grgreen.SetPoint(i,radmasses[i],y2up[i]) grgreen.SetPoint(n+i,radmasses[n-i-1],y2down[n-i-1]) grgreen.SetFillColor(rt.kBlue) grgreen.Draw("f") gryellow = rt.TGraph(2*n) for i in range(0,n): gryellow.SetPoint(i,radmasses[i],y1up[i]) gryellow.SetPoint(n+i,radmasses[n-i-1],y1down[n-i-1]) gryellow.SetFillColor(rt.kBlue-7) gryellow.Draw("f,same") grmean.Draw("L") if obs: grobs.Draw("L") gtheory = rt.TGraphErrors(1) gtheory.SetLineColor(rt.kBlue) gtheory.SetLineWidth(4) ftheory=open("signalcrosssections.txt") j=0 glogtheory = rt.TGraphErrors(1) for lines in ftheory.readlines(): for line in lines.split("\r"): if label.split("_")[0] in line and line.count("Bulk")==label.split("_")[0].count("Bulk"): split=line.split(":") gtheory.SetPoint(j, float(split[0][-4:])/1000., float(split[1])) glogtheory.SetPoint(j, float(split[0][-4:])/1000., log(float(split[1]))) j+=1 #mg.Add(gtheory,"L") #gtheory.Draw("L") #if "HH" in label.split("_")[0]: # ltheory="Radion #rightarrow HH" crossing=0 for mass in range(int(radmasses[0]*1000.),int(radmasses[-1]*1000.)): if exp(glogtheory.Eval(mass/1000.))>grmean.Eval(mass/1000.) and crossing>=0: print label,"exp crossing",mass crossing=-1 if exp(glogtheory.Eval(mass/1000.))<grmean.Eval(mass/1000.) and crossing<=0: print label,"exp crossing",mass crossing=1 crossing=0 for mass in range(int(radmasses[0]*1000.),int(radmasses[-1]*1000.)): if exp(glogtheory.Eval(mass/1000.))>grobs.Eval(mass/1000.) and crossing>=0: print label,"obs crossing",mass crossing=-1 if exp(glogtheory.Eval(mass/1000.))<grobs.Eval(mass/1000.) and crossing<=0: print label,"obs crossing",mass crossing=1 leg = rt.TLegend(0.43,0.65,0.95,0.89) leg2 = rt.TLegend(0.43,0.65,0.95,0.89) leg.SetFillColor(rt.kWhite) leg.SetFillStyle(0) leg.SetTextSize(0.04) leg.SetBorderSize(0) leg2.SetFillColor(rt.kWhite) leg2.SetFillStyle(0) leg2.SetTextSize(0.04) leg2.SetBorderSize(0) if obs: leg.AddEntry(grobs, "Observed", "L") leg.AddEntry(gryellow, "Expected (68%)", "f") leg.AddEntry(grgreen, "Expected (95%)", "f") #leg.AddEntry(gtheory, ltheory, "L") if obs: leg2.AddEntry(grobs, " ", "") leg2.AddEntry(grmean, " ", "L") leg2.AddEntry(grmean, " ", "L") #leg2.AddEntry(gtheory, " ", "") leg.Draw() leg2.Draw("same") banner = TLatex(0.22,0.93,"CMS Preliminary, 19.7 fb^{-1}, #sqrt{s} = 8TeV"); banner.SetNDC() banner.SetTextSize(0.045) banner.Draw(); if withAcceptance: c1.SaveAs("brazilianFlag_acc_%s.root" %label) c1.SaveAs("brazilianFlag_acc_%s.pdf" %label) else: c1.SaveAs("brazilianFlag_%s.root" %label) c1.SaveAs("brazilianFlag_%s.pdf" %label)
def Load(self, use_merged_tracks): """ Sets access to TTree's and does some sanity checks """ self.roads = [] self.tracks = [] nfiles = [] nentries = [] for i in self.banks: print 'Working on bank', i try: roads = ROOT.FTKRoadStream() if self.ftracks is not None: tracks = ROOT.FTKTrackStream() except: print "Couldn't import libftk module, or wrong libftk version" print "Check location and compilation settings:", self.libftk return -1 # Roads tree if not _IGNORE_ROADS: print "Loading merged roads:", self.froads % i tree1 = ROOT.TChain("ftkdata", "Merged data") ROOT.SetOwnership(tree1, False) nfiles1 = tree1.Add(self.froads % i) nentries1 = tree1.GetEntries() if nfiles1 == 0 or nentries1 == 0: print "Didn't find any events in road TChain in bank", i print "Check the path to root file:", self.froads % i return -1 tree1.SetBranchAddress("FTKBank%d." % i, ROOT.AddressOf(roads)) self.roads.append((roads, tree1, nfiles1, nentries1, i)) nfiles.append(nfiles1) nentries.append(nentries1) print 'Added', nfiles1, 'road files with', nentries1, 'entries in bank #', i # Tracks tree if self.ftracks is not None and not _IGNORE_TRACKS: print "Loading tracks:", self.ftracks % i tree2 = ROOT.TChain("ftkdata", "Tracks") ROOT.SetOwnership(tree2, False) nfiles2 = tree2.Add(self.ftracks % i) nentries2 = tree2.GetEntries() if nfiles2 == 0 or nentries2 == 0: print "Didn't find any events in track TChain in bank", i print "Check the path to root file:", self.ftracks % i return -1 if use_merged_tracks == '1': tree2.SetBranchAddress("FTKBankMerged", ROOT.AddressOf(tracks)) else: tree2.SetBranchAddress("FTKBank%d." % i, ROOT.AddressOf(tracks)) self.tracks.append((tracks, tree2, nfiles2, nentries2, i)) nfiles.append(nfiles2) nentries.append(nentries2) print 'Added', nfiles2, 'track files with', nentries2, 'entries in bank #', i if _IGNORE_ROADS: self.roads = [None for i in self.tracks] if _IGNORE_TRACKS: self.tracks = [None for i in self.roads] if len(set(nfiles)) != 1: print 'Error: different number of files in different regions:', nfiles return -1 if len(set(nentries)) != 1: print 'Error: different number of events in different regions:', nentries return -1 self.nentries = nentries[0]
def addressof(event, s): if ROOT.gROOT.GetVersion() >= '6.22': from cppyy.ll import cast return cast['void*'](ROOT.addressof(event, s)) else: return ROOT.AddressOf(event, s)
myChain = ROOT.TChain("DGF") filelist = sys.argv[:] del filelist[0] for file in filelist: if file.find('root'): myChain.AddFile(file) nEntries = myChain.GetEntries() print 'Found', nEntries, ' entries in chain' myEvent = ROOT.ORDGFEvent() myChain.SetBranchAddress('fDGFEvent', ROOT.AddressOf(myEvent)) myChain.GetEntry(0) eventTimeOld = myEvent.GetEventTime() bufferStart = myEvent.GetBufferTime() runStart = bufferStart myChain.GetEntry(1) eventTimeNew = myEvent.GetEventTime() runTime = 0 liveTime = 0 triggerDeadTime = 0 nBuffers = 0 nEvents = 0 frac = 0.01
def main(): print('Preparing for profiling!') # First we do the ROOT setup and loop over the ROOT header/event trees init_root() root_data_dir = os.environ['BEACON_DATA_DIR'] root_data_dir += "/../root/" root_data_dir += 'run' + str(run) event_file = ROOT.TFile(root_data_dir + '/event.root') header_file = ROOT.TFile(root_data_dir + '/header.root') event_tree = event_file.Get('event') header_tree = header_file.Get('header') event = ROOT.beacon.Event() header = ROOT.beacon.Header() event_tree.SetBranchAddress('event', ROOT.AddressOf(event)) header_tree.SetBranchAddress('header', ROOT.AddressOf(header)) num_loops_over_events = 5 num_random_accesses = 100 num_entries = header_tree.GetEntries() dd = bt.DataDirectory() print('Ready!') print('.') print('.') print('.') print('Profiling the ROOT data reading...', end='', flush=True) root_seq = [] root_ra = [] for i in range(num_loops_over_events): read_trees(event_tree, header_tree, num_entries) root_seq.append(read_trees.elapsed) for j in range(num_random_accesses): random_access_trees(event_tree, header_tree, random.randint(0, num_entries - 1)) root_ra.append(random_access_trees.elapsed) print(' Done!') # Then before we test the BeaconTau reader we gzip our chosen raw data... beacon_data_dir = os.environ['BEACON_DATA_DIR'] gzip_event_files(beacon_data_dir + '/run' + str(run) + '/event') print('Profiling BeaconTau with gzipped data...', end='', flush=True) # Now we try reading the gzipped data run_analyzer = dd.run(run) bt_gzip_seq = [] bt_gzip_ra = [] for i in range(num_loops_over_events): read_beacon_tau_run(run_analyzer, num_entries) bt_gzip_seq.append(read_beacon_tau_run.elapsed) for j in range(num_random_accesses): random_access_beacon_tau_run(run_analyzer, random.randint(0, num_entries - 1)) bt_gzip_ra.append(random_access_beacon_tau_run.elapsed) del (run_analyzer) print(' Done!') # Now we un-gzip all the binary data... print('Unzipping for second BeaconTau test...', end='', flush=True) gunzip_event_files(beacon_data_dir + '/run' + str(run) + '/event') print(' Done!') run_analyzer = dd.run(run) # And time looping over the non-gzipped data print('Profiling BeaconTau with non-gzipped data...', end='', flush=True) bt_not_gzip_seq = [] bt_not_gzip_ra = [] for i in range(num_loops_over_events): read_beacon_tau_run(run_analyzer, num_entries) bt_not_gzip_seq.append(read_beacon_tau_run.elapsed) for j in range(num_random_accesses): random_access_beacon_tau_run(run_analyzer, random.randint(0, num_entries - 1)) bt_not_gzip_ra.append(random_access_beacon_tau_run.elapsed) del (run_analyzer) print(' Done!') # Finally, we tweak the max number of event files allowed in memory and repeated looping over data is very fast. # The downside is you use more RAM, hence why this is configurable and set to a (reasonably) low number. print( 'Profiling BeaconTau with non-gzipped data and increased max_files_in_memory...', end='', flush=True) run_analyzer = dd.run(run) num_files = len(glob.glob(beacon_data_dir + '/run%s' % run + '/event/*')) run_analyzer.file_reader.events.max_files_in_memory = num_files bt_not_gzip_more_mem_seq = [] bt_not_gzip_more_mem_ra = [] for i in range(num_loops_over_events): read_beacon_tau_run(run_analyzer, num_entries) bt_not_gzip_more_mem_seq.append(read_beacon_tau_run.elapsed) for j in range(num_random_accesses): random_access_beacon_tau_run(run_analyzer, random.randint(0, num_entries - 1)) bt_not_gzip_more_mem_ra.append(random_access_beacon_tau_run.elapsed) print(' Done!') print('Zipping event files back up...', end='', flush=True) gzip_event_files(beacon_data_dir + '/run' + str(run) + '/event') # Back to original status print(' Done!') print('********************************************************') print('Profiling summary:') print('********************************************************') print_summary('ROOT reading all events sequentially', root_seq) print_summary('ROOT reading a single random entry', root_ra) print('********************************************************') print_summary('BeaconTau reading all gzipped data', bt_gzip_seq) print_summary('BeaconTau reading a single random gzipped entry', bt_gzip_ra) print('********************************************************') print_summary('BeaconTau reading all non-gzipped data', bt_not_gzip_seq) print_summary('BeaconTau reading a single random non-gzipped entry', bt_not_gzip_ra) print('********************************************************') print_summary( 'BeaconTau reading all non-gzipped data (with large max_files_in_memory)', bt_not_gzip_more_mem_seq) print_summary( 'BeaconTau reading a single random non-gzipped entry (with large max_files_in_memory)', bt_not_gzip_more_mem_ra) print('********************************************************')
def __init__(self, filename, treename, firstrow=0, nrows=None): from string import find # cache inputs self.status = 0 from random import randint self.postfix = randint(1, 1000000) if type(filename) == type(""): self.filename = [filename] else: self.filename = filename self.currentTreeNumber = -1 self.treename = treename self.nrows = nrows # make sure all files exist fnames = [] for fname in self.filename: if not os.path.exists(fname): print "** Ntuple *** "\ "root file %s not found" % fname sys.exit(0) # check file size size = os.path.getsize(fname) if size == 0: print "== ZERO length == %s" % fname continue else: fnames.append(fname) self.filename = fnames if len(self.filename) == 0: self.status = -3 return # create a chain of files self.chain = ROOT.TChain(treename) if not self.chain: print "*** Ntuple *** can't create chain %s" % treename sys.exit(0) # ------------------------------------ # add files to chain # ------------------------------------ for fname in self.filename: try: self.chain.Add(fname) except: print "*** problem with file %s" % fname self.entries = self.chain.GetEntries() self.tree = self.chain tree = self.tree if tree == None: print "** problem accessing Tree - "\ "perhaps the name %s is wrong?" % treename sys.exit(0) # get names of variables from root file branches = tree.GetListOfBranches() # get number of variables try: nbranches = branches.GetEntries() except: print "** ====> problem accessing branches\n" self.status = -1 return bnamemap = {} self.vars = [] for i in xrange(nbranches): # get the ith branch (aka variable) bname = branches[i].GetName() # just in case, check for duplicates! if bnamemap.has_key(bname): print '** duplicate branch name: %s' % bname continue else: bnamemap[bname] = 1 # assume one leaf/branch # Get all leaves associated with this branch leaves = branches[i].GetListOfLeaves() if leaves == None: print "No leaves found!" sys.exit(0) leaf = leaves[0] if leaf == None: print "No leaf found" sys.exit(0) leafname = leaf.GetName() # get leaf type (int, float, double, etc.) tname = leaf.GetTypeName() if find(tname, 'vector') > -1: #print '**skipping %s\t%s for now' % (tname, name) continue # check for leaf counter flag = Long(0) leafcounter = leaf.GetLeafCounter(flag) if leafcounter: maxcount = leafcounter.GetMaximum() else: maxcount = leaf.GetLen() # store type and variable name self.vars.append( (tname, bname, maxcount) ) nlen = len(self.vars) # create a map of variable name to column number self.varmap = {} for ind, var in enumerate(self.vars): self.varmap[var] = ind nentries = self.entries if self.nrows != None: self.entries = min(self.nrows, nentries) else: self.entries = nentries # ------------------------------------ # set up branches as a struct # Root has a limit on how long a # string it can cope with, so split # into multiple strings # ------------------------------------ bufferCount = 0 newBuffer = True rec = "" bufferName = "" maxlength = 2000 self.buffermap = {} self.buffer = [] self.varname= [] for count, (tname, name, maxcount) in enumerate(self.vars): self.varname.append((name, maxcount)) # keep track of map from variable name to buffer count self.buffermap[name] = bufferCount if newBuffer: newBuffer = False bufferName = "S%d_%d" % (self.postfix, bufferCount) rec = "struct %s {" % bufferName if find(tname, 'vector') > -1: # special handling for vectors continue elif maxcount == 1: rec += "%s %s;" % (tname, name) else: rec += "%s %s[%d];" % (tname, name, maxcount) if (len(rec) > maxlength) or \ (count >= len(self.vars)-1): rec += "};" newBuffer = True # evaluate it ROOT.gROOT.ProcessLine(rec) # now import struct exec("from ROOT import %s" % bufferName) # add to list of buffers self.buffer.append(eval("%s()" % bufferName)) # remember to update buffer count bufferCount += 1 # create a generic event object self.event = Buffer(self.buffer, self.buffermap, self.vars) # Now that addresses are stable, give address of each variable for tname, name, maxcount in self.vars: jj = self.buffermap[name] tree.SetBranchAddress(name, ROOT.AddressOf(self.buffer[jj], name)) self.status = 0 # initialize row number self.row = firstrow
def writeTree(box, model, directory, mg, mchi, xsecULObs, xsecULExpPlus2, xsecULExpPlus, xsecULExp, xsecULExpMinus, xsecULExpMinus2, signif): tmpFileName = "%s/%s_xsecUL_mg_%s_mchi_%s_%s.root" % ("/tmp", model, mg, mchi, box) fileOut = rt.TFile.Open(tmpFileName, "recreate") if opt.signif: signifTree = rt.TTree("signifTree", "signifTree") try: from ROOT import MyStruct except ImportError: myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi; Double_t x; Double_t y; Double_t signif; }" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() signifTree.Branch("mg", rt.AddressOf(s, "mg"), 'mg/D') signifTree.Branch("mchi", rt.AddressOf(s, "mchi"), 'mchi/D') signifTree.Branch("x", rt.AddressOf(s, "x"), 'x/D') signifTree.Branch("y", rt.AddressOf(s, "y"), 'y/D') signifTree.Branch("signif_%s" % box, rt.AddressOf(s, "signif"), 'signif/D') else: xsecTree = rt.TTree("xsecTree", "xsecTree") try: from ROOT import MyStruct except ImportError: myStructCmd = "struct MyStruct{Double_t mg;Double_t mchi; Double_t x; Double_t y;" ixsecUL = 0 myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 0) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 1) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 2) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 3) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 4) myStructCmd += "Double_t xsecUL%i;" % (ixsecUL + 5) ixsecUL += 6 myStructCmd += "}" rt.gROOT.ProcessLine(myStructCmd) from ROOT import MyStruct s = MyStruct() xsecTree.Branch("mg", rt.AddressOf(s, "mg"), 'mg/D') xsecTree.Branch("mchi", rt.AddressOf(s, "mchi"), 'mchi/D') xsecTree.Branch("x", rt.AddressOf(s, "x"), 'x/D') xsecTree.Branch("y", rt.AddressOf(s, "y"), 'y/D') s.mg = mg s.mchi = mchi if 'T1x' in model: s.x = float(model[model.find('x') + 1:model.find('y')].replace( 'p', '.')) s.y = float(model[model.find('y') + 1:].replace('p', '.')) elif model == 'T1bbbb': s.x = 1 s.y = 0 elif model == 'T1tttt': s.x = 0 s.y = 1 else: s.x = -1 s.y = -1 if opt.signif: s.signif = signif signifTree.Fill() fileOut.cd() signifTree.Write() fileOut.Close() outputFileName = "%s/%s_signif_mg_%s_mchi_%s_%s.root" % ( directory, model, mg, mchi, box) print "INFO: significance values being written to %s" % outputFileName special_call(["mv", tmpFileName, outputFileName], 0) else: ixsecUL = 0 xsecTree.Branch("xsecULObs_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 0)), 'xsecUL%i/D' % (ixsecUL + 0)) xsecTree.Branch("xsecULExpPlus2_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 1)), 'xsecUL%i/D' % (ixsecUL + 1)) xsecTree.Branch("xsecULExpPlus_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 2)), 'xsecUL%i/D' % (ixsecUL + 2)) xsecTree.Branch("xsecULExp_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 3)), 'xsecUL%i/D' % (ixsecUL + 3)) xsecTree.Branch("xsecULExpMinus_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 4)), 'xsecUL%i/D' % (ixsecUL + 4)) xsecTree.Branch("xsecULExpMinus2_%s" % box, rt.AddressOf(s, "xsecUL%i" % (ixsecUL + 5)), 'xsecUL%i/D' % (ixsecUL + 5)) exec 's.xsecUL%i = xsecULObs[ixsecUL]' % (ixsecUL + 0) exec 's.xsecUL%i = xsecULExpPlus2[ixsecUL]' % (ixsecUL + 1) exec 's.xsecUL%i = xsecULExpPlus[ixsecUL]' % (ixsecUL + 2) exec 's.xsecUL%i = xsecULExp[ixsecUL]' % (ixsecUL + 3) exec 's.xsecUL%i = xsecULExpMinus[ixsecUL]' % (ixsecUL + 4) exec 's.xsecUL%i = xsecULExpMinus2[ixsecUL]' % (ixsecUL + 5) ixsecUL += 4 xsecTree.Fill() fileOut.cd() xsecTree.Write() fileOut.Close() outputFileName = "%s/%s_xsecUL_mg_%s_mchi_%s_%s.root" % ( directory, model, mg, mchi, box) print "INFO: xsec UL values being written to %s" % outputFileName special_call(["mv", tmpFileName, outputFileName], 0) return outputFileName
def _addressOf(self): """(Internal) Return address of edm wrapper""" return ROOT.AddressOf(self._wrapper)