Skip to main content

gondola_core/physics/searchlight/
vertex.rs

1//! The vertex (stopping point of the primary) for searchlight:
2//! lines with an error growing with the distance from their
3//! closest hit, and an adaptive fit to these lines and points
4// This file is part of gaps-online-software and published
5// under the GPLv3 license
6
7use std::collections::HashSet;
8
9use glam::{DMat3, DVec3};
10
11use crate::prelude::*;
12
13use super::{fit_line, SearchlightHits, C_LIGHT_MM_NS};
14
15/// A line for the vertex fit, with an error which grows with
16/// the distance from its closest hit:
17///
18/// sigma(s)^2 = sigma0^2 + (theta*s)^2
19#[derive(Debug, Clone)]
20pub struct SearchlightLine {
21  /// a point on the line (mm)
22  pub a      : DVec3,
23  /// unit vector along the line
24  pub u      : DVec3,
25  /// the hits of the line (indices into SearchlightHits)
26  pub hits   : Vec<usize>,
27  /// error at the hits (mm)
28  pub sigma0 : f64,
29  /// growth of the error with the distance (rad)
30  pub theta  : f64,
31}
32
33impl SearchlightLine {
34  /// Distance of the point v from the line
35  pub fn dist(&self, v : DVec3) -> f64 {
36    let w = v - self.a;
37    (w - w.dot(self.u)*self.u).length()
38  }
39
40  /// Error of the line at the point v
41  pub fn sigma(&self, v : DVec3, hits : &SearchlightHits) -> f64 {
42    let s = if self.hits.is_empty() {
43      0.0
44    } else {
45      self.hits.iter().map(|&k| (hits.pos[k] - v).length()).fold(f64::INFINITY, f64::min)
46    };
47    (self.sigma0*self.sigma0 + (self.theta*s).powi(2)).sqrt()
48  }
49}
50
51/// Settings for the vertex of searchlight
52#[derive(Debug, Clone)]
53pub struct SearchlightVertexSettings {
54  /// secondary pairs (inner -> outer TOF hit at beta ~ 1):
55  /// time resolution per hit (ns), position error of a TOF
56  /// hit (mm), the window in units of the uncertainty and the
57  /// smallest beta of a secondary
58  pub pair_sigma_t     : f64,
59  pub pair_sigma_pos   : f64,
60  pub pair_n_sigma     : f64,
61  pub pair_beta_min    : f64,
62  /// tracker-only lines: through pairs of tracker hits at least
63  /// trk_min_dz (mm) apart in z, collecting the hits within
64  /// trk_radius (mm), at least trk_min_hits hits
65  pub trk_lines        : bool,
66  pub trk_radius       : f64,
67  pub trk_min_hits     : usize,
68  pub trk_min_dz       : f64,
69  /// line errors (mm, rad): secondaries with tracker hits, with
70  /// TOF hits only, and the primary
71  pub sigma0_sec       : f64,
72  pub sigma0_tof_only  : f64,
73  pub theta_sec        : f64,
74  pub sigma0_prim      : f64,
75  pub theta_prim       : f64,
76  /// the primary line takes part if both seed hits have at least
77  /// this edep (MeV) and the outer one is earlier
78  pub use_primary      : bool,
79  pub seed_edep_min    : f64,
80  /// the tracker hit with the largest energy as a point, if above
81  /// e_point_min (MeV), with the error e_point_err (mm)
82  pub use_e_point      : bool,
83  pub e_point_min      : f64,
84  pub e_point_err      : f64,
85  /// adaptive fit: chi2 of the transition from inlier to outlier,
86  /// and the temperatures of the annealing
87  pub chi2_cut         : f64,
88  pub temperatures     : Vec<f64>,
89  /// the vertex has to be inside this box (mm)
90  pub box_min          : DVec3,
91  pub box_max          : DVec3,
92}
93
94impl Default for SearchlightVertexSettings {
95  fn default() -> Self {
96    Self {
97      pair_sigma_t     : 0.17,
98      pair_sigma_pos   : 50.0,
99      pair_n_sigma     : 3.0,
100      pair_beta_min    : 0.7,
101      trk_lines        : true,
102      trk_radius       : 30.0,
103      trk_min_hits     : 3,
104      trk_min_dz       : 50.0,
105      sigma0_sec       : 20.0,
106      sigma0_tof_only  : 50.0,
107      theta_sec        : 0.05,
108      sigma0_prim      : 20.0,
109      theta_prim       : 0.05,
110      use_primary      : true,
111      seed_edep_min    : 3.0,
112      use_e_point      : true,
113      e_point_min      : 5.0,
114      e_point_err      : 30.0,
115      chi2_cut         : 9.0,
116      temperatures     : vec![64.0, 16.0, 4.0, 1.0],
117      box_min          : DVec3::new(-800.0, -800.0, 150.0),
118      box_max          : DVec3::new(800.0, 800.0, 1200.0),
119    }
120  }
121}
122
123impl SearchlightVertexSettings {
124  pub(crate) fn inside(&self, p : DVec3) -> bool {
125    p.cmpge(self.box_min).all() && p.cmple(self.box_max).all()
126  }
127}
128
129/// The points of closest approach of two lines (unit vectors
130/// u1, u2), None for parallel lines
131pub(crate) fn closest_points(a1 : DVec3, u1 : DVec3, a2 : DVec3, u2 : DVec3) -> Option<(DVec3, DVec3)> {
132  let w = a1 - a2;
133  let b = u1.dot(u2);
134  let d = 1.0 - b*b;
135  if d < 1e-9 {
136    return None;
137  }
138  let s = (b*u2.dot(w) - u1.dot(w))/d;
139  let t = (u2.dot(w) - b*u1.dot(w))/d;
140  Some((a1 + s*u1, a2 + t*u2))
141}
142
143/// Pairs (inner, outer) of TOF hits which can be one particle
144/// leaving the detector: the outer hit is later, at a velocity
145/// close to the speed of light. Each hit is used at most once,
146/// the best matching pairs first.
147pub(crate) fn secondary_pairs(hits : &SearchlightHits, s : &SearchlightVertexSettings, exclude : &[usize]) -> Vec<(usize, usize)> {
148  let sigma = (2.0*s.pair_sigma_t.powi(2) + 2.0*(s.pair_sigma_pos/C_LIGHT_MM_NS).powi(2)).sqrt();
149  let ok = |k : usize| hits.t[k].is_finite() && !exclude.contains(&k);
150  let mut cand = Vec::<(f64, usize, usize)>::new();
151  for i in (0..hits.ntof).filter(|&k| hits.inner[k] && ok(k)) {
152    for o in (0..hits.ntof).filter(|&k| !hits.inner[k] && ok(k)) {
153      let dt = hits.t[o] - hits.t[i];
154      let l  = (hits.pos[o] - hits.pos[i]).length();
155      // dt - l/c is 0 for beta = 1 and l/c (1/beta - 1) for slower ones
156      let r  = dt - l/C_LIGHT_MM_NS;
157      let hi = s.pair_n_sigma*sigma + l/C_LIGHT_MM_NS*(1.0/s.pair_beta_min - 1.0);
158      if -s.pair_n_sigma*sigma < r && r < hi {
159        cand.push((r.abs()/sigma, i, o));
160      }
161    }
162  }
163  cand.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2)));
164  let mut used  = HashSet::<usize>::new();
165  let mut pairs = Vec::<(usize, usize)>::new();
166  for (_, i, o) in cand {
167    if used.contains(&i) || used.contains(&o) {
168      continue;
169    }
170    pairs.push((i, o));
171    used.insert(i);
172    used.insert(o);
173  }
174  pairs
175}
176
177/// Centroid and principal axis of points
178fn pca_line(points : &[DVec3]) -> (DVec3, DVec3) {
179  let c = points.iter().fold(DVec3::ZERO, |s, &p| s + p)/(points.len() as f64);
180  let mut m = DMat3::ZERO;
181  for &p in points {
182    let d = p - c;
183    m += DMat3::from_cols(d*d.x, d*d.y, d*d.z);
184  }
185  (c, principal_eigenvector(m))
186}
187
188/// The eigenvector of the largest eigenvalue of a symmetric 3x3
189/// matrix (cyclic Jacobi rotations)
190fn principal_eigenvector(m : DMat3) -> DVec3 {
191  let mut a = m.to_cols_array_2d();
192  let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
193  for _ in 0..50 {
194    let off = a[0][1].abs() + a[0][2].abs() + a[1][2].abs();
195    if off < 1e-12*(a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1e-300) {
196      break;
197    }
198    for (p, q) in [(0usize, 1usize), (0, 2), (1, 2)] {
199      if a[p][q].abs() < 1e-300 {
200        continue;
201      }
202      let theta = 0.5*(a[q][q] - a[p][p])/a[p][q];
203      let t = theta.signum()/(theta.abs() + (theta*theta + 1.0).sqrt());
204      let t = if theta == 0.0 { 1.0 } else { t };
205      let c = 1.0/(t*t + 1.0).sqrt();
206      let s = t*c;
207      for k in 0..3 {
208        let (akp, akq) = (a[k][p], a[k][q]);
209        a[k][p] = c*akp - s*akq;
210        a[k][q] = s*akp + c*akq;
211      }
212      for k in 0..3 {
213        let (apk, aqk) = (a[p][k], a[q][k]);
214        a[p][k] = c*apk - s*aqk;
215        a[q][k] = s*apk + c*aqk;
216      }
217      for k in 0..3 {
218        let (vkp, vkq) = (v[k][p], v[k][q]);
219        v[k][p] = c*vkp - s*vkq;
220        v[k][q] = s*vkp + c*vkq;
221      }
222    }
223  }
224  let j = (0..3).max_by(|&x, &y| a[x][x].total_cmp(&a[y][y])).unwrap();
225  DVec3::new(v[0][j], v[1][j], v[2][j]).normalize()
226}
227
228/// Secondaries seen only in the tracker: lines through pairs of
229/// free tracker hits in different layers take all free hits
230/// within trk_radius; the lines with the most hits are taken
231/// greedily, each hit used once
232pub(crate) fn tracker_lines(hits : &SearchlightHits, free : &[usize], s : &SearchlightVertexSettings) -> Vec<SearchlightLine> {
233  let trk : Vec<usize> = free.iter().copied().filter(|&k| !hits.is_tof[k]).collect();
234  let mut cand = Vec::<(usize, f64, Vec<usize>)>::new();
235  for x in 0..trk.len() {
236    for y in x+1..trk.len() {
237      let (j, k) = (trk[x], trk[y]);
238      let d = hits.pos[k] - hits.pos[j];
239      if d.z.abs() < s.trk_min_dz {
240        continue;
241      }
242      let seed = SearchlightLine { a : hits.pos[j], u : d.normalize(), hits : vec![], sigma0 : 0.0, theta : 0.0 };
243      let near : Vec<usize> = free.iter().copied().filter(|&m| seed.dist(hits.pos[m]) < s.trk_radius).collect();
244      if near.len() >= s.trk_min_hits {
245        let pts : Vec<DVec3> = near.iter().map(|&m| hits.pos[m]).collect();
246        let (a, u) = pca_line(&pts);
247        let line = SearchlightLine { a, u, hits : vec![], sigma0 : 0.0, theta : 0.0 };
248        let res  = near.iter().map(|&m| line.dist(hits.pos[m])).sum::<f64>()/(near.len() as f64);
249        cand.push((near.len(), res, near));
250      }
251    }
252  }
253  // most hits first, then the smallest residual (a stable sort keeps the order otherwise)
254  cand.sort_by(|x, y| y.0.cmp(&x.0).then(x.1.total_cmp(&y.1)));
255  let mut used  = HashSet::<usize>::new();
256  let mut lines = Vec::<SearchlightLine>::new();
257  for (_, _, near) in cand {
258    let near : Vec<usize> = near.into_iter().filter(|m| !used.contains(m)).collect();
259    if near.len() < s.trk_min_hits || near.iter().filter(|&&m| !hits.is_tof[m]).count() < 2 {
260      continue;
261    }
262    let pts : Vec<DVec3> = near.iter().map(|&m| hits.pos[m]).collect();
263    let (a, u) = pca_line(&pts);
264    used.extend(near.iter().copied());
265    lines.push(SearchlightLine { a, u, hits : near, sigma0 : s.sigma0_sec, theta : s.theta_sec });
266  }
267  lines
268}
269
270/// Adaptive vertex fit (deterministic annealing) to lines and
271/// points (position, error), starting at v0. The weight of a
272/// measurement is
273///
274/// w = 1/(1 + exp((chi2 - chi2_cut)/(2T)))
275///
276/// Returns the vertex and the number of compatible measurements
277pub(crate) fn adaptive_vertex(lines  : &[SearchlightLine],
278                              points : &[(DVec3, f64)],
279                              hits   : &SearchlightHits,
280                              s      : &SearchlightVertexSettings,
281                              v0     : DVec3) -> Option<(DVec3, usize)> {
282  let mut v = v0;
283  for &temp in &s.temperatures {
284    for _ in 0..3 {
285      let mut a    = DMat3::ZERO;
286      let mut b    = DVec3::ZERO;
287      let mut wsum = 0.0;
288      for l in lines {
289        let s2   = l.sigma(v, hits).powi(2);
290        let chi2 = l.dist(v).powi(2)/s2;
291        let w    = 1.0/(1.0 + ((chi2 - s.chi2_cut)/(2.0*temp)).exp());
292        let proj = (DMat3::IDENTITY - DMat3::from_cols(l.u*l.u.x, l.u*l.u.y, l.u*l.u.z))*(w/s2);
293        a += proj;
294        b += proj*l.a;
295        wsum += w;
296      }
297      for &(p, err) in points {
298        let chi2 = (v - p).length_squared()/(err*err);
299        let w    = 1.0/(1.0 + ((chi2 - s.chi2_cut)/(2.0*temp)).exp());
300        a += DMat3::IDENTITY*(w/(err*err));
301        b += p*(w/(err*err));
302        wsum += w;
303      }
304      if wsum < 1e-6 {
305        return None;
306      }
307      let det = a.determinant();
308      if det == 0.0 || !det.is_finite() {
309        return None;
310      }
311      v = a.inverse()*b;
312    }
313  }
314  let ncomp = lines.iter().filter(|l| l.dist(v).powi(2)/l.sigma(v, hits).powi(2) < s.chi2_cut).count()
315            + points.iter().filter(|(p, err)| (v - *p).length_squared()/(err*err) < s.chi2_cut).count();
316  Some((v, ncomp))
317}
318
319/// The starting points of the vertex fit: the points, and the
320/// midpoints of the closest approach of all pairs of lines
321fn vertex_seeds(lines : &[SearchlightLine], points : &[(DVec3, f64)]) -> Vec<DVec3> {
322  let mut seeds : Vec<DVec3> = points.iter().map(|&(p, _)| p).collect();
323  for k in 0..lines.len() {
324    for l in k+1..lines.len() {
325      if let Some((p1, p2)) = closest_points(lines[k].a, lines[k].u, lines[l].a, lines[l].u) {
326        seeds.push(0.5*(p1 + p2));
327      }
328    }
329  }
330  seeds
331}
332
333/// chi2 of a vertex, each measurement contributing at most chi2_cut
334fn vertex_chi2(v : DVec3, lines : &[SearchlightLine], points : &[(DVec3, f64)], hits : &SearchlightHits, s : &SearchlightVertexSettings) -> f64 {
335  lines.iter().map(|l| (l.dist(v).powi(2)/l.sigma(v, hits).powi(2)).min(s.chi2_cut)).sum::<f64>()
336    + points.iter().map(|(p, err)| ((v - *p).length_squared()/(err*err)).min(s.chi2_cut)).sum::<f64>()
337}
338
339/// All vertex candidates of the adaptive fit, one per starting
340/// point (candidates within 10 mm of an earlier one are dropped):
341/// (vertex, compatible measurements, chi2)
342pub(crate) fn vertex_candidates(lines  : &[SearchlightLine],
343                                points : &[(DVec3, f64)],
344                                hits   : &SearchlightHits,
345                                s      : &SearchlightVertexSettings) -> Vec<(DVec3, usize, f64)> {
346  let mut out = Vec::<(DVec3, usize, f64)>::new();
347  for sd in vertex_seeds(lines, points) {
348    if !s.inside(sd) {
349      continue;
350    }
351    let Some((v, ncomp)) = adaptive_vertex(lines, points, hits, s, sd) else {
352      continue;
353    };
354    if ncomp < 2 || !s.inside(v) || out.iter().any(|c| (v - c.0).length() < 10.0) {
355      continue;
356    }
357    out.push((v, ncomp, vertex_chi2(v, lines, points, hits, s)));
358  }
359  out
360}
361
362/// The tracker hit with the largest energy as a point for the
363/// vertex, if above e_point_min
364pub(crate) fn e_point(hits : &SearchlightHits, s : &SearchlightVertexSettings) -> Vec<(DVec3, f64)> {
365  if !s.use_e_point {
366    return vec![];
367  }
368  let mut best : Option<usize> = None;
369  for k in (0..hits.len()).filter(|&k| !hits.is_tof[k]) {
370    if best.is_none_or(|b| hits.e[k] > hits.e[b]) {
371      best = Some(k);
372    }
373  }
374  match best {
375    Some(k) if hits.e[k] > s.e_point_min => vec![(hits.pos[k], s.e_point_err)],
376    _                                     => vec![],
377  }
378}
379
380/// The best adaptive fit over all starting points (the points,
381/// and the midpoints of the closest approach of all pairs of
382/// lines): the most compatible measurements, then the smallest
383/// chi2. Returns the vertex and the number of compatible
384/// measurements.
385pub(crate) fn find_vertex(lines  : &[SearchlightLine],
386                          points : &[(DVec3, f64)],
387                          hits   : &SearchlightHits,
388                          s      : &SearchlightVertexSettings) -> Option<(DVec3, usize)> {
389  let mut best : Option<(DVec3, usize, f64)> = None;
390  for sd in vertex_seeds(lines, points) {
391    if !s.inside(sd) {
392      continue;
393    }
394    let Some((v, ncomp)) = adaptive_vertex(lines, points, hits, s, sd) else {
395      continue;
396    };
397    if ncomp < 2 || !s.inside(v) {
398      continue;
399    }
400    let chi2 = vertex_chi2(v, lines, points, hits, s);
401    let better = match best {
402      None                  => true,
403      Some((_, n, c)) => ncomp > n || (ncomp == n && chi2 < c),
404    };
405    if better {
406      best = Some((v, ncomp, chi2));
407    }
408  }
409  best.map(|(v, n, _)| (v, n))
410}
411
412/// The vertex from the secondaries: pairs of TOF hits at beta ~ 1
413/// and tracker-only lines, the highest-energy tracker hit, and
414/// the primary seed line if its seed hits look right.
415///
416/// # Arguments:
417///   * seed : (outer, inner) seed hit
418pub(crate) fn simple_vertex(hits     : &SearchlightHits,
419                            s        : &SearchlightVertexSettings,
420                            cleaning : &LineFitCleaning,
421                            seed     : (usize, usize)) -> Option<DVec3> {
422  let (o, i) = seed;
423  let n      = hits.len();
424  let all : Vec<usize> = (0..n).collect();
425  let mut used    = HashSet::<usize>::new();
426  let mut primary = None;
427  if let Some((a, u, acc)) = fit_line(hits, &all, (o, i), cleaning) {
428    used.extend(acc.iter().copied());
429    primary = Some(SearchlightLine { a, u, hits : acc, sigma0 : s.sigma0_prim, theta : s.theta_prim });
430  }
431  let mut lines    = Vec::<SearchlightLine>::new();
432  let mut sec_used = HashSet::<usize>::new();
433  for (pi, po) in secondary_pairs(hits, s, &[o]) {
434    let free : Vec<usize> = (0..n).filter(|k| !sec_used.contains(k) && (!used.contains(k) || *k == pi || *k == po)).collect();
435    let (Some(spo), Some(spi)) = (free.iter().position(|&k| k == po), free.iter().position(|&k| k == pi)) else {
436      continue;
437    };
438    if let Some((a, u, acc)) = fit_line(hits, &free, (spo, spi), cleaning) {
439      let sigma0 = if acc.iter().any(|&k| !hits.is_tof[k]) { s.sigma0_sec } else { s.sigma0_tof_only };
440      sec_used.extend(acc.iter().copied());
441      lines.push(SearchlightLine { a, u, hits : acc, sigma0, theta : s.theta_sec });
442    }
443  }
444  if s.trk_lines {
445    let free : Vec<usize> = (0..n).filter(|k| !used.contains(k) && !sec_used.contains(k)).collect();
446    lines.extend(tracker_lines(hits, &free, s));
447  }
448  let points = e_point(hits, s);
449  let seed_ok = hits.e[o] >= s.seed_edep_min && hits.e[i] >= s.seed_edep_min && hits.t[o] < hits.t[i];
450  if s.use_primary && seed_ok {
451    if let Some(p) = primary {
452      lines.push(p);
453    }
454  }
455  find_vertex(&lines, &points, hits, s).map(|(v, _)| v)
456}