Skip to main content

gondola_core/events/
tof_hit.rs

1// This file is part of gaps-online-software and published 
2// under the GPLv3 license
3
4use crate::prelude::*;
5use std::f32::consts::PI;
6
7/// Waveform peak
8///
9/// Helper to form TofHits
10#[derive(Debug,Copy,Clone,PartialEq)]
11pub struct Peak {
12  pub paddle_end_id : u16,
13  pub time          : f32,
14  pub charge        : f32,
15  pub height        : f32
16}
17
18impl Peak {
19  pub fn new() -> Self {
20    Self {
21      // but why??
22      paddle_end_id : 40,
23      time          : 0.0,
24      charge        : 0.0,
25      height        : 0.0,
26    }
27  }
28}
29
30impl Default for Peak {
31  fn default() -> Self {
32    Self::new()
33  }
34}
35
36impl fmt::Display for Peak {
37  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38    write!(f, "<Peak:
39  p_end_id : {:.2} 
40  time // charge // height    : {:.2} // {:.2} // {:.2}>", 
41            self.paddle_end_id,
42            self.time,
43            self.charge,
44            self.height)
45  }
46}
47
48//----------------------------------------------------------------
49
50/// An extracted hit from a TofPaddle, as extracted by the 
51/// online software and provided algorithm
52/// (in v0.11 algorithm is provided by J.Zweerink)
53///
54/// A TofHit holds the information for an extracted single 
55/// hit on a peak, which is defined by a peak in at least one 
56/// of the two waveforms. 
57/// The TofHit holds extracted information for both of the 
58/// waveforms, only if both are available a position reconstruction
59/// on the paddle can be attempted.
60///
61/// A and B are the different ends of the paddle
62#[derive(Debug,Copy,Clone,PartialEq)]
63#[cfg_attr(feature = "pybindings", pyclass)]
64pub struct TofHit {
65  
66  // We currently have 3 bytes to spare
67
68  /// The ID of the paddle in TOF notation
69  /// (1-160)
70  pub paddle_id      : u8,
71  pub time_a         : f16,
72  pub time_b         : f16,
73  pub peak_a         : f16,
74  pub peak_b         : f16,
75  pub charge_a       : f16,
76  pub charge_b       : f16,
77  pub version        : ProtocolVersion,
78  // use event quality for hit quality
79  pub quality        : EventQuality, 
80  pub baseline_a     : f16,
81  pub baseline_a_rms : f16,
82  pub baseline_b     : f16,
83  pub baseline_b_rms : f16,
84  // phase of the sine fit
85  pub phase          : f16,
86  pub tot_low_a      : f16,
87  pub tot_low_b      : f16,
88  pub tot_high_a     : f16,
89  pub tot_high_b     : f16,
90  pub tot_slp_low_a  : f16,
91  pub tot_slp_low_b  : f16,
92  pub tot_slp_high_a : f16, 
93  pub tot_slp_high_b : f16,
94  //-------------------------------
95  // NON-SERIALIZED FIELDS
96  //-------------------------------
97
98  /// Length of the paddle the hit is on, will get 
99  /// populated from db
100  pub paddle_len     : f32,
101  /// (In)famous constant timing offset per paddle
102  pub timing_offset  : f32,
103  pub coax_cable_time: f32,
104  pub hart_cable_time: f32,
105  /// normalized t0, where we have the phase difference
106  /// limited to -pi/2 -> pi/2
107  pub event_t0       : f32,
108  pub x              : f32,
109  pub y              : f32,
110  pub z              : f32,
111
112  // fields which won't get 
113  // serialized
114  pub valid          : bool,
115}
116
117// methods without pybindings
118impl TofHit {
119  pub fn new() -> Self {
120    Self{
121      paddle_id       : 0,
122      time_a          : f16::from_f32(0.0),
123      time_b          : f16::from_f32(0.0),
124      peak_a          : f16::from_f32(0.0),
125      peak_b          : f16::from_f32(0.0),
126      charge_a        : f16::from_f32(0.0),
127      charge_b        : f16::from_f32(0.0),
128      paddle_len      : f32::NAN,
129      timing_offset   : 0.0,
130      coax_cable_time : f32::NAN,
131      hart_cable_time : f32::NAN,
132      event_t0        : f32::NAN,
133      x               : f32::NAN,
134      y               : f32::NAN,
135      z               : f32::NAN,
136      
137      valid           : true,
138      // v1 variables 
139      version         : ProtocolVersion::V1,
140      quality         : EventQuality::Unknown, 
141      baseline_a      : f16::from_f32(0.0),
142      baseline_a_rms  : f16::from_f32(0.0),
143      baseline_b      : f16::from_f32(0.0),
144      baseline_b_rms  : f16::from_f32(0.0),
145      phase           : f16::from_f32(0.0),
146      tot_low_a       : f16::from_f32(0.0),
147      tot_low_b       : f16::from_f32(0.0),
148      tot_high_a      : f16::from_f32(0.0),
149      tot_high_b      : f16::from_f32(0.0),
150      tot_slp_low_a   : f16::from_f32(0.0),
151      tot_slp_low_b   : f16::from_f32(0.0),
152      tot_slp_high_a  : f16::from_f32(0.0),
153      tot_slp_high_b  : f16::from_f32(0.0),
154    }
155  }
156  
157  /// Adds an extracted peak to this TofHit. A peak will be 
158  /// for only a single waveform only, so we have to take 
159  /// care of the A/B sorting by means of PaddleEndId
160  pub fn add_peak(&mut self, peak : &Peak)  {
161    if self.paddle_id != TofHit::get_pid(peak.paddle_end_id) {
162      //error!("Can't add peak to 
163    }
164    if peak.paddle_end_id < 1000 {
165      error!("Invalide paddle end id {}", peak.paddle_end_id);
166    }
167    if peak.paddle_end_id > 2000 {
168      self.set_time_b  (peak.time);
169      self.set_peak_b  (peak.height);
170      self.set_charge_b(peak.charge);
171    } else if peak.paddle_end_id < 2000 {
172      self.set_time_a  (peak.time);
173      self.set_peak_a  (peak.height);
174      self.set_charge_a(peak.charge);
175    }
176  }
177  
178  // None of the setters will have pybindings
179  pub fn set_time_b(&mut self, t : f32) {
180    self.time_b = f16::from_f32(t)
181  }
182  
183  pub fn set_time_a(&mut self, t : f32) {
184    self.time_a = f16::from_f32(t);
185  }
186
187  pub fn set_peak_a(&mut self, p : f32) {
188    self.peak_a = f16::from_f32(p)
189  }
190
191  pub fn set_peak_b(&mut self, p : f32) {
192    self.peak_b = f16::from_f32(p)
193  }
194
195  pub fn set_charge_a(&mut self, c : f32) {
196    self.charge_a = f16::from_f32(c)
197  }
198
199  pub fn set_charge_b(&mut self, c : f32) {
200    self.charge_b = f16::from_f32(c)
201  }
202}
203
204// wrapper methods which duplicate the rust code,
205// but need addional configuration with pyo3, e.g.
206// the #getter attribute
207#[cfg(feature="pybindings")]
208#[pymethods]
209impl TofHit {
210  
211  /// The paddle id (1-160) of the hit paddle
212  #[getter]
213  #[pyo3(name="paddle_id")]
214  fn paddle_id_py(&self) -> u8 {
215    self.paddle_id
216  }
217
218  #[getter]
219  #[pyo3(name="timing_offset")]
220  fn get_timing_offset(&self) -> f32 {
221    self.timing_offset
222  }
223
224  /// The length of the paddle, only available after 
225  /// the paddle information has been added through
226  /// "set_paddle"
227  #[getter]
228  #[pyo3(name="paddle_len")]
229  fn get_paddle_len_py(&self) -> f32 {
230    self.paddle_len
231  }
232  
233  /// Set the length and cable length for the paddle
234  /// FIXME - take gaps_online.db.Paddle as argument
235  #[pyo3(name="set_paddle")]
236  //fn set_paddle_py(&mut self, plen : f32, coax_cbl_time : f32, hart_cbl_time : f32 ) {
237  fn set_paddle_py(&mut self, paddle : &TofPaddle) -> PyResult<()> {
238    Ok(self.set_paddle(paddle)?)
239  }
240  
241  /// The time in ns the signal spends in the coax 
242  /// cables from the SiPMs to the RAT
243  #[getter]
244  #[pyo3(name="coax_cbl_time")]
245  fn get_coax_cbl_time(&self) -> f32 {
246    self.coax_cable_time
247  }
248
249  /// The time in ns the signal spends in the Harting
250  /// cables from the RATs to the MTB
251  #[getter]
252  #[pyo3(name="hart_cbl_time")]
253  fn get_hart_cbl_time(&self) -> f32 {
254    self.hart_cable_time
255  }
256  
257  /// Calculate the position across the paddle from
258  /// the two times at the paddle ends
259  ///
260  /// **This will be measured from the A side**
261  ///
262  /// Just to be extra clear, this assumes the two 
263  /// sets of cables for each paddle end have the
264  /// same length
265  #[getter]
266  #[pyo3(name="pos")] 
267  fn get_pos_py(&self) -> f32 {
268    self.get_pos() 
269  } 
270  
271  #[getter]
272  #[pyo3(name="x")]
273  fn x_py(&self) -> f32 {
274    self.x
275  }
276  
277  #[getter]
278  #[pyo3(name="y")]
279  fn y_py(&self) -> f32 {
280    self.y
281  }
282
283  #[getter]
284  #[pyo3(name="z")]
285  fn z_py(&self) -> f32 {
286    self.z
287  }
288  
289  #[getter]
290  #[pyo3(name="version")]
291  fn version_py(&self) -> ProtocolVersion {
292    self.version
293  }
294
295  #[getter]
296  #[pyo3(name="phase")]
297  fn phase_py(&self) -> f32 {
298    self.phase.to_f32()
299  }
300
301  #[getter] 
302  #[pyo3(name="phase_ns")] 
303  fn phase_ns_py(&self) -> f32 {
304    self.get_phase_ns()
305  }
306
307  #[getter]
308  #[pyo3(name="cable_delay")]
309  /// Get the cable correction time
310  fn get_cable_delay_py(&self) -> f32 {
311    self.get_cable_delay()
312  }
313
314  /// Get the delay relative to other readoutboards based 
315  /// on the channel9 sine wave
316  #[getter]
317  #[pyo3(name="phase_delay")]
318  fn get_phase_delay_py(&self) -> f32 { 
319    self.get_phase_delay()
320  }
321  
322  /// That this works, the length of the paddle has to 
323  /// be set before (in mm).
324  /// This assumes that the cable on both sides of the paddle are 
325  /// the same length
326  #[getter]
327  #[pyo3(name="t0")]
328  fn get_t0_py(&self) -> f32 {
329    self.get_global_t0()
330  }
331  
332  /// Event t0 is the calculated interaction time based on 
333  /// the RELATIVE phase shifts consdering ALL hits in this
334  /// event. This might be of importance to catch rollovers
335  /// in the phase of channel9. 
336  /// In total, we are restricting ourselves to a time of 
337  /// 50ns per events and adjust the phase in such a way that 
338  /// everything fits into this interval. This will 
339  /// significantly import the beta reconstruction for particles
340  /// which hit the TOF within this timing window.
341  ///
342  /// If a timing offset is set, this will be added
343  #[getter]
344  #[pyo3(name="event_t0")]
345  fn get_event_t0_py(&self) -> f32 {
346    //self.get_t0()
347    self.get_global_t0()
348  }
349
350  /// Calculate the interaction time based on the peak timings measured 
351  /// at the paddle ends A and B
352  ///
353  /// This does not correct for any cable length
354  /// or ch9 phase shift
355  #[getter]
356  #[pyo3(name="t0_uncorrected")]
357  fn get_t0_uncorrected_py(&self) -> f32 {
358    self.get_t0_uncorrected()
359  }
360
361  /// Deposited energy (MeV), the default: Birk's law with the
362  /// attenuation model of the simulation's digitizer (see get_edep)
363  #[getter]
364  #[pyo3(name="edep")]
365  fn get_edep_py(&self) -> f32 {
366    self.get_edep()
367  }
368
369  /// Deposited energy (MeV) following Birk's law, without the
370  /// attenuation correction
371  #[getter]
372  #[pyo3(name="edep_noatt")]
373  fn get_edep_noatt_py(&self) -> f32 {
374    self.get_edep_noatt()
375  }
376
377  /// Deposited energy (MeV), linear in the peaks, with Elena's
378  /// attenuation correction
379  #[getter]
380  #[pyo3(name="edep_linear")]
381  fn get_edep_linear_py(&self) -> f32 {
382    self.get_edep_linear()
383  }
384
385  /// Deposited energy (MeV), linear in the peaks, without the
386  /// attenuation correction (Philip's)
387  #[getter]
388  #[pyo3(name="edep_linear_noatt")]
389  fn get_edep_linear_noatt_py(&self) -> f32 {
390    self.get_edep_linear_noatt()
391  }
392
393  /// Arrival time of the photons at side A
394  #[getter]
395  #[pyo3(name="time_a")]
396  fn get_time_a_py(&self) -> f32 {
397    self.get_time_a()
398  }
399
400  /// Arrival time of the photons at side B
401  #[getter]
402  #[pyo3(name="time_b")]
403  fn get_time_b_py(&self) -> f32 {
404    self.get_time_b()
405  }
406
407  #[getter]
408  #[pyo3(name="TOT_low_a")]
409  fn get_tot_low_a_py(&self) -> f32 {
410      self.get_tot_low_a()
411  }
412
413  #[getter]
414  #[pyo3(name="TOT_low_b")]
415  fn get_tot_low_b_py(&self) -> f32 {
416      self.get_tot_low_b()
417  }
418
419  #[getter]
420  #[pyo3(name="TOT_high_a")]
421  fn get_tot_high_a_py(&self) -> f32 {
422      self.get_tot_high_a()
423  }
424
425  #[getter]
426  #[pyo3(name="TOT_high_b")]
427  fn get_tot_high_b_py(&self) -> f32 {
428      self.get_tot_high_b()
429  }
430
431  #[getter]
432  #[pyo3(name="TOT_slp_low_a")]
433  fn get_tot_slp_low_a_py(&self) -> f32 {
434      self.get_tot_slp_low_a()
435  }
436
437  #[getter]
438  #[pyo3(name="TOT_slp_low_b")]
439  fn get_tot_slp_low_b_py(&self) -> f32 {
440      self.get_tot_slp_low_b()
441  }
442
443  #[getter]
444  #[pyo3(name="TOT_slp_high_a")]
445  fn get_tot_slp_high_a_py(&self) -> f32 {
446      self.get_tot_slp_high_a()
447  }
448
449  #[getter]
450  #[pyo3(name="TOT_slp_high_b")]
451  fn get_tot_slp_high_b_py(&self) -> f32 {
452      self.get_tot_slp_high_b()
453  }
454
455  #[getter]
456  #[pyo3(name="peak_a")]
457  fn get_peak_a_py(&self) -> f32 {
458    self.get_peak_a()
459  }
460  
461  #[getter]
462  #[pyo3(name="peak_b")]
463  fn get_peak_b_py(&self) -> f32 {
464    self.get_peak_b()
465  }
466  
467  #[getter]
468  #[pyo3(name="charge_a")]
469  fn get_charge_a_py(&self) -> f32 {
470    self.get_charge_a()
471  }
472  
473  #[getter]
474  #[pyo3(name="charge_b")]
475  fn get_charge_b_py(&self) -> f32 {
476    self.get_charge_b()
477  }
478  
479  #[getter]
480  #[pyo3(name="baseline_a")]
481  fn get_bl_a_py(&self) -> f32 {
482    self.get_bl_a()
483  }
484  
485  #[getter]
486  #[pyo3(name="baseline_b")]
487  fn get_bl_b_py(&self) -> f32 {
488    self.get_bl_b()
489  }
490  
491  #[getter]
492  #[pyo3(name="baseline_a_rms")]
493  fn get_bl_a_rms_py(&self) -> f32 {
494    self.get_bl_a_rms()
495  }
496  
497  #[getter]
498  #[pyo3(name="baseline_b_rms")]
499  fn get_bl_b_rms_py(&self) -> f32 {
500    self.get_bl_b_rms()
501  }
502}
503
504// methods which are available in rust, but can 
505// have an implementation in python.
506// Sets the pymethods attribute conditionally
507#[cfg_attr(feature="pybindings", pymethods)]
508impl TofHit {
509  /// Calculate the distance to another hit. For this 
510  /// to work, the hit coordinates have had to be 
511  /// determined, so this will only return a 
512  /// propper result after the paddle information 
513  /// is added
514  pub fn distance(&self, other : &TofHit) -> f32 {
515    ((self.x - other.x).powi(2) + (self.y - other.y).powi(2) + (self.z - other.z).powi(2)).sqrt()
516  } 
517  
518  /// If the two reconstructed pulse times are not related to each other by the paddle length,
519  /// meaning that they can't be caused by the same event, we dub this hit as "not following
520  /// causality"
521  pub fn obeys_causality(&self) -> bool {
522    (self.paddle_len/(10.0*C_LIGHT_PADDLE)) - f32::abs(self.time_a.to_f32() - self.time_b.to_f32()) > 0.0
523    && self.get_t0_uncorrected() > 0.0
524  }
525}
526
527#[cfg(feature="pybindings")]
528pythonize!(TofHit);
529
530// methods which have wrapped pybindings
531impl TofHit {
532   
533  /// Calculate the position across the paddle from
534  /// the two times at the paddle ends
535  ///
536  /// **This will be measured from the A side**
537  ///
538  /// Just to be extra clear, this assumes the two 
539  /// sets of cables for each paddle end have the
540  /// same length
541  pub fn get_pos(&self) -> f32 {
542    let t0 = self.get_t0_uncorrected();
543    let clean_t_a = self.time_a.to_f32() - t0;
544    return clean_t_a*C_LIGHT_PADDLE*10.0; 
545  }
546  
547  /// Get the cable correction time
548  pub fn get_cable_delay(&self) -> f32 {
549    self.hart_cable_time - self.coax_cable_time 
550  }
551
552  /// Get the delay relative to other readoutboards based 
553  /// on the channel9 sine wave
554  pub fn get_phase_delay(&self) -> f32 { 
555    let freq : f32 = 20.0e6;
556    let phase = self.phase.to_f32();
557    // fit allows for negative phase shift.
558    // that means to distinguish 2 points, we
559    // only have HALF of the sine wave
560    // FIXME - implement warning?
561    //while phase < -PI {
562    //  phase += 2.0*PI;
563    //}
564    //while phase > PI {
565    //  phase -= 2.0*PI;
566    //}
567    (phase/(2.0*PI*freq))*1.0e9f32 
568  }
569  
570  /// That this works, the length of the paddle has to 
571  /// be set before (in mm).
572  /// This assumes that the cable on both sides of the paddle are 
573  /// the same length
574  pub fn get_global_t0(&self) -> f32 {
575    //self.get_t0_uncorrected() + self.get_phase_delay() + self.get_cable_delay()
576    self.event_t0 //- self.timing_offset
577  }
578
579  /// Calculate the interaction time based on the peak timings measured 
580  /// at the paddle ends A and B
581  ///
582  /// This does not correct for any cable length
583  /// or ch9 phase shift
584  pub fn get_t0_uncorrected(&self) -> f32 {
585    0.5*(self.time_a.to_f32() + self.time_b.to_f32() - (self.paddle_len/(10.0*C_LIGHT_PADDLE)))
586  }
587
588  /// Deposited energy (MeV), the default. Birk's law with the
589  /// attenuation model of the simulation's digitizer (GapsDigitizer::
590  /// tof_energy_to_peak_voltage and tof_paddle_attenuation_factor):
591  /// per side its own coefficients, normalised at the paddle center.
592  /// Both peaks are corrected for the attenuation, averaged, and
593  /// the Birk's law relation peak = 35.26*E/(1 + 0.021*E) is inverted.
594  /// Needs the paddle (set_paddle) for the position along it.
595  ///
596  /// Returns NaN if the paddle length is not set.
597  pub fn get_edep(&self) -> f32 {
598    let len   = self.paddle_len;
599    // f32::clamp below panics for a NaN bound
600    if !(len > 0.0) {
601      error!("Paddle length {} for paddle {} is not valid, was set_paddle called? Can't calculate edep!", len, self.paddle_id);
602      return f32::NAN;
603    }
604    // distance from side A, within the paddle
605    let x_a   = self.get_pos().clamp(0.0, len);
606    let att   = |p0 : f32, p1 : f32, p2 : f32, dist : f32| {
607      ((p0 - p1*dist).exp() + p2) / ((p0 - p1*0.5*len).exp() + p2)
608    };
609    let att_a = att(3.94,  0.001211,  20.87, x_a);
610    let att_b = att(3.831, 0.0013103, 23.42, len - x_a);
611    let v = (self.get_peak_a()/att_a + self.get_peak_b()/att_b) / 2.0;
612    1000.0 * v / (35260.0 - 21.0 * v)
613  }
614
615  /// Deposited energy (MeV) following Birk's law, without the
616  /// attenuation correction
617  pub fn get_edep_noatt(&self) -> f32 {
618    let peak_a = self.peak_a.to_f32();
619    let peak_b = self.peak_b.to_f32();
620    let avg_peak = (peak_a + peak_b) / 2.0;
621    1000.0 * avg_peak / (35260.0 - 21.0 * avg_peak)
622  }
623
624  /// Deposited energy (MeV), linear in the peaks, with Elena's
625  /// attenuation correction (normalised at the paddle end, vertical
626  /// muon peak at 0.97 MeV). Not the model of the simulation.
627  pub fn get_edep_linear(&self) -> f32 {
628    let x0    = self.get_pos();
629    let att_a = ((3.9-0.00126*(x0)).exp()+22.15) / ((3.9).exp()+22.15);
630    let att_b = ((3.9-0.00126*(self.paddle_len - x0)).exp()+22.15) / ((3.9).exp()+22.15);
631    let edep  = 0.0159 * (self.get_peak_a()/att_a + self.get_peak_b()/att_b) / 2.; // vertical muon peak @ 0.97 MeV
632    return edep; 
633  }
634
635  /// Deposited energy (MeV), linear in the peaks, without the
636  /// attenuation correction (Philip's)
637  pub fn get_edep_linear_noatt(&self) -> f32 {
638    (1.29/34.3)*(self.peak_a.to_f32() + self.peak_b.to_f32()) / 2.0
639  }
640
641  /// Arrival time of the photons at side A
642  pub fn get_time_a(&self) -> f32 {
643    self.time_a.to_f32()
644  }
645
646  /// Arrival time of the photons at side B
647  pub fn get_time_b(&self) -> f32 {
648    self.time_b.to_f32()
649  }
650  
651  pub fn get_tot_low_a(&self) -> f32 {
652    self.tot_low_a.to_f32()
653  }
654
655  pub fn get_tot_low_b(&self) -> f32 {
656    self.tot_low_b.to_f32()
657  }
658
659  pub fn get_tot_high_a(&self) -> f32 {
660    self.tot_high_a.to_f32()
661  }
662
663  pub fn get_tot_high_b(&self) -> f32 {
664    self.tot_high_b.to_f32()
665  }
666
667  pub fn get_tot_slp_low_a(&self) -> f32 {
668    self.tot_slp_low_a.to_f32()
669  }
670
671  pub fn get_tot_slp_low_b(&self) -> f32 {
672    self.tot_slp_low_b.to_f32()
673  }
674
675  pub fn get_tot_slp_high_a(&self) -> f32 {
676    self.tot_slp_high_a.to_f32()
677  }
678  pub fn get_tot_slp_high_b(&self) -> f32 {
679    self.tot_slp_high_b.to_f32()
680  }
681  pub fn get_peak_a(&self) -> f32 {
682    self.peak_a.to_f32()
683  }
684  
685  pub fn get_peak_b(&self) -> f32 {
686    self.peak_b.to_f32()
687  }
688  
689  pub fn get_charge_a(&self) -> f32 {
690    self.charge_a.to_f32()
691  }
692  
693  pub fn get_charge_b(&self) -> f32 {
694    self.charge_b.to_f32()
695  }
696  
697  pub fn get_bl_a(&self) -> f32 {
698    self.baseline_a.to_f32()
699  }
700  
701  pub fn get_bl_b(&self) -> f32 {
702    self.baseline_b.to_f32()
703  }
704  
705  pub fn get_bl_a_rms(&self) -> f32 {
706    self.baseline_a_rms.to_f32()
707  }
708  
709  pub fn get_bl_b_rms(&self) -> f32 {
710    self.baseline_b_rms.to_f32()
711  }
712
713
714  ///// Get the (official) paddle id
715  /////
716  ///// Convert the paddle end id following 
717  ///// the convention
718  /////
719  ///// A-side : paddle id + 1000
720  ///// B-side : paddle id + 2000
721  /////
722  ///// FIXME - maybe return Result?
723  ////#[deprecated(since="0.10", note="We are not using a paddle end id anymore")]
724  pub fn get_pid(paddle_end_id : u16) -> u8 {
725    if paddle_end_id < 1000 {
726      return 0;
727    }
728    if paddle_end_id > 2000 {
729      return (paddle_end_id - 2000) as u8;
730    }
731    if paddle_end_id < 2000 {
732      return (paddle_end_id - 1000) as u8;
733    }
734    return 0;
735  }
736
737  /// The relative phase converted to ns using 
738  /// a frequency of 20MHz (50ns period)
739  pub fn get_phase_ns(&self) -> f32 {
740    let mut phase_ns = 50.0*self.phase.to_f32()/(2.0*PI);
741    // make sure the phase is always positive 
742    // FIXME - there is a slight, possible, unconfirmed issue with the sine fit. 
743    //       - it sometimes might latch on to the "wrong" side, and thus this has 
744    //       - to be corrected. If it is not the sine fit, it is something else 
745    //       - unknown. Just adding a full phase make things easier downstream.
746    phase_ns += 50.0;
747    phase_ns
748  }
749
750  pub fn get_phase_rollovers(&self) -> i16 {
751    let mut phase = self.phase.to_f32();
752    let mut ro = 0i16;
753    while phase < PI/2.0 {
754      phase += PI/2.0;
755      ro += 1;
756    }
757    while phase > PI/2.0 {
758      phase -= PI/2.0;
759      ro -= 1;
760    }
761    ro
762  }
763  
764
765}
766
767#[cfg(feature="database")]
768impl TofHit {
769  pub fn set_paddle(&mut self, paddle : &TofPaddle) -> Result<(), UserError> {
770    if self.paddle_id != paddle.paddle_id as u8 {
771      return Err(UserError::WrongPaddleId);
772    }
773    self.coax_cable_time = paddle.coax_cable_time;
774    self.hart_cable_time = paddle.harting_cable_time;
775    self.paddle_len = paddle.length * 10.0; // stupid units!
776    let pr          = paddle.principal();
777    //println!("Principal {:?}", pr);
778    let rel_pos     = self.get_pos();
779    let pos         = (paddle.global_pos_x_l0_A*10.0 + pr.0*rel_pos,
780                       paddle.global_pos_y_l0_A*10.0 + pr.1*rel_pos,
781                       paddle.global_pos_z_l0_A*10.0 + pr.2*rel_pos);
782    self.x          = pos.0;
783    self.y          = pos.1;
784    self.z          = pos.2;
785    Ok(())
786  }
787}
788
789//-------------------------
790
791// dedicated rust-only implementations 
792impl TofHit {
793  pub fn get_t0_with_local_corrections(&self) -> f32 {
794    self.get_t0_uncorrected() + self.get_cable_delay() + self.get_phase_ns() 
795  }
796}
797
798
799// Implementation of traits 
800//-------------------------
801
802impl Default for TofHit {
803  fn default() -> Self {
804    Self::new()
805  }
806}
807
808impl fmt::Display for TofHit {
809  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
810    let mut paddle_info = String::from("");
811    if self.paddle_len == 0.0 {
812      paddle_info = String::from("NOT SET!");
813    }
814    write!(f, "<TofHit (version : {}):
815  Paddle ID       {}
816  Peak:
817    LE Time A/B   {:.2} {:.2}   
818    Height  A/B   {:.2} {:.2}
819    Charge  A/B   {:.2} {:.2}
820  ** time over threshold information
821    Lo TOT A/B    {:.2} {:.2}
822    Hi TOT A/B    {:.2} {:.2}
823    Lo Slope A/B  {:.2} {:.2}
824    Hi Slope A/B  {:.2} {:.2}
825  ** paddle {} ** 
826    Length        {:.2}
827    Timing offset {:.2} (ns)
828    Coax cbl time {:.2}
829    Hart cbl time {:.2}
830  ** reconstructed interaction
831    energy_dep    {:.2}   
832    edep_linear   {:.2}
833    pos_across    {:.2}   
834    t0 (uncorr)   {:.2}  
835    t0 (local c)  {:.2}  
836    t0 (global c) {:.2}
837    ev t0 [DEPR]  {:.2}
838    x, y, z       {:.2} {:.2} {:.2}
839  ** V1 variables
840    phase (ch9)   {:.4}
841      n phs ro    {}
842    baseline A/B  {:.2} {:.2}
843    bl. RMS  A/B  {:.2} {:.2}>",
844            self.version,
845            self.paddle_id,
846            self.get_time_a(),
847            self.get_time_b(),
848            self.get_peak_a(),
849            self.get_peak_b(),
850            self.get_charge_a(),
851            self.get_charge_b(),
852            self.get_tot_low_a(),
853            self.get_tot_low_b(),
854            self.get_tot_high_a(),
855            self.get_tot_high_b(),
856            self.get_tot_slp_low_a(),
857            self.get_tot_slp_low_b(),
858            self.get_tot_slp_high_a(),
859            self.get_tot_slp_high_b(),
860            paddle_info,
861            self.paddle_len,
862            self.timing_offset,
863            self.coax_cable_time,
864            self.hart_cable_time,
865            self.get_edep(),
866            self.get_edep_linear(),
867            self.get_pos(),
868            //self.get_t0(),
869            self.get_t0_uncorrected(),
870            self.get_t0_with_local_corrections(),
871            self.get_global_t0(),
872            self.event_t0,
873            self.x,
874            self.y,
875            self.z,
876            self.phase,
877            self.get_phase_rollovers(),
878            self.baseline_a,
879            self.baseline_b,
880            self.baseline_a_rms,
881            self.baseline_b_rms,
882            )
883  }
884}
885
886impl Serialization for TofHit {
887  
888  const HEAD          : u16   = 61680; //0xF0F0)
889  const TAIL          : u16   = 3855;
890  const SIZE          : usize = 44; // size in bytes with HEAD and TAIL
891
892  /// Serialize the packet
893  ///
894  /// Not all fields will get serialized, 
895  /// only the relevant data for the 
896  /// flight computer
897  //
898  /// **A note about protocol versions **
899  /// When we serialize (to_bytestream) we will
900  /// always write the latest version.
901  /// Deserialization can also read previous versions
902  fn to_bytestream(&self) -> Vec<u8> {
903
904    let mut bytestream = Vec::<u8>::with_capacity(Self::SIZE);
905    bytestream.extend_from_slice(&Self::HEAD.to_le_bytes());
906    bytestream.push(self.paddle_id); 
907    bytestream.extend_from_slice(&self.time_a      .to_le_bytes()); 
908    bytestream.extend_from_slice(&self.time_b      .to_le_bytes()); 
909    bytestream.extend_from_slice(&self.peak_a      .to_le_bytes()); 
910    bytestream.extend_from_slice(&self.peak_b      .to_le_bytes()); 
911    bytestream.extend_from_slice(&self.charge_a    .to_le_bytes()); 
912    bytestream.extend_from_slice(&self.charge_b    .to_le_bytes()); 
913    bytestream.extend_from_slice(&self.tot_low_a   .to_le_bytes());
914    bytestream.extend_from_slice(&self.baseline_a   .to_le_bytes());
915    bytestream.extend_from_slice(&self.baseline_a_rms.to_le_bytes());
916    bytestream.extend_from_slice(&self.phase       .to_le_bytes());
917    let quality_version = self.quality as u8 | self.version.to_u8();
918    bytestream.push(quality_version);
919    //bytestream.push(self.version.to_u8());
920    bytestream.extend_from_slice(&self.baseline_b  .to_le_bytes());
921    bytestream.extend_from_slice(&self.baseline_b_rms.to_le_bytes());
922    bytestream.extend_from_slice(&self.tot_low_b   .to_le_bytes());
923    bytestream.extend_from_slice(&self.tot_high_a  .to_le_bytes());
924    bytestream.extend_from_slice(&self.tot_high_b  .to_le_bytes());
925    bytestream.extend_from_slice(&self.tot_slp_low_a.to_le_bytes());
926    bytestream.extend_from_slice(&self.tot_slp_low_b.to_le_bytes());
927    bytestream.extend_from_slice(&self.tot_slp_high_a.to_le_bytes());
928    bytestream.extend_from_slice(&self.tot_slp_high_b.to_le_bytes());
929    bytestream.extend_from_slice(&Self::TAIL       .to_le_bytes()); 
930    bytestream
931  }
932
933
934  /// Deserialization
935  ///
936  ///
937  /// # Arguments:
938  ///
939  /// * bytestream : 
940  fn from_bytestream(stream : &Vec<u8>, pos : &mut usize) 
941    -> Result<Self, SerializationError> {
942    let mut pp             = Self::new();
943    let mut version_lt_011 = false;
944    let (size,_,__)        = Self::guess_size(stream, *pos, 28)?;
945    if size == 30 {
946      version_lt_011 = true;
947      let head      = parse_u16(stream, pos);
948      if head != Self::HEAD {
949        error!("Decoding of HEAD failed! Got {} instead!", head);
950        return Err(SerializationError::HeadInvalid);
951      }
952    } else {
953      Self::verify_fixed(stream, pos)?;
954    }
955    // since we passed the above test, the packet
956    // is valid
957    pp.valid          = true;
958    pp.paddle_id      = parse_u8(stream, pos);
959    pp.time_a         = parse_f16(stream, pos);
960    pp.time_b         = parse_f16(stream, pos);
961    pp.peak_a         = parse_f16(stream, pos);
962    pp.peak_b         = parse_f16(stream, pos);
963    pp.charge_a       = parse_f16(stream, pos);
964    pp.charge_b       = parse_f16(stream, pos);
965    pp.tot_low_a      = parse_f16(stream, pos);
966    pp.baseline_a     = parse_f16(stream, pos);
967    pp.baseline_a_rms = parse_f16(stream, pos);
968    let mut phase_vec = Vec::<u8>::new();
969    phase_vec.push(parse_u8(stream, pos));
970    phase_vec.push(parse_u8(stream, pos));
971    pp.phase          = parse_f16(&phase_vec, &mut 0);
972    let quality_version_u8  = parse_u8(stream, pos);
973    let quality             = EventQuality::from(quality_version_u8 & 0x3f);
974    let version             = ProtocolVersion::from(quality_version_u8 & 0xc0); 
975    pp.version        = version;
976    pp.quality        = quality;
977    match pp.version {
978      ProtocolVersion::V1 => {
979      }
980      _ => ()
981    }
982    pp.baseline_b      = parse_f16(stream, pos);
983    pp.baseline_b_rms  = parse_f16(stream, pos);
984    if !version_lt_011 {
985      pp.tot_low_b       = parse_f16(stream, pos);
986      pp.tot_high_a      = parse_f16(stream, pos);
987      pp.tot_high_b      = parse_f16(stream, pos);
988      pp.tot_slp_low_a   = parse_f16(stream, pos);
989      pp.tot_slp_low_b   = parse_f16(stream, pos);
990      pp.tot_slp_high_a  = parse_f16(stream, pos);
991      pp.tot_slp_high_b  = parse_f16(stream, pos);
992      *pos += 2; // always have to do this when using verify fixed
993    } else {
994      let tail = parse_u16(stream, pos);
995      if tail != Self::TAIL {
996        error!("Decoding of TAIL failed for version {}! Got {} instead!", version, tail);
997        return Err(SerializationError::TailInvalid);
998      }
999    }
1000    Ok(pp)
1001  }
1002}
1003
1004#[cfg(feature="random")]
1005impl FromRandom for TofHit {
1006  fn from_random() -> TofHit {
1007    let mut pp  = TofHit::new();
1008    let mut rng = rand::rng();
1009    // randomly create old/new style hits 
1010    let version_lt_011 = rng.random::<bool>();
1011        
1012    pp.paddle_id       = rng.random_range(0..161);
1013    pp.time_a          = f16::from_f32(rng.random::<f32>());
1014    pp.time_b          = f16::from_f32(rng.random::<f32>());
1015    pp.peak_a          = f16::from_f32(rng.random::<f32>());
1016    pp.peak_b          = f16::from_f32(rng.random::<f32>());
1017    pp.charge_a        = f16::from_f32(rng.random::<f32>());
1018    pp.charge_b        = f16::from_f32(rng.random::<f32>());
1019    pp.version         = ProtocolVersion::from_random();
1020    pp.quality         = EventQuality::from_random();
1021    pp.baseline_a      = f16::from_f32(rng.random::<f32>());
1022    pp.baseline_a_rms  = f16::from_f32(rng.random::<f32>());
1023    pp.baseline_b      = f16::from_f32(rng.random::<f32>());
1024    pp.baseline_b_rms  = f16::from_f32(rng.random::<f32>());
1025    pp.phase           = f16::from_f32(rng.random::<f32>());
1026    
1027    if !version_lt_011 {
1028      pp.tot_low_a      = f16::from_f32(rng.random::<f32>());
1029      pp.tot_low_b      = f16::from_f32(rng.random::<f32>());
1030      pp.tot_high_a     = f16::from_f32(rng.random::<f32>());
1031      pp.tot_high_b     = f16::from_f32(rng.random::<f32>()); 
1032      pp.tot_slp_low_a  = f16::from_f32(rng.random::<f32>());
1033      pp.tot_slp_low_b  = f16::from_f32(rng.random::<f32>());
1034      pp.tot_slp_high_a = f16::from_f32(rng.random::<f32>()); 
1035      pp.tot_slp_high_b = f16::from_f32(rng.random::<f32>()); 
1036    }
1037    pp.paddle_len       = 0.0; 
1038    pp.coax_cable_time  = 0.0; 
1039    pp.hart_cable_time  = 0.0; 
1040    pp.x                = 0.0; 
1041    pp.y                = 0.0; 
1042    pp.z                = 0.0; 
1043    pp.event_t0         = 0.0; 
1044    pp
1045  }
1046}
1047
1048//---------------------------------------------------------------
1049
1050#[cfg(feature = "random")]
1051#[test]
1052fn serialization_tofhit() {
1053  for _ in 0..100 {
1054    let mut pos = 0;
1055    let data = TofHit::from_random();
1056    let mut test = TofHit::from_bytestream(&data.to_bytestream(),&mut pos).unwrap();
1057    // Manually zero these fields, since comparison with nan will fail and 
1058    // from_random did not touch these
1059    test.paddle_len       = 0.0; 
1060    test.coax_cable_time  = 0.0; 
1061    test.hart_cable_time  = 0.0; 
1062    test.x                = 0.0; 
1063    test.y                = 0.0; 
1064    test.z                = 0.0; 
1065    test.event_t0         = 0.0;
1066    assert_eq!(pos, TofHit::SIZE);
1067    assert_eq!(data, test);
1068  }
1069}
1070
1071#[test]
1072fn edep_without_paddle_is_nan() {
1073  // a hit without set_paddle has a NaN paddle length
1074  let h = TofHit::new();
1075  assert!(h.paddle_len.is_nan());
1076  assert!(h.get_edep().is_nan());
1077  let mut h = TofHit::new();
1078  h.paddle_len = 0.0;
1079  assert!(h.get_edep().is_nan());
1080}
1081
1082#[test]
1083fn edep_inverts_the_digitizer_model() {
1084  // the simulation makes the peaks with Birk's law times its
1085  // attenuation (normalised at the paddle center); get_edep has to
1086  // give back the deposited energy anywhere along the paddle
1087  let len = 1800.0_f32;
1088  let att = |p0 : f32, p1 : f32, p2 : f32, dist : f32| {
1089    ((p0 - p1*dist).exp() + p2) / ((p0 - p1*0.5*len).exp() + p2)
1090  };
1091  for x in [200.0_f32, 900.0, 1600.0] {
1092    for energy in [1.0_f32, 5.0, 20.0] {
1093      let peak = 35.26*energy/(1.0 + 0.021*energy);
1094      let mut h = TofHit::new();
1095      h.paddle_len = len;
1096      // time difference of the two ends for a hit x from side A
1097      let time_b = 50.0_f32;
1098      h.time_b = f16::from_f32(time_b);
1099      h.time_a = f16::from_f32(time_b + (2.0*x - len)/(10.0*C_LIGHT_PADDLE));
1100      h.peak_a = f16::from_f32(peak*att(3.94,  0.001211,  20.87, x));
1101      h.peak_b = f16::from_f32(peak*att(3.831, 0.0013103, 23.42, len - x));
1102      assert!((h.get_pos() - x).abs() < 10.0, "position {} for {}", h.get_pos(), x);
1103      let e = h.get_edep();
1104      assert!((e/energy - 1.0).abs() < 0.02, "edep {} for {} MeV at {} mm", e, energy, x);
1105      // without the attenuation correction, the energy is off away from the center
1106      if x != 900.0 {
1107        assert!((h.get_edep_noatt()/energy - 1.0).abs() > 0.02);
1108      }
1109    }
1110  }
1111}