FairShip
Loading...
Searching...
No Matches
shipPatRec.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4__author__ = "Mikhail Hushchyn"
5
6import logging
7
8import global_variables
9import numpy as np
10
11logger = logging.getLogger(__name__)
12
13r_scale = 1.0
14max_x = global_variables.ShipGeo.strawtubes_geo.width # == 200 * u.cm
15
16
17def initialize(fgeo) -> None:
18 pass
19
20
21def execute(smeared_hits, ship_geo, method: str = ""):
22 """
23 Main function of track pattern recognition.
24
25 Parameters:
26 -----------
27 SmearedHits : list
28 Smeared hits. SmearedHits = [{'digiHit': key,
29 'xtop': xtop, 'ytop': ytop, 'z': ztop,
30 'xbot': xbot, 'ybot': ybot,
31 'dist': dist2wire, 'detID': detID}, {...}, ...]
32 """
33
34 recognized_tracks = {}
35
36 logger.debug("PatRec input: %d smeared hits, method=%s", len(smeared_hits), method or "none")
37
38 if method == "TemplateMatching":
39 recognized_tracks = template_matching_pattern_recognition(smeared_hits, ship_geo)
40 elif method == "FH":
41 recognized_tracks = fast_hough_transform_pattern_recognition(smeared_hits, ship_geo)
42 elif method == "AR":
43 recognized_tracks = artificial_retina_pattern_recognition(smeared_hits, ship_geo)
44 else:
45 hits_y12, hits_stereo12, hits_y34, hits_stereo34 = hits_split(smeared_hits)
46 atrack = {"y12": hits_y12, "stereo12": hits_stereo12, "y34": hits_y34, "stereo34": hits_stereo34}
47 recognized_tracks[0] = atrack
48
49 logger.debug("PatRec output: %d tracks", len(recognized_tracks))
50
51 return recognized_tracks
52
53
54def finalize() -> None:
55 pass
56
57
58
63
64
65def template_matching_pattern_recognition(SmearedHits, ShipGeo):
66 """
67 Main function of track pattern recognition.
68
69 Parameters:
70 -----------
71 SmearedHits : list
72 Smeared hits. SmearedHits = [{'digiHit': key,
73 'xtop': xtop, 'ytop': ytop, 'z': ztop,
74 'xbot': xbot, 'ybot': ybot,
75 'dist': dist2wire, 'detID': detID}, {...}, ...]
76 """
77
78 recognized_tracks = {}
79
80 if len(SmearedHits) > 500:
81 print("Too large hits in the event!")
82 return recognized_tracks
83
84 min_hits = 3
85
86
87 SmearedHits_12y, SmearedHits_12stereo, SmearedHits_34y, SmearedHits_34stereo = hits_split(SmearedHits)
88
89
90 recognized_tracks_y12 = pat_rec_view(SmearedHits_12y, min_hits)
91 # recognized_tracks_y12 = [{'hits_y': [hit1, hit2, ...], 'k_y': float, 'b_y': float}, {...}, ...]
92
93
94 recognized_tracks_12 = pat_rec_stereo_views(SmearedHits_12stereo, recognized_tracks_y12, min_hits)
95 # recognized_tracks_12 = [{'hits_y': [hit1, hit2, ...], 'hits_stereo': [hit1, hit2, ...], 'k_y': float, 'b_y': float}, {...}, ...]
96
97
98 recognized_tracks_y34 = pat_rec_view(SmearedHits_34y, min_hits)
99 # recognized_tracks_y34 = [{'hits_y': [hit1, hit2, ...], 'k_y': float, 'b_y': float}, {...}, ...]
100
101
102 recognized_tracks_34 = pat_rec_stereo_views(SmearedHits_34stereo, recognized_tracks_y34, min_hits)
103 # recognized_tracks_34 = [{'hits_y': [hit1, hit2, ...], 'hits_stereo': [hit1, hit2, ...], 'k_y': float, 'b_y': float}, {...}, ...]
104
105
106 recognized_tracks_combo = tracks_combination_using_extrapolation(
107 recognized_tracks_12, recognized_tracks_34, ShipGeo.Bfield.z
108 )
109
110 # Prepare output of PatRec
111 recognized_tracks = _prepare_output(recognized_tracks_combo, min_hits)
112
113 return recognized_tracks
114
115
116def pat_rec_view(SmearedHits, min_hits: int):
117 """
118 Main function of track pattern recognition.
119
120 Parameters:
121 -----------
122 SmearedHits : list
123 Smeared hits. SmearedHits = [{'digiHit': key,
124 'xtop': xtop, 'ytop': ytop, 'z': ztop,
125 'xbot': xbot, 'ybot': ybot,
126 'dist': dist2wire, 'detID': detID}, {...}, ...]
127 """
128
129 long_recognized_tracks = []
130 n_seeds_tried = 0
131 n_seeds_slope_cut = 0
132
133 # Take 2 hits as a track seed
134 for ahit1 in SmearedHits:
135 for ahit2 in SmearedHits:
136 if ahit1["z"] >= ahit2["z"]:
137 continue
138 if ahit1["detID"] == ahit2["detID"]:
139 continue
140
141 n_seeds_tried += 1
142 k_seed = 1.0 * (ahit2["ytop"] - ahit1["ytop"]) / (ahit2["z"] - ahit1["z"])
143 b_seed = ahit1["ytop"] - k_seed * ahit1["z"]
144
145 if abs(k_seed) > 1:
146 n_seeds_slope_cut += 1
147 continue
148
149 atrack = {}
150 atrack["hits_y"] = [ahit1, ahit2]
151 atrack_layers = [ahit1["detID"] // 10000, ahit2["detID"] // 10000]
152
153 # Add new hits to the seed
154 for ahit3 in SmearedHits:
155 if ahit3["detID"] == ahit1["detID"] or ahit3["detID"] == ahit2["detID"]:
156 continue
157
158 layer3 = ahit3["detID"] // 10000
159 if layer3 in atrack_layers:
160 continue
161
162 in_bin = hit_in_window(ahit3["z"], ahit3["ytop"], k_seed, b_seed, window_width=1.4 * r_scale)
163 if in_bin:
164 atrack["hits_y"].append(ahit3)
165 atrack_layers.append(layer3)
166
167 if len(atrack["hits_y"]) >= min_hits:
168 long_recognized_tracks.append(atrack)
169
170 # Remove clones
171 recognized_tracks = reduce_clones_using_one_track_per_hit(long_recognized_tracks, min_hits)
172
173 logger.debug(
174 "pat_rec_view: %d hits, %d seeds tried, %d cut by slope, %d tracks before clone removal, %d after",
175 len(SmearedHits),
176 n_seeds_tried,
177 n_seeds_slope_cut,
178 len(long_recognized_tracks),
179 len(recognized_tracks),
180 )
181
182 # Track fit
183 for atrack in recognized_tracks:
184 z_coords = [ahit["z"] for ahit in atrack["hits_y"]]
185 y_coords = [ahit["ytop"] for ahit in atrack["hits_y"]]
186 [atrack["k_y"], atrack["b_y"]] = np.polyfit(z_coords, y_coords, deg=1)
187
188 return recognized_tracks
189
190
191
196
197
199 """
200 Main function of track pattern recognition.
201
202 Parameters:
203 -----------
204 SmearedHits : list
205 Smeared hits. SmearedHits = [{'digiHit': key,
206 'xtop': xtop, 'ytop': ytop, 'z': ztop,
207 'xbot': xbot, 'ybot': ybot,
208 'dist': dist2wire, 'detID': detID}, {...}, ...]
209 """
210
211 recognized_tracks = {}
212
213 if len(SmearedHits) > 500:
214 print("Too large hits in the event!")
215 return recognized_tracks
216
217 min_hits = 3
218
219
220 SmearedHits_12y, SmearedHits_12stereo, SmearedHits_34y, SmearedHits_34stereo = hits_split(SmearedHits)
221
222
223 recognized_tracks_y12 = fast_hough_pat_rec_y_view(SmearedHits_12y, min_hits)
224
225
226 recognized_tracks_12 = fast_hough_pat_rec_stereo_views(SmearedHits_12stereo, recognized_tracks_y12, min_hits)
227
228
229 recognized_tracks_y34 = fast_hough_pat_rec_y_view(SmearedHits_34y, min_hits)
230
231
232 recognized_tracks_34 = fast_hough_pat_rec_stereo_views(SmearedHits_34stereo, recognized_tracks_y34, min_hits)
233
234
235 recognized_tracks_combo = tracks_combination_using_extrapolation(
236 recognized_tracks_12, recognized_tracks_34, ShipGeo.Bfield.z
237 )
238
239 # Prepare output of PatRec
240 recognized_tracks = _prepare_output(recognized_tracks_combo, min_hits)
241
242 return recognized_tracks
243
244
245def fast_hough_pat_rec_y_view(SmearedHits, min_hits: int):
246 """
247 Main function of track pattern recognition.
248
249 Parameters:
250 -----------
251 SmearedHits : list
252 Smeared hits. SmearedHits = [{'digiHit': key,
253 'xtop': xtop, 'ytop': ytop, 'z': ztop,
254 'xbot': xbot, 'ybot': ybot,
255 'dist': dist2wire, 'detID': detID}, {...}, ...]
256 """
257
258 long_recognized_tracks = []
259 n_seeds_tried = 0
260 n_seeds_slope_cut = 0
261
262 # Take 2 hits as a track seed
263 for ahit1 in SmearedHits:
264 for ahit2 in SmearedHits:
265 if ahit1["z"] >= ahit2["z"]:
266 continue
267 if ahit1["detID"] == ahit2["detID"]:
268 continue
269
270 n_seeds_tried += 1
271 k_seed = 1.0 * (ahit2["ytop"] - ahit1["ytop"]) / (ahit2["z"] - ahit1["z"])
272 b_seed = ahit1["ytop"] - k_seed * ahit1["z"]
273
274 if abs(k_seed) > 1:
275 n_seeds_slope_cut += 1
276 continue
277
278 atrack = {}
279 atrack["hits_y"] = [ahit1, ahit2]
280 atrack_layers = [ahit1["detID"] // 10000, ahit2["detID"] // 10000]
281
282 # Add new hits to the seed
283 for ahit3 in SmearedHits:
284 if ahit3["detID"] == ahit1["detID"] or ahit3["detID"] == ahit2["detID"]:
285 continue
286
287 layer3 = ahit3["detID"] // 10000
288 if layer3 in atrack_layers:
289 continue
290
291 in_bin = hit_in_bin(
292 ahit3["z"],
293 ahit3["ytop"],
294 k_seed,
295 b_seed,
296 k_size=0.7 / 2000 * r_scale,
297 b_size=1700.0 / 1000 * r_scale,
298 )
299 if in_bin:
300 atrack["hits_y"].append(ahit3)
301 atrack_layers.append(layer3)
302
303 if len(atrack["hits_y"]) >= min_hits:
304 long_recognized_tracks.append(atrack)
305
306 # Remove clones
307 recognized_tracks = reduce_clones_using_one_track_per_hit(long_recognized_tracks, min_hits)
308
309 logger.debug(
310 "fast_hough_y_view: %d hits, %d seeds tried, %d cut by slope, %d tracks before clone removal, %d after",
311 len(SmearedHits),
312 n_seeds_tried,
313 n_seeds_slope_cut,
314 len(long_recognized_tracks),
315 len(recognized_tracks),
316 )
317
318 # Track fit
319 for atrack in recognized_tracks:
320 z_coords = [ahit["z"] for ahit in atrack["hits_y"]]
321 y_coords = [ahit["ytop"] for ahit in atrack["hits_y"]]
322 [atrack["k_y"], atrack["b_y"]] = np.polyfit(z_coords, y_coords, deg=1)
323
324 return recognized_tracks
325
326
327def fast_hough_pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, min_hits: int):
328
329 recognized_tracks_stereo = []
330 used_hits = set()
331 n_y_tracks_with_stereo = 0
332
333 for atrack_y in recognized_tracks_y:
334 k_y = atrack_y["k_y"]
335 b_y = atrack_y["b_y"]
336
337 # Get hit zx projections
338 for ahit in SmearedHits_stereo:
339 x_center = get_zy_projection(ahit["z"], ahit["ytop"], ahit["xtop"], ahit["ybot"], ahit["xbot"], k_y, b_y)
340 ahit["zx_projection"] = x_center
341
342 long_recognized_tracks_stereo = []
343
344 for ahit1 in SmearedHits_stereo:
345 for ahit2 in SmearedHits_stereo:
346 if ahit1["z"] >= ahit2["z"]:
347 continue
348 if ahit1["detID"] == ahit2["detID"]:
349 continue
350 if ahit1["digiHit"] in used_hits:
351 continue
352 if ahit2["digiHit"] in used_hits:
353 continue
354
355 if abs(ahit1["zx_projection"]) > max_x or abs(ahit2["zx_projection"]) > max_x:
356 continue
357
358 k_seed = 1.0 * (ahit2["zx_projection"] - ahit1["zx_projection"]) / (ahit2["z"] - ahit1["z"])
359 b_seed = ahit1["zx_projection"] - k_seed * ahit1["z"]
360
361 atrack_stereo = {}
362 atrack_stereo["hits_stereo"] = [ahit1, ahit2]
363 atrack_stereo_layers = [ahit1["detID"] // 10000, ahit2["detID"] // 10000]
364
365 for ahit3 in SmearedHits_stereo:
366 if ahit3["digiHit"] == ahit1["digiHit"] or ahit3["digiHit"] == ahit2["digiHit"]:
367 continue
368 if ahit3["digiHit"] in used_hits:
369 continue
370
371 if abs(ahit3["zx_projection"]) > max_x:
372 continue
373
374 layer3 = ahit3["detID"] // 10000
375 if layer3 in atrack_stereo_layers:
376 continue
377
378 in_bin = hit_in_bin(
379 ahit3["z"],
380 ahit3["zx_projection"],
381 k_seed,
382 b_seed,
383 k_size=0.6 / 200 * r_scale,
384 b_size=1000.0 / 70 * r_scale,
385 )
386 if in_bin:
387 atrack_stereo["hits_stereo"].append(ahit3)
388 atrack_stereo_layers.append(layer3)
389
390 if len(atrack_stereo["hits_stereo"]) >= min_hits:
391 long_recognized_tracks_stereo.append(atrack_stereo)
392
393 # Remove clones
394 max_track = None
395 max_n_hits = -999
396
397 for atrack_stereo in long_recognized_tracks_stereo:
398 if len(atrack_stereo["hits_stereo"]) > max_n_hits:
399 max_track = atrack_stereo
400 max_n_hits = len(atrack_stereo["hits_stereo"])
401
402 atrack = {}
403 atrack["hits_y"] = atrack_y["hits_y"]
404 atrack["k_y"] = atrack_y["k_y"]
405 atrack["b_y"] = atrack_y["b_y"]
406 atrack["hits_stereo"] = []
407
408 if max_track is not None:
409 atrack["hits_stereo"] = max_track["hits_stereo"]
410 n_y_tracks_with_stereo += 1
411 for ahit in max_track["hits_stereo"]:
412 used_hits.add(ahit["digiHit"])
413
414 recognized_tracks_stereo.append(atrack)
415
416 logger.debug(
417 "fast_hough_stereo: %d stereo hits, %d y-tracks, %d matched with stereo",
418 len(SmearedHits_stereo),
419 len(recognized_tracks_y),
420 n_y_tracks_with_stereo,
421 )
422
423 return recognized_tracks_stereo
424
425
426def hit_in_bin(x, y, k_bin, b_bin, k_size, b_size):
427 """
428 Counts hits in a bin of track parameter space (b, k).
429
430 Parameters
431 ---------
432 x : array-like
433 Array of x coordinates of hits.
434 y : array-like
435 Array of x coordinates of hits.
436 k_bin : float
437 Track parameter: y = k_bin * x + b_bin
438 b_bin : float
439 Track parameter: y = k_bin * x + b_bin
440
441 Return
442 ------
443 track_inds : array-like
444 Hit indexes of a track: [ind1, ind2, ...]
445 """
446
447 b_left = y - (k_bin - 0.5 * k_size) * x
448 b_right = y - (k_bin + 0.5 * k_size) * x
449
450 sel = (b_left >= b_bin - 0.5 * b_size) * (b_right <= b_bin + 0.5 * b_size) + (b_left <= b_bin + 0.5 * b_size) * (
451 b_right >= b_bin - 0.5 * b_size
452 )
453
454 return sel
455
456
457
462
463from scipy.optimize import minimize
464
465
467 """
468 Main function of track pattern recognition.
469
470 Parameters:
471 -----------
472 SmearedHits : list
473 Smeared hits. SmearedHits = [{'digiHit': key,
474 'xtop': xtop, 'ytop': ytop, 'z': ztop,
475 'xbot': xbot, 'ybot': ybot,
476 'dist': dist2wire, 'detID': detID}, {...}, ...]
477 """
478
479 recognized_tracks = {}
480
481 if len(SmearedHits) > 500:
482 print("Too large hits in the event!")
483 return recognized_tracks
484
485 min_hits = 3
486
487
488 SmearedHits_12y, SmearedHits_12stereo, SmearedHits_34y, SmearedHits_34stereo = hits_split(SmearedHits)
489
490
491 recognized_tracks_y12 = artificial_retina_pat_rec_y_view(SmearedHits_12y, min_hits)
492
493
494 recognized_tracks_12 = artificial_retina_pat_rec_stereo_views(SmearedHits_12stereo, recognized_tracks_y12, min_hits)
495
496
497 recognized_tracks_y34 = artificial_retina_pat_rec_y_view(SmearedHits_34y, min_hits)
498
499
500 recognized_tracks_34 = artificial_retina_pat_rec_stereo_views(SmearedHits_34stereo, recognized_tracks_y34, min_hits)
501
502
503 recognized_tracks_combo = tracks_combination_using_extrapolation(
504 recognized_tracks_12, recognized_tracks_34, ShipGeo.Bfield.z
505 )
506
507 # Prepare output of PatRec
508 recognized_tracks = _prepare_output(recognized_tracks_combo, min_hits)
509
510 return recognized_tracks
511
512
513def artificial_retina_pat_rec_y_view(SmearedHits, min_hits: int):
514 """
515 Main function of track pattern recognition.
516
517 Parameters:
518 -----------
519 SmearedHits : list
520 Smeared hits. SmearedHits = [{'digiHit': key,
521 'xtop': xtop, 'ytop': ytop, 'z': ztop,
522 'xbot': xbot, 'ybot': ybot,
523 'dist': dist2wire, 'detID': detID}, {...}, ...]
524 """
525
526 long_recognized_tracks = []
527 used_hits = np.zeros(len(SmearedHits))
528
529 hits_z = np.array([ahit["z"] for ahit in SmearedHits])
530 hits_y = np.array([ahit["ytop"] for ahit in SmearedHits])
531
532 for i in range(len(SmearedHits)):
533 hits_z_unused = hits_z[used_hits == 0]
534 hits_y_unused = hits_y[used_hits == 0]
535
536 sigma = 1.0 * r_scale
537 best_seed_params = get_best_seed(hits_z_unused, hits_y_unused, sigma, sample_weight=None)
538
539 res = minimize(
540 retina_func,
541 best_seed_params,
542 args=(hits_z_unused, hits_y_unused, sigma, None),
543 method="BFGS",
544 jac=retina_grad,
545 options={"gtol": 1e-6, "disp": False, "maxiter": 5},
546 )
547 [k_seed_upd, b_seed_upd] = res.x
548
549 atrack = {}
550 atrack["hits_y"] = []
551 atrack_layers = []
552 hit_ids = []
553
554 # Add new hits to the seed
555 for i_hit3 in range(len(SmearedHits)):
556 if used_hits[i_hit3] == 1:
557 continue
558
559 ahit3 = SmearedHits[i_hit3]
560 layer3 = ahit3["detID"] // 10000
561 if layer3 in atrack_layers:
562 continue
563
564 in_bin = hit_in_window(ahit3["z"], ahit3["ytop"], k_seed_upd, b_seed_upd, window_width=1.4 * r_scale)
565 if in_bin:
566 atrack["hits_y"].append(ahit3)
567 atrack_layers.append(layer3)
568 hit_ids.append(i_hit3)
569
570 if len(atrack["hits_y"]) >= min_hits:
571 long_recognized_tracks.append(atrack)
572 used_hits[hit_ids] = 1
573 else:
574 break
575
576 # Remove clones
577 recognized_tracks = reduce_clones_using_one_track_per_hit(long_recognized_tracks, min_hits)
578
579 logger.debug(
580 "ar_y_view: %d hits, %d tracks before clone removal, %d after",
581 len(SmearedHits),
582 len(long_recognized_tracks),
583 len(recognized_tracks),
584 )
585
586 # Track fit
587 for atrack in recognized_tracks:
588 z_coords = [ahit["z"] for ahit in atrack["hits_y"]]
589 y_coords = [ahit["ytop"] for ahit in atrack["hits_y"]]
590 [atrack["k_y"], atrack["b_y"]] = np.polyfit(z_coords, y_coords, deg=1)
591
592 return recognized_tracks
593
594
595def artificial_retina_pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, min_hits: int):
596
597 recognized_tracks_stereo = []
598 used_hits = set()
599 n_y_tracks_with_stereo = 0
600
601 for atrack_y in recognized_tracks_y:
602 k_y = atrack_y["k_y"]
603 b_y = atrack_y["b_y"]
604
605 # Get hit zx projections
606 for ahit in SmearedHits_stereo:
607 x_center = get_zy_projection(ahit["z"], ahit["ytop"], ahit["xtop"], ahit["ybot"], ahit["xbot"], k_y, b_y)
608 ahit["zx_projection"] = x_center
609
610 long_recognized_tracks_stereo = []
611 hits_z = []
612 hits_x = []
613
614 for ahit in SmearedHits_stereo:
615 if ahit["digiHit"] in used_hits:
616 continue
617 if abs(ahit["zx_projection"]) > max_x:
618 continue
619 hits_z.append(ahit["z"])
620 hits_x.append(ahit["zx_projection"])
621 hits_z = np.array(hits_z)
622 hits_x = np.array(hits_x)
623
624 sigma = 15.0 * r_scale
625 best_seed_params = get_best_seed(hits_z, hits_x, sigma, sample_weight=None)
626
627 res = minimize(
628 retina_func,
629 best_seed_params,
630 args=(hits_z, hits_x, sigma, None),
631 method="BFGS",
632 jac=retina_grad,
633 options={"gtol": 1e-6, "disp": False, "maxiter": 5},
634 )
635 [k_seed_upd, b_seed_upd] = res.x
636
637 atrack_stereo = {}
638 atrack_stereo["hits_stereo"] = []
639 atrack_stereo_layers = []
640
641 for ahit3 in SmearedHits_stereo:
642 if ahit3["digiHit"] in used_hits:
643 continue
644
645 if abs(ahit3["zx_projection"]) > max_x:
646 continue
647
648 layer3 = ahit3["detID"] // 10000
649 if layer3 in atrack_stereo_layers:
650 continue
651
652 in_bin = hit_in_window(
653 ahit3["z"], ahit3["zx_projection"], k_seed_upd, b_seed_upd, window_width=15.0 * r_scale
654 )
655 if in_bin:
656 atrack_stereo["hits_stereo"].append(ahit3)
657 atrack_stereo_layers.append(layer3)
658
659 if len(atrack_stereo["hits_stereo"]) >= min_hits:
660 long_recognized_tracks_stereo.append(atrack_stereo)
661
662 # Remove clones
663 max_track = None
664 max_n_hits = -999
665
666 for atrack_stereo in long_recognized_tracks_stereo:
667 if len(atrack_stereo["hits_stereo"]) > max_n_hits:
668 max_track = atrack_stereo
669 max_n_hits = len(atrack_stereo["hits_stereo"])
670
671 atrack = {}
672 atrack["hits_y"] = atrack_y["hits_y"]
673 atrack["k_y"] = atrack_y["k_y"]
674 atrack["b_y"] = atrack_y["b_y"]
675 atrack["hits_stereo"] = []
676
677 if max_track is not None:
678 atrack["hits_stereo"] = max_track["hits_stereo"]
679 n_y_tracks_with_stereo += 1
680 for ahit in max_track["hits_stereo"]:
681 used_hits.add(ahit["digiHit"])
682
683 recognized_tracks_stereo.append(atrack)
684
685 logger.debug(
686 "ar_stereo: %d stereo hits, %d y-tracks, %d matched with stereo",
687 len(SmearedHits_stereo),
688 len(recognized_tracks_y),
689 n_y_tracks_with_stereo,
690 )
691
692 return recognized_tracks_stereo
693
694
695def get_best_seed(x, y, sigma: float, sample_weight=None):
696 best_retina_val = 0
697 best_seed_params = [0, 0]
698
699 for i_1 in range(len(x) - 1):
700 for i_2 in range(i_1 + 1, len(x)):
701 if x[i_1] >= x[i_2]:
702 continue
703
704 seed_k = (y[i_2] - y[i_1]) / (x[i_2] - x[i_1] + 10**-6)
705 seed_b = y[i_1] - seed_k * x[i_1]
706
707 retina_val = retina_func([seed_k, seed_b], x, y, sigma, sample_weight)
708
709 if retina_val < best_retina_val:
710 best_retina_val = retina_val
711 best_seed_params = [seed_k, seed_b]
712
713 return best_seed_params
714
715
716def retina_func(track_prams, x, y, sigma, sample_weight=None):
717 """
718 Calculates the artificial retina function value.
719 Parameters
720 ----------
721 track_prams : array-like
722 Track parameters [k, b].
723 x : array-like
724 Array of x coordinates of hits.
725 y : array-like
726 Array of x coordinates of hits.
727 sigma : float
728 Standard deviation of hit form a track.
729 sample_weight : array-like
730 Hit weights used during the track fit.
731 Returns
732 -------
733 retina : float
734 Negative value of the artificial retina function.
735 """
736
737 rs = track_prams[0] * x + track_prams[1] - y
738
739 if sample_weight is None:
740 exps = np.exp(-((rs / sigma) ** 2))
741 else:
742 exps = np.exp(-((rs / sigma) ** 2)) * sample_weight
743
744 retina = exps.sum()
745
746 return -retina
747
748
749def retina_grad(track_prams, x, y, sigma, sample_weight=None):
750 """
751 Calculates the artificial retina gradient.
752 Parameters
753 ----------
754 track_prams : array-like
755 Track parameters [k, b].
756 x : array-like
757 Array of x coordinates of hits.
758 y : array-like
759 Array of x coordinates of hits.
760 sigma : float
761 Standard deviation of hit form a track.
762 sample_weight : array-like
763 Hit weights used during the track fit.
764 Returns
765 -------
766 retina : float
767 Negative value of the artificial retina gradient.
768 """
769
770 rs = track_prams[0] * x + track_prams[1] - y
771
772 if sample_weight is None:
773 exps = np.exp(-((rs / sigma) ** 2))
774 else:
775 exps = np.exp(-((rs / sigma) ** 2)) * sample_weight
776
777 dks = -2.0 * rs / sigma**2 * exps * x
778 dbs = -2.0 * rs / sigma**2 * exps
779
780 return -np.array([dks.sum(), dbs.sum()])
781
782
783
788
789
790def hits_split(smeared_hits):
791 """
792 Split hits into groups of station views.
793
794 Parameters:
795 -----------
796 SmearedHits : list
797 Smeared hits. SmearedHits = [{'digiHit': key,
798 'xtop': xtop, 'ytop': ytop, 'z': ztop,
799 'xbot': xbot, 'ybot': ybot,
800 'dist': dist2wire, 'detID': detID}, {...}, ...]
801 """
802
803 smeared_hits_12y = []
804 smeared_hits_12stereo = []
805 smeared_hits_34y = []
806 smeared_hits_34stereo = []
807
808 for i_hit in range(len(smeared_hits)):
809 ahit = smeared_hits[i_hit]
810
811 detID = ahit["detID"]
812 decode = global_variables.modules["strawtubes"].StrawDecode(detID)
813 # StrawDecode returns a tuple of (statnb, vnb, lnb, snb).
814 is_y12 = ((decode[0] == 1) + (decode[0] == 2)) * ((decode[1] == 0) + (decode[1] == 3))
815 is_stereo12 = ((decode[0] == 1) + (decode[0] == 2)) * ((decode[1] == 1) + (decode[1] == 2))
816 is_y34 = ((decode[0] == 3) + (decode[0] == 4)) * ((decode[1] == 0) + (decode[1] == 3))
817 is_stereo34 = ((decode[0] == 3) + (decode[0] == 4)) * ((decode[1] == 1) + (decode[1] == 2))
818
819 if is_y12:
820 smeared_hits_12y.append(ahit)
821 if is_stereo12:
822 smeared_hits_12stereo.append(ahit)
823 if is_y34:
824 smeared_hits_34y.append(ahit)
825 if is_stereo34:
826 smeared_hits_34stereo.append(ahit)
827
828 logger.debug(
829 "hits_split: y12=%d, stereo12=%d, y34=%d, stereo34=%d",
830 len(smeared_hits_12y),
831 len(smeared_hits_12stereo),
832 len(smeared_hits_34y),
833 len(smeared_hits_34stereo),
834 )
835
836 return smeared_hits_12y, smeared_hits_12stereo, smeared_hits_34y, smeared_hits_34stereo
837
838
839def reduce_clones_using_one_track_per_hit(recognized_tracks, min_hits: int = 3):
840 """
841 Split hits into groups of station views.
842
843 Parameters:
844 -----------
845 recognized_tracks : list
846 Track hits. Tracks = [{'hits_y': [hit1, hit2, hit3, ...]}, {...}, ...]
847 min_hits : int
848 Minimal number of hits per track.
849 """
850
851 used_hits = set()
852 tracks_no_clones = []
853 n_hits = [len(atrack["hits_y"]) for atrack in recognized_tracks]
854
855 for i_track in np.argsort(n_hits)[::-1]:
856 atrack = recognized_tracks[i_track]
857 new_track = {}
858 new_track["hits_y"] = []
859
860 for i_hit in range(len(atrack["hits_y"])):
861 ahit = atrack["hits_y"][i_hit]
862 if ahit["digiHit"] not in used_hits:
863 new_track["hits_y"].append(ahit)
864
865 if len(new_track["hits_y"]) >= min_hits:
866 tracks_no_clones.append(new_track)
867 for ahit in new_track["hits_y"]:
868 used_hits.add(ahit["digiHit"])
869
870 return tracks_no_clones
871
872
873def tracks_combination_using_extrapolation(recognized_tracks_12, recognized_tracks_34, z_magnet):
874 recognized_tracks_combo = []
875
876 i_track_y12 = []
877 i_track_y34 = []
878 deltas_y = []
879
880 for i_12 in range(len(recognized_tracks_12)):
881 atrack_12 = recognized_tracks_12[i_12]
882 y_center_y12 = atrack_12["k_y"] * z_magnet + atrack_12["b_y"]
883
884 for i_34 in range(len(recognized_tracks_34)):
885 atrack_34 = recognized_tracks_34[i_34]
886 y_center_y34 = atrack_34["k_y"] * z_magnet + atrack_34["b_y"]
887
888 i_track_y12.append(i_12)
889 i_track_y34.append(i_34)
890 deltas_y.append(abs(y_center_y12 - y_center_y34))
891
892 max_dy = 50
893 used_y12 = []
894 used_y34 = []
895
896 for i in np.argsort(deltas_y):
897 dy = deltas_y[i]
898 i_12 = i_track_y12[i]
899 i_34 = i_track_y34[i]
900
901 if (dy < max_dy) and (i_12 not in used_y12) and (i_34 not in used_y34):
902 atrack = {}
903 atrack["hits_y12"] = recognized_tracks_12[i_12]["hits_y"]
904 atrack["hits_stereo12"] = recognized_tracks_12[i_12]["hits_stereo"]
905 atrack["hits_y34"] = recognized_tracks_34[i_34]["hits_y"]
906 atrack["hits_stereo34"] = recognized_tracks_34[i_34]["hits_stereo"]
907 atrack["k_y12"] = recognized_tracks_12[i_12]["k_y"]
908 atrack["b_y12"] = recognized_tracks_12[i_12]["b_y"]
909 atrack["k_y34"] = recognized_tracks_34[i_34]["k_y"]
910 atrack["b_y34"] = recognized_tracks_34[i_34]["b_y"]
911 recognized_tracks_combo.append(atrack)
912 used_y12.append(i_12)
913 used_y34.append(i_34)
914
915 for i_12 in range(len(recognized_tracks_12)):
916 if i_12 not in used_y12:
917 atrack = {
918 "hits_y12": recognized_tracks_12[i_12]["hits_y"],
919 "hits_stereo12": recognized_tracks_12[i_12]["hits_stereo"],
920 "hits_y34": [],
921 "hits_stereo34": [],
922 "k_y12": recognized_tracks_12[i_12]["k_y"],
923 "b_y12": recognized_tracks_12[i_12]["b_y"],
924 "k_y34": None,
925 "b_y34": None,
926 }
927 recognized_tracks_combo.append(atrack)
928
929 for i_34 in range(len(recognized_tracks_34)):
930 if i_34 not in used_y34:
931 atrack = {
932 "hits_y12": [],
933 "hits_stereo12": [],
934 "hits_y34": recognized_tracks_34[i_34]["hits_y"],
935 "hits_stereo34": recognized_tracks_34[i_34]["hits_stereo"],
936 "k_y12": None,
937 "b_y12": None,
938 "k_y34": recognized_tracks_34[i_34]["k_y"],
939 "b_y34": recognized_tracks_34[i_34]["b_y"],
940 }
941 recognized_tracks_combo.append(atrack)
942
943 logger.debug(
944 "tracks_combo: %d 12-tracks, %d 34-tracks, %d matched pairs, %d total combos",
945 len(recognized_tracks_12),
946 len(recognized_tracks_34),
947 len(used_y12),
948 len(recognized_tracks_combo),
949 )
950
951 return recognized_tracks_combo
952
953
954def _prepare_output(recognized_tracks_combo, min_hits):
955 """Prepare PatRec output, filtering tracks with too few hits and preserving track parameters."""
956 recognized_tracks = {}
957 i_track = 0
958 n_rejected = 0
959 for atrack_combo in recognized_tracks_combo:
960 hits_y12 = atrack_combo["hits_y12"]
961 hits_stereo12 = atrack_combo["hits_stereo12"]
962 hits_y34 = atrack_combo["hits_y34"]
963 hits_stereo34 = atrack_combo["hits_stereo34"]
964
965 if (
966 len(hits_y12) >= min_hits
967 and len(hits_stereo12) >= min_hits
968 and len(hits_y34) >= min_hits
969 and len(hits_stereo34) >= min_hits
970 ):
971 atrack = {
972 "y12": hits_y12,
973 "stereo12": hits_stereo12,
974 "y34": hits_y34,
975 "stereo34": hits_stereo34,
976 "k_y12": atrack_combo.get("k_y12"),
977 "b_y12": atrack_combo.get("b_y12"),
978 "k_y34": atrack_combo.get("k_y34"),
979 "b_y34": atrack_combo.get("b_y34"),
980 }
981 recognized_tracks[i_track] = atrack
982 i_track += 1
983 else:
984 n_rejected += 1
985
986 logger.debug(
987 "output: %d tracks accepted, %d rejected by min_hits=%d filter",
988 i_track,
989 n_rejected,
990 min_hits,
991 )
992
993 return recognized_tracks
994
995
996def hit_in_window(x, y, k_bin, b_bin, window_width=1.0) -> bool:
997 """
998 Check whether a hit falls within a window around a straight-line track.
999
1000 Parameters
1001 ---------
1002 x : float
1003 Z coordinate of the hit.
1004 y : float
1005 Y (or projected X) coordinate of the hit.
1006 k_bin : float
1007 Track slope: y = k_bin * x + b_bin
1008 b_bin : float
1009 Track intercept: y = k_bin * x + b_bin
1010 window_width : float
1011 Half-width of the acceptance window in the y direction.
1012
1013 Return
1014 ------
1015 flag : bool
1016 True if the hit is within the window.
1017 """
1018
1019 y_approx = k_bin * x + b_bin
1020
1021 flag = False
1022 if np.abs(y_approx - y) <= window_width:
1023 flag = True
1024
1025 return flag
1026
1027
1028def get_zy_projection(z, xtop, ytop, xbot, ybot, k_y, b_y):
1029 """
1030 Project a stereo straw hit onto the ZX plane using the Y-view track parameters.
1031
1032 A stereo straw is tilted: its top-end is at (xtop, ytop) and bottom-end at
1033 (xbot, ybot), both at the same z. The Y-view track gives the y position at
1034 this z as y_track = k_y * z + b_y. This function finds the x coordinate
1035 where the straw wire crosses y_track by parameterising the wire as a line
1036 in the XY plane and evaluating it at y = y_track.
1037
1038 Note: the caller passes (ytop, xtop, ybot, xbot) — the argument names here
1039 are swapped relative to the geometric meaning because the call sites swap
1040 the x/y coordinates. This is intentional: the straw wire is parameterised
1041 as x(y), not y(x), because the stereo straws are nearly vertical.
1042
1043 Parameters
1044 ----------
1045 z : float
1046 Z coordinate of the hit.
1047 xtop : float
1048 First coordinate of wire top-end (actually ytop at call site).
1049 ytop : float
1050 Second coordinate of wire top-end (actually xtop at call site).
1051 xbot : float
1052 First coordinate of wire bottom-end (actually ybot at call site).
1053 ybot : float
1054 Second coordinate of wire bottom-end (actually xbot at call site).
1055 k_y : float
1056 Slope of the Y-view track: y = k_y * z + b_y.
1057 b_y : float
1058 Intercept of the Y-view track.
1059
1060 Returns
1061 -------
1062 y : float
1063 The projected x coordinate of the hit in the ZX plane.
1064 """
1065 x = k_y * z + b_y
1066 k = (ytop - ybot) / (xtop - xbot + 10**-6)
1067 b = ytop - k * xtop
1068 y = k * x + b
1069
1070 return y
1071
1072
1073def pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, min_hits: int):
1074
1075 recognized_tracks_stereo = []
1076 used_hits = set()
1077 n_y_tracks_with_stereo = 0
1078
1079 for atrack_y in recognized_tracks_y:
1080 k_y = atrack_y["k_y"]
1081 b_y = atrack_y["b_y"]
1082
1083 # Get hit zx projections
1084 for ahit in SmearedHits_stereo:
1085 x_center = get_zy_projection(ahit["z"], ahit["ytop"], ahit["xtop"], ahit["ybot"], ahit["xbot"], k_y, b_y)
1086 ahit["zx_projection"] = x_center
1087
1088 long_recognized_tracks_stereo = []
1089
1090 for ahit1 in SmearedHits_stereo:
1091 for ahit2 in SmearedHits_stereo:
1092 if ahit1["z"] >= ahit2["z"]:
1093 continue
1094 if ahit1["detID"] == ahit2["detID"]:
1095 continue
1096 if ahit1["digiHit"] in used_hits:
1097 continue
1098 if ahit2["digiHit"] in used_hits:
1099 continue
1100
1101 if abs(ahit1["zx_projection"]) > max_x or abs(ahit2["zx_projection"]) > max_x:
1102 continue
1103
1104 k_seed = 1.0 * (ahit2["zx_projection"] - ahit1["zx_projection"]) / (ahit2["z"] - ahit1["z"])
1105 b_seed = ahit1["zx_projection"] - k_seed * ahit1["z"]
1106
1107 atrack_stereo = {}
1108 atrack_stereo["hits_stereo"] = [ahit1, ahit2]
1109 atrack_stereo_layers = [ahit1["detID"] // 10000, ahit2["detID"] // 10000]
1110
1111 for ahit3 in SmearedHits_stereo:
1112 if ahit3["digiHit"] == ahit1["digiHit"] or ahit3["digiHit"] == ahit2["digiHit"]:
1113 continue
1114 if ahit3["digiHit"] in used_hits:
1115 continue
1116
1117 if abs(ahit3["zx_projection"]) > max_x:
1118 continue
1119
1120 layer3 = ahit3["detID"] // 10000
1121 if layer3 in atrack_stereo_layers:
1122 continue
1123
1124 in_bin = hit_in_window(
1125 ahit3["z"], ahit3["zx_projection"], k_seed, b_seed, window_width=15.0 * r_scale
1126 )
1127 if in_bin:
1128 atrack_stereo["hits_stereo"].append(ahit3)
1129 atrack_stereo_layers.append(layer3)
1130
1131 if len(atrack_stereo["hits_stereo"]) >= min_hits:
1132 long_recognized_tracks_stereo.append(atrack_stereo)
1133
1134 # Remove clones
1135 max_track = None
1136 max_n_hits = -999
1137
1138 for atrack_stereo in long_recognized_tracks_stereo:
1139 if len(atrack_stereo["hits_stereo"]) > max_n_hits:
1140 max_track = atrack_stereo
1141 max_n_hits = len(atrack_stereo["hits_stereo"])
1142
1143 atrack = {}
1144 atrack["hits_y"] = atrack_y["hits_y"]
1145 atrack["k_y"] = atrack_y["k_y"]
1146 atrack["b_y"] = atrack_y["b_y"]
1147 atrack["hits_stereo"] = []
1148
1149 if max_track is not None:
1150 atrack["hits_stereo"] = max_track["hits_stereo"]
1151 n_y_tracks_with_stereo += 1
1152 for ahit in max_track["hits_stereo"]:
1153 used_hits.add(ahit["digiHit"])
1154
1155 recognized_tracks_stereo.append(atrack)
1156
1157 logger.debug(
1158 "pat_rec_stereo: %d stereo hits, %d y-tracks, %d matched with stereo",
1159 len(SmearedHits_stereo),
1160 len(recognized_tracks_y),
1161 n_y_tracks_with_stereo,
1162 )
1163
1164 return recognized_tracks_stereo
fast_hough_transform_pattern_recognition(SmearedHits, ShipGeo)
Fast Hough Transform.
pat_rec_view(SmearedHits, int min_hits)
None finalize()
Definition shipPatRec.py:54
get_zy_projection(z, xtop, ytop, xbot, ybot, k_y, b_y)
fast_hough_pat_rec_y_view(SmearedHits, int min_hits)
execute(smeared_hits, ship_geo, str method="")
Definition shipPatRec.py:21
get_best_seed(x, y, float sigma, sample_weight=None)
artificial_retina_pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, int min_hits)
reduce_clones_using_one_track_per_hit(recognized_tracks, int min_hits=3)
hits_split(smeared_hits)
The End of the PatRec Methods.
None initialize(fgeo)
Definition shipPatRec.py:17
fast_hough_pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, int min_hits)
template_matching_pattern_recognition(SmearedHits, ShipGeo)
Template Matching.
Definition shipPatRec.py:65
artificial_retina_pattern_recognition(SmearedHits, ShipGeo)
_prepare_output(recognized_tracks_combo, min_hits)
hit_in_bin(x, y, k_bin, b_bin, k_size, b_size)
retina_grad(track_prams, x, y, sigma, sample_weight=None)
pat_rec_stereo_views(SmearedHits_stereo, recognized_tracks_y, int min_hits)
tracks_combination_using_extrapolation(recognized_tracks_12, recognized_tracks_34, z_magnet)
artificial_retina_pat_rec_y_view(SmearedHits, int min_hits)
retina_func(track_prams, x, y, sigma, sample_weight=None)
bool hit_in_window(x, y, k_bin, b_bin, window_width=1.0)