Belle II Software  release-08-01-10
ndFinderTest.py
1 #!/usr/bin/env python3
2 
3 
10 
11 import basf2
12 from generators import add_phokhara_generator
13 from simulation import add_simulation
14 from reconstruction import add_reconstruction
15 from ROOT import Belle2
16 import numpy as np
17 import glob
18 
19 
20 def addGen(main, args):
21  main.add_module('EventInfoSetter',
22  runList=[1],
23  expList=[0],
24  evtNumList=args.nevents
25  )
26  main.add_module('Progress')
27  main.add_module('Gearbox')
28  main.add_module('Geometry')
29  add_phokhara_generator(main, finalstate=args.finalState)
30 
31  if args.bkgfiles is not None:
32  def strip(x): return x.split('/')[-1].split('.')[0]
33  bkgraws = args.bkgfiles.strip("'")
34  bkgfiles = glob.glob(bkgraws)
35  print('bkgfiles', bkgfiles)
36  add_simulation(main, bkgfiles=bkgfiles)
37  else:
38  add_simulation(main)
39  add_reconstruction(main)
40 
41 
42 def addRead(main, args):
43  main.add_module('RootInput', inputFileName=args.genFileName)
44  main.add_module('Progress')
45  main.add_module('Gearbox')
46  main.add_module('Geometry')
47 
48 
49 def add_cdc_finders(path):
50  """
51  This function adds the CDC trigger TSF and Finder modules to a path.
52  @path modules are added to this path
53  """
54  # TSF
55  InTS = Belle2.FileSystem.findFile("data/trg/cdc/innerLUT_Bkg_p0.70_b0.80.coe")
56  OutTS = Belle2.FileSystem.findFile("data/trg/cdc/outerLUT_Bkg_p0.70_b0.80.coe")
57  path.add_module('CDCTriggerTSF',
58  InnerTSLUTFile=InTS,
59  OuterTSLUTFile=OutTS,
60  TSHitCollectionName="CDCTriggerSegmentHits")
61  # 2D finder
62  path.add_module('CDCTrigger2DFinder')
63  # 3D finder
64  axialFile = Belle2.FileSystem.findFile(args.axialFile)
65  stereoFile = Belle2.FileSystem.findFile(args.stereoFile)
66  path.add_module("CDCTriggerNDFinder",
67  logLevel=basf2.LogLevel.DEBUG, debugLevel=1000,
68  minhits=args.minhits,
69  minweight=args.minweight,
70  minpts=args.minpts,
71  mincells=args.mincells,
72  minhits_axial=args.minhits_axial,
73  minassign=args.minassign,
74  thresh=args.thresh,
75  diagonal=args.diagonal,
76  axialFile=axialFile,
77  stereoFile=stereoFile,
78  verbose=args.verbose
79  )
80 
81 
82 class QuickCheck(basf2.Module):
83  def initialize(self):
84  self.storenstoren = np.zeros(10, dtype='int')
85  self.storemstorem = np.zeros(10, dtype='int')
86  self.store2dstore2d = np.zeros(10, dtype='int')
87  self.store3dstore3d = np.zeros(10, dtype='int')
88  self.storeunitsstoreunits = np.zeros(10, dtype='int')
89 
90  def getUniqRecTS(self, rec):
91  sls = []
92  for tshit in rec.getRelationsTo('CDCTriggerSegmentHits'):
93  sls.append(tshit.getISuperLayer())
94  return np.unique(sls)
95 
96  def event(self):
97  recos = Belle2.PyStoreArray("RecoTracks")
98  nrecos = len(recos)
99  mrecos = 0
100  unitsrecos = 0
101  for rec in recos:
102  cdcuniq = np.unique([cdchit.getICLayer() for cdchit in rec.getCDCHitList()])
103  ncdc = len(cdcuniq)
104  if ncdc > 25:
105  mrecos += 1
106 
107  nunits = len(self.getUniqRecTSgetUniqRecTS(rec))
108  if nunits >= 4:
109  unitsrecos += 1
110 
111  find2ds = Belle2.PyStoreArray("TRGCDC2DFinderTracks")
112  n2ds = len(find2ds)
113 
114  find3ds = Belle2.PyStoreArray("CDCTrigger3DFinderTracks")
115  n3ds = len(find3ds)
116 
117  [nrecos, mrecos, unitsrecos, n2ds, n3ds] = self.setMaxsetMax([nrecos, mrecos, unitsrecos, n2ds, n3ds])
118 
119  self.storenstoren[nrecos] += 1
120  self.storemstorem[mrecos] += 1
121  self.store2dstore2d[n2ds] += 1
122  self.store3dstore3d[n3ds] += 1
123  self.storeunitsstoreunits[unitsrecos] += 1
124 
125  def setMax(self, valList, maxval=10):
126  trimmed = []
127  for value in valList:
128  if value >= maxval:
129  value = maxval - 1
130  trimmed.append(value)
131  return trimmed
132 
133  def terminate(self):
134  def mystr(val):
135  return '%3s' % ('%d' % val)
136  headline0 = [' ' for i in range(6)]
137  headline0.insert(4, 'TrackType')
138  headline1 = [' NTrack', '__|'] + ['___' for i in range(5)]
139  headline2 = [' ' * 3, '|', 'Reco', 'Reco ', 'Reco', '2DFinder', '3DFinder']
140  headline3 = [' ' * 3, '|', ' ', '>25CDC', '>4TS', ' ', ' ']
141 
142  def uline(strarr, sep=' ', fmt='%.9s', fmtOut='%9s'):
143  return sep.join([fmtOut % (fmt % x) for x in strarr])
144  print('number of tracks (NTrack in rows) of type TrackType (in columns) in number of events (elements)')
145  print(uline(headline0))
146  print(uline(headline1))
147  print(uline(headline2))
148  print(uline(headline3))
149  print(uline(['_' * 5 for i in range(7)]))
150 
151  for itrack, (nevents, mevents, unitsevents, events2d, events3d) in enumerate(
152  zip(self.storenstoren, self.storemstorem, self.storeunitsstoreunits, self.store2dstore2d, self.store3dstore3d)):
153  entryline = [mystr(itrack), '|',
154  mystr(nevents),
155  mystr(mevents),
156  mystr(unitsevents),
157  mystr(events2d),
158  mystr(events3d)]
159  print(uline(entryline))
160 
161 
162 def addTrgOutput(main, args):
163  quickCheck = QuickCheck()
164  main.add_module(quickCheck)
165 
166 
167 def add_matching(path, finderNames):
168  for finderName in finderNames:
169  path.add_module('CDCTriggerRecoMatcher',
170  TrgTrackCollectionName=finderName)
171 
172 
173 def mainFunc(args):
174  basf2.set_log_level(basf2.LogLevel.WARNING)
175  basf2.set_random_seed(args.seed)
176  main = basf2.create_path()
177  addGen(main, args)
178  main.add_module('RootOutput',
179  outputFileName=args.genFileName,
180  updateFileCatalog=False)
181  add_cdc_finders(main)
182  add_matching(main, ["CDCTrigger3DFinderTracks", "TRGCDC2DFinderTracks"])
183  addTrgOutput(main, args)
184  main.add_module('RootOutput',
185  outputFileName=args.outputFileName,
186  updateFileCatalog=False)
187  basf2.process(main)
188  print(basf2.statistics)
189 
190 
191 def mainFuncRead(args):
192  basf2.set_log_level(basf2.LogLevel.WARNING)
193  basf2.set_random_seed(args.seed)
194  main = basf2.create_path()
195  addRead(main, args)
196  add_cdc_finders(main)
197  add_matching(main, ["CDCTrigger3DFinderTracks", "TRGCDC2DFinderTracks"])
198  addTrgOutput(main, args)
199  main.add_module('RootOutput',
200  outputFileName=args.outputFileName,
201  updateFileCatalog=False)
202 
203  basf2.process(main, max_event=args.nevents)
204  print(basf2.statistics)
205 
206 
207 if __name__ == "__main__":
208  import argparse
209  parser = argparse.ArgumentParser(description='Test NDFinder in TRG with ISR simulation', epilog='NDFinder Test')
210  parser.add_argument('--finalState', default='pi+pi-', help='final state: mu+mu- pi+pi- pi+pi-pi0')
211  parser.add_argument('--seed', default=1234567, help='random seed', type=int)
212  parser.add_argument('--nevents', default=100, help='number of events to generate', type=int)
213  parser.add_argument('--bkgfiles', default=None, help='path to background mixing files')
214  parser.add_argument('--outputFileName', default="ndFinderTest.root", help='output trg file name')
215  parser.add_argument('--genFileName', default="ndFinderGen.root", help='output gen file name')
216  parser.add_argument('--minweight', default=12, type=int, help='NDFinder')
217  parser.add_argument('--minhits', default=4, type=int, help='NDFinder')
218  parser.add_argument('--minhits_axial', default=2, type=int, help='NDFinder')
219  parser.add_argument('--minpts', default=2, type=int, help='NDFinder')
220  parser.add_argument('--diagonal', action='store_true', help='NDFinder')
221  parser.add_argument('--mincells', default=5, type=int, help='NDFinder')
222  parser.add_argument('--minassign', default=0.8, type=float, help='NDFinder')
223  parser.add_argument('--thresh', default=0.85, type=float, help='NDFinder')
224  parser.add_argument('--readGen', action='store_true', help='skip generation, read from file')
225  parser.add_argument('--axialFile',
226  default="data/trg/cdc/ndFinderAxialShallow.txt.gz",
227  # default="data/trg/cdc/ndFinderArrayAxialComp.txt.gz",
228  help='NDFinder File name of the axial hit patterns')
229  parser.add_argument('--stereoFile',
230  default="data/trg/cdc/ndFinderStereoShallow.txt.gz",
231  # default="data/trg/cdc/ndFinderArrayStereoComp.txt.gz",
232  help='NDFinder File name of the stereo hit patterns')
233  parser.add_argument('--verbose', action='store_true', help='NDFinder')
234 
235  args = parser.parse_args()
236  if args.readGen:
237  mainFuncRead(args)
238  else:
239  mainFunc(args)
static std::string findFile(const std::string &path, bool silent=false)
Search for given file or directory in local or central release directory, and return absolute path if...
Definition: FileSystem.cc:148
A (simplified) python wrapper for StoreArray.
Definition: PyStoreArray.h:72
def setMax(self, valList, maxval=10)
def getUniqRecTS(self, rec)
Definition: ndFinderTest.py:90