1use std::collections::HashSet;
18
19use glam::DVec3;
20
21use crate::prelude::*;
22
23use super::*;
24
25#[derive(Debug, Clone)]
27pub struct SearchlightTrackSettings {
28 pub sigma_strip : f64,
30 pub sigma_ms : f64,
33 pub tof_err : f64,
35 pub n_sigma : f64,
38 pub along_margin : f64,
40 pub loose_factor : f64,
43 pub min_dz : f64,
45 pub min_hits : usize,
46 pub min_trk : usize,
48 pub tof_weight : f64,
50 pub max_chi2_ndf : f64,
51 pub tof_pairs : bool,
53 pub theta_ms : f64,
56 pub sigma0_min : f64,
58}
59
60impl Default for SearchlightTrackSettings {
61 fn default() -> Self {
62 Self {
63 sigma_strip : 3.5,
64 sigma_ms : 5.0,
65 tof_err : 30.0,
66 n_sigma : 3.0,
67 along_margin : 10.0,
68 loose_factor : 2.5,
69 min_dz : 50.0,
70 min_hits : 3,
71 min_trk : 2,
72 tof_weight : 0.7,
73 max_chi2_ndf : 10.0,
74 tof_pairs : true,
75 theta_ms : 0.1,
76 sigma0_min : 10.0,
77 }
78 }
79}
80
81#[derive(Debug, Clone)]
83pub struct SearchlightTimingSettings {
84 pub window : f64,
86 pub beta_sec : f64,
88 pub beta_min : f64,
90 pub margin : f64,
92 pub w_time : f64,
94}
95
96impl Default for SearchlightTimingSettings {
97 fn default() -> Self {
98 Self {
99 window : 0.5,
100 beta_sec : 0.95,
101 beta_min : 0.1,
102 margin : 0.5,
103 w_time : 1.0,
104 }
105 }
106}
107
108struct HitWindows {
110 ex : Vec<f64>,
111 ey : Vec<f64>,
112 wx : Vec<f64>,
113 wy : Vec<f64>,
114}
115
116fn hit_windows(hits : &SearchlightHits, s : &SearchlightTrackSettings) -> HitWindows {
117 let n = hits.len();
118 let wt = s.n_sigma*s.tof_err.hypot(s.sigma_ms);
119 let mut w = HitWindows { ex : vec![s.tof_err; n], ey : vec![s.tof_err; n], wx : vec![wt; n], wy : vec![wt; n] };
120 for k in 0..n {
121 if hits.measured[k] < 0 {
122 continue;
123 }
124 let e_m = s.sigma_strip;
125 let e_a = 2.0*hits.half_chord[k]/12f64.sqrt();
126 let w_m = s.n_sigma*e_m.hypot(s.sigma_ms);
127 let w_a = hits.half_chord[k] + s.along_margin;
128 if hits.measured[k] == 0 {
129 (w.ex[k], w.ey[k], w.wx[k], w.wy[k]) = (e_m, e_a, w_m, w_a);
130 } else {
131 (w.ex[k], w.ey[k], w.wx[k], w.wy[k]) = (e_a, e_m, w_a, w_m);
132 }
133 }
134 w
135}
136
137fn inliers(hits : &SearchlightHits, a : DVec3, u : DVec3, w : &HitWindows, idx : &[usize], factor : f64) -> Vec<usize> {
140 if u.z.abs() < 1e-6 {
141 return vec![];
142 }
143 idx.iter().copied().filter(|&k| {
144 let p = hits.pos[k];
145 let t = (p.z - a.z)/u.z;
146 (p.x - (a.x + t*u.x)).abs() <= factor*w.wx[k] && (p.y - (a.y + t*u.y)).abs() <= factor*w.wy[k]
147 }).collect()
148}
149
150fn fit(hits : &SearchlightHits, w : &HitWindows, idx : &[usize]) -> Option<(LineFit, DVec3, DVec3)> {
152 let xs : Vec<f32> = idx.iter().map(|&k| hits.pos[k].x as f32).collect();
153 let ys : Vec<f32> = idx.iter().map(|&k| hits.pos[k].y as f32).collect();
154 let zs : Vec<f32> = idx.iter().map(|&k| hits.pos[k].z as f32).collect();
155 let ex : Vec<f32> = idx.iter().map(|&k| w.ex[k] as f32).collect();
156 let ey : Vec<f32> = idx.iter().map(|&k| w.ey[k] as f32).collect();
157 let f = LineFit::fit(&xs, &ys, &zs, Some(&ex), Some(&ey))?;
158 if ![f.x0, f.y0, f.tx, f.ty].iter().all(|x| x.is_finite()) {
159 return None;
160 }
161 let a = DVec3::new(f.x0 as f64, f.y0 as f64, f.z0 as f64);
162 let u = DVec3::new(f.tx as f64, f.ty as f64, 1.0).normalize();
163 Some((f, a, u))
164}
165
166#[derive(Debug, Clone)]
168pub struct SearchlightTrack {
169 pub line : SearchlightLine,
170 pub hits : Vec<usize>,
171 pub ntrk : usize,
172 pub ntof : usize,
173 pub chi2n : f64,
174}
175
176fn track_candidate(hits : &SearchlightHits, w : &HitWindows, free : &[usize], seed : (usize, usize), s : &SearchlightTrackSettings)
177 -> Option<(LineFit, Vec<usize>, usize, usize, f64)> {
178 let d = hits.pos[seed.1] - hits.pos[seed.0];
179 if d.z.abs() < s.min_dz {
180 return None;
181 }
182 let mut idx = inliers(hits, hits.pos[seed.0], d.normalize(), w, free, s.loose_factor);
183 for _ in 0..3 {
184 if idx.len() < s.min_hits {
185 return None;
186 }
187 let (_, a, u) = fit(hits, w, &idx)?;
188 let new = inliers(hits, a, u, w, free, 1.0);
189 if new.iter().collect::<HashSet<_>>() == idx.iter().collect::<HashSet<_>>() {
190 break;
191 }
192 idx = new;
193 }
194 if idx.len() < s.min_hits {
195 return None;
196 }
197 let trk : Vec<usize> = idx.iter().copied().filter(|&k| !hits.is_tof[k]).collect();
198 let layers : HashSet<i64> = trk.iter().map(|&k| hits.pos[k].z.round() as i64).collect();
199 if layers.len() < s.min_trk {
200 return None;
201 }
202 let (f, _, _) = fit(hits, w, &idx)?;
203 let chi2n = f.chi2 as f64/(f.ndof.max(1) as f64);
204 if chi2n > s.max_chi2_ndf {
205 return None;
206 }
207 let ntrk = trk.len();
208 let ntof = idx.len() - ntrk;
209 Some((f, idx, ntrk, ntof, chi2n))
210}
211
212fn track_line(f : &LineFit, hits : Vec<usize>, s : &SearchlightTrackSettings) -> SearchlightLine {
215 let a = DVec3::new(f.x0 as f64, f.y0 as f64, f.z0 as f64);
216 let u = DVec3::new(f.tx as f64, f.ty as f64, 1.0).normalize();
217 let theta = ((f.tx_err as f64).hypot(f.ty_err as f64)/2f64.sqrt()).hypot(s.theta_ms);
218 let sigma0 = s.sigma0_min.max((f.x0_err as f64).hypot(f.y0_err as f64)/2f64.sqrt());
219 SearchlightLine { a, u, hits, sigma0, theta }
220}
221
222pub(crate) fn find_tracks(hits : &SearchlightHits,
230 free : &[usize],
231 s : &SearchlightTrackSettings,
232 vs : &SearchlightVertexSettings,
233 exclude : &[usize]) -> Vec<SearchlightTrack> {
234 let w = hit_windows(hits, s);
235 let mut free : Vec<usize> = free.to_vec();
236 free.sort();
237 let pairs = if s.tof_pairs { secondary_pairs(hits, vs, exclude) } else { vec![] };
238 let mut tracks = Vec::<SearchlightTrack>::new();
239 while free.len() >= s.min_hits {
240 let fs : HashSet<usize> = free.iter().copied().collect();
241 let trk : Vec<usize> = free.iter().copied().filter(|&k| !hits.is_tof[k]).collect();
242 let tof : Vec<usize> = free.iter().copied().filter(|&k| hits.is_tof[k]).collect();
243 let mut seeds = Vec::<(usize, usize)>::new();
244 for x in 0..trk.len() {
245 for y in x+1..trk.len() {
246 seeds.push((trk[x], trk[y]));
247 }
248 for &k in &tof {
249 seeds.push((k, trk[x]));
250 }
251 }
252 for &(pi, po) in &pairs {
253 if fs.contains(&pi) && fs.contains(&po) {
254 seeds.push((po, pi));
255 }
256 }
257 let mut best : Option<((f64, f64), (LineFit, Vec<usize>, usize, usize, f64))> = None;
258 for sd in seeds {
259 let Some(c) = track_candidate(hits, &w, &free, sd, s) else {
260 continue;
261 };
262 let key = (c.2 as f64 + s.tof_weight*c.3 as f64, -c.4);
263 let better = match &best {
264 None => true,
265 Some((k, _)) => key.0 > k.0 || (key.0 == k.0 && key.1 > k.1),
266 };
267 if better {
268 best = Some((key, c));
269 }
270 }
271 let Some((_, (f, idx, ntrk, ntof, chi2n))) = best else {
272 break;
273 };
274 let used : HashSet<usize> = idx.iter().copied().collect();
275 free.retain(|k| !used.contains(k));
276 tracks.push(SearchlightTrack { line : track_line(&f, idx.clone(), s), hits : idx, ntrk, ntof, chi2n });
277 }
278 tracks
279}
280
281pub(crate) fn timing_score(v : DVec3, hits : &SearchlightHits, anchor : usize, exclude : &HashSet<usize>, s : &SearchlightTimingSettings) -> (usize, f64) {
289 let ta = hits.t[anchor];
290 let da = (v - hits.pos[anchor]).length();
291 let lo = ta + da/C_LIGHT_MM_NS - s.margin;
292 let hi = ta + da/(s.beta_min*C_LIGHT_MM_NS) + s.margin;
293 let mut est = Vec::<f64>::new();
294 for k in 0..hits.ntof {
295 if exclude.contains(&k) || !hits.t[k].is_finite() || hits.t[k] <= ta {
296 continue;
297 }
298 let tv = hits.t[k] - (hits.pos[k] - v).length()/(s.beta_sec*C_LIGHT_MM_NS);
299 if lo <= tv && tv <= hi {
300 est.push(tv);
301 }
302 }
303 if est.is_empty() {
304 return (0, f64::NAN);
305 }
306 est.sort_by(|a, b| a.total_cmp(b));
307 let (mut best, mut t0, mut j) = (0usize, f64::NAN, 0usize);
309 for k in 0..est.len() {
310 while est[k] - est[j] > s.window {
311 j += 1;
312 }
313 if k - j + 1 > best {
314 best = k - j + 1;
315 let g = &est[j..=k];
316 let mut g = g.to_vec();
317 g.sort_by(|a, b| a.total_cmp(b));
318 let m = g.len();
319 t0 = if m % 2 == 1 { g[m/2] } else { 0.5*(g[m/2 - 1] + g[m/2]) };
320 }
321 }
322 (best, t0)
323}
324
325pub type SearchlightVertexQuality = [f64; 4];
329
330pub(crate) fn independent_vertex(hits : &SearchlightHits, s : &SearchlightSettings, seed : (usize, usize))
340 -> Option<Option<(DVec3, SearchlightVertexQuality)>> {
341 let (o, i) = seed;
342 let vs = &s.vertex;
343 let seed_ok = hits.e[o] >= vs.seed_edep_min && hits.e[i] >= vs.seed_edep_min && hits.t[o] < hits.t[i];
344 let all : Vec<usize> = (0..hits.len()).collect();
345 let (_, _, prim) = fit_line(hits, &all, (o, i), &s.cleaning)?;
346 if !seed_ok {
347 return None;
348 }
349 let used : HashSet<usize> = prim.iter().copied().collect();
350 let tracks = if s.use_tracks {
351 let free : Vec<usize> = all.iter().copied().filter(|k| !used.contains(k) && *k != o).collect();
352 find_tracks(hits, &free, &s.tracks, vs, &[o])
353 } else {
354 vec![]
355 };
356 let points = e_point(hits, vs);
357 let lines : Vec<SearchlightLine> = tracks.iter().map(|t| t.line.clone()).collect();
358 let ntracks = tracks.len() as f64;
359 let timing = |v : DVec3| if s.use_timing { timing_score(v, hits, i, &used, &s.timing).0 } else { 0 };
360 let w_time = if s.use_timing { s.timing.w_time } else { 0.0 };
361 let mut best : Option<((f64, f64), DVec3, usize, usize)> = None;
362 for (v, ncomp, chi2) in vertex_candidates(&lines, &points, hits, vs) {
363 let nt = timing(v);
364 let key = (ncomp as f64 + w_time*nt as f64, -chi2);
365 let better = match &best {
366 None => true,
367 Some((k, _, _, _)) => key.0 > k.0 || (key.0 == k.0 && key.1 > k.1),
368 };
369 if better {
370 best = Some((key, v, ncomp, nt));
371 }
372 }
373 if let Some((_, v, ncomp, nt)) = best {
374 return Some(Some((v, [nt as f64, ncomp as f64, 1.0, ntracks])));
375 }
376 if let Some(&(p, _)) = points.first() {
377 return Some(Some((p, [timing(p) as f64, 1.0, 0.0, ntracks])));
378 }
379 Some(None)
380}