ATLAS Offline Software
LArG4FSStartPointFilterLegacy.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
3 
4 import sys
5 import os
6 from os.path import isfile
7 from optparse import OptionParser
8 from random import randint
9 from math import sqrt
10 
11 usage = "usage: %prog [options] input1 [input2...]"
12 
13 parser = OptionParser(usage=usage, version="%prog v0.0.1 $Id: LArG4FSStartPointFilter.py 711210 2015-11-27 15:56:00Z jchapman $")
14 
15 parser.add_option("-p","--particle", dest="part", type="choice", action="append", choices=["11","22","2112"], help="particle to be filtered out (default - no filter)")
16 parser.add_option("-t","--truncate", dest="numevents", type=int, help="Truncate the number of events (default - all)")
17 parser.add_option("-l","--outevents", dest="outevents", type=int, help="Truncate the number of output (default - all)")
18 parser.add_option("-o","--output", dest="outfile", help="Name of output file")
19 
20 parser.set_defaults(part=[],outfile="genevents.ascii",numevents=0,outevents=0,draw=False,execute=False)
21 
22 (options, args) = parser.parse_args()
23 
24 print (options, args)
25 
26 if len(args) == 0 :
27  print ("ERROR: No input! Aborting")
28  sys.exit(1)
29 
30 stpoints = []
31 globallinever = ""
32 globallinehead = ""
33 
34 #reading input
35 for infilename in args :
36  #opening file
37  print ("Opening file",infilename)
38  infile = open(infilename)
39  #first line is empty
40  linever = infile.readline().rstrip("\n")
41  if linever=="":
42  linever = infile.readline().rstrip("\n")
43  print(linever)
44  if (globallinever == "") :
45  globallinever = linever
46  linehead = infile.readline().rstrip("\n")
47  print(linehead)
48  if (globallinehead == "") :
49  globallinehead = linehead
50  #must be FS SP header OR normal HepMC GenEvent header
51  if (( not linever.startswith("HepMC::Version")) or ("START_EVENT_LISTING" not in linehead) or (linever != globallinever)) :
52  print ("ERROR: Wrong input:",infilename,"omitting", file=sys.stderr)
53  continue
54  #starting the loop
55  stpointsloc = []
56  line = infile.readline()
57  while ((line != "") and ( not line.startswith("HepMC::" ))) :
58  line1 = infile.readline()
59  line2 = infile.readline()
60  line3 = infile.readline()
61  line4 = infile.readline()
62 
63  stpoint = [line,line1,line2,line3]
64  if "Ascii" in globallinehead:
65  if (line[0] != "E") or (line1[0] != "U") or (line2[0] != "P") or (line3[0] != "V") or (line4[0] != "P"):
66  print ("ERROR:",infilename,"is not a valid file!")
67  sys.exit(1)
68  stpoint.append(line4)
69  else:
70  #checking every event for being single particle event [HepMC2 style]
71  if (line[0] != "E") or (line1[0] != "U") or (line2[0] != "V") or (line3[0] != "P") :
72  #This event structure was default in HepMC2,
73  #but it results in empty pool files in HepMC3.
74  #The HepMC3 reader always require both input and output particle.
75  print ("ERROR:",infilename,"is not a valid file!")
76  sys.exit(1)
77 
78  #adding extra line according to HepMC3 style
79  if line4[0] == "P":
80  stpoint.append(line4)
81 
82  #uncommnent the following 3 lines if you want to read old HepMC2 files
83  # if line4[0] == "E":
84  # line_dummy = "P 1 999 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 4 0 0 -1 0"
85  # stpoint.insert(-1,line_dummy)
86 
87  stpointsloc.append(stpoint)
88 
89  line = line4
90  if line[0] != "E":
91  line = infile.readline()
92 
93  infile.close()
94  stpoints += stpointsloc
95  if ("tfile" in dir()) :
96  del tinfo
97  tfile.close()
98 
99 if len(stpoints) == 0 :
100  print ("ERROR: no events found is not a valid file!")
101  sys.exit(1)
102 
103 #creating an output stream
104 if isfile(options.outfile) :
105  print ("WARNING: File",options.outfile,"already exists.")
106 outdata = open(options.outfile,"w")
107 outdata.write(globallinever)
108 outdata.write("\n")
109 outdata.write(globallinehead)
110 outdata.write("\n")
111 
112 stpsize = len(stpoints)
113 if (options.numevents > stpsize) :
114  print ("WARNING: requested number of events is bigger then provided in input files")
115  options.numevents = 0
116 
117 if (options.numevents == 0) :
118  options.numevents = stpsize #all events
119 
120 i = 0
121 while i < options.numevents :
122  if (stpsize == 0) :
123  print ("INFO: We've run out of starting point.\nIt's okay if you didn't specify -t option, but may mean that you do not have enough otherwise.")
124  break
125  rand = randint(0,stpsize-1)
126  stpoint = stpoints.pop(rand) #take a random event
127  stpsize-=1
128  parsed = stpoint[-1].split() #last line - the particle. PDG code and 4-vector is there.
129  pid_filt = parsed[2]
130  if "Ascii" in globallinehead:
131  pid_filt = parsed[3]
132  if (options.part == []) or (pid_filt in options.part) : #check PDG
133  parsed = stpoint[0].split() #first line - event itself. The number of event is there
134  parsed[1] = str(i) #Change the number of event...
135  stpoint[0] = " ".join(parsed) #...and construct the line back
136  if (options.draw) :
137  parsed = stpoint[2].split() #third line - the vertex.
138  x = float(parsed[3])
139  y = float(parsed[4])
140  z = float(parsed[5])
141  r = sqrt(x*x + y*y)
142  hist.Fill(z,r)
143  if len(options.outfile) > 0 :
144  for iline in stpoint:
145  outdata.write(iline.rstrip("\n")+"\n")
146  i += 1
147 
148 outdata.write(globallinehead.replace("START","END"))
149 outdata.close()
150 print ("INFO: Written", i, options.numevents, "starting points")
151 
152 if (options.outevents > i) :
153  print ("WARNING: requested number of events is bigger then provided in input files")
154  options.outevents = 0
155 
156 if (options.outevents == 0) :
157  options.outevents = i #all events
158 
159 #starting the filter
160 exec = __file__.replace("LArG4FSStartPointFilterLegacy.py","LArG4FSStartPointFilterBody.py")
161 #print('athena -c "options={:s}" {:s}'.format(str(options),exec))
162 os.system('athena -c "options={:s}" {:s}'.format(str(options),exec))
163 
vtune_athena.format
format
Definition: vtune_athena.py:14
beamspotman.dir
string dir
Definition: beamspotman.py:623
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
Trk::open
@ open
Definition: BinningType.h:40
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
str
Definition: BTagTrackIpAccessor.cxx:11
readCCLHist.float
float
Definition: readCCLHist.py:83
Trk::split
@ split
Definition: LayerMaterialProperties.h:38