Skip to main content

gondola_core/physics/searchlight/
mod.rs

1//! Searchlight - the reconstruction of the primary track
2//!
3//! The cleaned linefit is seeded through the earliest outer and
4//! the earliest inner TOF hit. When the primary's paddle is not
5//! read out, one of these seed hits belongs to a secondary, and
6//! the fit goes astray. Searchlight flags such seed hits by their
7//! timing and energy, and replaces them by other points: the
8//! vertex (the stopping point of the primary, found from the
9//! secondaries like a searchlight sweeping back to their origin),
10//! high-energy tracker hits and triggered paddles without a hit.
11//! Each candidate line is a cleaned fit, and a logistic
12//! regression over a few features of the candidates picks one.
13//!
14//! All lengths are in mm, times in ns, energies in MeV.
15// This file is part of gaps-online-software and published
16// under the GPLv3 license
17
18pub mod detector;
19pub mod vertex;
20pub mod candidates;
21pub mod tracks;
22#[cfg(feature="pybindings")]
23pub mod python;
24
25pub use detector::*;
26pub use vertex::*;
27pub use candidates::*;
28pub use tracks::*;
29
30use glam::DVec3;
31
32use crate::prelude::*;
33
34/// Speed of light (mm/ns)
35pub(crate) const C_LIGHT_MM_NS : f64 = 299.792458;
36
37//---------------------------------------------------------
38
39/// The hits of an event, as searchlight uses them: TOF hits
40/// first, then tracker hits
41#[derive(Debug, Clone, Default)]
42pub struct SearchlightHits {
43  /// positions (mm)
44  pub pos       : Vec<DVec3>,
45  /// position errors in x and y for the fits (mm)
46  pub err       : Vec<f64>,
47  /// TOF: normalized hit times (ns), tracker: NaN
48  pub t         : Vec<f64>,
49  /// TOF: edep, tracker: calibrated energy (MeV)
50  pub e         : Vec<f64>,
51  pub is_tof    : Vec<bool>,
52  /// inner TOF (cube) paddle
53  pub inner     : Vec<bool>,
54  /// TOF: paddle id, tracker: 0
55  pub paddle_id : Vec<u8>,
56  /// tracker: the coordinate the strip measures (0: x, 1: y),
57  /// -1 for TOF hits and unknown strips
58  pub measured  : Vec<i8>,
59  /// tracker: half length of the strip (mm), TOF: 0
60  pub half_chord : Vec<f64>,
61  /// number of TOF hits
62  pub ntof      : usize,
63}
64
65impl SearchlightHits {
66  /// Position error of all hits in the fits (mm)
67  pub const ERR : f64 = LINEFIT_DEFAULT_ERR_XY as f64;
68
69  /// # Arguments:
70  ///   * tof      : TOF hits (position in mm, normalized time,
71  ///                edep, paddle id)
72  ///   * tracker  : tracker hits (position in mm, energy in MeV,
73  ///                strip id)
74  ///   * geometry : if given, TOF hits in overlapping paddles at
75  ///                the same time are moved to the middle of the
76  ///                overlap (TofEvent::merge_overlapping_hits),
77  ///                and the strips of the tracker hits are looked
78  ///                up (for the secondary tracks)
79  pub fn new(tof : &[(DVec3, f64, f64, u8)], tracker : &[(DVec3, f64, u32)], geometry : Option<&SearchlightGeometry>) -> Self {
80    let overlaps = geometry.map(|g| &g.overlaps);
81    let mut tof_pos : Vec<DVec3> = tof.iter().map(|h| h.0).collect();
82    if let Some(ov) = overlaps {
83      let mut ev = TofEvent::new();
84      for h in tof {
85        let mut hit = TofHit::new();
86        hit.paddle_id = h.3;
87        (hit.x, hit.y, hit.z) = (h.0.x as f32, h.0.y as f32, h.0.z as f32);
88        hit.event_t0 = h.1 as f32;
89        ev.hits.push(hit);
90      }
91      ev.hit_times_normalized = true;
92      if ev.merge_overlapping_hits(ov, TofPaddleOverlaps::DEFAULT_MAX_DT) > 0 {
93        for (p, h) in tof_pos.iter_mut().zip(&ev.hits) {
94          // only the merged hits change, the others keep their full precision
95          let moved = DVec3::new(h.x as f64, h.y as f64, h.z as f64);
96          if (moved - *p).length() > 1e-3 {
97            *p = moved;
98          }
99        }
100      }
101    }
102    let n = tof.len() + tracker.len();
103    let mut hits = Self {
104      pos       : Vec::with_capacity(n),
105      err       : vec![Self::ERR; n],
106      t         : Vec::with_capacity(n),
107      e         : Vec::with_capacity(n),
108      is_tof    : Vec::with_capacity(n),
109      inner     : Vec::with_capacity(n),
110      paddle_id : Vec::with_capacity(n),
111      measured  : vec![-1; n],
112      half_chord : vec![0.0; n],
113      ntof      : tof.len(),
114    };
115    for (h, p) in tof.iter().zip(tof_pos) {
116      hits.pos.push(p);
117      hits.t.push(h.1);
118      hits.e.push(h.2);
119      hits.is_tof.push(true);
120      hits.inner.push(h.3 <= TOF_INNER_MAX_PADDLE_ID);
121      hits.paddle_id.push(h.3);
122    }
123    for (k, h) in tracker.iter().enumerate() {
124      hits.pos.push(h.0);
125      hits.t.push(f64::NAN);
126      hits.e.push(h.1);
127      hits.is_tof.push(false);
128      hits.inner.push(false);
129      hits.paddle_id.push(0);
130      if let Some(st) = geometry.and_then(|g| g.strips.get(&h.2)) {
131        hits.measured[tof.len() + k]   = st.measured as i8;
132        hits.half_chord[tof.len() + k] = st.half_chord;
133      }
134    }
135    hits
136  }
137
138  /// The hits of a TelemetryEvent. The TOF hit times have to be
139  /// normalized (TofEvent::normalize_hit_times), the tracker hits
140  /// calibrated (energy in MeV) and with coordinates.
141  pub fn from_event(event : &TelemetryEvent, geometry : Option<&SearchlightGeometry>) -> Self {
142    let tof : Vec<(DVec3, f64, f64, u8)> = event.tof_event.hits.iter().map(|h| {
143      (DVec3::new(h.x as f64, h.y as f64, h.z as f64), h.event_t0 as f64, h.get_edep() as f64, h.paddle_id)
144    }).collect();
145    // the tracker hit coordinates are in cm
146    let trk : Vec<(DVec3, f64, u32)> = event.tracker_hits.iter().filter(|h| h.has_coordinates).map(|h| {
147      (10.0*DVec3::new(h.x as f64, h.y as f64, h.z as f64), h.energy as f64, h.get_stripid())
148    }).collect();
149    Self::new(&tof, &trk, geometry)
150  }
151
152  pub fn len(&self) -> usize {
153    self.pos.len()
154  }
155
156  pub fn is_empty(&self) -> bool {
157    self.pos.is_empty()
158  }
159
160  /// The hits with an extra point (e.g. the vertex) appended, with
161  /// its own error, no time and no energy
162  pub fn with_point(&self, p : DVec3, err : f64) -> Self {
163    let mut h = self.clone();
164    h.pos.push(p);
165    h.err.push(err);
166    h.t.push(f64::NAN);
167    h.e.push(0.0);
168    h.is_tof.push(false);
169    h.inner.push(false);
170    h.paddle_id.push(0);
171    h.measured.push(-1);
172    h.half_chord.push(0.0);
173    h
174  }
175
176  /// The earliest outer and the earliest inner TOF hit, if both exist
177  pub fn seed(&self) -> Option<(usize, usize)> {
178    let first = |inner : bool| {
179      (0..self.ntof).filter(|&k| self.inner[k] == inner && self.t[k].is_finite())
180                    .min_by(|&x, &y| self.t[x].total_cmp(&self.t[y]))
181    };
182    Some((first(false)?, first(true)?))
183  }
184}
185
186/// The cleaned fit through the hits idx, seeded through seed
187/// (indices into idx). Returns a point on the line, its direction
188/// (unit vector) and the accepted hits (indices into hits).
189pub(crate) fn fit_line(hits     : &SearchlightHits,
190                       idx      : &[usize],
191                       seed     : (usize, usize),
192                       cleaning : &LineFitCleaning) -> Option<(DVec3, DVec3, Vec<usize>)> {
193  let xs   : Vec<f32> = idx.iter().map(|&k| hits.pos[k].x as f32).collect();
194  let ys   : Vec<f32> = idx.iter().map(|&k| hits.pos[k].y as f32).collect();
195  let zs   : Vec<f32> = idx.iter().map(|&k| hits.pos[k].z as f32).collect();
196  let errs : Vec<f32> = idx.iter().map(|&k| hits.err[k] as f32).collect();
197  let r = LineFit::fit_cleaned_with_seed(&xs, &ys, &zs, Some(&errs), Some(&errs), seed, cleaning)?;
198  let a = DVec3::new(r.fit.x0 as f64, r.fit.y0 as f64, r.fit.z0 as f64);
199  let d = r.fit.direction();
200  let u = DVec3::new(d.0 as f64, d.1 as f64, d.2 as f64).normalize();
201  let acc = idx.iter().zip(&r.accepted).filter(|(_, ok)| **ok).map(|(&k, _)| k).collect();
202  Some((a, u, acc))
203}
204
205//---------------------------------------------------------
206
207/// Settings of searchlight
208#[derive(Debug, Clone)]
209#[cfg_attr(feature="pybindings", pyclass)]
210pub struct SearchlightSettings {
211  /// hit cleaning of all candidate fits
212  pub cleaning      : LineFitCleaning,
213  /// TOF hits below this edep are not primary-like (MeV); a seed
214  /// hit below it is flagged
215  pub edep_min      : f64,
216  /// tracker hits above this energy are primary-like (MeV) and
217  /// seed candidates
218  pub trk_e_min     : f64,
219  /// error of the vertex as a fit point (mm)
220  pub vertex_err    : f64,
221  pub use_vertex    : bool,
222  pub use_tracker   : bool,
223  /// triggered paddles without a hit: candidates through the point
224  /// on the paddle closest to the best candidate, iterated
225  /// trig_iter times, if the paddle is closer than trig_max_dist
226  /// (mm), with the error trig_err (mm) and the hit cleaning
227  /// trig_cleaning
228  pub use_trigger   : bool,
229  pub trig_max_dist : f64,
230  pub trig_err      : f64,
231  pub trig_iter     : usize,
232  pub trig_cleaning : LineFitCleaning,
233  pub vertex        : SearchlightVertexSettings,
234  /// For seeds which pass the flags: a vertex without the primary
235  /// line (independent_vertex), offered as an outer+vertex candidate
236  /// if today's line has no primary-like tracker hits, with its
237  /// quality as features. Otherwise the simple vertex is used.
238  pub independent_vertex : bool,
239  /// in the independent vertex: secondary tracks from the RANSAC
240  /// track finder (needs the strips in the geometry), otherwise
241  /// only the highest-energy tracker hit
242  pub use_tracks    : bool,
243  /// in the independent vertex: the timing score for the choice
244  /// among the vertex candidates and as a quality feature
245  pub use_timing    : bool,
246  pub tracks        : SearchlightTrackSettings,
247  pub timing        : SearchlightTimingSettings,
248  /// weights of the logistic regression over the features of the
249  /// candidates (see candidates::features). Empty: the candidate
250  /// with the most energy-weighted inliers wins.
251  pub weights       : Vec<f64>,
252}
253
254impl SearchlightSettings {
255  /// Weights of the selection with all parts, trained on the
256  /// antiproton MC (untriggered production of 2026-11 with the Track
257  /// or GAPS 833 trigger applied offline, primary stopping in the
258  /// tracker, 53,565 events; TofHit::get_edep with the attenuation of
259  /// the digitizer, edep_min = 3 MeV): a candidate is good if it is
260  /// within 8 degree of the true direction
261  pub const DEFAULT_WEIGHTS : [f64; SEARCHLIGHT_N_FEATURES] = [
262    -0.9146565230836554, 0.8037962715355819, 0.11380610309136566, 0.0465517668825525, 0.4997414823021247,
263    -0.6183449951464622, -2.133149460830834, -0.43308369178450046, -0.3331666890703525, -0.6335681553983455,
264     0.3902274865448129, 0.03537145399918948, -1.2074140855508566, 0.16296848129855848, -1.1177336044379842,
265     0.4470678104382029, -0.2193816192654419, -0.12680299189576139, -0.4225894728911204, 0.25029053288077463,
266     0.14970104837868786];
267
268  /// Weights of the selection without the independent vertex
269  /// (phase A), trained in the same way. The quality features
270  /// are not used.
271  pub const PHASE_A_WEIGHTS : [f64; SEARCHLIGHT_N_FEATURES] = [
272    -0.9072604498110872, 0.7393581770894417, 0.11453568156458313, 0.02471789186902378, 0.5252756225296815,
273    -0.6749453636286099, -1.9669227517078338, -0.3739474489710377, -0.3543520777504734, -0.7459347575696731,
274     0.26364432521037673, 0.3472351736673516, -1.2065206085659124, 0.20317867344204546, -1.0903262450255007,
275     0.5302275067983919, -0.17461937132353927, 0.0, 0.0, 0.0, 0.0];
276
277  /// The settings without the independent vertex, the secondary
278  /// tracks and the timing (phase A), with their weights
279  pub fn phase_a() -> Self {
280    Self {
281      independent_vertex : false,
282      use_tracks         : false,
283      use_timing         : false,
284      weights            : Self::PHASE_A_WEIGHTS.to_vec(),
285      ..Self::default()
286    }
287  }
288}
289
290impl Default for SearchlightSettings {
291  fn default() -> Self {
292    let mut cleaning = LineFitCleaning::new(150.0);
293    cleaning.final_radius = 75.0;
294    // a tight cylinder for the trigger candidates: their line
295    // continues into the vertex region with its secondaries
296    let trig_cleaning = LineFitCleaning::new(75.0);
297    Self {
298      cleaning,
299      edep_min      : 3.0,
300      trk_e_min     : 3.0,
301      vertex_err    : 30.0,
302      use_vertex    : true,
303      use_tracker   : true,
304      use_trigger   : true,
305      trig_max_dist : 1000.0,
306      trig_err      : 50.0,
307      trig_iter     : 3,
308      trig_cleaning,
309      vertex        : SearchlightVertexSettings::default(),
310      independent_vertex : true,
311      use_tracks    : true,
312      use_timing    : true,
313      tracks        : SearchlightTrackSettings::default(),
314      timing        : SearchlightTimingSettings::default(),
315      weights       : Self::DEFAULT_WEIGHTS.to_vec(),
316    }
317  }
318}
319
320//---------------------------------------------------------
321
322/// The result of searchlight for one event
323#[derive(Debug, Clone, Default)]
324#[cfg_attr(feature="pybindings", pyclass)]
325pub struct SearchlightResult {
326  /// (outer, inner) seed hit, indices into SearchlightHits
327  pub seed       : Option<(usize, usize)>,
328  /// (outer seed hit flagged, inner seed hit flagged)
329  pub flags      : (bool, bool),
330  /// the simple vertex (with the primary line if its seed passes
331  /// the flags), the best estimate of the stopping point
332  pub vertex     : Option<DVec3>,
333  /// the independent vertex, if it was searched for and found; it
334  /// is used for the candidates instead of the simple vertex
335  pub independent_vertex : Option<DVec3>,
336  /// the quality of the independent vertex
337  pub vertex_quality : Option<SearchlightVertexQuality>,
338  /// all candidates, and the chosen one (index into candidates)
339  pub candidates : Vec<SearchlightCandidateFit>,
340  pub best       : Option<usize>,
341}
342
343impl SearchlightResult {
344  /// The chosen candidate
345  pub fn primary(&self) -> Option<&SearchlightCandidateFit> {
346    self.best.map(|k| &self.candidates[k])
347  }
348}
349
350impl fmt::Display for SearchlightResult {
351  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
352    match self.primary() {
353      None    => write!(f, "<SearchlightResult: no primary>"),
354      Some(c) => write!(f, "<SearchlightResult: {}, direction ({:.3}, {:.3}, {:.3}), probability {:.3}, flags {:?}, {} candidates>",
355                        c.kind.as_ref(), c.u.x, c.u.y, c.u.z, c.prob, self.flags, self.candidates.len()),
356    }
357  }
358}
359
360//---------------------------------------------------------
361
362/// The searchlight reconstruction of the primary track
363#[derive(Debug, Clone, Default)]
364#[cfg_attr(feature="pybindings", pyclass)]
365pub struct Searchlight {
366  pub geometry : SearchlightGeometry,
367  pub settings : SearchlightSettings,
368}
369
370impl Searchlight {
371  pub fn new(geometry : SearchlightGeometry, settings : SearchlightSettings) -> Self {
372    Self { geometry, settings }
373  }
374
375  /// Reconstruct the primary of a TelemetryEvent (normalized TOF
376  /// hit times, calibrated tracker hits), see reconstruct_hits.
377  pub fn reconstruct(&self, event : &TelemetryEvent, triggered : &[u8]) -> SearchlightResult {
378    if !event.tof_event.hit_times_normalized {
379      warn!("The TOF hit times are not normalized, searchlight can not reconstruct this event!");
380      return SearchlightResult::default();
381    }
382    let hits = SearchlightHits::from_event(event, Some(&self.geometry));
383    self.reconstruct_hits(&hits, triggered)
384  }
385
386  /// Reconstruct the primary
387  ///
388  /// # Arguments:
389  ///   * hits      : the hits of the event
390  ///   * triggered : paddle ids of triggered paddles without a
391  ///                 hit (may be empty)
392  pub fn reconstruct_hits(&self, hits : &SearchlightHits, triggered : &[u8]) -> SearchlightResult {
393    use SearchlightCandidate as K;
394    let s = &self.settings;
395    let mut res = SearchlightResult::default();
396    let Some((o, i)) = hits.seed() else {
397      return res;
398    };
399    res.seed = Some((o, i));
400    let outer_bad = hits.t[o] > hits.t[i] || hits.e[o] < s.edep_min;
401    let inner_bad = hits.e[i] < s.edep_min;
402    res.flags = (outer_bad, inner_bad);
403    let p = &hits.pos;
404    let n = hits.len();
405    let mut cands = Vec::<SearchlightCandidateFit>::new();
406    cands.extend(candidate(hits, (o, i), K::Today, &s.cleaning, None, p[o], p[i]));
407    // the independent vertex for seeds which pass the flags, the
408    // simple vertex otherwise for the candidates; the simple vertex
409    // is the better stopping point, so it is always the result
410    let simple = if s.use_vertex { simple_vertex(hits, &s.vertex, &s.cleaning, (o, i)) } else { None };
411    let independent = if s.use_vertex && s.independent_vertex { independent_vertex(hits, s, (o, i)) } else { None };
412    let (v, quality) = match independent {
413      Some(Some((v, q))) => (Some(v), Some(q)),
414      Some(None)         => (None, None),
415      None               => (simple, None),
416    };
417    res.vertex = simple;
418    res.independent_vertex = quality.and(v);
419    res.vertex_quality = quality;
420    if let Some(v) = v {
421      if (v - p[o]).length() > 1.0 {
422        cands.extend(candidate(hits, (o, n), K::OuterVertex, &s.cleaning, Some((v, s.vertex_err)), p[o], v));
423      }
424      if (v - p[i]).length() > 1.0 {
425        cands.extend(candidate(hits, (i, n), K::InnerVertex, &s.cleaning, Some((v, s.vertex_err)), p[i], v));
426      }
427    }
428    if s.use_tracker {
429      for k in (0..n).filter(|&k| !hits.is_tof[k] && hits.e[k] >= s.trk_e_min) {
430        for (seed, kind) in [(o, K::OuterTracker), (i, K::InnerTracker)] {
431          if (p[k] - p[seed]).length() > 1.0 {
432            cands.extend(candidate(hits, (seed, k), kind, &s.cleaning, None, p[seed], p[k]));
433          }
434        }
435      }
436    }
437    // which candidates may replace the seed: those which keep the
438    // good seed hit
439    let (allowed, flagged_outer) : (Vec<K>, Option<bool>) = match (outer_bad, inner_bad) {
440      (true, false) => (vec![K::InnerVertex, K::InnerTracker, K::InnerTrigger], Some(true)),
441      (false, true) => (vec![K::OuterVertex, K::OuterTracker, K::OuterTrigger], Some(false)),
442      _             => {
443        // with the independent vertex: outer+vertex too, if today's
444        // line has no primary-like tracker hits
445        let mut allowed = vec![K::Today];
446        if s.independent_vertex {
447          let n_hi = cands.iter().find(|c| c.kind == K::Today).map(|c| {
448            c.hits.iter().filter(|&&k| k < n && !hits.is_tof[k] && hits.e[k] >= s.trk_e_min).count()
449          });
450          if n_hi.is_none_or(|n_hi| n_hi == 0) {
451            allowed.push(K::OuterVertex);
452          }
453        }
454        (allowed, None)
455      }
456    };
457    // triggered paddles without a hit on the flagged side: the line
458    // from the good seed hit through the closest point on the paddle,
459    // iterated
460    if let (true, Some(outer)) = (s.use_trigger, flagged_outer) {
461      let (keep, kind) = if outer { (i, K::InnerTrigger) } else { (o, K::OuterTrigger) };
462      let base : Vec<&SearchlightCandidateFit> = {
463        let b : Vec<_> = cands.iter().filter(|c| allowed.contains(&c.kind)).collect();
464        if b.is_empty() { cands.iter().collect() } else { b }
465      };
466      let mut b0 : Option<&SearchlightCandidateFit> = None;
467      for c in base {
468        if b0.is_none_or(|b| score(hits, &c.hits, s) > score(hits, &b.hits, s)) {
469          b0 = Some(c);
470        }
471      }
472      if let Some(b0) = b0 {
473        let (a0, u0) = (b0.a, b0.u);
474        let mut new = Vec::<SearchlightCandidateFit>::new();
475        for &pid in triggered {
476          if (pid <= TOF_INNER_MAX_PADDLE_ID) == outer {
477            continue;
478          }
479          let (mut a, mut u) = (a0, u0);
480          let mut found : Option<SearchlightCandidateFit> = None;
481          let mut point = DVec3::ZERO;
482          for _ in 0..s.trig_iter {
483            let Some((pt, d)) = self.geometry.closest_on_paddle(pid, a, u) else {
484              found = None;
485              break;
486            };
487            point = pt;
488            if d > s.trig_max_dist {
489              found = None;
490              break;
491            }
492            let Some(c2) = candidate(hits, (keep, n), kind, &s.trig_cleaning, Some((pt, s.trig_err)), DVec3::ZERO, DVec3::ZERO) else {
493              break;
494            };
495            (a, u) = (c2.a, c2.u);
496            found = Some(c2);
497          }
498          if let Some(mut c) = found {
499            // for the inner seed and an outer paddle, the line starts at the paddle
500            (c.start, c.target) = if outer { (point, p[keep]) } else { (p[keep], point) };
501            new.push(c);
502          }
503        }
504        cands.extend(new);
505      }
506    }
507    if cands.is_empty() {
508      return res;
509    }
510    for c in cands.iter_mut() {
511      // orient inwards: from the outer-most point of the candidate to the other one
512      if (c.target - c.start).dot(c.u) < 0.0 {
513        c.u = -c.u;
514      }
515      c.features = features(hits, c, s, v, quality.as_ref());
516      c.prob = if s.weights.is_empty() {
517        score(hits, &c.hits, s)
518      } else {
519        let x : f64 = s.weights.iter().zip(&c.features).map(|(w, f)| w*f).sum();
520        1.0/(1.0 + (-x).exp())
521      };
522    }
523    // the most probable among the allowed candidates (the first
524    // candidate if none is allowed)
525    let mut best : Option<usize> = None;
526    for c in cands.iter_mut() {
527      c.allowed = allowed.contains(&c.kind);
528    }
529    if !cands.iter().any(|c| c.allowed) {
530      cands[0].allowed = true;
531    }
532    for (k, c) in cands.iter().enumerate() {
533      if c.allowed && best.is_none_or(|b| c.prob > cands[b].prob) {
534        best = Some(k);
535      }
536    }
537    res.best = best;
538    res.candidates = cands;
539    res
540  }
541}
542
543//---------------------------------------------------------
544
545#[cfg(test)]
546mod tests {
547  use super::*;
548  use std::collections::HashSet;
549
550  /// a horizontal paddle along y, 180 x 16 cm, centered at (x, 0, z) (cm)
551  fn paddle(pid : u8, x : f32, z : f32) -> TofPaddle {
552    let mut p = TofPaddle::new();
553    p.paddle_id = pid as i16;
554    p.width     = 16.0;
555    p.length    = 180.0;
556    p.height    = 0.635;
557    p.normal_z  = 1.0;
558    p.global_pos_x_l0   = x;
559    p.global_pos_z_l0   = z;
560    p.global_pos_x_l0_A = x;
561    p.global_pos_y_l0_A = -90.0;
562    p.global_pos_z_l0_A = z;
563    p.global_pos_x_l0_B = x;
564    p.global_pos_y_l0_B = 90.0;
565    p.global_pos_z_l0_B = z;
566    p
567  }
568
569  /// an outer paddle (id 100) at z = 2 m, an inner one (id 10) at
570  /// z = 1.1 m, and an outer one (id 101) far away
571  fn geometry() -> SearchlightGeometry {
572    SearchlightGeometry::new(&HashMap::from([(100u8, paddle(100, 0.0, 200.0)), (10, paddle(10, 0.0, 110.0)),
573                                             (101, paddle(101, 100.0, 200.0))]))
574  }
575
576  /// a primary from (20, 30, 2000) along u, at beta 0.4, with an
577  /// outer and an inner TOF hit and tracker hits every 100 mm in z,
578  /// stopping at z = 400 mm
579  fn primary_event(outer_late : bool) -> (SearchlightHits, DVec3) {
580    let u  = DVec3::new(0.05, -0.08, -1.0).normalize();
581    let a  = DVec3::new(20.0, 30.0, 2000.0);
582    let at = |z : f64| a + ((z - a.z)/u.z)*u;
583    let t  = |p : DVec3| (p - a).length()/(0.4*C_LIGHT_MM_NS);
584    let (po, pi) = (at(2000.0), at(1100.0));
585    // with outer_late, the outer hit is a secondary leaving the detector after the inner one
586    let to = if outer_late { t(pi) + 5.0 } else { t(po) };
587    let tof = vec![(po, to, 12.0, 100u8), (pi, t(pi), 12.0, 10u8)];
588    let trk : Vec<(DVec3, f64, u32)> = [982.0, 882.0, 782.0, 682.0, 582.0, 482.0].iter().map(|&z| (at(z), 8.0, 0)).collect();
589    (SearchlightHits::new(&tof, &trk, None), u)
590  }
591
592  fn angle(a : DVec3, b : DVec3) -> f64 {
593    a.normalize().dot(b.normalize()).abs().min(1.0).acos().to_degrees()
594  }
595
596  #[test]
597  fn searchlight_closest_on_paddle() {
598    let geo = geometry();
599    // a vertical line through (100, 500, *): closest point on paddle 100 (along y at x = 0)
600    let (p, d) = geo.closest_on_paddle(100, DVec3::new(100.0, 500.0, 0.0), DVec3::Z).unwrap();
601    assert!((p - DVec3::new(0.0, 500.0, 2000.0)).length() < 1e-9);
602    assert!((d - 100.0).abs() < 1e-9);
603    // beyond the end of the paddle, the point is limited to its length
604    let (p, _) = geo.closest_on_paddle(100, DVec3::new(0.0, 2000.0, 0.0), DVec3::Z).unwrap();
605    assert!((p.y - 900.0).abs() < 1e-9);
606    assert!(geo.closest_on_paddle(55, DVec3::ZERO, DVec3::Z).is_none());
607  }
608
609  #[test]
610  fn searchlight_vertex_from_lines() {
611    let v   = DVec3::new(100.0, -50.0, 600.0);
612    let s   = SearchlightVertexSettings::default();
613    let dir = [DVec3::new(1.0, 0.2, 0.3), DVec3::new(-0.4, 1.0, -0.2), DVec3::new(0.1, -0.3, 1.0)];
614    let hits = SearchlightHits::new(&[], &dir.iter().map(|d| (v + 200.0*d.normalize(), 1.0, 0)).collect::<Vec<_>>(), None);
615    let lines : Vec<SearchlightLine> = dir.iter().enumerate().map(|(k, d)| {
616      SearchlightLine { a : v + 300.0*d.normalize(), u : d.normalize(), hits : vec![k], sigma0 : 20.0, theta : 0.05 }
617    }).collect();
618    let (found, ncomp) = find_vertex(&lines, &[], &hits, &s).unwrap();
619    assert!((found - v).length() < 1e-6);
620    assert_eq!(ncomp, 3);
621    // an outlier line does not move the vertex much
622    let mut with_outlier = lines.clone();
623    with_outlier.push(SearchlightLine { a : v + DVec3::new(0.0, 400.0, 0.0), u : DVec3::X, hits : vec![0], sigma0 : 20.0, theta : 0.05 });
624    let (found, _) = find_vertex(&with_outlier, &[], &hits, &s).unwrap();
625    assert!((found - v).length() < 1.0);
626  }
627
628  #[test]
629  fn searchlight_tracker_line() {
630    // hits along a line: one tracker line through their centroid along
631    // their principal axis
632    let u    = DVec3::new(0.3, -0.5, 0.8).normalize();
633    let pts  : Vec<(DVec3, f64, u32)> = (0..6).map(|k| (DVec3::new(10.0, 20.0, 30.0) + (k as f64*50.0)*u, 1.0, 0)).collect();
634    let hits = SearchlightHits::new(&[], &pts, None);
635    let s    = SearchlightVertexSettings { trk_min_dz : 10.0, ..Default::default() };
636    let lines = tracker_lines(&hits, &(0..pts.len()).collect::<Vec<_>>(), &s);
637    assert_eq!(lines.len(), 1);
638    assert!((lines[0].a - DVec3::new(10.0, 20.0, 30.0) - 125.0*u).length() < 1e-9);
639    assert!(angle(lines[0].u, u) < 1e-6);
640    assert_eq!(lines[0].hits.len(), 6);
641  }
642
643  #[test]
644  fn searchlight_secondary_pairs() {
645    // an inner hit and an outer hit 1 m away 3.34 ns later (beta 1), and
646    // one 10 ns later (beta 0.33, not a secondary)
647    let tof = vec![(DVec3::new(0.0, 0.0, 1000.0), 0.0, 2.0, 10u8),
648                   (DVec3::new(0.0, 0.0, 2000.0), 1000.0/C_LIGHT_MM_NS, 2.0, 100u8),
649                   (DVec3::new(0.0, 1000.0, 1000.0), 10.0, 2.0, 101u8)];
650    let hits = SearchlightHits::new(&tof, &[], None);
651    let s    = SearchlightVertexSettings::default();
652    assert_eq!(secondary_pairs(&hits, &s, &[]), vec![(0, 1)]);
653    assert!(secondary_pairs(&hits, &s, &[1]).is_empty());
654  }
655
656  #[test]
657  fn searchlight_good_seed() {
658    let (hits, u) = primary_event(false);
659    let s   = SearchlightSettings::default();
660    let sl  = Searchlight::new(geometry(), s.clone());
661    let res = sl.reconstruct_hits(&hits, &[]);
662    assert_eq!(res.seed, Some((0, 1)));
663    assert_eq!(res.flags, (false, false));
664    // the result is the simple vertex, also with the independent one
665    assert_eq!(res.vertex, simple_vertex(&hits, &s.vertex, &s.cleaning, (0, 1)));
666    let p = res.primary().unwrap();
667    assert_eq!(p.kind, SearchlightCandidate::Today);
668    assert!(angle(p.u, u) < 0.01);
669    // inwards: the direction points down, along the flight
670    assert!(p.u.z < 0.0);
671    assert_eq!(p.features.len(), SEARCHLIGHT_N_FEATURES);
672    // 2 TOF and 6 tracker hits, beta 0.4 is measured and physical
673    assert_eq!((p.features[1], p.features[2], p.features[6], p.features[7]), (2.0, 6.0, 0.0, 0.0));
674  }
675
676  #[test]
677  fn searchlight_flagged_outer_seed() {
678    // the outer hit comes after the inner one: it is a secondary, the
679    // primary is reconstructed from the inner seed and the tracker hits
680    let (hits, u) = primary_event(true);
681    let sl  = Searchlight::new(geometry(), SearchlightSettings::default());
682    let res = sl.reconstruct_hits(&hits, &[]);
683    assert_eq!(res.flags, (true, false));
684    let p = res.primary().unwrap();
685    assert!(matches!(p.kind, SearchlightCandidate::InnerVertex | SearchlightCandidate::InnerTracker | SearchlightCandidate::InnerTrigger));
686    assert!(angle(p.u, u) < 0.5);
687    // only the candidates which keep the inner seed hit take part
688    assert!(p.allowed);
689    for c in &res.candidates {
690      assert_eq!(c.allowed, matches!(c.kind, SearchlightCandidate::InnerVertex | SearchlightCandidate::InnerTracker | SearchlightCandidate::InnerTrigger));
691    }
692    // without any weights, the most energy-weighted inliers win
693    let mut s = SearchlightSettings::default();
694    s.weights.clear();
695    let res = Searchlight::new(geometry(), s).reconstruct_hits(&hits, &[]);
696    assert!(res.primary().unwrap().kind != SearchlightCandidate::Today);
697  }
698
699  /// two secondaries from v, through the tracker layers (strips
700  /// alternating between measuring x and y) and an outer TOF paddle.
701  /// They must not be back to back: then one line fits both.
702  fn secondaries(v : DVec3) -> (SearchlightHits, [DVec3; 2]) {
703    let dirs = [DVec3::new(0.6, 0.0, 1.0).normalize(), DVec3::new(-0.3, 0.5, 1.0).normalize()];
704    let mut trk = Vec::<(DVec3, f64, u32)>::new();
705    for d in dirs {
706      for z in [982.0, 882.0, 782.0, 682.0, 582.0, 482.0, 382.0] {
707        let s = (z - v.z)/d.z;
708        if s > 30.0 {
709          trk.push((v + s*d, 0.5, 0));
710        }
711      }
712    }
713    let tof = dirs.iter().enumerate().map(|(k, d)| {
714      let s = (if d.z > 0.0 { 2000.0 } else { 0.0 } - v.z)/d.z;
715      (v + s*d, 10.0 + s/(0.95*C_LIGHT_MM_NS), 2.0, 100 + k as u8)
716    }).collect::<Vec<_>>();
717    let mut hits = SearchlightHits::new(&tof, &trk, None);
718    for k in hits.ntof..hits.len() {
719      hits.measured[k]   = if (hits.pos[k].z.round() as i64/100) % 2 == 0 { 0 } else { 1 };
720      hits.half_chord[k] = 40.0;
721    }
722    (hits, dirs)
723  }
724
725  #[test]
726  fn searchlight_track_finder() {
727    let v = DVec3::new(50.0, -80.0, 400.0);
728    let (hits, dirs) = secondaries(v);
729    let free : Vec<usize> = (0..hits.len()).collect();
730    let tracks = find_tracks(&hits, &free, &SearchlightTrackSettings::default(), &SearchlightVertexSettings::default(), &[]);
731    assert_eq!(tracks.len(), 2);
732    for t in &tracks {
733      // each track has the hits of one secondary, and passes the vertex
734      let d = dirs.iter().map(|d| angle(t.line.u, *d)).fold(f64::INFINITY, f64::min);
735      assert!(d < 1e-3);
736      assert!(t.line.dist(v) < 1e-3);
737      assert!(t.ntrk >= 2 && t.ntof == 1);
738    }
739    let all : HashSet<usize> = tracks.iter().flat_map(|t| t.hits.iter().copied()).collect();
740    assert_eq!(all.len(), hits.len());
741  }
742
743  #[test]
744  fn searchlight_timing_score() {
745    // the primary's last TOF hit at t = 0, 600 mm before the vertex; the
746    // secondaries leave the vertex at t = 10 ns
747    let v = DVec3::new(50.0, -80.0, 400.0);
748    let (mut hits, _) = secondaries(v);
749    hits = SearchlightHits {
750      pos       : [vec![v + DVec3::new(0.0, 0.0, 600.0)], hits.pos].concat(),
751      err       : [vec![SearchlightHits::ERR], hits.err].concat(),
752      t         : [vec![0.0], hits.t].concat(),
753      e         : [vec![12.0], hits.e].concat(),
754      is_tof    : [vec![true], hits.is_tof].concat(),
755      inner     : [vec![true], hits.inner].concat(),
756      paddle_id : [vec![10], hits.paddle_id].concat(),
757      measured  : [vec![-1], hits.measured].concat(),
758      half_chord : [vec![0.0], hits.half_chord].concat(),
759      ntof      : hits.ntof + 1,
760    };
761    let s = SearchlightTimingSettings::default();
762    let (n, t0) = timing_score(v, &hits, 0, &HashSet::from([0]), &s);
763    assert_eq!(n, 2);
764    assert!((t0 - 10.0).abs() < 1e-9);
765    // 200 mm away, the two estimates do not agree anymore
766    let (n, _) = timing_score(v + DVec3::new(200.0, 0.0, 0.0), &hits, 0, &HashSet::from([0]), &s);
767    assert!(n < 2);
768  }
769
770  #[test]
771  fn searchlight_settings_phases() {
772    let a = SearchlightSettings::phase_a();
773    assert!(!a.independent_vertex && !a.use_tracks && !a.use_timing);
774    assert_eq!(a.weights.len(), SEARCHLIGHT_N_FEATURES);
775    assert!(a.weights[SEARCHLIGHT_N_FEATURES - 4..].iter().all(|w| *w == 0.0));
776    let b = SearchlightSettings::default();
777    assert!(b.independent_vertex && b.use_tracks && b.use_timing);
778    // a good seed with tracker hits: the same primary in both
779    let (hits, u) = primary_event(false);
780    for s in [a, b] {
781      let res = Searchlight::new(geometry(), s).reconstruct_hits(&hits, &[]);
782      let p = res.primary().unwrap();
783      assert_eq!(p.kind, SearchlightCandidate::Today);
784      assert!(angle(p.u, u) < 0.01);
785      assert_eq!(p.features.len(), SEARCHLIGHT_N_FEATURES);
786    }
787  }
788
789  #[test]
790  fn searchlight_no_seed() {
791    let hits = SearchlightHits::new(&[(DVec3::new(0.0, 0.0, 2000.0), 0.0, 10.0, 100u8)], &[], None);
792    let res  = Searchlight::new(geometry(), SearchlightSettings::default()).reconstruct_hits(&hits, &[]);
793    assert!(res.seed.is_none() && res.primary().is_none());
794  }
795}