Skip to main content

gondola_core/physics/
reconstruction.rs

1// This file is part of gaps-online-software and published 
2// under the GPLv3 license
3
4use crate::prelude::*;
5
6use argmin::core::{
7  CostFunction,
8  Executor,
9  State,
10  TerminationReason,
11};
12use argmin::solver::neldermead::NelderMead;
13
14#[cfg(feature="database")]
15use std::collections::BTreeMap;
16
17
18#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
19#[repr(u8)]
20#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
21pub enum FitStatus {
22  Unknown        = 0u8,
23  DidNotConverge = 10u8,
24  /// LineFit::fit_cleaned: the fit of the last iteration
25  /// failed (e.g. less than 2 hits accepted), this is the
26  /// fit of the iteration before
27  FallbackPreviousIteration = 20u8,
28  Success        = 42u8,
29}
30
31expand_and_test_enum!(FitStatus, test_fitstatus_repr);
32
33
34/// Describe line depending on z since that is our
35/// best constrained value
36///
37/// This model has 6 free parameters, 3 for 
38/// the anchor point and 3 for the direction
39pub fn line3d(z : f32, x_a : f32, y_a : f32, z_a : f32, dx : f32, dy : f32, dz : f32) -> (f32, f32, f32) {
40  // avoid zero division error 
41  //let dx_nz : f32 = dx if dx !=0 {dx} else { 1e-5 };
42  //let dy_nz : f32 = dy if dy !=0 {dy} else { 1e-5 };
43  let dz_nz : f32 = if dz != 0.0 {dz} else { 1e-5 };
44  let x = x_a + ((dx/dz_nz) * (z - z_a));
45  let y = y_a + ((dy/dz_nz) * (z - z_a));
46  (x,y,z)
47}
48
49//------------------------------------------------------------
50
51/// Default error on the x/y coordinates of a hit, in case
52/// no errors are given (same as in the python version)
53pub const LINEFIT_DEFAULT_ERR_XY : f32 = 10.0;
54
55/// TOF paddles with ids up to this one form the inner TOF
56/// (cube), the ones above the outer TOF (umbrella, cortina)
57pub const TOF_INNER_MAX_PADDLE_ID : u8 = 60;
58
59/// The cost function a LineFit minimizes
60#[derive(Debug, Copy, Clone, PartialEq)]
61#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
62pub enum LineFitCost {
63  /// sum of the squared, normalized residuals (LineFit::fit)
64  Chi2,
65  /// sum of the normalized distances (LineFit::fit_sum_of_distances)
66  SumOfDistances,
67}
68
69/// Settings for the hit cleaning of LineFit::fit_cleaned
70///
71/// A hit is accepted if its distance from the line is at
72/// most the radius of a cylinder around the line.
73///
74/// The radius of the cylinder starts at cylinder_radius. If
75/// final_radius is smaller, it shrinks after each fit by
76/// shrink_factor, down to final_radius, so that a wide
77/// cylinder collects the hits around a poor first line and a
78/// narrow one removes the hits which do not belong to the
79/// track once the line is better known.
80#[derive(Debug, Copy, Clone, PartialEq)]
81#[cfg_attr(feature="pybindings", pyclass)]
82pub struct LineFitCleaning {
83  /// Only hits within a cylinder of this radius (in mm)
84  /// around the line are used in the fit
85  pub cylinder_radius : f32,
86  /// Maximum number of fits. The iteration stops earlier
87  /// once the final radius is reached and the set of
88  /// accepted hits does not change anymore
89  pub max_iterations  : u32,
90  /// The cost function for each fit
91  pub cost            : LineFitCost,
92  /// The radius (in mm) the cylinder shrinks to. If it is
93  /// not smaller than cylinder_radius, the radius stays
94  /// the same (the default)
95  pub final_radius    : f32,
96  /// After each fit, the radius is multiplied by this
97  /// factor (but not below final_radius). A factor outside
98  /// of (0, 1) goes to final_radius right away
99  pub shrink_factor   : f32,
100}
101
102impl LineFitCleaning {
103  pub fn new(cylinder_radius : f32) -> Self {
104    Self {
105      cylinder_radius,
106      max_iterations : 10,
107      cost           : LineFitCost::Chi2,
108      final_radius   : cylinder_radius,
109      shrink_factor  : 0.5,
110    }
111  }
112
113  /// The radius of the cylinder after the next fit
114  fn next_radius(&self, radius : f32) -> f32 {
115    let target = self.final_radius.min(self.cylinder_radius);
116    if self.shrink_factor > 0.0 && self.shrink_factor < 1.0 {
117      (radius*self.shrink_factor).max(target)
118    } else {
119      target
120    }
121  }
122}
123
124/// The result of LineFit::fit_cleaned
125#[derive(Debug, Clone, PartialEq)]
126#[cfg_attr(feature="pybindings", pyclass)]
127pub struct CleanedLineFit {
128  /// the fit to the accepted hits of the last iteration
129  pub fit        : LineFit,
130  /// for each hit, if it is used in the fit
131  pub accepted   : Vec<bool>,
132  /// the indices of the two hits the first line was
133  /// constructed through (for fit_cleaned_event: first the
134  /// outer, then the inner TOF hit)
135  pub seed       : (usize, usize),
136  /// number of fits which have been performed
137  pub iterations : u32,
138  /// true if the final radius was reached and the set of
139  /// accepted hits did not change anymore, false if
140  /// max_iterations was reached or the last fit failed
141  /// (then fit.status is FallbackPreviousIteration)
142  pub converged  : bool,
143  /// the radius of the cylinder (in mm) the accepted hits
144  /// have been selected with
145  pub radius     : f32,
146}
147
148/// A straight line through a pointcloud, parametrized
149/// in z, since that is our best constrained value
150///
151/// x(z) = x0 + tx * (z - z0)
152/// y(z) = y0 + ty * (z - z0)
153///
154/// The anchor z0 is fixed to the mean z of the hits, so
155/// the line has 4 free parameters (x0, y0, tx, ty). The
156/// 6 parameter model of line3d is degenerate (the anchor
157/// can slide along the line and the direction vector can
158/// be scaled), which only introduces flat directions
159/// for a minimizer.
160///
161/// For the standard chi2 (sum of squared, normalized
162/// residuals) the fit decouples into two independent
163/// weighted linear regressions x(z) and y(z), which
164/// can be solved analytically (LineFit::fit).
165///
166/// The python version minimizes the sum of the normalized
167/// distances instead (sum of sqrt(rx^2/sx^2 + ry^2/sy^2)),
168/// which is less sensitive to outliers, but has no closed
169/// form solution. This is available through
170/// LineFit::fit_sum_of_distances, which uses the analytic
171/// solution as a seed for a Nelder-Mead minimization.
172#[derive(Debug, Copy, Clone, PartialEq)]
173#[cfg_attr(feature="pybindings", pyclass)]
174pub struct LineFit {
175  /// anchor point
176  pub x0       : f32,
177  pub y0       : f32,
178  pub z0       : f32,
179  /// slopes dx/dz and dy/dz
180  pub tx       : f32,
181  pub ty       : f32,
182  /// parameter errors (from the analytic chi2 fit)
183  pub x0_err   : f32,
184  pub y0_err   : f32,
185  pub tx_err   : f32,
186  pub ty_err   : f32,
187  /// sum of the squared, normalized residuals
188  pub chi2     : f32,
189  /// value of the minimized cost function. For the
190  /// analytic fit this is the same as chi2
191  pub cost     : f32,
192  /// 2*npoints - 4
193  pub ndof     : u32,
194  pub npoints  : u32,
195  pub status   : FitStatus,
196}
197
198impl LineFit {
199  pub fn new() -> Self {
200    Self {
201      x0       : 0.0,
202      y0       : 0.0,
203      z0       : 0.0,
204      tx       : 0.0,
205      ty       : 0.0,
206      x0_err   : 0.0,
207      y0_err   : 0.0,
208      tx_err   : 0.0,
209      ty_err   : 0.0,
210      chi2     : 0.0,
211      cost     : 0.0,
212      ndof     : 0,
213      npoints  : 0,
214      status   : FitStatus::Unknown,
215    }
216  }
217
218  /// Analytic, weighted least squares fit of a straight line
219  /// to the given points.
220  ///
221  /// Returns None if there are less than 2 points, or all
222  /// points have the same z (the line can not be described
223  /// as a function of z)
224  ///
225  /// # Arguments:
226  ///   * errs_x, errs_y : errors on x and y for each point.
227  ///                      If None, LINEFIT_DEFAULT_ERR_XY
228  ///                      will be used
229  pub fn fit(xs     : &[f32],
230             ys     : &[f32],
231             zs     : &[f32],
232             errs_x : Option<&[f32]>,
233             errs_y : Option<&[f32]>) -> Option<Self> {
234    let points = LineFitPoints::new(xs, ys, zs, errs_x, errs_y)?;
235    let (x0, tx, x0_var, tx_var) = points.regression(&points.xs, &points.wx)?;
236    let (y0, ty, y0_var, ty_var) = points.regression(&points.ys, &points.wy)?;
237    let mut lf  = Self::new();
238    lf.z0       = points.z0 as f32;
239    lf.x0       = x0 as f32;
240    lf.y0       = y0 as f32;
241    lf.tx       = tx as f32;
242    lf.ty       = ty as f32;
243    lf.x0_err   = x0_var.sqrt() as f32;
244    lf.y0_err   = y0_var.sqrt() as f32;
245    lf.tx_err   = tx_var.sqrt() as f32;
246    lf.ty_err   = ty_var.sqrt() as f32;
247    lf.chi2     = points.chi2(&[x0, y0, tx, ty]) as f32;
248    lf.cost     = lf.chi2;
249    lf.npoints  = xs.len() as u32;
250    lf.ndof     = 2*lf.npoints - 4;
251    lf.status   = FitStatus::Success;
252    Some(lf)
253  }
254
255  /// Fit a straight line to the given points by minimizing
256  /// the sum of the normalized distances, as done in the
257  /// python version of the linefit.
258  ///
259  /// The analytic chi2 fit is used as a seed for the
260  /// minimization with the Nelder-Mead algorithm. The parameter
261  /// errors are the ones of the seed.
262  pub fn fit_sum_of_distances(xs     : &[f32],
263                              ys     : &[f32],
264                              zs     : &[f32],
265                              errs_x : Option<&[f32]>,
266                              errs_y : Option<&[f32]>) -> Option<Self> {
267    let mut lf  = Self::fit(xs, ys, zs, errs_x, errs_y)?;
268    let points  = LineFitPoints::new(xs, ys, zs, errs_x, errs_y)?;
269    let seed    = vec![lf.x0 as f64, lf.y0 as f64, lf.tx as f64, lf.ty as f64];
270    // initial simplex - step sizes from the seed errors, so
271    // that they come with the right scale for each parameter
272    let steps   = [lf.x0_err as f64, lf.y0_err as f64, lf.tx_err as f64, lf.ty_err as f64];
273    let mut simplex = vec![seed.clone()];
274    for k in 0..seed.len() {
275      let mut vertex = seed.clone();
276      vertex[k] += if steps[k] > 0.0 { steps[k] } else { 1e-3 };
277      simplex.push(vertex);
278    }
279    let solver = match NelderMead::new(simplex).with_sd_tolerance(1e-8) {
280      Err(err) => {
281        error!("Unable to set up Nelder-Mead solver! {err}");
282        lf.status = FitStatus::DidNotConverge;
283        return Some(lf);
284      }
285      Ok(solver) => solver
286    };
287    let result = Executor::new(points.clone(), solver)
288      .configure(|state| state.max_iters(2000))
289      .run();
290    match result {
291      Err(err) => {
292        error!("Minimization failed! {err}");
293        lf.status = FitStatus::DidNotConverge;
294      }
295      Ok(res) => {
296        let state = res.state();
297        if let Some(best) = state.get_best_param() {
298          lf.x0   = best[0] as f32;
299          lf.y0   = best[1] as f32;
300          lf.tx   = best[2] as f32;
301          lf.ty   = best[3] as f32;
302          lf.chi2 = points.chi2(best) as f32;
303          lf.cost = state.get_best_cost() as f32;
304        }
305        lf.status = match state.get_termination_reason() {
306          Some(TerminationReason::SolverConverged) => FitStatus::Success,
307          _                                        => FitStatus::DidNotConverge,
308        };
309      }
310    }
311    Some(lf)
312  }
313
314  /// Fit a straight line, using only hits within a cylinder
315  /// around the line (LineFitCleaning::cylinder_radius).
316  ///
317  /// The hits have to be ordered in time, with the TOF hits
318  /// first. Tracker hits do not have a time (NaN).
319  ///
320  /// 1) The first line is constructed through the first two
321  ///    hits with a time. These are not necessarily one outer
322  ///    and one inner TOF hit, fit_cleaned_event makes sure
323  ///    of that, using the paddle ids.
324  /// 2) All hits within the cylinder around the line are
325  ///    accepted, the others rejected.
326  /// 3) The line is fitted to the accepted hits.
327  /// 4) The radius of the cylinder shrinks, if this is
328  ///    configured (LineFitCleaning::final_radius).
329  /// 5) Steps 2) to 4) are repeated with the fitted line
330  ///    until the final radius is reached and the accepted
331  ///    hits do not change anymore, or
332  ///    LineFitCleaning::max_iterations is reached.
333  ///
334  /// If a fit after the first one fails (e.g. less than 2 hits
335  /// are accepted with a smaller radius), the fit of the
336  /// iteration before is returned, with its accepted hits and
337  /// the status FitStatus::FallbackPreviousIteration.
338  ///
339  /// Returns None if there are less than 2 hits with a time,
340  /// the first two of them are at the same position, or the
341  /// first fit fails (less than 2 hits are accepted or they
342  /// can not be fit).
343  ///
344  /// # Arguments:
345  ///   * ts             : hit times, NaN for tracker hits
346  ///   * errs_x, errs_y : errors on x and y for each point.
347  ///                      If None, LINEFIT_DEFAULT_ERR_XY
348  ///                      will be used
349  pub fn fit_cleaned(xs       : &[f32],
350                     ys       : &[f32],
351                     zs       : &[f32],
352                     ts       : &[f32],
353                     errs_x   : Option<&[f32]>,
354                     errs_y   : Option<&[f32]>,
355                     cleaning : &LineFitCleaning) -> Option<CleanedLineFit> {
356    if ts.len() != xs.len() {
357      error!("Got {} t values for {} points!", ts.len(), xs.len());
358      return None;
359    }
360    let mut timed = (0..ts.len()).filter(|k| !ts[*k].is_nan());
361    let (Some(i), Some(j)) = (timed.next(), timed.next()) else {
362      error!("Need at least 2 hits with a time (TOF hits) to construct the first line!");
363      return None;
364    };
365    Self::fit_cleaned_with_seed(xs, ys, zs, errs_x, errs_y, (i, j), cleaning)
366  }
367
368  /// Fit a straight line to the hits of an event, using only
369  /// hits within a cylinder around the line, see fit_cleaned.
370  ///
371  /// The first line is constructed through the first outer
372  /// and the first inner TOF hit (in time), the inner TOF
373  /// being the paddles up to TOF_INNER_MAX_PADDLE_ID.
374  ///
375  /// The hits are the TOF hits (in the order of
376  /// event.tof_event.hits), followed by the tracker hits (in
377  /// the order of event.tracker_hits), so for the n TOF hits,
378  /// accepted[k] is the TOF hit k for k < n and the tracker
379  /// hit k - n otherwise. Tracker hits without coordinates
380  /// are never accepted.
381  ///
382  /// Returns None if the TOF paddle information has not been
383  /// set for the event (TofEvent::set_paddles), there is no
384  /// outer or no inner TOF hit with a time, or the fit fails
385  /// (see fit_cleaned).
386  pub fn fit_cleaned_event(event : &TelemetryEvent, cleaning : &LineFitCleaning) -> Option<CleanedLineFit> {
387    // without paddle information the TOF hits have no
388    // coordinates, get_pointcloud reports that
389    let tof   = event.tof_event.get_pointcloud()?;
390    let first = |inner : bool| -> Option<usize> {
391      event.tof_event.hits.iter().enumerate()
392        .filter(|(_, h)| (h.paddle_id <= TOF_INNER_MAX_PADDLE_ID) == inner && !h.event_t0.is_nan())
393        .min_by(|(_, a), (_, b)| a.event_t0.total_cmp(&b.event_t0))
394        .map(|(k, _)| k)
395    };
396    let (Some(outer), Some(inner)) = (first(false), first(true)) else {
397      error!("Need at least one outer and one inner TOF hit with a time to construct the first line!");
398      return None;
399    };
400    let points : Vec<(f32, f32, f32, f32, f32)> = tof.into_iter()
401      .chain(event.get_tracker_pointcloud())
402      .collect();
403    let usable : Vec<bool> = event.tof_event.hits.iter().map(|_| true)
404      .chain(event.tracker_hits.iter().map(|h| h.has_coordinates))
405      .collect();
406    let xs : Vec<f32> = points.iter().map(|p| p.0).collect();
407    let ys : Vec<f32> = points.iter().map(|p| p.1).collect();
408    let zs : Vec<f32> = points.iter().map(|p| p.2).collect();
409    Self::fit_cleaned_core(&xs, &ys, &zs, None, None, &usable, (outer, inner), cleaning)
410  }
411
412  /// Fit a straight line, using only hits within a cylinder
413  /// around the line, see fit_cleaned. The first line is
414  /// constructed through the two hits with the indices
415  /// given by seed.
416  pub fn fit_cleaned_with_seed(xs       : &[f32],
417                               ys       : &[f32],
418                               zs       : &[f32],
419                               errs_x   : Option<&[f32]>,
420                               errs_y   : Option<&[f32]>,
421                               seed     : (usize, usize),
422                               cleaning : &LineFitCleaning) -> Option<CleanedLineFit> {
423    Self::fit_cleaned_core(xs, ys, zs, errs_x, errs_y, &vec![true; xs.len()], seed, cleaning)
424  }
425
426  /// The iteration of fit_cleaned. Hits which are not usable
427  /// are never accepted.
428  fn fit_cleaned_core(xs       : &[f32],
429                      ys       : &[f32],
430                      zs       : &[f32],
431                      errs_x   : Option<&[f32]>,
432                      errs_y   : Option<&[f32]>,
433                      usable   : &[bool],
434                      seed     : (usize, usize),
435                      cleaning : &LineFitCleaning) -> Option<CleanedLineFit> {
436    let n = xs.len();
437    if ys.len() != n || zs.len() != n || usable.len() != n {
438      error!("Got {} x, {} y and {} z values! They need to be of the same length!", n, ys.len(), zs.len());
439      return None;
440    }
441    for errs in [errs_x, errs_y].into_iter().flatten() {
442      if errs.len() != n {
443        error!("Got {} errors for {} points!", errs.len(), n);
444        return None;
445      }
446    }
447    let (i, j) = seed;
448    if i >= n || j >= n {
449      error!("Seed hits {:?} out of range for {} points!", seed, n);
450      return None;
451    }
452    let anchor = (xs[i], ys[i], zs[i]);
453    let dir    = (xs[j] - xs[i], ys[j] - ys[i], zs[j] - zs[i]);
454    let norm   = (dir.0*dir.0 + dir.1*dir.1 + dir.2*dir.2).sqrt();
455    if norm == 0.0 {
456      error!("The two seed hits are at the same position, can not construct a line!");
457      return None;
458    }
459    let final_radius = cleaning.final_radius.min(cleaning.cylinder_radius);
460    let mut line     = (anchor, (dir.0/norm, dir.1/norm, dir.2/norm));
461    let mut accepted : Vec<bool> = Vec::new();
462    let mut fit : Option<LineFit> = None;
463    let mut converged = false;
464    let mut iterations = 0;
465    // the radius for the next selection of hits, and the
466    // one the accepted hits of fit have been selected with
467    let mut radius   = cleaning.cylinder_radius;
468    let mut fit_radius = radius;
469    while iterations < cleaning.max_iterations {
470      let now : Vec<bool> = (0..n)
471        .map(|k| usable[k] && distance_to_line((xs[k], ys[k], zs[k]), line.0, line.1) <= radius)
472        .collect();
473      if fit.is_some() && now == accepted {
474        // the same hits give the same fit
475        fit_radius = radius;
476        if radius <= final_radius {
477          converged = true;
478          break;
479        }
480        radius = cleaning.next_radius(radius);
481        continue;
482      }
483      let select = |vs : &[f32]| -> Vec<f32> {
484        vs.iter().zip(&now).filter(|(_, a)| **a).map(|(v, _)| *v).collect()
485      };
486      let (ex, ey) = (errs_x.map(select), errs_y.map(select));
487      let (sx, sy, sz) = (select(xs), select(ys), select(zs));
488      // with a previous fit to fall back to, less than 2 hits
489      // are an expected outcome (e.g. of a shrinking cylinder)
490      // and not worth an error from the fit
491      let result = if fit.is_some() && sx.len() < 2 {
492        None
493      } else {
494        match cleaning.cost {
495          LineFitCost::Chi2           => Self::fit(&sx, &sy, &sz, ex.as_deref(), ey.as_deref()),
496          LineFitCost::SumOfDistances => Self::fit_sum_of_distances(&sx, &sy, &sz, ex.as_deref(), ey.as_deref()),
497        }
498      };
499      let Some(lf) = result else {
500        // keep the fit of the iteration before, if there is one
501        let mut previous = fit?;
502        previous.status  = FitStatus::FallbackPreviousIteration;
503        return Some(CleanedLineFit {
504          fit        : previous,
505          accepted,
506          seed,
507          iterations,
508          converged  : false,
509          radius     : fit_radius,
510        });
511      };
512      iterations += 1;
513      accepted    = now;
514      fit_radius  = radius;
515      radius      = cleaning.next_radius(radius);
516      line        = ((lf.x0, lf.y0, lf.z0), lf.direction());
517      fit         = Some(lf);
518    }
519    Some(CleanedLineFit {
520      fit  : fit?,
521      accepted,
522      seed,
523      iterations,
524      converged,
525      radius : fit_radius,
526    })
527  }
528
529  /// Distance of a point from the line (in the units of
530  /// the coordinates)
531  pub fn distance(&self, x : f32, y : f32, z : f32) -> f32 {
532    distance_to_line((x, y, z), (self.x0, self.y0, self.z0), self.direction())
533  }
534
535  /// Evaluate the line at a given z
536  pub fn eval(&self, z : f32) -> (f32, f32, f32) {
537    (self.x0 + self.tx*(z - self.z0), self.y0 + self.ty*(z - self.z0), z)
538  }
539
540  /// Unit direction vector of the line, pointing
541  /// towards +z
542  pub fn direction(&self) -> (f32, f32, f32) {
543    let norm = (self.tx*self.tx + self.ty*self.ty + 1.0).sqrt();
544    (self.tx/norm, self.ty/norm, 1.0/norm)
545  }
546
547  /// Cosine of the zenith angle of the line
548  pub fn cos_theta(&self) -> f32 {
549    self.direction().2
550  }
551
552  /// The parameters of the line in the form as expected
553  /// by line3d (x_a, y_a, z_a, dx, dy, dz)
554  pub fn line3d_params(&self) -> (f32, f32, f32, f32, f32, f32) {
555    (self.x0, self.y0, self.z0, self.tx, self.ty, 1.0)
556  }
557}
558
559impl fmt::Display for LineFit {
560  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
561    let mut repr = String::from("<LineFit");
562    repr += &(format!("\n  status {}", self.status));
563    repr += &(format!("\n  anchor x0 {:.2} +- {:.2} y0 {:.2} +- {:.2} z0 {:.2}",
564                      self.x0, self.x0_err, self.y0, self.y0_err, self.z0));
565    repr += &(format!("\n  slopes tx {:.4} +- {:.4} ty {:.4} +- {:.4}",
566                      self.tx, self.tx_err, self.ty, self.ty_err));
567    repr += &(format!("\n  chi2 {:.2} / ndof {} (cost {:.2}, npoints {})>",
568                      self.chi2, self.ndof, self.cost, self.npoints));
569    write!(f,"{}", repr)
570  }
571}
572
573#[cfg(feature="pybindings")]
574#[pymethods]
575impl LineFit {
576  /// Analytic, weighted least squares fit of a straight line
577  /// to the given points. Returns None if there are less than
578  /// 2 points, or all points have the same z.
579  ///
580  /// # Arguments:
581  ///   * errs_x, errs_y : errors on x and y for each point.
582  ///                      If None, LINEFIT_DEFAULT_ERR_XY
583  ///                      will be used
584  #[staticmethod]
585  #[pyo3(name="fit", signature = (xs, ys, zs, errs_x = None, errs_y = None))]
586  fn fit_py(xs     : Vec<f32>,
587            ys     : Vec<f32>,
588            zs     : Vec<f32>,
589            errs_x : Option<Vec<f32>>,
590            errs_y : Option<Vec<f32>>) -> Option<Self> {
591    Self::fit(&xs, &ys, &zs, errs_x.as_deref(), errs_y.as_deref())
592  }
593
594  /// Fit a straight line by minimizing the sum of the normalized
595  /// distances of the points from the line (as the python
596  /// version line_fit), which is less sensitive to outliers.
597  /// Returns None under the same conditions as fit.
598  #[staticmethod]
599  #[pyo3(name="fit_sum_of_distances", signature = (xs, ys, zs, errs_x = None, errs_y = None))]
600  fn fit_sum_of_distances_py(xs     : Vec<f32>,
601                             ys     : Vec<f32>,
602                             zs     : Vec<f32>,
603                             errs_x : Option<Vec<f32>>,
604                             errs_y : Option<Vec<f32>>) -> Option<Self> {
605    Self::fit_sum_of_distances(&xs, &ys, &zs, errs_x.as_deref(), errs_y.as_deref())
606  }
607
608  /// Fit a straight line, using only hits within a cylinder
609  /// around the line (LineFitCleaning). The first line is
610  /// constructed through the first two hits with a time
611  /// (ts not NaN), which are not necessarily one outer and
612  /// one inner TOF hit, see fit_cleaned_event for that.
613  ///
614  /// Returns a CleanedLineFit, or None if there are less than
615  /// 2 hits with a time, or less than 2 hits are accepted.
616  ///
617  /// # Arguments:
618  ///   * ts             : hit times, NaN for tracker hits
619  ///   * cleaning       : the cylinder radius etc.
620  ///   * errs_x, errs_y : errors on x and y for each point.
621  ///                      If None, LINEFIT_DEFAULT_ERR_XY
622  ///                      will be used
623  #[staticmethod]
624  #[pyo3(name="fit_cleaned", signature = (xs, ys, zs, ts, cleaning, errs_x = None, errs_y = None))]
625  fn fit_cleaned_py(xs       : Vec<f32>,
626                    ys       : Vec<f32>,
627                    zs       : Vec<f32>,
628                    ts       : Vec<f32>,
629                    cleaning : &LineFitCleaning,
630                    errs_x   : Option<Vec<f32>>,
631                    errs_y   : Option<Vec<f32>>) -> Option<CleanedLineFit> {
632    Self::fit_cleaned(&xs, &ys, &zs, &ts, errs_x.as_deref(), errs_y.as_deref(), cleaning)
633  }
634
635  /// Fit a straight line to the TOF and tracker hits of an
636  /// event, using only hits within a cylinder around the line.
637  /// The first line is constructed through the first outer
638  /// and the first inner TOF hit (in time).
639  ///
640  /// accepted of the result has the TOF hits first (in the
641  /// order of event.tof.hits), followed by the tracker hits
642  /// (in the order of event.tracker). Tracker hits without
643  /// coordinates are never accepted.
644  ///
645  /// Returns None if the TOF paddle information has not been
646  /// set for the event (event.tof_set_paddles or hydrate),
647  /// there is no outer or no inner TOF hit with a time, or
648  /// the fit fails. The TOF hits only have a time (event_t0)
649  /// after event.tof_normalize_hit_times (with or without
650  /// timing offsets).
651  #[staticmethod]
652  #[pyo3(name="fit_cleaned_event")]
653  fn fit_cleaned_event_py(event : &TelemetryEvent, cleaning : &LineFitCleaning) -> Option<CleanedLineFit> {
654    Self::fit_cleaned_event(event, cleaning)
655  }
656
657  /// Fit a straight line, using only hits within a cylinder
658  /// around the line, see fit_cleaned. The first line is
659  /// constructed through the two hits with the indices
660  /// given by seed.
661  #[staticmethod]
662  #[pyo3(name="fit_cleaned_with_seed", signature = (xs, ys, zs, seed, cleaning, errs_x = None, errs_y = None))]
663  fn fit_cleaned_with_seed_py(xs       : Vec<f32>,
664                              ys       : Vec<f32>,
665                              zs       : Vec<f32>,
666                              seed     : (usize, usize),
667                              cleaning : &LineFitCleaning,
668                              errs_x   : Option<Vec<f32>>,
669                              errs_y   : Option<Vec<f32>>) -> Option<CleanedLineFit> {
670    Self::fit_cleaned_with_seed(&xs, &ys, &zs, errs_x.as_deref(), errs_y.as_deref(), seed, cleaning)
671  }
672
673  /// Distance of a point from the line (in the units of
674  /// the coordinates)
675  #[pyo3(name="distance")]
676  fn distance_py(&self, x : f32, y : f32, z : f32) -> f32 {
677    self.distance(x, y, z)
678  }
679
680  /// Evaluate the line at a given z, returns (x, y, z)
681  #[pyo3(name="eval")]
682  fn eval_py(&self, z : f32) -> (f32, f32, f32) {
683    self.eval(z)
684  }
685
686  /// Unit direction vector of the line, pointing
687  /// towards +z
688  #[getter]
689  #[pyo3(name="direction")]
690  fn get_direction_py(&self) -> (f32, f32, f32) {
691    self.direction()
692  }
693
694  /// Cosine of the zenith angle of the line
695  #[getter]
696  #[pyo3(name="cos_theta")]
697  fn get_cos_theta_py(&self) -> f32 {
698    self.cos_theta()
699  }
700
701  /// The parameters of the line in the form as expected
702  /// by line3d (x_a, y_a, z_a, dx, dy, dz)
703  #[getter]
704  #[pyo3(name="line3d_params")]
705  fn get_line3d_params_py(&self) -> (f32, f32, f32, f32, f32, f32) {
706    self.line3d_params()
707  }
708
709  /// Anchor point, x
710  #[getter]
711  fn get_x0(&self) -> f32 {
712    self.x0
713  }
714
715  /// Anchor point, y
716  #[getter]
717  fn get_y0(&self) -> f32 {
718    self.y0
719  }
720
721  /// Anchor point, z (fixed to the mean z of the hits)
722  #[getter]
723  fn get_z0(&self) -> f32 {
724    self.z0
725  }
726
727  /// Slope dx/dz
728  #[getter]
729  fn get_tx(&self) -> f32 {
730    self.tx
731  }
732
733  /// Slope dy/dz
734  #[getter]
735  fn get_ty(&self) -> f32 {
736    self.ty
737  }
738
739  /// Error on x0 (from the analytic chi2 fit)
740  #[getter]
741  fn get_x0_err(&self) -> f32 {
742    self.x0_err
743  }
744
745  /// Error on y0 (from the analytic chi2 fit)
746  #[getter]
747  fn get_y0_err(&self) -> f32 {
748    self.y0_err
749  }
750
751  /// Error on tx (from the analytic chi2 fit)
752  #[getter]
753  fn get_tx_err(&self) -> f32 {
754    self.tx_err
755  }
756
757  /// Error on ty (from the analytic chi2 fit)
758  #[getter]
759  fn get_ty_err(&self) -> f32 {
760    self.ty_err
761  }
762
763  /// Sum of the squared, normalized residuals
764  #[getter]
765  fn get_chi2(&self) -> f32 {
766    self.chi2
767  }
768
769  /// Value of the minimized cost function. For the
770  /// analytic fit this is the same as chi2
771  #[getter]
772  fn get_cost(&self) -> f32 {
773    self.cost
774  }
775
776  /// 2*npoints - 4
777  #[getter]
778  fn get_ndof(&self) -> u32 {
779    self.ndof
780  }
781
782  /// Number of points used in the fit
783  #[getter]
784  fn get_npoints(&self) -> u32 {
785    self.npoints
786  }
787
788  #[getter]
789  fn get_status(&self) -> FitStatus {
790    self.status
791  }
792
793  fn __repr__(&self) -> String {
794    self.to_string()
795  }
796}
797
798#[cfg(feature="pybindings")]
799#[pymethods]
800impl LineFitCleaning {
801  /// Settings for the hit cleaning of LineFit.fit_cleaned.
802  /// The radius of the cylinder starts at cylinder_radius,
803  /// and shrinks by shrink_factor after each fit down to
804  /// final_radius, if that is given and smaller.
805  #[new]
806  #[pyo3(signature = (cylinder_radius, max_iterations = 10, cost = LineFitCost::Chi2,
807                      final_radius = None, shrink_factor = 0.5))]
808  fn new_py(cylinder_radius : f32,
809            max_iterations  : u32,
810            cost            : LineFitCost,
811            final_radius    : Option<f32>,
812            shrink_factor   : f32) -> Self {
813    Self {
814      cylinder_radius,
815      max_iterations,
816      cost,
817      final_radius : final_radius.unwrap_or(cylinder_radius),
818      shrink_factor,
819    }
820  }
821
822  /// Only hits within a cylinder of this radius (in mm)
823  /// around the line are used in the fit
824  #[getter]
825  fn get_cylinder_radius(&self) -> f32 {
826    self.cylinder_radius
827  }
828
829  #[setter]
830  fn set_cylinder_radius(&mut self, cylinder_radius : f32) {
831    self.cylinder_radius = cylinder_radius;
832  }
833
834  /// The radius (in mm) the cylinder shrinks to. If it is
835  /// not smaller than cylinder_radius, the radius stays
836  /// the same
837  #[getter]
838  fn get_final_radius(&self) -> f32 {
839    self.final_radius
840  }
841
842  #[setter]
843  fn set_final_radius(&mut self, final_radius : f32) {
844    self.final_radius = final_radius;
845  }
846
847  /// After each fit, the radius is multiplied by this
848  /// factor (but not below final_radius). A factor outside
849  /// of (0, 1) goes to final_radius right away
850  #[getter]
851  fn get_shrink_factor(&self) -> f32 {
852    self.shrink_factor
853  }
854
855  #[setter]
856  fn set_shrink_factor(&mut self, shrink_factor : f32) {
857    self.shrink_factor = shrink_factor;
858  }
859
860  /// Maximum number of fits. The iteration stops earlier
861  /// once the final radius is reached and the set of
862  /// accepted hits does not change anymore
863  #[getter]
864  fn get_max_iterations(&self) -> u32 {
865    self.max_iterations
866  }
867
868  #[setter]
869  fn set_max_iterations(&mut self, max_iterations : u32) {
870    self.max_iterations = max_iterations;
871  }
872
873  /// The cost function for each fit
874  #[getter]
875  fn get_cost(&self) -> LineFitCost {
876    self.cost
877  }
878
879  #[setter]
880  fn set_cost(&mut self, cost : LineFitCost) {
881    self.cost = cost;
882  }
883
884  fn __repr__(&self) -> String {
885    let shrinking = if self.final_radius < self.cylinder_radius {
886      format!(", shrinking to {} mm by {}", self.final_radius, self.shrink_factor)
887    } else {
888      String::new()
889    };
890    format!("<LineFitCleaning: cylinder_radius {} mm{}, max_iterations {}, cost {:?}>",
891            self.cylinder_radius, shrinking, self.max_iterations, self.cost)
892  }
893}
894
895#[cfg(feature="pybindings")]
896#[pymethods]
897impl CleanedLineFit {
898  /// The fit to the accepted hits of the last iteration
899  #[getter]
900  fn get_fit(&self) -> LineFit {
901    self.fit
902  }
903
904  /// For each hit, if it is used in the fit
905  #[getter]
906  fn get_accepted(&self) -> Vec<bool> {
907    self.accepted.clone()
908  }
909
910  /// The indices of the two hits the first line was
911  /// constructed through (for fit_cleaned_event: first the
912  /// outer, then the inner TOF hit)
913  #[getter]
914  fn get_seed(&self) -> (usize, usize) {
915    self.seed
916  }
917
918  /// Number of fits which have been performed
919  #[getter]
920  fn get_iterations(&self) -> u32 {
921    self.iterations
922  }
923
924  /// True if the final radius was reached and the set of
925  /// accepted hits did not change anymore, False if
926  /// max_iterations was reached or the last fit failed
927  /// (then fit.status is FitStatus.FallbackPreviousIteration)
928  #[getter]
929  fn get_converged(&self) -> bool {
930    self.converged
931  }
932
933  /// The radius of the cylinder (in mm) the accepted hits
934  /// have been selected with
935  #[getter]
936  fn get_radius(&self) -> f32 {
937    self.radius
938  }
939
940  fn __repr__(&self) -> String {
941    format!("<CleanedLineFit: {} of {} hits accepted (radius {} mm), seed {:?}, {} iterations, converged {}\n{}>",
942            self.accepted.iter().filter(|a| **a).count(), self.accepted.len(), self.radius,
943            self.seed, self.iterations, self.converged, self.fit)
944  }
945}
946
947/// Distance of point p from the line through anchor a with
948/// unit direction d
949fn distance_to_line(p : (f32, f32, f32), a : (f32, f32, f32), d : (f32, f32, f32)) -> f32 {
950  let v = (p.0 - a.0, p.1 - a.1, p.2 - a.2);
951  let c = (v.1*d.2 - v.2*d.1, v.2*d.0 - v.0*d.2, v.0*d.1 - v.1*d.0);
952  (c.0*c.0 + c.1*c.1 + c.2*c.2).sqrt()
953}
954
955//------------------------------------------------------------
956
957/// The points (and their weights) a LineFit is performed on.
958/// Also serves as the cost function for the minimization.
959#[derive(Debug, Clone)]
960struct LineFitPoints {
961  xs : Vec<f64>,
962  ys : Vec<f64>,
963  zs : Vec<f64>,
964  /// weights 1/err^2
965  wx : Vec<f64>,
966  wy : Vec<f64>,
967  /// common anchor z for x(z) and y(z)
968  z0 : f64,
969}
970
971impl LineFitPoints {
972  fn new(xs     : &[f32],
973         ys     : &[f32],
974         zs     : &[f32],
975         errs_x : Option<&[f32]>,
976         errs_y : Option<&[f32]>) -> Option<Self> {
977    if xs.len() != ys.len() || xs.len() != zs.len() {
978      error!("Got {} x, {} y and {} z values! They need to be of the same length!", xs.len(), ys.len(), zs.len());
979      return None;
980    }
981    if xs.len() < 2 {
982      error!("Not enough points! Need at least 2, got {}", xs.len());
983      return None;
984    }
985    let weights = |errs : Option<&[f32]>| -> Option<Vec<f64>> {
986      match errs {
987        None    => Some(vec![1.0/(LINEFIT_DEFAULT_ERR_XY as f64).powi(2); xs.len()]),
988        Some(e) => {
989          if e.len() != xs.len() {
990            error!("Got {} errors for {} points!", e.len(), xs.len());
991            return None;
992          }
993          Some(e.iter().map(|k| 1.0/(*k as f64).powi(2)).collect())
994        }
995      }
996    };
997    let zs : Vec<f64> = zs.iter().map(|k| *k as f64).collect();
998    let z0 = zs.iter().sum::<f64>()/zs.len() as f64;
999    Some(Self {
1000      xs : xs.iter().map(|k| *k as f64).collect(),
1001      ys : ys.iter().map(|k| *k as f64).collect(),
1002      zs,
1003      wx : weights(errs_x)?,
1004      wy : weights(errs_y)?,
1005      z0,
1006    })
1007  }
1008
1009  /// Weighted linear regression v(z) = a + b*(z - z0)
1010  ///
1011  /// Returns a, b, var(a), var(b) or None if all z
1012  /// are the same
1013  fn regression(&self, vs : &[f64], ws : &[f64]) -> Option<(f64, f64, f64, f64)> {
1014    let sw   : f64 = ws.iter().sum();
1015    let zbar : f64 = ws.iter().zip(&self.zs).map(|(w,z)| w*z).sum::<f64>()/sw;
1016    let vbar : f64 = ws.iter().zip(vs).map(|(w,v)| w*v).sum::<f64>()/sw;
1017    let mut szz = 0.0f64;
1018    let mut szv = 0.0f64;
1019    for k in 0..vs.len() {
1020      szz += ws[k]*(self.zs[k] - zbar).powi(2);
1021      szv += ws[k]*(self.zs[k] - zbar)*(vs[k] - vbar);
1022    }
1023    if szz <= f64::EPSILON*sw {
1024      // not an error of the program: the fit just returns None,
1025      // e.g. for candidate lines of searchlight with all hits on
1026      // one paddle plane
1027      debug!("All points have the same z, can not fit a line as a function of z!");
1028      return None;
1029    }
1030    let b     = szv/szz;
1031    // shift the anchor from the weighted mean zbar to z0
1032    let a     = vbar + b*(self.z0 - zbar);
1033    let var_b = 1.0/szz;
1034    let var_a = 1.0/sw + (self.z0 - zbar).powi(2)/szz;
1035    Some((a, b, var_a, var_b))
1036  }
1037
1038  /// Squared, normalized residuals in x and y for each
1039  /// point, for parameters x0, y0, tx, ty
1040  fn residuals2<'a>(&'a self, p : &'a [f64]) -> impl Iterator<Item = (f64, f64)> + 'a {
1041    (0..self.xs.len()).map(move |k| {
1042      let dz = self.zs[k] - self.z0;
1043      let rx = self.xs[k] - (p[0] + p[2]*dz);
1044      let ry = self.ys[k] - (p[1] + p[3]*dz);
1045      (rx*rx*self.wx[k], ry*ry*self.wy[k])
1046    })
1047  }
1048
1049  fn chi2(&self, p : &[f64]) -> f64 {
1050    self.residuals2(p).map(|(rx2, ry2)| rx2 + ry2).sum()
1051  }
1052
1053  fn sum_of_distances(&self, p : &[f64]) -> f64 {
1054    self.residuals2(p).map(|(rx2, ry2)| (rx2 + ry2).sqrt()).sum()
1055  }
1056}
1057
1058impl CostFunction for LineFitPoints {
1059  type Param  = Vec<f64>;
1060  type Output = f64;
1061
1062  fn cost(&self, p : &Self::Param) -> Result<Self::Output, argmin::core::Error> {
1063    Ok(self.sum_of_distances(p))
1064  }
1065}
1066
1067//------------------------------------------------------------
1068
1069/// The overlap of two neighbouring TOF paddles, see
1070/// TofPaddleOverlaps
1071#[cfg(feature="database")]
1072#[derive(Debug, Copy, Clone, PartialEq)]
1073pub struct TofPaddleOverlap {
1074  /// Unit vector across both paddles (perpendicular to their
1075  /// principal axis and to their normal)
1076  pub across   : [f32;3],
1077  /// Position of the middle of the overlap along `across` (mm)
1078  pub position : f32,
1079  /// Width of the overlap (mm)
1080  pub width    : f32,
1081}
1082
1083/// Neighbouring TOF paddles of a panel overlap a little across
1084/// their width (about 11 mm). If both paddles of such a pair are
1085/// hit at the same time, the particle went through the overlap,
1086/// which fixes its position across the paddles much better than
1087/// the width of a single paddle (160 mm).
1088///
1089/// The overlaps are found once from the paddle geometry and can
1090/// then be used for all events, see TofEvent::merge_overlapping_hits.
1091#[cfg(feature="database")]
1092#[derive(Debug, Clone, Default)]
1093#[cfg_attr(feature="pybindings", pyclass)]
1094pub struct TofPaddleOverlaps {
1095  /// (paddle id a, paddle id b) with a < b -> their overlap
1096  pub overlaps : BTreeMap<(u8, u8), TofPaddleOverlap>,
1097}
1098
1099#[cfg(feature="database")]
1100impl TofPaddleOverlaps {
1101  /// Paddles further apart than this along their normal do not
1102  /// belong to the same panel (mm)
1103  pub const MAX_NORMAL_DISTANCE : f32 = 60.0;
1104  /// Overlaps narrower than this are ignored (mm)
1105  pub const MIN_WIDTH : f32 = 0.5;
1106  /// Default for the largest time difference of two hits in
1107  /// overlapping paddles to be merged (ns)
1108  pub const DEFAULT_MAX_DT : f32 = 1.0;
1109
1110  /// Find the overlapping pairs: parallel paddles of the same
1111  /// panel whose widths overlap
1112  ///
1113  /// # Arguments:
1114  ///   * paddles : paddle id -> paddle, as from the database
1115  pub fn new(paddles : &HashMap<u8, TofPaddle>) -> Self {
1116    let dot   = |a : [f32;3], b : [f32;3]| a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
1117    let cross = |a : [f32;3], b : [f32;3]| [a[1]*b[2] - a[2]*b[1],
1118                                            a[2]*b[0] - a[0]*b[2],
1119                                            a[0]*b[1] - a[1]*b[0]];
1120    let vec3  = |v : (f32, f32, f32)| [v.0, v.1, v.2];
1121    let mut overlaps = BTreeMap::<(u8, u8), TofPaddleOverlap>::new();
1122    let mut ids : Vec<u8> = paddles.keys().copied().collect();
1123    ids.sort();
1124    for (k, &a) in ids.iter().enumerate() {
1125      for &b in &ids[k+1..] {
1126        let (pa, pb) = (&paddles[&a], &paddles[&b]);
1127        let (na, nb) = (vec3(pa.normal()), vec3(pb.normal()));
1128        let (ra, rb) = (vec3(pa.principal()), vec3(pb.principal()));
1129        if (dot(na, nb).abs() - 1.0).abs() > 1e-3 || (dot(ra, rb).abs() - 1.0).abs() > 1e-3 {
1130          continue;
1131        }
1132        // the database has positions and sizes in cm
1133        let (ca, cb) = (vec3(pa.center_pos()), vec3(pb.center_pos()));
1134        let ca = [10.0*ca[0], 10.0*ca[1], 10.0*ca[2]];
1135        let d  = [10.0*cb[0] - ca[0], 10.0*cb[1] - ca[1], 10.0*cb[2] - ca[2]];
1136        if dot(d, na).abs() > Self::MAX_NORMAL_DISTANCE {
1137          continue;
1138        }
1139        let across = cross(na, ra);
1140        let norm   = dot(across, across).sqrt();
1141        if norm < 0.5 {
1142          // normal or principal axis not set
1143          continue;
1144        }
1145        let across = [across[0]/norm, across[1]/norm, across[2]/norm];
1146        let da     = dot(d, across);
1147        let width  = 5.0*(pa.width + pb.width) - da.abs();
1148        if width < Self::MIN_WIDTH || dot(d, ra).abs() >= 5.0*(pa.length + pb.length) {
1149          continue;
1150        }
1151        let position = dot(ca, across) + da.signum()*(5.0*pa.width - 0.5*width);
1152        overlaps.insert((a, b), TofPaddleOverlap { across, position, width });
1153      }
1154    }
1155    Self { overlaps }
1156  }
1157
1158  /// The overlap of the paddles a and b (in any order), if any
1159  pub fn get(&self, a : u8, b : u8) -> Option<&TofPaddleOverlap> {
1160    self.overlaps.get(&(a.min(b), a.max(b)))
1161  }
1162
1163  pub fn len(&self) -> usize {
1164    self.overlaps.len()
1165  }
1166
1167  pub fn is_empty(&self) -> bool {
1168    self.overlaps.is_empty()
1169  }
1170}
1171
1172#[cfg(feature="database")]
1173#[cfg(feature="pybindings")]
1174#[pymethods]
1175impl TofPaddleOverlaps {
1176  /// Find the overlapping pairs of TOF paddles: parallel paddles
1177  /// of the same panel whose widths overlap
1178  ///
1179  /// # Arguments:
1180  ///   * paddles : dict paddle id -> TofPaddle, e.g. from
1181  ///               TofPaddle.all_as_dict()
1182  #[new]
1183  fn new_py(paddles : HashMap<u8, TofPaddle>) -> Self {
1184    Self::new(&paddles)
1185  }
1186
1187  /// The overlapping pairs (paddle id a, paddle id b), a < b
1188  #[getter]
1189  #[pyo3(name="pairs")]
1190  fn get_pairs_py(&self) -> Vec<(u8, u8)> {
1191    self.overlaps.keys().copied().collect()
1192  }
1193
1194  /// The overlap of the paddles a and b as (unit vector across
1195  /// the paddles, position of the middle of the overlap along
1196  /// it in mm, width of the overlap in mm), or None
1197  #[pyo3(name="overlap")]
1198  fn overlap_py(&self, a : u8, b : u8) -> Option<((f32, f32, f32), f32, f32)> {
1199    self.get(a, b).map(|o| ((o.across[0], o.across[1], o.across[2]), o.position, o.width))
1200  }
1201
1202  fn __len__(&self) -> usize {
1203    self.len()
1204  }
1205
1206  fn __repr__(&self) -> String {
1207    format!("<TofPaddleOverlaps: {} overlapping pairs>", self.len())
1208  }
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213  use super::*;
1214
1215  /// points on the line through (1,2,0) with slopes
1216  /// tx = 0.5, ty = -0.25
1217  fn line_points() -> (Vec<f32>, Vec<f32>, Vec<f32>) {
1218    let zs : Vec<f32> = vec![-100.0, -50.0, 0.0, 30.0, 80.0, 120.0];
1219    let xs = zs.iter().map(|z| 1.0 + 0.5*z).collect();
1220    let ys = zs.iter().map(|z| 2.0 - 0.25*z).collect();
1221    (xs, ys, zs)
1222  }
1223
1224  #[test]
1225  fn linefit_exact_line() {
1226    let (xs, ys, zs) = line_points();
1227    let lf = LineFit::fit(&xs, &ys, &zs, None, None).unwrap();
1228    assert_eq!(lf.status, FitStatus::Success);
1229    assert_eq!(lf.ndof, 8);
1230    assert!((lf.tx - 0.5).abs()  < 1e-5);
1231    assert!((lf.ty + 0.25).abs() < 1e-5);
1232    let (x, y, _) = lf.eval(0.0);
1233    assert!((x - 1.0).abs() < 1e-4);
1234    assert!((y - 2.0).abs() < 1e-4);
1235    assert!(lf.chi2 < 1e-6);
1236  }
1237
1238  #[test]
1239  fn linefit_not_enough_points() {
1240    assert!(LineFit::fit(&[1.0], &[1.0], &[1.0], None, None).is_none());
1241    // all points at the same z
1242    assert!(LineFit::fit(&[1.0, 2.0], &[1.0, 2.0], &[5.0, 5.0], None, None).is_none());
1243  }
1244
1245  #[test]
1246  fn linefit_chi2_is_minimal() {
1247    let (mut xs, mut ys, zs) = line_points();
1248    xs[1] += 7.0;
1249    ys[3] -= 4.0;
1250    let errs = vec![3.0f32; xs.len()];
1251    let lf   = LineFit::fit(&xs, &ys, &zs, Some(&errs), Some(&errs)).unwrap();
1252    let pts  = LineFitPoints::new(&xs, &ys, &zs, Some(&errs), Some(&errs)).unwrap();
1253    let best = [lf.x0 as f64, lf.y0 as f64, lf.tx as f64, lf.ty as f64];
1254    let chi2 = pts.chi2(&best);
1255    for k in 0..4 {
1256      for delta in [-1e-2, 1e-2] {
1257        let mut p = best;
1258        p[k] += delta;
1259        assert!(pts.chi2(&p) > chi2);
1260      }
1261    }
1262  }
1263
1264  #[test]
1265  fn linefit_sum_of_distances_outlier() {
1266    let (mut xs, ys, zs) = line_points();
1267    // one large outlier, which pulls the chi2 fit
1268    // considerably more than the sum of distances
1269    xs[2] += 200.0;
1270    let lf_chi2 = LineFit::fit(&xs, &ys, &zs, None, None).unwrap();
1271    let lf_dist = LineFit::fit_sum_of_distances(&xs, &ys, &zs, None, None).unwrap();
1272    assert_eq!(lf_dist.status, FitStatus::Success);
1273    assert!(lf_dist.cost <= LineFitPoints::new(&xs, &ys, &zs, None, None).unwrap()
1274                            .sum_of_distances(&[lf_chi2.x0 as f64, lf_chi2.y0 as f64,
1275                                                lf_chi2.tx as f64, lf_chi2.ty as f64]) as f32);
1276    assert!((lf_dist.tx - 0.5).abs() < (lf_chi2.tx - 0.5).abs() + 1e-6);
1277    assert!((lf_dist.eval(0.0).0 - 1.0).abs() < (lf_chi2.eval(0.0).0 - 1.0).abs());
1278  }
1279
1280  /// A vertical track along the z axis: two TOF hits, which
1281  /// are 30 mm off (TOF position resolution), followed by
1282  /// tracker hits on the track and one far away
1283  fn track_with_outlier() -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
1284    let mut xs = vec![30.0, -30.0];
1285    let mut zs = vec![1000.0, 0.0];
1286    let mut ts = vec![0.0, 3.5];
1287    for k in 1..10 {
1288      xs.push(0.0);
1289      zs.push(100.0*k as f32);
1290      ts.push(f32::NAN);
1291    }
1292    // outlier
1293    xs.push(100.0);
1294    zs.push(500.0);
1295    ts.push(f32::NAN);
1296    let ys = vec![0.0; xs.len()];
1297    (xs, ys, zs, ts)
1298  }
1299
1300  #[test]
1301  fn linefit_distance() {
1302    let (xs, ys, zs) = line_points();
1303    let lf = LineFit::fit(&xs, &ys, &zs, None, None).unwrap();
1304    assert!(lf.distance(xs[2], ys[2], zs[2]) < 1e-4);
1305    // (1, 2, 0) is perpendicular to the direction (0.5, -0.25, 1)
1306    // of the line, which goes through (1, 2, 0)
1307    assert!((lf.distance(2.0, 4.0, 0.0) - 5.0f32.sqrt()).abs() < 1e-4);
1308    // a point on the z axis of a vertical line
1309    let lf = LineFit::fit(&[0.0, 0.0], &[0.0, 0.0], &[0.0, 1.0], None, None).unwrap();
1310    assert!((lf.distance(3.0, 4.0, 17.0) - 5.0).abs() < 1e-5);
1311  }
1312
1313  #[test]
1314  fn linefit_cleaned_rejects_outlier() {
1315    let (xs, ys, zs, ts) = track_with_outlier();
1316    let cleaned = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &LineFitCleaning::new(20.0)).unwrap();
1317    assert_eq!(cleaned.seed, (0, 1));
1318    assert!(cleaned.converged);
1319    // the tracker hits at z = 100 and 900 are 24 mm from the
1320    // first line through the TOF hits and only get accepted
1321    // after the first fit
1322    assert!(cleaned.iterations >= 2);
1323    let mut expected = vec![true; xs.len()];
1324    *expected.last_mut().unwrap() = false;
1325    assert_eq!(cleaned.accepted, expected);
1326    assert_eq!(cleaned.fit.npoints, 11);
1327    // the track is vertical, only the TOF hits pull the
1328    // line away from it
1329    assert!(cleaned.fit.tx.abs() < 0.03);
1330    assert!(cleaned.fit.ty.abs() < 1e-6);
1331  }
1332
1333  #[test]
1334  fn linefit_cleaned_large_radius_is_plain_fit() {
1335    let (xs, ys, zs, ts) = track_with_outlier();
1336    let cleaned = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &LineFitCleaning::new(1e6)).unwrap();
1337    let plain   = LineFit::fit(&xs, &ys, &zs, None, None).unwrap();
1338    assert!(cleaned.accepted.iter().all(|a| *a));
1339    assert_eq!(cleaned.iterations, 1);
1340    assert_eq!(cleaned.fit, plain);
1341  }
1342
1343  #[test]
1344  fn linefit_cleaned_needs_two_tof_hits() {
1345    let (xs, ys, zs, mut ts) = track_with_outlier();
1346    ts[1] = f32::NAN;
1347    assert!(LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &LineFitCleaning::new(20.0)).is_none());
1348    // the seed are the first two hits with a time
1349    ts[3] = 1.0;
1350    let cleaned = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &LineFitCleaning::new(20.0)).unwrap();
1351    assert_eq!(cleaned.seed, (0, 3));
1352  }
1353
1354  #[test]
1355  fn linefit_cleaning_next_radius() {
1356    let mut cleaning = LineFitCleaning::new(300.0);
1357    // no shrinking by default
1358    assert_eq!(cleaning.next_radius(300.0), 300.0);
1359    cleaning.final_radius = 50.0;
1360    let mut radii = vec![300.0];
1361    for _ in 0..4 {
1362      radii.push(cleaning.next_radius(*radii.last().unwrap()));
1363    }
1364    assert_eq!(radii, vec![300.0, 150.0, 75.0, 50.0, 50.0]);
1365    // a factor outside of (0, 1) goes to the final radius
1366    for factor in [0.0, 1.0, 2.0] {
1367      cleaning.shrink_factor = factor;
1368      assert_eq!(cleaning.next_radius(300.0), 50.0);
1369    }
1370  }
1371
1372  /// A vertical track (x = y = 0) through an outer TOF hit at
1373  /// z = 2000, an inner one at z = 1200 and 7 tracker layers,
1374  /// plus two hits 120 mm off the track at z = 500 and 700
1375  fn track_for_shrinking() -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
1376    let mut zs : Vec<f32> = vec![2000.0, 1200.0];
1377    zs.extend((0..7).map(|k| 400.0 + 100.0*k as f32));
1378    let mut xs = vec![0.0; zs.len()];
1379    let mut ts = vec![f32::NAN; zs.len()];
1380    ts[0] = 0.0;
1381    ts[1] = 3.0;
1382    xs.extend([120.0, 120.0]);
1383    zs.extend([500.0, 700.0]);
1384    ts.extend([f32::NAN, f32::NAN]);
1385    let ys = vec![0.0; zs.len()];
1386    (xs, ys, zs, ts)
1387  }
1388
1389  #[test]
1390  fn linefit_cleaned_shrinking_cylinder() {
1391    let (xs, ys, zs, ts) = track_for_shrinking();
1392    let n = xs.len();
1393    // a wide cylinder accepts the hits off the track
1394    let mut cleaning = LineFitCleaning::new(300.0);
1395    let wide = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &cleaning).unwrap();
1396    assert!(wide.accepted.iter().all(|a| *a));
1397    assert!(wide.converged);
1398    assert_eq!(wide.radius, 300.0);
1399    assert!(wide.fit.tx.abs() > 0.01);
1400    // shrinking 300 -> 150 -> 75 -> 50 mm: the line pulled
1401    // towards them is about 100 mm away from them, so they
1402    // are dropped at 75 mm and the fit is exact
1403    cleaning.final_radius = 50.0;
1404    let shrunk = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &cleaning).unwrap();
1405    assert!(shrunk.accepted[..n-2].iter().all(|a| *a));
1406    assert!(!shrunk.accepted[n-2] && !shrunk.accepted[n-1]);
1407    assert!(shrunk.converged);
1408    assert_eq!(shrunk.radius, 50.0);
1409    // a fit at 300 and at 75 mm, at 150 and 50 mm the hits
1410    // did not change
1411    assert_eq!(shrunk.iterations, 2);
1412    assert!(shrunk.fit.tx.abs() < 1e-4);
1413    assert_eq!(shrunk.fit.status, FitStatus::Success);
1414  }
1415
1416  #[test]
1417  fn linefit_cleaned_fallback_previous_iteration() {
1418    // three hits, which all fit into 400 mm, but not into 1 mm
1419    // around the line through them
1420    let xs = vec![0.0, 100.0, -300.0];
1421    let ys = vec![0.0, 0.0, 0.0];
1422    let zs = vec![2000.0, 1200.0, 1600.0];
1423    let ts = vec![0.0, 3.0, f32::NAN];
1424    let mut cleaning = LineFitCleaning::new(400.0);
1425    cleaning.final_radius  = 1.0;
1426    cleaning.shrink_factor = 0.0;
1427    let cleaned = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &cleaning).unwrap();
1428    assert_eq!(cleaned.fit.status, FitStatus::FallbackPreviousIteration);
1429    assert!(!cleaned.converged);
1430    assert_eq!(cleaned.radius, 400.0);
1431    assert_eq!(cleaned.iterations, 1);
1432    assert_eq!(cleaned.accepted, vec![true, true, true]);
1433    // the same as the fit to all three
1434    let all = LineFit::fit(&xs, &ys, &zs, None, None).unwrap();
1435    assert_eq!((cleaned.fit.tx, cleaned.fit.x0), (all.tx, all.x0));
1436  }
1437
1438  fn tof_hit(paddle_id : u8, x : f32, z : f32, t : f32) -> TofHit {
1439    let mut h = TofHit::new();
1440    h.paddle_id = paddle_id;
1441    h.x         = x;
1442    h.y         = 0.0;
1443    h.z         = z;
1444    h.event_t0  = t;
1445    // the hits bypass set_paddle, but get_edep needs
1446    // the paddle length (mm)
1447    h.paddle_len = 1800.0;
1448    h
1449  }
1450
1451  /// The vertical track of track_with_outlier as an event.
1452  /// The first two TOF hits in time are both outer: one on
1453  /// the track (umbrella) and one far off (cortina).
1454  fn event_with_two_outer_hits() -> TelemetryEvent {
1455    let mut ev = TelemetryEvent::new();
1456    ev.tof_event.hits = vec![tof_hit(70, 30.0, 1000.0, 0.0),
1457                             tof_hit(120, 500.0, 800.0, 1.0),
1458                             tof_hit(10, -30.0, 0.0, 3.5)];
1459    ev.tof_event.paddles_set = true;
1460    for k in 1..10 {
1461      let mut h = TrackerHit::new();
1462      // tracker coordinates are in cm
1463      h.z = 10.0*k as f32;
1464      h.has_coordinates = true;
1465      ev.tracker_hits.push(h);
1466    }
1467    // a tracker hit without coordinates (at the origin, which
1468    // is close to the track)
1469    ev.tracker_hits.push(TrackerHit::new());
1470    ev
1471  }
1472
1473  #[test]
1474  fn linefit_cleaned_event_seeds_outer_and_inner() {
1475    let ev = event_with_two_outer_hits();
1476    let cleaned = LineFit::fit_cleaned_event(&ev, &LineFitCleaning::new(20.0)).unwrap();
1477    // the umbrella and the cube hit, not the two first in time
1478    assert_eq!(cleaned.seed, (0, 2));
1479    assert!(cleaned.converged);
1480    let mut expected = vec![true; 3 + 10];
1481    expected[1]  = false;
1482    expected[12] = false;
1483    assert_eq!(cleaned.accepted, expected);
1484    assert!(cleaned.fit.tx.abs() < 0.03);
1485    // seeding with the first two hits in time goes wrong:
1486    // the line through the umbrella and the cortina hit
1487    // misses all tracker hits
1488    let tof = ev.tof_event.get_pointcloud().unwrap();
1489    let pts : Vec<_> = tof.into_iter().chain(ev.get_tracker_pointcloud()).collect();
1490    let col = |f : fn(&(f32, f32, f32, f32, f32)) -> f32| -> Vec<f32> { pts.iter().map(f).collect() };
1491    let (xs, ys, zs, ts) = (col(|p| p.0), col(|p| p.1), col(|p| p.2), col(|p| p.3));
1492    let by_time = LineFit::fit_cleaned(&xs, &ys, &zs, &ts, None, None, &LineFitCleaning::new(20.0));
1493    let by_time = by_time.unwrap();
1494    assert_eq!(by_time.seed, (0, 1));
1495    assert_eq!(by_time.accepted.iter().filter(|a| **a).count(), 2);
1496  }
1497
1498  #[test]
1499  fn linefit_cleaned_event_needs_outer_and_inner() {
1500    let mut ev = event_with_two_outer_hits();
1501    ev.tof_event.paddles_set = false;
1502    assert!(LineFit::fit_cleaned_event(&ev, &LineFitCleaning::new(20.0)).is_none());
1503    ev.tof_event.paddles_set = true;
1504    // no inner hit
1505    ev.tof_event.hits.pop();
1506    assert!(LineFit::fit_cleaned_event(&ev, &LineFitCleaning::new(20.0)).is_none());
1507  }
1508}
1509
1510#[cfg(test)]
1511#[cfg(feature="database")]
1512mod overlap_tests {
1513  use super::*;
1514
1515  /// a horizontal paddle along y, 180 x 16 cm, centered at (x, 0, z) (cm)
1516  fn paddle(pid : u8, x : f32, z : f32) -> TofPaddle {
1517    let mut p = TofPaddle::new();
1518    p.paddle_id = pid as i16;
1519    p.width     = 16.0;
1520    p.length    = 180.0;
1521    p.height    = 0.635;
1522    p.normal_z  = 1.0;
1523    p.global_pos_x_l0   = x;
1524    p.global_pos_z_l0   = z;
1525    p.global_pos_x_l0_A = x;
1526    p.global_pos_y_l0_A = -90.0;
1527    p.global_pos_z_l0_A = z;
1528    p.global_pos_x_l0_B = x;
1529    p.global_pos_y_l0_B = 90.0;
1530    p.global_pos_z_l0_B = z;
1531    p
1532  }
1533
1534  /// three paddles of a panel, neighbours overlapping by 10.9 mm
1535  /// (staggered by 0.7 cm), and one paddle far away
1536  fn paddles() -> HashMap<u8, TofPaddle> {
1537    HashMap::from([(1u8, paddle(1, 0.0, 0.0)), (2, paddle(2, 14.91, 0.7)),
1538                   (3, paddle(3, 29.82, 0.0)), (4, paddle(4, 0.0, 100.0))])
1539  }
1540
1541  fn hit(pid : u8, x : f32, y : f32, z : f32, t : f32) -> TofHit {
1542    let mut h = TofHit::new();
1543    h.paddle_id = pid;
1544    (h.x, h.y, h.z) = (x, y, z);
1545    h.event_t0 = t;
1546    h
1547  }
1548
1549  #[test]
1550  fn tof_paddle_overlaps_geometry() {
1551    let ov = TofPaddleOverlaps::new(&paddles());
1552    assert_eq!(ov.overlaps.keys().copied().collect::<Vec<_>>(), vec![(1, 2), (2, 3)]);
1553    let o = ov.get(2, 1).unwrap();
1554    assert!((o.width - 10.9).abs() < 1e-3);
1555    // across is +-x, the middle of the overlap at x = 80 - 5.45 mm
1556    assert!((o.across[0].abs() - 1.0).abs() < 1e-6);
1557    assert!((o.position*o.across[0] - 74.55).abs() < 1e-3);
1558  }
1559
1560  #[test]
1561  fn tofevent_merge_overlapping_hits() {
1562    let ov = TofPaddleOverlaps::new(&paddles());
1563    let mut ev = TofEvent::new();
1564    ev.hits.push(hit(1, 10.0, 300.0, 0.0, 0.0));
1565    ev.hits.push(hit(2, 140.0, 320.0, 7.0, 0.4));
1566    ev.hits.push(hit(4, 0.0, 0.0, 1000.0, 5.0));
1567    // hit times not normalized, nothing happens
1568    assert_eq!(ev.merge_overlapping_hits(&ov, 1.0), 0);
1569    assert_eq!(ev.hits[0].x, 10.0);
1570    ev.hit_times_normalized = true;
1571    assert_eq!(ev.merge_overlapping_hits(&ov, 1.0), 1);
1572    // both hits moved to the middle of the overlap across the
1573    // paddles, along the paddles and the normal nothing changes
1574    for (h, y, z) in [(&ev.hits[0], 300.0, 0.0), (&ev.hits[1], 320.0, 7.0)] {
1575      assert!((h.x - 74.55).abs() < 1e-3);
1576      assert_eq!((h.y, h.z), (y, z));
1577    }
1578    assert_eq!((ev.hits[2].x, ev.hits[2].y, ev.hits[2].z), (0.0, 0.0, 1000.0));
1579    // merging again does not change anything
1580    assert_eq!(ev.merge_overlapping_hits(&ov, 1.0), 1);
1581    assert!((ev.hits[0].x - 74.55).abs() < 1e-3);
1582    // too far apart in time
1583    let mut late = TofEvent::new();
1584    late.hits.push(hit(1, 10.0, 300.0, 0.0, 0.0));
1585    late.hits.push(hit(2, 140.0, 320.0, 7.0, 1.5));
1586    late.hit_times_normalized = true;
1587    assert_eq!(late.merge_overlapping_hits(&ov, 1.0), 0);
1588    assert_eq!(late.hits[1].x, 140.0);
1589  }
1590}