1pub 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
34pub(crate) const C_LIGHT_MM_NS : f64 = 299.792458;
36
37#[derive(Debug, Clone, Default)]
42pub struct SearchlightHits {
43 pub pos : Vec<DVec3>,
45 pub err : Vec<f64>,
47 pub t : Vec<f64>,
49 pub e : Vec<f64>,
51 pub is_tof : Vec<bool>,
52 pub inner : Vec<bool>,
54 pub paddle_id : Vec<u8>,
56 pub measured : Vec<i8>,
59 pub half_chord : Vec<f64>,
61 pub ntof : usize,
63}
64
65impl SearchlightHits {
66 pub const ERR : f64 = LINEFIT_DEFAULT_ERR_XY as f64;
68
69 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 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 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 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 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 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
186pub(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#[derive(Debug, Clone)]
209#[cfg_attr(feature="pybindings", pyclass)]
210pub struct SearchlightSettings {
211 pub cleaning : LineFitCleaning,
213 pub edep_min : f64,
216 pub trk_e_min : f64,
219 pub vertex_err : f64,
221 pub use_vertex : bool,
222 pub use_tracker : bool,
223 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 pub independent_vertex : bool,
239 pub use_tracks : bool,
243 pub use_timing : bool,
246 pub tracks : SearchlightTrackSettings,
247 pub timing : SearchlightTimingSettings,
248 pub weights : Vec<f64>,
252}
253
254impl SearchlightSettings {
255 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 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 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 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#[derive(Debug, Clone, Default)]
324#[cfg_attr(feature="pybindings", pyclass)]
325pub struct SearchlightResult {
326 pub seed : Option<(usize, usize)>,
328 pub flags : (bool, bool),
330 pub vertex : Option<DVec3>,
333 pub independent_vertex : Option<DVec3>,
336 pub vertex_quality : Option<SearchlightVertexQuality>,
338 pub candidates : Vec<SearchlightCandidateFit>,
340 pub best : Option<usize>,
341}
342
343impl SearchlightResult {
344 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#[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 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 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 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 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 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 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 (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 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 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#[cfg(test)]
546mod tests {
547 use super::*;
548 use std::collections::HashSet;
549
550 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 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 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 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 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 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 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 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 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 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 assert!(p.u.z < 0.0);
671 assert_eq!(p.features.len(), SEARCHLIGHT_N_FEATURES);
672 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 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 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 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 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 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 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 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 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}