4 from __future__
import print_function
7 parser = argparse.ArgumentParser(description=
'Flattens Wrapper Files')
8 parser.add_argument(
'inname', metavar=
'inputfile', type=str, nargs=
'+',
9 help=
'input file name (should be FPGATrackSim Wrapper File)')
10 parser.add_argument(
'--evts', action=
'store', type=int,
11 help=
'number of events to process', default=(1<<30))
12 parser.add_argument(
'--trim', action=
'store', type=float,
13 help=
'trim modules with less than given fraction of tracks', default=
None)
14 parser.add_argument(
'--nslices', action=
'store', type=int,
15 help=
'number of slices to build', default=6)
16 parser.add_argument(
'--keylayer', action=
'store', type=str,
17 help=
'keylayer as det,bec,layer', default=
"strip,barrel,2")
18 parser.add_argument(
'--keylayer2', action=
'store', type=str,
19 help=
'second keylayer subdivides slices', default=
None)
20 parser.add_argument(
'--outfilelabel', action=
'store', type=str,
21 help=
'label to start outfile with', default=
"Unlabled")
22 parser.add_argument(
'--etarange', action=
'store', type=str,
23 help=
'range of eta for slice', default=
"-100,100")
24 parser.add_argument(
'--fullgran', action=
'store_true')
25 parser.add_argument(
'--test1slice', action=
'store_true')
27 args = parser.parse_args()
35 from collections
import defaultdict
46 defaultdictlambda=
lambda : defaultdict(defaultdictlambda)
50 for key,val
in tree.items():
51 if 'dict' in type(val).__name__:
54 if 'list' in type(val).__name__:
55 retv[key]=[func(subval)
for subval
in val]
64 dets=[
"pixel",
"strip"]
65 regs=[
"barrel",
"endcap"]
68 int2det = {1:
"pixel", 0:
"strip"}
69 det2int = {v:k
for k,v
in int2det.items()}
70 int2reg = {0:
"barrel", 2:
"endcap"}
71 reg2int = {v:k
for k,v
in int2reg.items()}
75 striprows={
'barrel' : {0:[
None]+[4]*14,
83 'endcap' : {i:[4,4,2,4,2,2]
for i
in range(12)}
88 abcchipsperrow={
'barrel' : {i+1:[10,10,10,10]
for i
in range(14)},
89 'endcap' : {0:[8,8,9,9],
100 for reg
in stripsperrow:
102 for mod
in stripsperrow[reg]:
103 rowbounds[reg][mod]=[
sum(stripsperrow[reg][mod][0:i+1])
for i
in range(len(stripsperrow[reg][mod]))]
108 if "ITK-22" in args.inname:
110 elif "ITK-23" in args.inname:
114 layers={
"pixel": {
"barrel":5,
"endcap": 8
if geom==
"ITK-22" else 8 },
"strip" : {
"barrel":8,
"endcap":12}}
122 if name
not in hists:
123 hists[name]=makehist(name)
132 if len(args.inname)==1
and os.path.isdir(args.inname[0]):
133 fileList = glob.glob(
"%s/*.root" % args.inname)
136 Data = ROOT.TChain(
"ExtrapolationEngineTest")
138 for file
in fileList:
139 msg.info(
"Adding file %s" %(file))
142 num_entries =
min(args.evts,Data.GetEntries())
143 msg.info(
"reading track input: %d entries\n" % (num_entries))
152 key_det,key_reg,key_lyr = keystring.split(
",")
153 key[
"lyr"]=
int(key_lyr)
154 key[
"det"]=det2int[key_det]
155 key[
"reg"]=reg2int[key_reg]
166 min_eta,max_eta = [
float(s)
for s
in args.etarange.split(
",")]
173 if trk.SensitiveIsPixel[hit_idx] == 0:
174 layer = 2*trk.SensitiveLayerDisc[hit_idx]+trk.SensitiveSide[hit_idx]
176 layer = trk.SensitiveLayerDisc[hit_idx]
181 strip = trk.SensitivePhiIndex[hit_idx]
182 bec=int2reg[abs(trk.SensitiveBarrelEndcap[hit_idx])]
184 etamod=trk.SensitiveEtaModule[hit_idx]
185 localrow,globalrow=
None,
None
186 r=trk.SensitivePosR[hit_idx]
187 z=trk.SensitivePosZ[hit_idx]
190 if trk.SensitiveIsPixel[hit_idx] == 0:
192 if "strip_number" not in hists:
193 hists[
"strip_number"]=ROOT.TH2D(
"strip_number_hist",
";module;strip",500,0,500,800,0,8000)
194 hists[
"strip_number"].Fill(reg2int[bec]*100+layer*10+etamod,strip)
197 localrow = bisect.bisect_left(rowbounds[bec][abs(etamod)],strip)
199 rows_in_module=striprows[bec][layer][abs(etamod)]
201 if localrow > rows_in_module:
202 msg.error(
"Error row(%d) greater than number of rows in module %d" %(localrow,rows_in_module))
203 globalrow=rows_in_module*etamod+localrow
207 if "z_mod6" not in hists:
208 hists[
"z_mod6"]=ROOT.TH2D(
"z_mod6",
";z;lyr",2500,0,500,10,0,10)
209 hists[
"z_mod6"].Fill(z,layer)
212 localrow=trk.SensitiveEtaModule[hit_idx]
215 lambda n: ROOT.TH2D(n,
";z[mm]; r[mm]",3000,0,+3000,1000,0,1000)).Fill(z,r)
217 return localrow,globalrow
224 if key[
"det"]!=trk.SensitiveIsPixel[hit_idx]:
226 if key[
"reg"]!=abs(trk.SensitiveBarrelEndcap[hit_idx]):
228 if getLayer(trk,hit_idx)!=key[
"lyr"]:
237 for hit_idx
in range(len(trk.SensitivePosX)):
239 rownew=
getRow(trk,hit_idx)[1]
240 if row
and (rownew!=row):
243 return row
if not mixedrows
else None
249 modules = defaultdict(defaultdictlambda)
251 for hit_idx
in range(len(trk.SensitivePosX)):
252 det = trk.SensitiveIsPixel[hit_idx]
253 reg = abs(trk.SensitiveBarrelEndcap[hit_idx])
255 row =
getRow(trk,hit_idx)[1]
256 phimod = trk.SensitivePhiModule[hit_idx]
257 r=trk.SensitivePosR[hit_idx]
258 z=trk.SensitivePosZ[hit_idx]
259 if reg==reg2int[
'barrel']:
260 if lyr
not in modules[det][reg]
or r < modules[det][reg][lyr][3]:
261 modules[det][reg][lyr]=(row,phimod,hit_idx,r,z)
263 if lyr
not in modules[det][reg]
or z < modules[det][reg][lyr][4]:
264 modules[det][reg][lyr]=(row,phimod,hit_idx,r,z)
266 for reg
in modules[det2int[
'strip']]:
267 if reg==reg2int[
'barrel']:
274 for lyr
in sorted(modules[det][reg].
keys(),reverse=
True):
275 if varlast < modules[det][reg][lyr][varidx]:
276 del modules[det][reg][lyr]
277 elif lyr+1==lastlyr
and lyr%2==0
and (varlast-modules[det][reg][lyr][varidx]) > 10.0:
278 del modules[det][reg][lyr+1]
281 varlast=modules[det][reg][lyr][varidx]
293 eta_vals_for_key_layer=
set()
302 if trk.StartEta > max_eta
or trk.StartEta < min_eta:
306 if not key1[
"lyr"]
in modules[key1[
"det"]][key1[
"reg"]]:
310 eta_vals_for_key_layer.add(modules[key1[
"det"]][key1[
"reg"]][key1[
"lyr"]][0])
314 msg.info(
"%d eta rows:",len(eta_vals_for_key_layer))
315 msg.info(
sorted(eta_vals_for_key_layer))
316 msg.info(
"Tracks Used = %d", tracks_used)
317 return eta_vals_for_key_layer
325 key_modules_per_slice =
float(len(eta_vals_for_key_layer))/nslices
326 key_modules_for_slices=[[]]
328 for i,row
in enumerate(
sorted(eta_vals_for_key_layer)):
329 if i >= len(key_modules_for_slices)*key_modules_per_slice:
330 key_modules_for_slices.append([])
331 key_modules_for_slices[-1].
append(row)
333 msg.info(
"Modules in slices %d", key_modules_for_slices)
338 return {m:i
for i,s
in enumerate(key_modules_for_slices)
for m
in s }
347 slice_modules=defaultdict(
lambda :
351 d:defaultdict(
lambda:0)
for d
in dirs}
352 for lyr
in range(layers[det][reg]) }
357 slice_tracks=defaultdict(
lambda:0)
362 missing_keylayer_hit=0
369 if trk.StartEta > max_eta
or trk.StartEta < min_eta:
374 if not key1[
"lyr"]
in modules[key1[
"det"]][key1[
"reg"]]:
375 missing_keylayer_hit+=1
377 mod1 = modules[key1[
"det"]][key1[
"reg"]][key1[
"lyr"]][0]
378 slicenum = mod_slice_map[mod1]
379 if args.test1slice
and slicenum!=0:
383 if not key2[
"lyr"]
in modules[key2[
"det"]][key2[
"reg"]]:
384 missing_keylayer_hit+=1
386 mod2 = modules[key2[
"det"]][key2[
"reg"]][key2[
"lyr"]][0]
387 slicenum=(slicenum,mod2)
393 for reg
in modules[det]:
394 for lyr
in modules[det][reg]:
395 modidxs=modules[det][reg][lyr]
396 slice_modules[slicenum][int2det[det]][int2reg[reg]][lyr][
"eta"][modidxs[0]]+=1
397 slice_modules[slicenum][int2det[det]][int2reg[reg]][lyr][
"phi"][modidxs[1]]+=1
401 if slicenum
not in slice_hists:
402 sliceid2int[slicenum]=len(slice_modules)-1
403 slice_hists[slicenum]=ROOT.TH2D(
"rz"+
str(sliceid2int[slicenum]),
"rz"+
str(slicenum)+
"; z[mm]; r[mm]",800,-200,+600,1000,0,1000)
404 slice_hists[slicenum].Fill(trk.SensitivePosZ[hit_idx],trk.SensitivePosR[hit_idx])
406 hname=int2det[det]+
"_"+int2reg[reg]+
"_"+
str(lyr)+
"_"+
str(modidxs[0])
407 if hname
not in slice_hists:
408 slice_hists[hname]=ROOT.TH1D(hname,hname+
"; z[mm]",800,-200,+600)
409 slice_hists[hname].Fill(trk.SensitivePosZ[hit_idx])
413 slice_tracks[slicenum]+=1
415 msg.info(
"Tracks Used=%d" %(tracks_used))
416 msg.info(
"%d tracks with no keylayer hit found or multiple hits in keylayer" %(
int(
str(missing_keylayer_hit))))
418 for hist
in slice_hists.values():
421 return slice_modules,sliceid2int,slice_tracks
431 for sliceid
in slice_modules:
434 for lyr
in slice_modules[sliceid][det][reg]:
435 for mod
in list(slice_modules[sliceid][det][reg][lyr][
"eta"]):
436 if slice_modules[sliceid][det][reg][lyr][
"eta"][mod]/
float(slice_tracks[sliceid]) < args.trim:
437 del slice_modules[sliceid][det][reg][lyr][
"eta"][mod]
444 nslices=len(sliceid2int)
445 rmap =
open(args.outfilelabel+
'_KeyLayer-%s%s%s_NSlices-%d.rmap' % (
446 args.keylayer.replace(
",",
"_"),
447 "_KeyLayer2-"+args.keylayer2.replace(
",",
"_")
if args.keylayer2
else "",
448 (
"_trim_%1.3f" % (args.trim,)).
replace(
".",
"_")
if args.trim
else "",
451 rmap.write(
"towers "+
str(nslices)+
" phi 16\n\n")
453 int2sliceid={v:k
for k,v
in sliceid2int.items()}
454 for i
in range(len(slice_modules)):
455 rmap.write(
"\n%d \n" % i)
456 sliceid=int2sliceid[i]
458 mindefault =
lambda x,default=0:
min(x)
if len(x)
else default
459 maxdefault =
lambda x,default=0:
max(x)
if len(x)
else default
463 for lyr
in range(layers[det][reg]):
464 rmap.write(
"%d %d %d %d %d %d %d %d %d\n" % (
465 1
if det==
"pixel" else 0,
466 1
if reg==
"endcap" else 0,
468 mindefault(slice_modules[sliceid][det][reg][lyr][
"phi"].
keys(),default=0),
469 maxdefault(slice_modules[sliceid][det][reg][lyr][
"phi"].
keys(),default=0),
470 len(slice_modules[sliceid][det][reg][lyr][
"phi"]),
471 mindefault(slice_modules[sliceid][det][reg][lyr][
"eta"].
keys(),default=0),
472 maxdefault(slice_modules[sliceid][det][reg][lyr][
"eta"].
keys(),default=0),
473 len(slice_modules[sliceid][det][reg][lyr][
"eta"])))
486 lyr:defaultdict(
lambda: 0)
for lyr
in range(layers[det][reg]) }
490 for sliceid
in slice_modules:
491 for det
in slice_modules[sliceid].
keys():
492 for reg
in slice_modules[sliceid][det].
keys():
493 for lyr
in slice_modules[sliceid][det][reg].
keys():
494 for etamod
in slice_modules[sliceid][det][reg][lyr][
"eta"].
keys():
495 duplication_count[det][reg][lyr][etamod]+=1
498 barrel_occupancies_4mrad_100mm={
"pixel": [2.5,1.2,0.9,0.75,0.6],
499 "strip": [0.4,0.4,0.3,0.3,0.2,0.2,0.2,0.2]}
500 barrel_lengths={
"pixel": [20,40,40,40,40],
501 "strip": [25,25,25,25,50,50,50,50]}
502 occupancies_per_module = {det:{reg: []
for reg
in regs}
for det
in dets}
504 for i
in range(len(barrel_lengths[det])):
505 occupancies_per_module[det][
'barrel'].
append(barrel_occupancies_4mrad_100mm[det][i]*barrel_lengths[det][i]/
float(100))
507 occupancies_per_module[det][
'endcap']=[0
for i
in range(layers[det][reg])]
509 layer_options = {
"FPGATrackSimlike" : {
"pixel" : [4],
"strip":[0,2,3,4,5,6,7]},
510 "Outer5" : {
"pixel" : [4],
"strip":[0,2,4,6]},
511 "Inner5" : {
"pixel" : [0,1,2,4,5],
"strip":[]},
512 "Mid5" : {
"pixel" : [2,4,5],
"strip":[0,2]}}
514 layer_options_occ = defaultdict(
lambda:1)
516 msg.info(
"%-5s %-6s %-5s %-12s %-10s %-10s" % (
"",
"",
"",
"",
"min/max",
"min/max",))
517 msg.info(
"%-5s %-6s %-5s %-12s %-10s %-10s" % (
"det",
"reg",
"lyr",
"duplication",
"modules",
"occupancy",))
520 for lyr
in range(layers[det][reg]):
522 if len(duplication_count[det][reg][lyr])!=0:
523 dup =
sum(duplication_count[det][reg][lyr].
values())/
float(len(duplication_count[det][reg][lyr]))
524 occs = [occupancies_per_module[det][reg][lyr]*len(slice_modules[sliceid][det][reg][lyr][
"eta"])
for sliceid
in slice_modules]
525 lens = [len(slice_modules[sliceid][det][reg][lyr][
"eta"])
for sliceid
in slice_modules]
527 for opt,config
in layer_options.items():
528 if lyr
in config[det]:
529 layer_options_occ[opt]*=
sum(occs)/
float(len(occs))
531 msg.info(
"%5s %5s %-5d %2.2f [%2d,%2d] [%2.2f,%2.2f]" % (det,reg,lyr,dup,
min(lens),
max(lens),
min(occs),
max(occs)))
533 msg.info(
"\nOccupancies:\n")
534 for opt,occ
in layer_options_occ.items():
550 for hit_idx
in range(len(trk.SensitivePosX)):
551 det = trk.SensitiveIsPixel[hit_idx]
552 reg = abs(trk.SensitiveBarrelEndcap[hit_idx])
554 row =
getRow(trk,hit_idx)[1]
555 r=trk.SensitivePosR[hit_idx]
556 z=trk.SensitivePosZ[hit_idx]
558 for sliceid,modules
in slice_modules.items():
560 lambda n: ROOT.TH2D(n,
"; z[mm]; r[mm]",3500,-500,+3000,1000,0,1000))
562 if row
in modules[int2det[det]][int2reg[reg]][lyr][
"eta"]:
571 histfile = ROOT.TFile(
"test.root",
'recreate')
578 nslices=len(eta_vals_for_key_layer)
585 msg.info(
"%d, two layers slices found"%(len(slice_modules)))
586 for x
in slice_modules.keys():
589 if args.trim:
trimSlice(slice_modules,slice_tracks)
597 for hist
in hists.values():