Skip to main content

gondola_core/physics/searchlight/
candidates.rs

1//! Candidate lines for the primary, their features and the
2//! selection
3// This file is part of gaps-online-software and published
4// under the GPLv3 license
5
6use glam::DVec3;
7
8use crate::prelude::*;
9
10use super::{fit_line, SearchlightHits, SearchlightSettings, SearchlightVertexQuality, C_LIGHT_MM_NS};
11
12/// The kind of a candidate line for the primary: through which
13/// two points its cleaned fit is seeded
14#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, FromRepr, AsRefStr, EnumIter)]
15#[repr(u8)]
16#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int, hash, frozen))]
17pub enum SearchlightCandidate {
18  /// the earliest outer and the earliest inner TOF hit
19  Today        = 0u8,
20  /// the outer seed hit and the vertex
21  OuterVertex  = 1u8,
22  /// the inner seed hit and the vertex
23  InnerVertex  = 2u8,
24  /// the outer seed hit and a high-energy tracker hit
25  OuterTracker = 3u8,
26  /// the inner seed hit and a high-energy tracker hit
27  InnerTracker = 4u8,
28  /// the outer seed hit and a triggered inner paddle without hit
29  OuterTrigger = 5u8,
30  /// the inner seed hit and a triggered outer paddle without hit
31  InnerTrigger = 6u8,
32}
33
34impl SearchlightCandidate {
35  /// Number of kinds (for the one-hot features)
36  pub const N : usize = 7;
37}
38
39impl fmt::Display for SearchlightCandidate {
40  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
41    write!(f, "<SearchlightCandidate: {}>", self.as_ref())
42  }
43}
44
45/// A candidate line for the primary
46#[derive(Debug, Clone)]
47pub struct SearchlightCandidateFit {
48  pub kind     : SearchlightCandidate,
49  /// a point on the line (mm)
50  pub a        : DVec3,
51  /// unit vector along the line, pointing inwards (from the
52  /// outer-most point of the candidate to the other one)
53  pub u        : DVec3,
54  /// accepted hits (indices into SearchlightHits; an extra point
55  /// such as the vertex has the index SearchlightHits::len())
56  pub hits     : Vec<usize>,
57  /// where the candidate starts and where it points to, for its
58  /// orientation
59  pub start    : DVec3,
60  pub target   : DVec3,
61  pub features : Vec<f64>,
62  pub prob     : f64,
63  /// if the candidate took part in the selection (it keeps the
64  /// good seed hit; if no candidate does, the first one)
65  pub allowed  : bool,
66}
67
68/// The fit seeded through the hits seed (indices into hits),
69/// cleaned with cleaning, optionally with an extra point with
70/// its own error (it gets the index hits.len())
71pub(crate) fn candidate(hits     : &SearchlightHits,
72                        seed     : (usize, usize),
73                        kind     : SearchlightCandidate,
74                        cleaning : &LineFitCleaning,
75                        extra    : Option<(DVec3, f64)>,
76                        start    : DVec3,
77                        target   : DVec3) -> Option<SearchlightCandidateFit> {
78  let with;
79  let h = match extra {
80    None             => hits,
81    Some((p, err))   => {
82      with = hits.with_point(p, err);
83      &with
84    }
85  };
86  let all : Vec<usize> = (0..h.len()).collect();
87  let (a, u, acc) = fit_line(h, &all, seed, cleaning)?;
88  Some(SearchlightCandidateFit { kind, a, u, hits : acc, start, target, features : vec![], prob : 0.0, allowed : false })
89}
90
91/// Energy-weighted inliers: primary-like hits count 1, low
92/// energy ones 0.2
93pub(crate) fn score(hits : &SearchlightHits, acc : &[usize], settings : &SearchlightSettings) -> f64 {
94  acc.iter().filter(|&&k| k < hits.len()).map(|&k| {
95    let min = if hits.is_tof[k] { settings.edep_min } else { settings.trk_e_min };
96    if hits.e[k] >= min { 1.0 } else { 0.2 }
97  }).sum()
98}
99
100/// Distance of the point p from the line through a along u
101fn dist(a : DVec3, u : DVec3, p : DVec3) -> f64 {
102  let w = p - a;
103  (w - w.dot(u)*u).length()
104}
105
106/// The features of a candidate for the selection (u has to be
107/// oriented already):
108///
109/// 1, primary-like TOF inliers, primary-like tracker inliers,
110/// other inliers, log(1 + tracker energy), mean residual / 50 mm,
111/// beta outside (0.05, 0.95), beta not measurable, distance to the
112/// vertex / 50 mm (at most 5), no vertex, one-hot candidate kind,
113/// and for the vertex candidates the quality of the independent
114/// vertex (zeros otherwise)
115pub(crate) fn features(hits     : &SearchlightHits,
116                       c        : &SearchlightCandidateFit,
117                       settings : &SearchlightSettings,
118                       vertex   : Option<DVec3>,
119                       quality  : Option<&SearchlightVertexQuality>) -> Vec<f64> {
120  let acc : Vec<usize> = c.hits.iter().copied().filter(|&k| k < hits.len()).collect();
121  let tof : Vec<usize> = acc.iter().copied().filter(|&k| hits.is_tof[k]).collect();
122  let trk : Vec<usize> = acc.iter().copied().filter(|&k| !hits.is_tof[k]).collect();
123  let n_hi_tof = tof.iter().filter(|&&k| hits.e[k] >= settings.edep_min).count();
124  let n_hi_trk = trk.iter().filter(|&&k| hits.e[k] >= settings.trk_e_min).count();
125  let n_lo     = acc.len() - n_hi_tof - n_hi_trk;
126  let e_trk    = trk.iter().map(|&k| hits.e[k]).sum::<f64>().ln_1p();
127  let res = if acc.is_empty() {
128    1.0
129  } else {
130    acc.iter().map(|&k| dist(c.a, c.u, hits.pos[k])).sum::<f64>()/(acc.len() as f64)/50.0
131  };
132  // beta from the TOF hits along the line (inwards): the times should increase
133  let (mut beta_bad, mut beta_none) = (0.0, 1.0);
134  if tof.len() >= 2 {
135    let s : Vec<f64> = tof.iter().map(|&k| (hits.pos[k] - c.start).dot(c.u)).collect();
136    let t : Vec<f64> = tof.iter().map(|&k| hits.t[k]).collect();
137    let smin = s.iter().copied().fold(f64::INFINITY, f64::min);
138    let smax = s.iter().copied().fold(f64::NEG_INFINITY, f64::max);
139    if smax - smin > 50.0 {
140      let nf = s.len() as f64;
141      let sm = s.iter().sum::<f64>()/nf;
142      let tm = t.iter().sum::<f64>()/nf;
143      let slope = s.iter().zip(&t).map(|(x, y)| (x - sm)*(y - tm)).sum::<f64>()
144                / s.iter().map(|x| (x - sm).powi(2)).sum::<f64>();
145      let beta = if slope != 0.0 { 1.0/(slope*C_LIGHT_MM_NS) } else { f64::INFINITY };
146      beta_none = 0.0;
147      beta_bad  = if beta > 0.05 && beta < 0.95 { 0.0 } else { 1.0 };
148    }
149  }
150  let (dv, nov) = match vertex {
151    Some(v) => ((dist(c.a, c.u, v)/50.0).min(5.0), 0.0),
152    None    => (0.0, 1.0),
153  };
154  let mut f = vec![1.0, n_hi_tof as f64, n_hi_trk as f64, n_lo as f64, e_trk, res, beta_bad, beta_none, dv, nov];
155  for k in 0..SearchlightCandidate::N {
156    f.push(if c.kind as usize == k { 1.0 } else { 0.0 });
157  }
158  let is_vertex = matches!(c.kind, SearchlightCandidate::OuterVertex | SearchlightCandidate::InnerVertex);
159  match quality {
160    Some(q) if is_vertex => f.extend_from_slice(q),
161    _                    => f.extend_from_slice(&[0.0; 4]),
162  }
163  f
164}
165
166/// Number of features of a candidate
167pub const SEARCHLIGHT_N_FEATURES : usize = 10 + SearchlightCandidate::N + 4;