Skip to main content

gondola_core/events/
tof_event.rs

1//! Basic event structure for all TOF systems
2// This file is part of gaps-online-software and published 
3// under the GPLv3 license
4
5use crate::prelude::*;
6
7#[cfg(feature="database")]
8use std::f32::consts::PI;
9use std::cmp::Ordering;
10
11/// Main event class for the TOF. This will be sent over telemetry and be 
12/// written to disk
13///
14/// CHANGELOG: v0.11 (gondola-core): Merges TofEvent, TofEventSummary and 
15/// MasterTriggerEvent all into a single TofEvent, based on former TofEventSummary.
16/// The new TofEvent has the ability to cary RBEvents and thus mimick the "old" TofEvent
17/// We are using the version flag to indicate:
18/// * ProtocolVersion::Unknown - The "old" TofEventSummary. (now "TofEvent"). No extra 
19///   variables for the GCU, no RBEvents
20/// * ProtocolVersion::V1      - The version crafted for Antarctica '24/'25 containing 
21///   a bunch of summary variables for the GCU (e.g. nhits(umbrella)). This version will 
22///   add these variables to the bytestream and also if ProtocolVersion::V1 is read out 
23///   from the bytestream, the variables are expected to be in it. This is to keep compatibility
24///   with the gcu
25/// * ProtocolVersion::V2     - v0.11 (gondola-core) version of TofEvent(Summary).
26///   This version will not write out GCU variables and does not expect them to be in the 
27///   bytestream. If desired, this version can read/write RBEvents. 
28/// * ProtocolVersion::V3     - the "latest and greatest". This version has gcuvariables 
29///                             AND rbevents. RBEvents can be stripped off later on.
30#[derive(Debug, Clone, PartialEq)]
31#[cfg_attr(feature="pybindings", pyclass)]
32pub struct TofEvent {
33  pub status            : EventStatus,
34  /// The version of this event. Prior to tof-dataclasses v0.11,
35  /// the default was `ProtocolVersion::Unknown`. 
36  /// Then for the Antarctic campaign we added more variables, 
37  /// so that the gcu doesn't have to compute them. These variables
38  /// will be included in the bytestream for `ProtocolVersion::V1`.
39  /// However, we don't want to write them to disk in the new (gondola-core > v0.11)
40  /// verion, so we will use ProtocolVersionV2 for the version to be
41  /// written to disk. ProtocolVersionV2 can (but not must) have RBEvents
42  pub version           : ProtocolVersion,
43  pub quality           : EventQuality,
44  pub trigger_sources   : u16,
45
46  /// the number of triggered paddles coming
47  /// from the MTB directly. This might NOT be
48  /// the same as the number of hits!
49  pub n_trigger_paddles  : u8,
50  pub event_id           : u32,
51  pub run_id             : u16,
52  pub timestamp32        : u32,
53  pub timestamp16        : u16,
54  /// scalar number of hits missed in
55  /// this event due to DRS on the RB
56  /// being busy
57  pub drs_dead_lost_hits : u16, 
58  pub dsi_j_mask         : u32,
59  pub channel_mask       : Vec<u16>,
60  pub mtb_link_mask      : u64,
61  pub hits               : Vec<TofHit>,
62  // a number of variables which are directly 
63  // read out from the MTB packet and won't get 
64  // serialized in this form but then used
65  // later to calculate other variables
66  pub mt_trigger_sources : u16,
67  pub mt_tiu_gps16       : u16,
68  pub mt_tiu_gps32       : u32, 
69  pub mt_timestamp       : u32,
70  pub mt_tiu_timestamp   : u32,
71  // a bunch of calculated variablels, used 
72  // for online interesting event search
73  // these will be only available in ProtocolVersion 1
74  pub n_hits_umb         : u8,
75  pub n_hits_cbe         : u8,
76  pub n_hits_cor         : u8,
77  pub tot_edep_umb       : f32,
78  pub tot_edep_cbe       : f32,
79  pub tot_edep_cor       : f32,
80  pub paddles_set        : bool,
81  /// True after normalize_hit_times, so that the hit times
82  /// (and the timing offsets) are only normalized once
83  pub hit_times_normalized : bool,
84  // this is new (v0.11) -> We are expanding TofEvent(Summary) 
85  // so that it is the same as TofEvent in v0.10 and is able 
86  // to carry waveforms. These then can be stripped off
87  pub rb_events          : Vec<RBEvent>,
88  /// Start time for a time to wait for incoming RBEvents
89  pub creation_time      : Instant,
90  pub write_to_disk      : bool, 
91}
92
93impl TofEvent {
94
95  pub fn new() -> Self {
96    Self {
97      status             : EventStatus::Unknown,
98      version            : ProtocolVersion::Unknown,
99      n_hits_umb         : 0,
100      n_hits_cbe         : 0,
101      n_hits_cor         : 0,
102      tot_edep_umb       : 0.0,
103      tot_edep_cbe       : 0.0,
104      tot_edep_cor       : 0.0,
105      quality            : EventQuality::Unknown,
106      trigger_sources    : 0,
107      n_trigger_paddles  : 0,
108      event_id           : 0,
109      run_id             : 0,
110      timestamp32        : 0,
111      timestamp16        : 0,
112      drs_dead_lost_hits : 0,
113      dsi_j_mask         : 0,
114      channel_mask       : Vec::<u16>::new(),
115      mtb_link_mask      : 0,
116      hits               : Vec::<TofHit>::new(),
117      mt_trigger_sources : 0,
118      mt_tiu_gps16       : 0,
119      mt_tiu_gps32       : 0, 
120      mt_timestamp       : 0,
121      mt_tiu_timestamp   : 0,
122      paddles_set        : false,
123      hit_times_normalized : false,
124      rb_events          : Vec::<RBEvent>::new(),
125      creation_time      : Instant::now(),
126      write_to_disk      : true,
127    }
128  }
129
130  /// Remove hits from the event as proposed by Elena. 
131  /// This is pretty similar to the non-causal hits, 
132  /// however, a bit stricter
133  pub fn elena_cuts(hit : &TofHit) -> bool {
134    let peak_cut   = 10.0f32;
135    let charge_cut = 5.0f32;
136    let time_sat   = 490.032;
137    
138    let hit_a = hit.time_a.to_f32() > 0.1
139             && hit.time_a.to_f32() < time_sat
140             && hit.peak_a.to_f32() > peak_cut
141             && hit.charge_a.to_f32() > charge_cut;
142    let hit_b = hit.time_b.to_f32() > 0.1
143             && hit.time_b.to_f32() < time_sat
144             && hit.peak_b.to_f32() > peak_cut
145             && hit.charge_b.to_f32() > charge_cut;
146    
147    return hit_a && hit_b;
148  }
149
150  /// Remove the hits from the event which are not passing 
151  /// Elena's cuts 
152  ///
153  /// # Arguments:
154  ///   * no_return : If true, don't return anything, which 
155  ///                 will make the execution time shorter
156  ///
157  pub fn remove_elena_hits(&mut self, no_return : bool) -> Option<Vec<TofHit>> {
158    if !no_return {
159      let mut removed = Vec::<TofHit>::new();
160      for h in &self.hits {
161        if Self::elena_cuts(h) {
162          removed.push(h.clone());
163        }
164      }
165      self.hits.retain(|h| Self::elena_cuts(h));
166      return Some(removed);
167    } else {
168      self.hits.retain(|h| Self::elena_cuts(h));
169      return None; 
170    }
171  }
172
173
174  /// The actual time-of-flight as calculated by the 
175  /// first inner hit time - first outer hit time. 
176  ///
177  /// This is a crude version and does not include 
178  /// any reconstruction, just the bare information 
179  /// as available to the TOF. 
180  ///
181  /// Be careful with using this number for anything else 
182  /// than a crude guess
183  ///
184  /// # Returns:
185  ///   * (tof,beta) for events with at least one inner and outer hit, 
186  ///     None for the others
187  pub fn get_tof(&mut self) -> Option<(f32,f32,f32,f32,f32)> {
188    // in case the hits are already normalized, this should do 
189    // nothing 
190    self.normalize_hit_times();
191    let mut outer_h = Vec::<TofHit>::new();
192    let mut inner_h = Vec::<TofHit>::new();
193    for h in &self.hits {
194      if h.paddle_id < 61 {
195        inner_h.push(*h);
196      } else {
197        outer_h.push(*h);
198      }
199    }
200    if inner_h.len() == 0 || outer_h.len() == 0 {
201      return None;
202    }
203    inner_h .sort_by(|a,b| (a.get_t0_with_local_corrections()).partial_cmp(&&b.get_t0_with_local_corrections()).unwrap_or(Ordering::Greater));
204    outer_h .sort_by(|a,b| (a.get_t0_with_local_corrections()).partial_cmp(&&b.get_t0_with_local_corrections()).unwrap_or(Ordering::Greater));
205    //let tof  = (inner_h[0].t0_fr() - outer_h[0].t0_fr()).abs();
206    let dist     = inner_h[0].distance(&outer_h[0])/1000.0; 
207    // fix wrong phase difference calculation 
208    let t0       = inner_h[0].get_t0_with_local_corrections() - inner_h[0].get_phase_ns() - inner_h[0].timing_offset;
209    let t1       = outer_h[0].get_t0_with_local_corrections() - outer_h[0].get_phase_ns() - outer_h[0].timing_offset;
210    let mut pd   = inner_h[0].get_phase_ns() - outer_h[0].get_phase_ns();
211    if pd > 25.0 {
212      pd -= 50.0;
213    }
214    if pd < -25.0 {
215      pd += 50.0; 
216    }
217    let tof = t0 - t1 + pd;  
218    //let mut tof  = inner_h[0].t0_fr() - outer_h[0].t0_fr();
219    //if tof > 50.0 {
220    //  tof -= 50.0; 
221    //}
222    let beta = dist.abs()/(tof*1e-9)/299792458.0;
223    //let pd   = inner_h[0].get_phase_ns() - outer_h[0].get_phase_ns();
224    let hart_diff = inner_h[0].hart_cable_time - outer_h[0].hart_cable_time;
225    Some((tof, beta, pd, dist, hart_diff))
226  }
227
228  /// Calculate the timestamp from the MTB inlcuding GPS and all
229  ///
230  /// This will be the most precise timestamp in GAPS, based on 
231  /// a 100MHz oscillator and if GPS is active, it will fix itself
232  /// with the GPS 1PPS pulse
233  pub fn get_mt_timestamp_abs(&self) -> u64 {
234    let gps = self.mt_tiu_gps32 as u64;
235    let mut timestamp = self.mt_timestamp as u64;
236    if timestamp < self.mt_tiu_timestamp as u64 {
237      // it has wrapped
238      timestamp += u32::MAX as u64 + 1;
239    }
240    let gps_mult = match 100_000_000u64.checked_mul(gps) {
241    //let gps_mult = match 100_000u64.checked_mul(gps) {
242      Some(result) => result,
243      None => {
244          // Handle overflow case here
245          // Example: log an error, return a default value, etc.
246          0 // Example fallback value
247      }
248    };
249    let ts = gps_mult + (timestamp - self.mt_tiu_timestamp as u64);
250    ts
251  }
252
253  /// Move hits out of RBEvents and in the general 
254  /// hitvector. 
255  ///
256  /// This should be done once an event is complete.
257  /// The RBEvents keep the associated waveforms, but 
258  /// the hits all move into a single vector
259  pub fn move_hits(&mut self) {
260    let mut all_hits = Vec::<TofHit>::with_capacity(5);
261    for rbev in &mut self.rb_events {
262       all_hits.append(&mut rbev.hits);
263    }
264    self.hits = all_hits;
265  }
266
267  /// Remove any RBEvents from the event. 
268  ///
269  /// This will move the hits out of the 
270  /// RBEvents and put them in the hit vector.
271  pub fn strip_rbevents(&mut self) {
272    if self.hits.len() == 0 {
273      self.move_hits();
274    }
275    self.rb_events.clear();
276  }
277
278  /// At the moment, this instance of TofEvent gets 
279  /// created, a timer begins to tick. 
280  ///
281  /// The age of the event is the elapsed time since
282  /// this instance (self) was created in seconds.
283  pub fn age(&self) -> u64 {
284    self.creation_time.elapsed().as_secs()
285  }
286 
287  /// The expectedd RBs participating in this event as 
288  /// infered from the RB link ids coming from the MTB
289  pub fn get_expected_rbs(&self, mapping : &HashMap<u8,u8>) -> Vec<u8> {
290    let mut expected_rbs = Vec::<u8>::new();
291    for k in self.get_rb_link_ids() {
292      match mapping.get(&k) {
293        None => {
294          error!("Seeing unassociated link id {k}");
295        }
296        Some(rb_id) => {
297          expected_rbs.push(*rb_id);
298        }
299      }
300    }
301    expected_rbs 
302  }
303
304  /// Simple check if the event contains as much RBEvents 
305  /// as expected from the provided boards masks by the MTB
306  pub fn is_complete(&mut self, exclude_rbs : Option<(&Vec<u8>,&DsiJChRbMapping)>) -> bool {
307    if exclude_rbs.is_none() {
308      return self.get_rb_link_ids().len() == self.rb_events.len();
309    } else {
310      let dead_rbs = exclude_rbs.unwrap();
311      let mut n_known_dead = 0usize;
312      let t_hits = self.get_trigger_hits();
313      for h in t_hits {
314        match dead_rbs.1.get(&h.0) {
315          None => {
316            continue;
317          }
318          Some(dsi) => {
319            match dsi.get(&h.1) {
320              None => {
321                continue;
322              }
323              Some(j) => {
324                match j.get(&h.2.0) {
325                  None => {
326                    continue;
327                  }
328                  Some(rb) => {
329                    if dead_rbs.0.contains(&rb) {
330                      n_known_dead += 1
331                    }
332                  }
333                }
334              }
335            }
336          }
337        }
338      } // end loop over trigger hits
339        //  we use <= here, because sometimes, 
340        //  the link ids are wrong, so n_known_dead 
341        //  might be false positive
342      let n_rb_link_ids = self.get_rb_link_ids().len();
343      //if n_rb_link_ids <= self.rb_events.len() + n_known_dead {
344      //  self.status = EventStatus::KnownDeadRB; 
345      //}
346      return n_rb_link_ids <= self.rb_events.len() + n_known_dead;
347    }
348  }
349  
350  /// The number of hits we did not get 
351  /// becaue of the DRS busy
352  pub fn get_lost_hits(&self) -> u16 {
353    let mut lost_hits = 0u16;
354    for rbev in &self.rb_events {
355      if rbev.header.drs_lost_trigger() {
356        let mut nhits = rbev.header.get_nchan() as u16;
357        // FIXME - I don't understand this - that would only work if the RB 
358        // sees 2 channels, that is 1 hit (?) Potential bug
359        if nhits > 0 {
360          nhits -= 1;
361        }
362        lost_hits += nhits;
363      }
364    }
365    lost_hits
366  }
367
368
369  /// Calculate extra variables for the GCU, 
370  /// set the protocol version to V1 and 
371  /// strip the waveforms if desired
372  /// 
373  /// # Arguments:
374  ///   * strip_rbevents : remove the rbevents from the TofEvent so they
375  ///                      won't bother the poor gcu
376  pub fn prepare_for_gcu(&mut self, strip_rbevents : bool) {
377    if strip_rbevents {
378      self.strip_rbevents();
379    }
380    self.version = ProtocolVersion::V1;
381    if self.n_hits_cbe == 0 && self.n_hits_umb == 0 && self.n_hits_cor == 0 {
382      self.calc_gcu_variables();
383    }
384  }
385 
386  /// Calculate the TOF part of the interesting events mechanism, whcih is
387  /// NHIT (CBE, COR, UMB) and EDEP (CBE, COR, UMB)
388  ///
389  /// The energies are the linear estimate without attenuation
390  /// (TofHit::get_edep_linear_noatt), not the default TofHit::get_edep:
391  /// this runs on the flight computer (liftof), where the hits do not
392  /// know their paddle, and the thresholds of the interesting events
393  /// are set for this estimate.
394  pub fn calc_gcu_variables(&mut self) {
395    if self.hits.len() == 0 {
396      for rbev in &self.rb_events {
397        for h in &rbev.hits {
398          if h.paddle_id <= 60 {
399            self.n_hits_cbe += 1;
400            self.tot_edep_cbe += h.get_edep_linear_noatt();
401          }
402          else if h.paddle_id <= 108 && h.paddle_id > 60 {
403            self.n_hits_umb += 1;
404            self.tot_edep_umb += h.get_edep_linear_noatt();
405          }
406          else {
407            self.n_hits_cor += 1;
408            self.tot_edep_cor += h.get_edep_linear_noatt();
409          }
410        }
411      }
412    } else { 
413      for h in &self.hits {
414        if h.paddle_id <= 60 {
415          self.n_hits_cbe += 1;
416          self.tot_edep_cbe += h.get_edep_linear_noatt();
417        }
418        else if h.paddle_id <= 108 && h.paddle_id > 60 {
419          self.n_hits_umb += 1;
420          self.tot_edep_umb += h.get_edep_linear_noatt();
421        }
422        else {
423          self.n_hits_cor += 1;
424          self.tot_edep_cor += h.get_edep_linear_noatt();
425        }
426      }
427    }
428  }
429
430  /// Ensure compatibility with older data, which 
431  /// contained a different type of TofEvent
432  pub fn decode_depr_tofevent_size_header(mask : &u32) 
433    -> (usize, usize) {
434    let rb_event_len = (mask & 0xFF)        as usize;
435    let miss_len     = ((mask & 0xFF00)     >> 8)  as usize;
436    (rb_event_len, miss_len)
437  }
438
439  /// Set timing offsets on the hit times of the events' hits,
440  /// which absorb any systematic besides the phase & cable length.
441  ///
442  /// This will NOT yet subtract these numbers. To 
443  /// do so, the hit times have to be "normalized" by 
444  /// calling ev.normalize_hit_times 
445  ///
446  /// Hits of paddles which are not in offsets get an offset
447  /// of 0, so an empty map removes all offsets.
448  ///
449  /// If the hit times have already been normalized, the
450  /// offsets can not be applied anymore. In that case,
451  /// nothing is changed and an error is logged.
452  ///
453  /// # Arguments:
454  ///   * offsets : a hashmap paddle id -> timing offset
455  #[cfg(feature="database")]
456  pub fn set_timing_offsets(&mut self, offsets : &HashMap<u8, f32>) {
457    if self.hit_times_normalized {
458      error!("The hit times of event {} have already been normalized, the timing offsets can not be applied anymore! Call set_timing_offsets before normalize_hit_times.", self.event_id);
459      return;
460    }
461    for h in self.hits.iter_mut() {
462      h.timing_offset = offsets.get(&h.paddle_id).copied().unwrap_or(0.0);
463    }
464  }
465
466  /// Remove hits from the hitseries which can not 
467  /// be caused by the same particle, which means 
468  /// that for these two specific hits beta with 
469  /// respect to the first hit in the event is 
470  /// larger than one
471  /// That this works, first hits need to be 
472  /// "normalized" by calling normalize_hit_times
473  ///
474  /// # Return:
475  ///
476  ///   * removed paddle ids, twindows
477  pub fn lightspeed_cleaning(&mut self, t_err : f32) -> (Vec<u8>, Vec<f32>) {
478    // first sort the hits in time
479    if self.hits.len() == 0 {
480      return (Vec::<u8>::new(), Vec::<f32>::new());
481    }
482    let mut twindows = Vec::<f32>::new();
483    self.hits.sort_by(|a,b| (a.event_t0).partial_cmp(&b.event_t0).unwrap_or(Ordering::Greater));
484    let first_hit = self.hits[0].clone(); // the clone here is a bit unfortunate, 
485                                           // this can be done better with walking 
486                                           // over the list and updating references
487    let mut clean_hits = Vec::<TofHit>::new(); 
488    let mut rm_hits    = Vec::<u8>::new();
489    // per definition, we can't remove the first hit, ever
490    clean_hits.push(first_hit.clone());
491    //error!("-----");
492    let mut prior_hit = first_hit;
493    //println!("TO FIRST {}",first_hit.event_t0);
494    for h in self.hits.iter().skip(1) {
495      let min_tdiff_cvac = 1e9*1e-3*prior_hit.distance(h)/299792458.0;
496      let twindow            = prior_hit.event_t0 + min_tdiff_cvac;
497
498      // FIXME - implement different strategies
499      // this is the "default" strategy
500      //if h.event_t0 < twindow {
501      //  rm_hits.push(h.paddle_id);
502      //  twindows.push(twindow);
503      //  continue;
504      //}
505      // this is the "lenient" strategy
506      if h.event_t0 + 2.0*t_err < twindow {
507        rm_hits.push(h.paddle_id);
508        twindows.push(twindow);
509        continue;
510      }
511      // this is the "aggressive" strategy
512      //if h.event_t0 - 2.0*t_err < twindow {
513      //  rm_hits.push(h.paddle_id);
514      //  continue;
515      //}
516      
517      // should we remove negative beta hits?
518      //if beta < 0.0 {
519      //  rm_hits.push(h.paddle_id);
520      //  continue;
521      //}
522      // update the prior hit only 
523      // when it is a good one. If it 
524      // is bad we continue to compare
525      // to the first hit
526      prior_hit = h.clone();
527      clean_hits.push(*h);
528    }
529    self.hits = clean_hits;
530    (rm_hits, twindows)
531  }
532
533
534  /// Non causal hits have hit times in ends A and be which 
535  /// are not compatible with the speed of light in the paddle, 
536  /// that is, the hit gets registered too early. If we look 
537  /// at a plot of the reconstructed position, these hits would 
538  /// correspond to positions outside of the paddle.
539  ///
540  /// #Returns:
541  ///   A vector of paddle ids with removed hits
542  ///
543  pub fn remove_non_causal_hits(&mut self) -> Vec<u8> {
544    let mut clean_hits = Vec::<TofHit>::new();
545    let mut removed_pids = Vec::<u8>::new();
546    for h in &self.hits {
547      if h.obeys_causality() {
548        clean_hits.push(*h);
549      } else {
550        removed_pids.push(h.paddle_id);
551      }
552    }
553    self.hits = clean_hits;
554    removed_pids
555  }
556
557  /// Revisit all hit times and apply all event-wide 
558  /// corrections (local, e.g. cable corrections) 
559  /// and global (phase difference, timing offsets) 
560  /// applied and then after, sort them by time.
561  ///
562  /// The order of functions calls needs to be 
563  /// 1) ev.set_timing_offsets 
564  /// 2) ev.normalize_hit_times
565  ///
566  /// This is only done once per event (see
567  /// hit_times_normalized), further calls do nothing.
568  #[cfg(feature="database")]
569  pub fn normalize_hit_times(&mut self) {
570    if self.hits.len() == 0 {
571      return;
572    }
573    if self.hit_times_normalized {
574      return;
575    }
576
577    let phase0 = self.hits[0].phase.to_f32();
578    // add the corrections here 
579    // 1) phase
580    // 2) second timing offsets 
581    for h in &mut self.hits {
582      let t0 = h.get_t0_uncorrected() + h.get_cable_delay();
583      // deal with the phase difference
584      let mut phase_diff = h.phase.to_f32() - phase0;
585      while phase_diff < - PI/2.0 {
586        phase_diff += 2.0*PI;
587      }
588      while phase_diff > PI/2.0 {
589        phase_diff -= 2.0*PI;
590      }
591      let t_shift = 50.0*phase_diff/(2.0*PI);
592      h.event_t0 = t0 + t_shift - h.timing_offset;
593    }
594    // start the first hit at 0
595    //self.hits.sort_by(|a,b| (a.event_t0).partial_cmp(&b.event_t0).unwrap_or(Ordering::Greater));
596    self.hits.sort_by(|a,b| (a.event_t0).total_cmp(&b.event_t0));
597    let t0_first_hit = self.hits[0].event_t0;
598    for h in self.hits.iter_mut() {
599      h.event_t0 -= t0_first_hit;
600    }
601    self.hit_times_normalized = true;
602  }
603
604  /// Set the timing offsets and normalize the hit times in
605  /// one go, see set_timing_offsets and normalize_hit_times.
606  ///
607  /// # Arguments:
608  ///   * offsets : a hashmap paddle id -> timing offset. If
609  ///               None, the offsets which have been set
610  ///               before (by default none) are used
611  #[cfg(feature="database")]
612  pub fn normalize_hit_times_with_offsets(&mut self, offsets : Option<&HashMap<u8, f32>>) {
613    if let Some(offsets) = offsets {
614      self.set_timing_offsets(offsets);
615    }
616    self.normalize_hit_times();
617  }
618
619  /// Hits in two overlapping paddles (see TofPaddleOverlaps) at
620  /// the same time come from a particle going through the
621  /// overlap: move both hits across the paddles to the middle of
622  /// the overlap. Their positions along the paddles and along the
623  /// normal are kept.
624  ///
625  /// Needs the hit positions (set_paddles) and normalized hit
626  /// times (normalize_hit_times), otherwise nothing is changed.
627  /// A hit whose paddle overlaps with two hit neighbours is moved
628  /// for each pair, the last pair (ordered by paddle ids) wins.
629  ///
630  /// # Arguments:
631  ///   * overlaps : the overlapping paddles
632  ///   * max_dt   : largest time difference of the two hits (ns)
633  ///
634  /// # Returns:
635  ///   * the number of merged pairs
636  #[cfg(feature="database")]
637  pub fn merge_overlapping_hits(&mut self, overlaps : &TofPaddleOverlaps, max_dt : f32) -> usize {
638    if !self.hit_times_normalized {
639      warn!("The hit times are not normalized, can not merge hits of overlapping paddles!");
640      return 0;
641    }
642    let mut index = HashMap::<u8, usize>::new();
643    for (k, h) in self.hits.iter().enumerate() {
644      index.entry(h.paddle_id).or_insert(k);
645    }
646    let mut nmerged = 0usize;
647    for (&(a, b), ov) in &overlaps.overlaps {
648      let (Some(&i), Some(&j)) = (index.get(&a), index.get(&b)) else {
649        continue;
650      };
651      let (hi, hj) = (&self.hits[i], &self.hits[j]);
652      if !(hi.event_t0.is_finite() && hj.event_t0.is_finite())
653         || (hi.event_t0 - hj.event_t0).abs() > max_dt
654         || !(hi.x.is_finite() && hj.x.is_finite()) {
655        continue;
656      }
657      for k in [i, j] {
658        let h     = &mut self.hits[k];
659        let shift = ov.position - (h.x*ov.across[0] + h.y*ov.across[1] + h.z*ov.across[2]);
660        h.x += shift*ov.across[0];
661        h.y += shift*ov.across[1];
662        h.z += shift*ov.across[2];
663      }
664      nmerged += 1;
665    }
666    nmerged
667  }
668
669  /// True if the hit times have been normalized with any
670  /// (non-zero) timing offset
671  pub fn timing_offsets_applied(&self) -> bool {
672    self.hit_times_normalized && self.hits.iter().any(|h| h.timing_offset != 0.0)
673  }
674
675  /// Certain quantitities can only be calculated if we know more 
676  /// about the paddle the hit was seen in. 
677  /// This meta information is not stored within the hit to save 
678  /// space for telemetry/storage reasons.
679  ///
680  /// The meta-information (e.g. paddle length) can be added by 
681  /// filling in the blanks from the specific paddles as obtained 
682  /// from the database shipped with gondola.
683  #[cfg(feature="database")]
684  pub fn set_paddles(&mut self, paddles : &HashMap<u8, TofPaddle>) {
685    let mut nerror = 0u8;
686    if paddles.is_empty() {
687      debug!("Unable to set paddles, empty map given!");
688      return;
689    }
690    if self.hits.len() == 0 {
691      for rbev  in &mut self.rb_events {
692        for h in &mut rbev.hits {
693          match paddles.get(&h.paddle_id) {
694            None => {
695              error!("Got paddle id {} which is not in given map!", h.paddle_id);
696              nerror += 1;
697              continue;
698            }
699            Some(pdl) => {
700              let _ = h.set_paddle(pdl);
701            }
702          }
703        }
704      }
705    } else {
706      for h in &mut self.hits {
707        match paddles.get(&h.paddle_id) {
708          None => {
709            error!("Got paddle id {} which is not in given map!", h.paddle_id);
710            nerror += 1;
711            continue;
712          }
713          Some(pdl) => {
714            let _ = h.set_paddle(pdl);
715          }
716        }
717      }
718    }
719    if nerror == 0 {
720      self.paddles_set = true;
721      //self.normalize_hit_times();
722    }
723  }
724
725  /// Get the pointcloud of this event, sorted by time. 
726  /// For this to work, the event times have to be 
727  /// normalized first, this means that the first hit 
728  /// in the event is at 0 and the hits have been 
729  /// sorted in time
730  /// 
731  /// # Returns
732  ///   (f32, f32, f32, f32, f32) : (x,y,z,t,edep)
733  pub fn get_pointcloud(&self) -> Option<Vec<(f32,f32,f32,f32,f32)>> {
734    let mut pc = Vec::<(f32,f32,f32,f32,f32)>::new();
735    if !self.paddles_set {
736      error!("Before getting the pointcloud, paddle information needs to be set for this event. Call TofEvent;:set_paddle");
737      return None;
738    }
739    for h in &self.hits {
740      let result = (h.x, h.y, h.z, h.event_t0, h.get_edep());
741      pc.push(result);
742    }
743    Some(pc)
744  }
745
746  /// Compare the MasterTriggerEvent::trigger_hits with 
747  /// the actual hits to determine from which paddles
748  /// we should have received HG hits (from waveforms)
749  /// but we did not get them
750  ///
751  /// WARNING: The current implementation of this is 
752  /// rather slow and not fit for production use
753  /// FIXME - rewrite as a closure
754  #[cfg(feature="database")]
755  pub fn get_missing_paddles_hg(&self, pid_map :   &DsiJChPidMapping) -> Vec<u8> {
756    let mut missing = Vec::<u8>::new();
757    for th in self.get_trigger_hits() {
758      if !pid_map.contains_key(&th.0) {
759        error!("Can't find {:?} in paddlemap!",th);
760        continue;
761      }
762      if !pid_map.get(&th.0).unwrap().contains_key(&th.1) {
763        error!("Can't find {:?} in paddlemap!",th);
764        continue;
765      }
766      if !pid_map.get(&th.0).unwrap().get(&th.1).unwrap().contains_key(&th.2.0) {
767        error!("Can't find {:?} in paddlemap!",th);
768        continue;
769      }
770      let pid = pid_map.get(&th.0).unwrap().get(&th.1).unwrap().get(&th.2.0).unwrap().0;
771      let mut found = false;
772      for h in &self.hits {
773        if h.paddle_id == pid {
774          found = true;
775          break
776        }
777      }
778      if !found {
779        missing.push(pid);
780      }
781    }
782    missing
783  }
784  
785  /// Get the triggered paddle ids
786  ///
787  /// Warning, this might be a bit slow
788  #[cfg(feature="database")]
789  pub fn get_triggered_paddles(&self, pid_map :   &DsiJChPidMapping) -> Vec<u8> {
790    let mut paddles = Vec::<u8>::with_capacity(3);
791    for th in &self.get_trigger_hits() {
792      let pid = pid_map.get(&th.0).unwrap().get(&th.1).unwrap().get(&th.2.0).unwrap().0;
793      paddles.push(pid);
794    }
795    paddles
796  }
797
798  /// Get the RB link IDs according to the mask
799  pub fn get_rb_link_ids(&self) -> Vec<u8> {
800    let mut links = Vec::<u8>::new();
801    for k in 0..64 {
802      if (self.mtb_link_mask >> k) as u64 & 0x1 == 1 {
803        links.push(k as u8);
804      }
805    }
806    links
807  }
808
809  /// Get the combination of triggered DSI/J/CH on 
810  /// the MTB which formed the trigger. This does 
811  /// not include further hits which fall into the 
812  /// integration window. For those, se rb_link_mask
813  ///
814  /// The returned values follow the TOF convention
815  /// to start with 1, so that we can use them to 
816  /// look up LTB ids in the db.
817  ///
818  /// # Returns
819  ///
820  ///   Vec<(hit)> where hit is (DSI, J, CH) 
821  pub fn get_trigger_hits(&self) -> Vec<(u8, u8, (u8, u8), LTBThreshold)> {
822    let mut hits = Vec::<(u8,u8,(u8,u8),LTBThreshold)>::with_capacity(5); 
823    //let n_masks_needed = self.dsi_j_mask.count_ones() / 2 + self.dsi_j_mask.count_ones() % 2;
824    let n_masks_needed = self.dsi_j_mask.count_ones();
825    if self.channel_mask.len() < n_masks_needed as usize {
826      error!("We need {} hit masks, but only have {}! This is bad!", n_masks_needed, self.channel_mask.len());
827      return hits;
828    }
829    let mut n_mask = 0;
830    trace!("Expecting {} hit masks", n_masks_needed);
831    trace!("ltb channels {:?}", self.dsi_j_mask);
832    trace!("hit masks {:?}", self.channel_mask); 
833    //println!("We see LTB Channels {:?} with Hit masks {:?} for {} masks requested by us!", self.dsi_j_mask, self.channel_mask, n_masks_needed);
834    
835    // one k here is for one ltb
836    for k in 0..32 {
837      if (self.dsi_j_mask >> k) as u32 & 0x1 == 1 {
838        let mut dsi = 0u8;
839        let mut j   = 0u8;
840        if k < 5 {
841          dsi = 1;
842          j   = k as u8 + 1;
843        } else if k < 10 {
844          dsi = 2;
845          j   = k as u8 - 5 + 1;
846        } else if k < 15 {
847          dsi = 3;
848          j   = k as u8- 10 + 1;
849        } else if k < 20 {
850          dsi = 4;
851          j   = k as u8- 15 + 1;
852        } else if k < 25 {
853          dsi = 5;
854          j   = k as u8 - 20 + 1;
855        } 
856        //let dsi = (k as f32 / 4.0).floor() as u8 + 1;       
857        //let j   = (k % 5) as u8 + 1;
858        //println!("n_mask {n_mask}");
859        let channels = self.channel_mask[n_mask]; 
860        for (i,ch) in LTB_CHANNELS.iter().enumerate() {
861          //let chn = *ch as u8 + 1;
862          let ph_chn = PHYSICAL_CHANNELS[i];
863          //let chn = i as u8 + 1;
864          //println!("i,ch {}, {}", i, ch);
865          let thresh_bits = ((channels & ch) >> (i*2)) as u8;
866          //println!("thresh_bits {}", thresh_bits);
867          if thresh_bits > 0 { // hit over threshold
868            hits.push((dsi, j, ph_chn, LTBThreshold::from(thresh_bits)));
869          }
870        }
871        n_mask += 1;
872      } // next ltb
873    }
874    hits
875  }
876  
877  /// Get the trigger sources from trigger source byte
878  pub fn get_trigger_sources(&self) -> Vec<TriggerType> {
879    TriggerType::transcode_trigger_sources(self.trigger_sources)
880  }
881  
882  /// The full GPS timestamp (10ns ticks since UNIX epoch)
883  ///
884  /// Only the lower 48 bits are sent, the upper bits are 
885  /// reconstructed from GPS_TIMESTAMP48_REFERENCE, so this
886  /// is only valid within +- 16.29 days around that.
887  pub fn get_timestamp48(&self) -> u64 {
888    expand_gps_timestamp48(((self.timestamp16 as u64) << 32) | self.timestamp32 as u64)
889  }
890  
891  /// Ttotal energy depostion in the TOF - Umbrella
892  ///
893  /// Utilizes Philip's formula based on 
894  /// peak height
895  pub fn get_edep_umbrella(&self) -> f32 {
896    let mut tot_edep = 0.0f32;
897    for h in &self.hits {
898      if h.paddle_id < 61 || h.paddle_id > 108 {
899        continue;
900      }
901      tot_edep += h.get_edep();
902    }
903    tot_edep
904  }
905  
906  /// Ttotal energy depostion in the TOF - Umbrella
907  ///
908  /// Utilizes Philip's formula based on 
909  /// peak height
910  pub fn get_edep_cube(&self) -> f32 {
911    let mut tot_edep = 0.0f32;
912    for h in &self.hits {
913      if h.paddle_id > 60 {
914        continue;
915      }
916      tot_edep += h.get_edep();
917    }
918    tot_edep
919  }
920  
921  /// Ttotal energy depostion in the Cortina
922  ///
923  /// Utilizes Philip's formula based on 
924  /// peak height
925  pub fn get_edep_cortina(&self) -> f32 {
926    let mut tot_edep = 0.0f32;
927    for h in &self.hits {
928      if h.paddle_id < 109 {
929        continue;
930      }
931      tot_edep += h.get_edep();
932    }
933    tot_edep
934  }
935  
936  /// Ttotal energy depostion in the complete TOF
937  ///
938  /// Utilizes Philip's formula based on 
939  /// peak height
940  pub fn get_edep(&self) -> f32 {
941    let mut tot_edep = 0.0f32;
942    for h in &self.hits {
943      tot_edep += h.get_edep();
944    }
945    tot_edep
946  }
947
948  /// The number of hits in the umbrella (UMB)
949  pub fn get_nhits_umb(&self) -> usize {
950    let mut nhit = 0;
951    for h in &self.hits {
952      if h.paddle_id > 60 && h.paddle_id < 109 {
953        nhit += 1;
954      }
955    }
956    nhit
957  }
958  
959  /// The number of hits in the cube (CBE)
960  pub fn get_nhits_cbe(&self) -> usize {
961    let mut nhit = 0;
962    for h in &self.hits {
963      if h.paddle_id < 61  {
964        nhit += 1;
965      }
966    }
967    nhit
968  }
969  
970  pub fn get_nhits_cor(&self) -> usize {
971    let mut nhit = 0;
972    for h in &self.hits {
973      if h.paddle_id > 108  {
974        nhit += 1;
975      }
976    }
977    nhit
978  }
979
980  pub fn get_nhits(&self) -> usize {
981    self.hits.len()
982  }
983  
984  /// Check if th eassociated RBEvents have any of their
985  /// mangling stati set
986  pub fn has_any_mangling(&self) -> bool {
987    for rbev in &self.rb_events {
988      if rbev.status == EventStatus::CellAndChnSyncErrors 
989      || rbev.status == EventStatus::CellSyncErrors 
990      || rbev.status == EventStatus::ChnSyncErrors {
991        return true;
992      }
993    }
994    false
995  }
996  
997  /// Get all waveforms of all RBEvents in this event
998  /// ISSUE - Performance, Memory
999  /// FIXME - reimplement this things where this
1000  ///         returns only a reference
1001  pub fn get_waveforms(&self) -> Vec<RBWaveform> {
1002    let mut wfs = Vec::<RBWaveform>::new();
1003    for ev in &self.rb_events {
1004      for wf in &ev.get_rbwaveforms() {
1005        wfs.push(wf.clone());
1006      }
1007    }
1008    wfs
1009  }
1010
1011  /// Change the status version when the event is already 
1012  /// packed. The status version is encoded in byte 2 
1013  /// (starting from 0) in the payload of the TofPacket 
1014  pub fn set_packed_status_version(pack : &mut TofPacket, version : ProtocolVersion) 
1015    -> Result<(), SerializationError> {
1016    if pack.packet_type != TofPacketType::TofEvent {
1017      return Err(SerializationError::IncorrectPacketType);
1018    }
1019    let mut status_version = pack.payload[2];
1020    // null the bytes relevant for the version 
1021    status_version  = status_version & 0x3f;
1022    // now or the bytes for the new version 
1023    status_version  = status_version | version.to_u8();
1024    pack.payload[2] = status_version; 
1025    Ok(()) 
1026  }
1027
1028  /// For events with ProtocolVersion == V3, 
1029  /// we have the rbevents at the end and the 
1030  /// packet contains the GCU variables.
1031  ///
1032  /// This can remove the rbevents from a packed bytestrem,
1033  /// and will reset the ProtocolVersion to V2.
1034  /// The result is an event which should be ready 
1035  /// to be sent to the GCU.
1036  pub fn strip_packed_rbevents_for_pv3(pack : &mut TofPacket)
1037    -> Result<(), SerializationError> {
1038    if pack.packet_type != TofPacketType::TofEvent {
1039      return Err(SerializationError::IncorrectPacketType);
1040    }
1041    let status_version = pack.payload[2];
1042    let mut version    = ProtocolVersion::from(status_version & 0xc0);
1043    if version != ProtocolVersion::V3 {
1044      error!("This operation can only be executed on {}, however, this is version {}!", ProtocolVersion::V3, version);
1045      return Err(SerializationError::WrongProtocolVersion);
1046    }
1047    // jump to the start of RBEvents 
1048    let mut pos = 0usize;
1049    pos += 10; // header 
1050    pos += 15; // gcu variables (protocolversion V1 & V3) 
1051    pos += 15;
1052    if pack.payload.len() >= pos {
1053      return Err(SerializationError::StreamTooShort);
1054    }
1055    let nmasks = parse_u8(&pack.payload, &mut pos);
1056    for _ in 0..nmasks {
1057      pos += 2;
1058    }
1059    pos += 8;
1060    let nhits  = parse_u16(&pack.payload,&mut pos);
1061    // set back the version
1062    for _ in 0..nhits {
1063      pos += TofHit::SIZE;
1064      // FIXME - if we don't be able to manage 
1065      //         to have a consistent size for 
1066      //         TofHit, we have to deserialize them 
1067      //         here (or write a minimal deserializer
1068    }
1069    // the next byte is finally the number of RBEvents. 
1070    // So we set that to 0, strip the rest of the paylod 
1071    // and re-attach the TAIL
1072    pack.payload.truncate(pack.payload.len() - pos);
1073    pack.payload.extend_from_slice(&Self::TAIL.to_le_bytes());
1074    version = ProtocolVersion::V2;
1075    Self::set_packed_status_version(pack, version)?;
1076    Ok(())
1077  }
1078}
1079
1080impl TofPackable for TofEvent {
1081  // v0.11 TofPacketType::TofEventSummary -> TofPacketType::TofEvent
1082  const TOF_PACKET_TYPE        : TofPacketType = TofPacketType::TofEvent;
1083  const TOF_PACKET_TYPE_ALT    : TofPacketType = TofPacketType::TofEventDeprecated;
1084}
1085
1086impl Serialization for TofEvent {
1087  
1088  const HEAD               : u16   = 43690; //0xAAAA
1089  const TAIL               : u16   = 21845; //0x5555
1090  
1091  fn to_bytestream(&self) -> Vec<u8> {
1092    let mut stream = Vec::<u8>::new();
1093    stream.extend_from_slice(&Self::HEAD.to_le_bytes());
1094    let status_version = self.status as u8 | self.version.to_u8();
1095    stream.push(status_version);
1096    stream.extend_from_slice(&self.trigger_sources.to_le_bytes());
1097    stream.extend_from_slice(&self.n_trigger_paddles.to_le_bytes());
1098    stream.extend_from_slice(&self.event_id.to_le_bytes());
1099    // depending on the version, we send the fc event packet
1100    if self.version == ProtocolVersion::V1 
1101      || self.version == ProtocolVersion::V3 {
1102      stream.extend_from_slice(&self.n_hits_umb  .to_le_bytes()); 
1103      stream.extend_from_slice(&self.n_hits_cbe  .to_le_bytes()); 
1104      stream.extend_from_slice(&self.n_hits_cor  .to_le_bytes()); 
1105      stream.extend_from_slice(&self.tot_edep_umb.to_le_bytes()); 
1106      stream.extend_from_slice(&self.tot_edep_cbe.to_le_bytes()); 
1107      stream.extend_from_slice(&self.tot_edep_cor.to_le_bytes()); 
1108    }
1109    stream.extend_from_slice(&(self.quality as u8).to_le_bytes());
1110    stream.extend_from_slice(&self.timestamp32.to_le_bytes());
1111    stream.extend_from_slice(&self.timestamp16.to_le_bytes());
1112    stream.extend_from_slice(&self.run_id.to_le_bytes());
1113    stream.extend_from_slice(&self.drs_dead_lost_hits.to_le_bytes());
1114    stream.extend_from_slice(&self.dsi_j_mask.to_le_bytes());
1115    let n_channel_masks = self.channel_mask.len();
1116    stream.push(n_channel_masks as u8);
1117    for k in 0..n_channel_masks {
1118      stream.extend_from_slice(&self.channel_mask[k].to_le_bytes());
1119    }
1120    stream.extend_from_slice(&self.mtb_link_mask.to_le_bytes());
1121    let nhits = self.hits.len() as u16;
1122    stream.extend_from_slice(&nhits.to_le_bytes());
1123    for k in 0..self.hits.len() {
1124      stream.extend_from_slice(&self.hits[k].to_bytestream());
1125    }
1126    // for the new (>=v0.11) event, we will always write 
1127    // the rb events
1128    if self.version == ProtocolVersion::V2 
1129      || self.version == ProtocolVersion::V3 {
1130      stream.push(self.rb_events.len() as u8);
1131      for rbev in &self.rb_events {
1132        stream.extend_from_slice(&rbev.to_bytestream());
1133      }
1134    }
1135    stream.extend_from_slice(&Self::TAIL.to_le_bytes());
1136    stream
1137  }
1138  
1139  fn from_bytestream(stream    : &Vec<u8>, 
1140                     pos       : &mut usize) 
1141    -> Result<Self, SerializationError>{
1142    let mut event = Self::new();
1143    let head      = parse_u16(stream, pos);
1144    if head != Self::HEAD {
1145      error!("Decoding of HEAD failed! Got {} instead!", head);
1146      return Err(SerializationError::HeadInvalid);
1147    }
1148    
1149    let status_version_u8   = parse_u8(stream, pos);
1150    let status              = EventStatus::from(status_version_u8 & 0x3f);
1151    let version             = ProtocolVersion::from(status_version_u8 & 0xc0); 
1152    event.status            = status;
1153    event.version           = version;
1154    event.trigger_sources   = parse_u16(stream, pos);
1155    event.n_trigger_paddles = parse_u8(stream, pos);
1156    event.event_id          = parse_u32(stream, pos);
1157    if event.version == ProtocolVersion::V1
1158      || event.version == ProtocolVersion::V3 {
1159      event.n_hits_umb      = parse_u8(stream, pos); 
1160      event.n_hits_cbe      = parse_u8(stream, pos); 
1161      event.n_hits_cor      = parse_u8(stream, pos); 
1162      event.tot_edep_umb    = parse_f32(stream, pos); 
1163      event.tot_edep_cbe    = parse_f32(stream, pos); 
1164      event.tot_edep_cor    = parse_f32(stream, pos); 
1165    }
1166    event.quality            = EventQuality::from(parse_u8(stream, pos));
1167    event.timestamp32        = parse_u32(stream, pos);
1168    event.timestamp16        = parse_u16(stream, pos);
1169    event.run_id             = parse_u16(stream, pos);
1170    event.drs_dead_lost_hits = parse_u16(stream, pos);
1171    event.dsi_j_mask         = parse_u32(stream, pos);
1172    let n_channel_masks        = parse_u8(stream, pos);
1173    for _ in 0..n_channel_masks {
1174      event.channel_mask.push(parse_u16(stream, pos));
1175    }
1176    event.mtb_link_mask      = parse_u64(stream, pos);
1177    let nhits                = parse_u16(stream, pos);
1178    //println!("{}", event);
1179    if nhits > 160 {
1180      error!("There are an abnormous amount of hits in this event!");
1181      return Err(SerializationError::StreamTooLong);
1182    } 
1183    for _ in 0..nhits {
1184      event.hits.push(TofHit::from_bytestream(stream, pos)?);
1185    }
1186    if event.version == ProtocolVersion::V2 
1187      || event.version == ProtocolVersion::V3 {
1188      let n_rb_events = parse_u8(stream, pos);
1189      if n_rb_events > 0 {
1190        for _ in 0..n_rb_events {
1191          event.rb_events.push(RBEvent::from_bytestream(stream, pos)?);
1192        }
1193      }
1194    }
1195
1196    let tail = parse_u16(stream, pos);
1197    if tail != Self::TAIL {
1198      error!("Decoding of TAIL failed for version {}! Got {} instead!", version, tail);
1199      return Err(SerializationError::TailInvalid);
1200    }
1201    Ok(event)
1202  }
1203  
1204  /// Allows to get TofEvent from a packet 
1205  /// of the deprecate packet type TofEventDeprecated.
1206  /// This packet type was formerly known as TofEvent
1207  ///
1208  /// This will produce an event with rbevents & hits.
1209  fn from_bytestream_alt(stream    : &Vec<u8>, 
1210                         pos       : &mut usize) 
1211    -> Result<Self, SerializationError> {
1212    let head = parse_u16(stream, pos);
1213    if head != TofEvent::HEAD {
1214      return Err(SerializationError::HeadInvalid);
1215    }
1216    let mut te            = Self::new();
1217    // the compression level will always be 0 for old data
1218    let _compression_level = parse_u8(stream, pos);
1219
1220    te.quality            = EventQuality::from(parse_u8(stream, pos));
1221    // at this position is the serialized TofEventHeader. We don't have that anymore (>v0.11). 
1222    // However, the only information we need from it is the run id, the other fields are anyway
1223    // empty
1224    *pos += 2; // for TofEventHeader::HEAD
1225    // FIXME - potentially dangerous for u16 overflow!
1226    te.run_id             = parse_u32(stream, pos) as u16;
1227    *pos += 43 - 6;// rest of TofEventHeader 
1228    //let header         = TofEventHeader::from_bytestream(stream, &mut pos)?;
1229    // now parse the "old" MasterTriggerEvent
1230    *pos += 2; // MasterTriggerEvent::HEAD
1231    let event_status   = parse_u8 (stream, pos);
1232    te.status              = EventStatus::from(event_status);
1233    if te.has_any_mangling() {
1234      te.status = EventStatus::AnyDataMangling;
1235    }
1236    te.event_id        = parse_u32(stream, pos);
1237    let mtb_timestamp  = parse_u32(stream, pos);
1238    let tiu_timestamp  = parse_u32(stream, pos);
1239    let tiu_gps32      = parse_u32(stream, pos);
1240    let _tiu_gps16     = parse_u16(stream,pos);
1241    let _crc           = parse_u32(stream, pos);
1242    let mt_timestamp   = (mt_event_get_timestamp_abs48(mtb_timestamp, tiu_gps32, tiu_timestamp ) as f64/1000.0).floor()  as u64; 
1243    te.timestamp32      = (mt_timestamp  & 0x00000000ffffffff ) as u32;
1244    te.timestamp16      = ((mt_timestamp & 0x0000ffff00000000 ) >> 32) as u16;
1245    te.trigger_sources  = parse_u16(stream, pos);
1246    te.dsi_j_mask       = parse_u32(stream, pos);
1247    let n_channel_masks = parse_u8(stream, pos);
1248    for _ in 0..n_channel_masks {
1249      te.channel_mask.push(parse_u16(stream, pos));
1250    }
1251
1252    te.mtb_link_mask      = parse_u64(stream, pos);
1253    let mt_event_tail     = parse_u16(stream, pos);
1254    if mt_event_tail != Self::TAIL {
1255      // (tail for mt event was the same)
1256      error!("Parsed TAIL from MT event is incorrect! Got {} instead of {} at pos {}", mt_event_tail, Self::TAIL, pos);
1257    }
1258    //let mt_event      = MasterTriggerEvent::from_bytestream(stream, &mut pos)?;
1259    let v_sizes           = Self::decode_depr_tofevent_size_header(&parse_u32(stream, pos));
1260    //println!("TofEvent - rbevents,  {:?}", v_sizes);
1261    for _ in 0..v_sizes.0 {
1262      // we are getting all waveforms for now, but we can 
1263      // discard them later
1264      let next_rb_event = RBEvent::from_bytestream(stream, pos)?;
1265      //println!("{}", next_rb_event);
1266      te.rb_events.push(next_rb_event);
1267    }
1268    //println!("{}",te);
1269    
1270    // FIXME - this is slow, use Arc<> instead. However, then make 
1271    // sure to copy them in case we get rid of the rb evvnts 
1272    // (or does Arc take care of it) 
1273    for rbev in &te.rb_events {
1274      for h in &rbev.hits {
1275        te.hits.push(*h);
1276      }
1277    }
1278    let tail = parse_u16(stream, pos);
1279    if tail != Self::TAIL {
1280      error!("Decoding of TAIL failed! Got {} instead!", tail);
1281      return Err(SerializationError::TailInvalid);
1282    }
1283    return Ok(te);
1284  }
1285}
1286    
1287impl Default for TofEvent {
1288  fn default() -> Self {
1289    Self::new()
1290  }
1291}
1292
1293impl fmt::Display for TofEvent {
1294  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1295    let mut repr = format!("<TofEvent (version {})", self.version);
1296    repr += &(format!("\n  EventID          : {}", self.event_id));
1297    repr += &(format!("\n  RunID            : {}", self.run_id));
1298    repr += &(format!("\n  EventStatus      : {}", self.status));
1299    repr += &(format!("\n  TriggerSources   : {:?}", self.get_trigger_sources()));
1300    repr += &(format!("\n  NTrigPaddles     : {}", self.n_trigger_paddles));
1301    repr += &(format!("\n  DRS dead hits    : {}", self.drs_dead_lost_hits));
1302    repr += &(format!("\n  timestamp32      : {}", self.timestamp32)); 
1303    repr += &(format!("\n  timestamp16      : {}", self.timestamp16)); 
1304    repr += &(format!("\n   |-> timestamp48 : {}", self.get_timestamp48())); 
1305    repr += &(format!("\n   |->       UNIX  : {}", (1e-8) * self.get_timestamp48() as f64)); 
1306    repr += &(format!("\n   |->        UTC  : {}", get_utc_timestamp_from_unix((1e-8) * self.get_timestamp48() as f64).unwrap_or(String::from("INVALID")))); 
1307    //repr += &(format!("\n  mt_tiu_gps16     : {}", self.mt_tiu_gps16));
1308    //repr += &(format!("\n  mt_tiu_gps32     : {}", self.mt_tiu_gps32)); 
1309    //repr += &(format!("\n  mt_timestamp     : {}", self.mt_timestamp));
1310    //repr += &(format!("\n  mt_tiu_timestamp : {}", self.mt_tiu_timestamp));
1311    //repr += &(format!("\n  gps timestamp    : {}", self.get_mt_timestamp_abs()));
1312    //repr += &(format!("\n  PrimaryBeta      : {}", self.get_beta())); 
1313    //repr += &(format!("\n  PrimaryCharge    : {}", self.primary_charge));
1314    if self.version == ProtocolVersion::V1 {
1315      repr += "\n ---- V1 variables ----";
1316      repr += &(format!("\n n_hits_umb   : {}", self.n_hits_umb  )); 
1317      repr += &(format!("\n n_hits_cbe   : {}", self.n_hits_cbe  )); 
1318      repr += &(format!("\n n_hits_cor   : {}", self.n_hits_cor  )); 
1319      repr += &(format!("\n tot_edep_umb : {}", self.tot_edep_umb)); 
1320      repr += &(format!("\n tot_edep_cbe : {}", self.tot_edep_cbe)); 
1321      repr += &(format!("\n tot_edep_cor : {}", self.tot_edep_cor)); 
1322    }
1323    repr += &(format!("\n  ** ** TRIGGER HITS (DSI/J/CH) [{} LTBS] ** **", self.dsi_j_mask.count_ones()));
1324    for k in self.get_trigger_hits() {
1325      repr += &(format!("\n  => {}/{}/({},{}) ({}) ", k.0, k.1, k.2.0, k.2.1, k.3));
1326    }
1327    repr += "\n  ** ** MTB LINK IDs ** **";
1328    let mut mtblink_str = String::from("\n  => ");
1329    for k in self.get_rb_link_ids() {
1330      mtblink_str += &(format!("{} ", k))
1331    }
1332    repr += &mtblink_str;
1333    repr += &(format!("\n  == Trigger hits {}, expected RBEvents {}",
1334            self.get_trigger_hits().len(),
1335            self.get_rb_link_ids().len()));
1336    repr += &String::from("\n  ** ** ** HITS ** ** **");
1337    for h in &self.hits {
1338      repr += &(format!("\n  {}", h));
1339    }
1340    if self.rb_events.len() > 0 {
1341      repr += &format!("\n -- has {} RBEvents with waveforms!", self.rb_events.len());
1342      repr += "\n -- -- boards: ";
1343      for b in &self.rb_events {
1344        repr += &format!("{} ", b.header.rb_id);
1345      }
1346    }
1347    repr += ">";
1348    write!(f, "{}", repr)
1349  }
1350}
1351
1352#[cfg(feature="random")]
1353impl FromRandom for TofEvent {
1354
1355  fn from_random() -> Self {
1356    let mut event             = Self::new();
1357    let mut rng               = rand::rng();
1358    let status                = EventStatus::from_random();
1359    let version               = ProtocolVersion::from_random();
1360    if version == ProtocolVersion::V1 {
1361      event.n_hits_umb        = rng.random::<u8>();
1362      event.n_hits_cbe        = rng.random::<u8>();
1363      event.n_hits_cor        = rng.random::<u8>();
1364      event.tot_edep_umb      = rng.random::<f32>();
1365      event.tot_edep_cbe      = rng.random::<f32>();
1366      event.tot_edep_cor      = rng.random::<f32>();
1367      event.quality           = EventQuality::from_random();
1368    }
1369    event.status             = status;
1370    event.version            = version;
1371    // variable packet for the FC
1372    event.trigger_sources    = rng.random::<u16>();
1373    event.n_trigger_paddles  = rng.random::<u8>();
1374    event.event_id           = rng.random::<u32>();
1375    event.timestamp32        = rng.random::<u32>();
1376    event.timestamp16        = rng.random::<u16>();
1377    event.drs_dead_lost_hits = rng.random::<u16>();
1378    event.dsi_j_mask         = rng.random::<u32>();
1379    let n_channel_masks        = rng.random::<u8>();
1380    for _ in 0..n_channel_masks {
1381      event.channel_mask.push(rng.random::<u16>());
1382    }
1383    event.mtb_link_mask      = rng.random::<u64>();
1384    //let nhits                  = rng.random::<u8>();
1385    let nhits: u16 = rng.random_range(0..5);
1386    for _ in 0..nhits {
1387      event.hits.push(TofHit::from_random());
1388    }
1389    if event.version == ProtocolVersion::V2 {
1390      let n_rb_events = rng.random_range(0..4);
1391      for _ in 0..n_rb_events {
1392        event.rb_events.push(RBEvent::from_random());
1393      }
1394    }
1395    event
1396  }
1397}
1398
1399//---------------------------------------------------
1400
1401#[cfg(feature="pybindings")]
1402#[pymethods]
1403impl TofEvent {
1404
1405  #[getter]
1406  #[pyo3(name="tof")] 
1407  fn get_tof_py(&mut self) -> Option<(f32,f32,f32,f32,f32)> {
1408    self.get_tof()
1409  }
1410
1411  #[pyo3(name="strip_rbevents")]
1412  fn strip_rbevents_py(&mut self) {
1413    self.strip_rbevents()
1414  }
1415  
1416  /// Calculate the TOF part of the interesting events mechanism, whcih is
1417  /// NHIT (CBE, COR, UMB) and EDEP (CBE, COR, UMB)
1418  #[pyo3(name="calc_gcu_variables")]
1419  fn calc_gcu_variables_py(&mut self) {
1420    self.calc_gcu_variables()
1421  }
1422
1423  /// Emit a copy of self
1424  fn copy(&self) -> Self {
1425    self.clone()
1426  }
1427
1428  /// Set timing offsets on the hit times of the events' hits,
1429  /// which absorb any systematic besides the phase & cable length.
1430  ///
1431  /// This will NOT yet subtract these numbers. To 
1432  /// do so, the hit times have to be "normalized" by 
1433  /// calling ev.normalize_hit_times 
1434  ///
1435  /// Hits of paddles which are not in offsets get an offset
1436  /// of 0. If the hit times have already been normalized,
1437  /// nothing is changed and an error is logged.
1438  ///
1439  /// # Arguments:
1440  ///   * offsets : a hashmap paddle id -> timing offset
1441  #[pyo3(name="set_timing_offsets")]
1442  pub fn set_timing_offsets_py(&mut self, timing_offsets : HashMap<u8, f32>) {
1443    self.set_timing_offsets(&timing_offsets);
1444  }
1445  
1446  /// Revisit all hit times and apply all event-wide 
1447  /// corrections (local, e.g. cable corrections) 
1448  /// and global (phase difference, timing offsets) 
1449  /// applied and then after, sort them by time.
1450  ///
1451  /// The timing offsets can either be given here, or set
1452  /// before with ev.set_timing_offsets.
1453  ///
1454  /// This is only done once per event, further calls
1455  /// do nothing (see hit_times_normalized)
1456  ///
1457  /// # Arguments:
1458  ///   * offsets : a dict paddle id -> timing offset. If
1459  ///               None, the offsets which have been set
1460  ///               before (by default none) are used
1461  #[pyo3(name="normalize_hit_times", signature = (offsets = None))]
1462  pub fn normalize_hit_times_py(&mut self, offsets : Option<HashMap<u8, f32>>) {
1463    self.normalize_hit_times_with_offsets(offsets.as_ref());
1464  }
1465  
1466  /// Remove hits from the hitseries which can not 
1467  /// be caused by the same particle, which means 
1468  /// that for these two specific hits beta with 
1469  /// respect to the first hit in the event is 
1470  /// larger than one
1471  /// That this works, first hits need to be 
1472  /// "normalized" by calling normalize_hit_times
1473  #[pyo3(name="lightspeed_cleaning")]
1474  pub fn lightspeed_cleaning_py(&mut self, t_err : f32) -> (Vec<u16>, Vec<f32>) {
1475    // return Vec<u16> here so that python does not 
1476    // interpret it as a byte
1477    let mut pids = Vec::<u16>::new();
1478    let (pids_rm, twindows) = self.lightspeed_cleaning(t_err);
1479    for pid in pids_rm {
1480      pids.push(pid as u16);
1481    }
1482    (pids, twindows)
1483  }
1484 
1485  /// The run id 
1486  #[getter]
1487  fn get_run_id(&self) -> u16 { 
1488    self.run_id
1489  }
1490
1491  /// Remove all hits from the event's hit series which 
1492  /// do NOT obey causality. that is where the timings
1493  /// measured at ends A and B can not be correlated
1494  /// by the assumed speed of light in the paddle
1495  #[pyo3(name="remove_non_causal_hits")]
1496  fn remove_non_causal_hits_py(&mut self) -> Vec<u16> {
1497    // return Vec<u16> here so that python does not 
1498    // interpret it as a byte
1499    let mut pids = Vec::<u16>::new();
1500    for pid in self.remove_non_causal_hits() {
1501      pids.push(pid as u16);
1502    }
1503    pids
1504  }
1505  
1506  /// Get the pointcloud of this event, sorted by time. 
1507  /// For this to work, the event times have to be 
1508  /// normalized first, this means that the first hit 
1509  /// in the event is at 0 and the hits have been 
1510  /// sorted in time
1511  /// 
1512  /// # Returns
1513  ///   (f32, f32, f32, f32, f32) : (x,y,z,t,edep)
1514  ///   Will return None if information about the tof paddles 
1515  ///   as obtained from the gondola_db is not available! 
1516  #[getter]
1517  #[pyo3(name="pointcloud")]
1518  fn get_pointcloud_py(&self) -> Option<Vec<(f32,f32,f32,f32,f32)>> {
1519    self.get_pointcloud()
1520  }
1521
1522  /// True if the hit times have been normalized (and the
1523  /// timing offsets, if any, been applied)
1524  #[getter]
1525  #[pyo3(name="hit_times_normalized")]
1526  fn get_hit_times_normalized_py(&self) -> bool {
1527    self.hit_times_normalized
1528  }
1529
1530  /// True if the hit times have been normalized with any
1531  /// (non-zero) timing offset
1532  #[getter]
1533  #[pyo3(name="timing_offsets_applied")]
1534  fn get_timing_offsets_applied_py(&self) -> bool {
1535    self.timing_offsets_applied()
1536  }
1537
1538  #[getter]
1539  #[pyo3(name="has_any_mangling")]
1540  fn has_any_mangling_py(&self) -> bool {
1541    self.has_any_mangling() 
1542  }
1543
1544  #[getter]
1545  fn get_event_id(&self) -> u32 {
1546    self.event_id
1547  }
1548  
1549  #[getter]
1550  fn get_event_status(&self) -> EventStatus {
1551    self.status
1552  }
1553  
1554  /// Compare the hg hits of the event with the triggered paddles and 
1555  /// return the paddles which have at least a missing HG hit
1556  #[pyo3(name="get_missing_paddles_hg")]
1557  fn get_missing_paddles_hg_py(&self, mapping : DsiJChPidMapping) -> Vec<u8> {
1558    self.get_missing_paddles_hg(&mapping)
1559  }
1560
1561  /// Get all the paddle ids which have been triggered
1562  #[pyo3(name="get_triggered_paddles")]
1563  fn get_triggered_paddles_py(&self, mapping : DsiJChPidMapping) -> Vec<u8> {
1564    self.get_triggered_paddles(&mapping)
1565  }
1566
1567  /// The hits we were not able to read out because the DRS4 chip
1568  /// on the RBs was busy
1569  #[getter]
1570  fn lost_hits(&self) -> u16 {
1571    self.drs_dead_lost_hits
1572  }
1573
1574  /// RB Link IDS (not RB ids) which fall into the 
1575  /// trigger window
1576  #[getter]
1577  fn rb_link_ids(&self) -> Vec<u32> {
1578    self.get_rb_link_ids().into_iter().map(|byte| byte as u32).collect()
1579  }
1580
1581  /// The event might have RBEvents associated with it
1582  #[getter]
1583  fn get_rb_events(&self) -> Vec<RBEvent> {
1584    self.rb_events.clone()
1585  }
1586
1587  /// Hits which formed a trigger
1588  #[getter]
1589  pub fn trigger_hits(&self) -> PyResult<Vec<(u8, u8, (u8, u8), LTBThreshold)>> {
1590    Ok(self.get_trigger_hits())
1591  }
1592  
1593  /// The active triggers in this event. This can be more than one, 
1594  /// if multiple trigger conditions are satisfied.
1595  #[getter]
1596  pub fn trigger_sources(&self) -> Vec<TriggerType> {
1597    self.get_trigger_sources()
1598  } 
1599  
1600  /// The active triggers in this event. This can be more than one, 
1601  /// if multiple trigger conditions are satisfied.
1602  #[getter]
1603  #[pyo3(name="trigger_sources_bytes")]
1604  pub fn get_trigger_sources_bytes_py(&self) -> u16 {
1605    self.trigger_sources
1606  } 
1607
1608  #[pyo3(name="move_hits")]
1609  pub fn move_hits_py(&mut self) {
1610    self.move_hits()
1611  }
1612
1613  #[getter]
1614  #[pyo3(name="hits")]
1615  pub fn hits_py<'_py>(&self) -> Vec<TofHit> {
1616  //pub fn hits_py<'_py>(&self) -> PyResult<Bound<'_,Vec<TofHit>>> {
1617    //Bound::new(py, self.hits)
1618    //FIXMEFIXMEFIXME
1619    self.hits.clone()
1620  }
1621  
1622  #[getter]
1623  #[pyo3(name="hitmap")]
1624  pub fn hitmap<'_py>(&self) -> HashMap<u8,TofHit> {
1625  //pub fn hits_py<'_py>(&self) -> PyResult<Bound<'_,Vec<TofHit>>> {
1626    //Bound::new(py, self.hits)
1627    //FIXMEFIXMEFIXME
1628    let mut hitmap = HashMap::<u8, TofHit>::new();
1629    for h in &self.hits {
1630      hitmap.insert(h.paddle_id, *h);
1631    }
1632    hitmap
1633  }
1634  
1635  /// Total energy depostion in the Umbrella
1636  ///
1637  /// Utilizes Philip's formula based on 
1638  /// peak height
1639  #[getter]
1640  #[pyo3(name="edep_umb")]
1641  pub fn get_edep_umbrella_py(&self) -> f32 {
1642    self.get_edep_umbrella()
1643  }
1644  
1645  /// Total energy depostion in the Cube
1646  ///
1647  /// Utilizes Philip's formula based on 
1648  /// peak height
1649  #[getter]
1650  #[pyo3(name="edep_cbe")]
1651  pub fn get_edep_cube_py(&self) -> f32 {
1652    self.get_edep_cube()
1653  }
1654  
1655  /// Total energy depostion in the Cortina
1656  ///
1657  /// Utilizes Philip's formula based on 
1658  /// peak height
1659  #[getter]
1660  #[pyo3(name="edep_cor")]
1661  pub fn get_edep_cortina_py(&self) -> f32 {
1662    self.get_edep_cortina()
1663  }
1664
1665  /// Total energy depostion in the complete TOF
1666  ///
1667  /// Utilizes Philip's formula based on 
1668  /// peak height
1669  #[getter]
1670  #[pyo3(name="edep")]
1671  pub fn get_edep_py(&self) -> f32 {
1672    self.get_edep()
1673  }
1674
1675  #[getter]
1676  #[pyo3(name="nhits")]
1677  pub fn nhits_py(&self) -> usize {
1678    self.get_nhits()
1679  }
1680
1681  #[getter]
1682  #[pyo3(name="dsi_j_mask")]
1683  pub fn get_dsi_j_mask_py(&self) -> u32 {
1684    self.dsi_j_mask
1685  }
1686
1687  #[getter]
1688  #[pyo3(name="channel_masks")]
1689  pub fn get_channel_masks_py(&self) -> Vec<u16> {
1690    self.channel_mask.clone()
1691  }
1692
1693  #[getter]
1694  #[pyo3(name="nhits_umb")]
1695  pub fn nhits_umb_py(&self) -> usize {
1696    self.get_nhits_umb()
1697  }
1698
1699  #[getter]
1700  #[pyo3(name="nhits_cbe")]
1701  fn get_nhits_cbe_py(&self) -> usize {
1702    self.get_nhits_cbe()
1703  }
1704  
1705  #[getter]
1706  #[pyo3(name="nhits_cor")]
1707  fn get_nhits_cor_py(&self) -> usize {
1708    self.get_nhits_cor()
1709  }
1710
1711  #[getter]
1712  fn get_timestamp16(&self) -> u16 {
1713    self.timestamp16
1714  }
1715  
1716  #[getter]
1717  fn get_timestamp32(&self) -> u32 {
1718    self.timestamp32
1719  }
1720  
1721  #[getter]
1722  fn timestamp48(&self) -> u64 {
1723    self.get_timestamp48()
1724  }
1725  
1726  #[getter]
1727  fn get_status(&self) -> EventStatus {
1728    self.status
1729  }
1730
1731  #[getter]
1732  #[pyo3(name="waveforms")]
1733  fn get_waveforms_py(&self) -> Vec<RBWaveform> {
1734    self.get_waveforms()
1735  }
1736
1737  #[staticmethod]
1738  #[pyo3(name = "set_packed_status_version")]
1739  fn set_packed_status_version_py(pack : &mut TofPacket, version : ProtocolVersion) 
1740    -> PyResult<()> {
1741    match Self::set_packed_status_version(pack, version) {
1742      Err(err) => {
1743        let err_mesg = format!("Unable to set status version! {}", err);
1744        return Err(PyValueError::new_err(err_mesg));
1745      } 
1746      Ok(_) => {
1747        return Ok(());
1748      }
1749    }
1750  }
1751
1752  #[staticmethod]
1753  #[pyo3(name = "strip_packed_rbevents_for_pv3")]
1754  fn strip_packed_rbevents_for_pv3_py(pack : &mut TofPacket) 
1755    -> PyResult<()> {
1756    match Self::strip_packed_rbevents_for_pv3(pack) {
1757      Err(err) => {
1758        let err_msg = format!("Unable to strip packed rbevents{}", err);
1759        return Err(PyValueError::new_err(err_msg));
1760      } 
1761      Ok(_) => {
1762        return Ok(());
1763      }
1764    }
1765  }
1766  
1767  #[cfg(feature="database")]
1768  #[staticmethod]
1769  fn unpack(pack : &TofPacket) -> PyResult<Self> {
1770    if pack.packet_type != Self::TOF_PACKET_TYPE {
1771      let err_msg = format!("This is a packet of type {}, but we need type {}", pack.packet_type, Self::TOF_PACKET_TYPE);
1772      return Err(PyValueError::new_err(err_msg));
1773    }
1774    let mut pos = 0;
1775    let mut ev = Self::from_bytestream(&pack.payload,&mut pos)?; 
1776    ev.set_paddles(&pack.tof_paddles);
1777    Ok(ev)
1778  }
1779
1780  /// Certain quantitities can only be calculated if we know more 
1781  /// about the paddle the hit was seen in. 
1782  /// This meta information is not stored within the hit to save 
1783  /// space for telemetry/storage reasons.
1784  ///
1785  /// The meta-information (e.g. paddle length) can be added by 
1786  /// filling in the blanks from the specific paddles as obtained 
1787  /// from the database shipped with gondola.
1788  #[cfg(feature="database")]
1789  #[pyo3(name="set_paddles")]
1790  fn set_paddles_py(&mut self, paddles : HashMap<u8, TofPaddle>) {
1791    self.set_paddles(&paddles); 
1792  }
1793
1794  /// Hits in two overlapping paddles at the same time come from
1795  /// a particle going through the overlap: move both hits across
1796  /// the paddles to the middle of the overlap. Needs the hit
1797  /// positions (set_paddles) and normalized hit times.
1798  ///
1799  /// # Arguments:
1800  ///   * overlaps : TofPaddleOverlaps
1801  ///   * max_dt   : largest time difference of the two hits (ns)
1802  ///
1803  /// # Returns:
1804  ///   * the number of merged pairs
1805  #[cfg(feature="database")]
1806  #[pyo3(name="merge_overlapping_hits", signature = (overlaps, max_dt = TofPaddleOverlaps::DEFAULT_MAX_DT))]
1807  fn merge_overlapping_hits_py(&mut self, overlaps : &TofPaddleOverlaps, max_dt : f32) -> usize {
1808    self.merge_overlapping_hits(overlaps, max_dt)
1809  }
1810
1811}
1812
1813#[cfg(feature="pybindings")]
1814pythonize_packable!(TofEvent);
1815
1816//---------------------------------------------------
1817
1818#[test]
1819#[cfg(feature="random")]
1820fn packable_tofeventv0() {
1821  for _ in 0..500 {
1822    let mut data = TofEvent::from_random();
1823    if data.version != ProtocolVersion::Unknown {
1824      continue;
1825    }
1826    let mut test : TofEvent = data.pack().unpack().unwrap();
1827    //println!("{}", data.hits[0]);
1828    //println!("{}", test.hits[0]);
1829    // Manually zero these fields, since comparison with nan will fail and 
1830    // from_random did not touch these
1831    //println!("{}", data);
1832    //println!("{}", test);
1833    let fix_time = Instant::now();
1834    test.creation_time = fix_time;
1835    data.creation_time = fix_time;
1836    for k in &mut data.rb_events {
1837      k.creation_time = None;
1838    }
1839    for k in &mut test.rb_events {
1840      k.creation_time = None;
1841    }
1842    for h in &mut test.hits {
1843      h.paddle_len       = 0.0; 
1844      h.coax_cable_time  = 0.0; 
1845      h.hart_cable_time  = 0.0; 
1846      h.x                = 0.0; 
1847      h.y                = 0.0; 
1848      h.z                = 0.0; 
1849      h.event_t0         = 0.0;
1850    }
1851    assert_eq!(data, test);
1852  }
1853}  
1854
1855#[test]
1856#[cfg(feature="random")]
1857fn packable_tofeventv1() {
1858  for _ in 0..500 {
1859    let mut data = TofEvent::from_random();
1860    if data.version != ProtocolVersion::V1 {
1861      continue;
1862    }
1863    let mut test : TofEvent = data.pack().unpack().unwrap();
1864    //println!("{}", data.hits[0]);
1865    //println!("{}", test.hits[0]);
1866    // Manually zero these fields, since comparison with nan will fail and 
1867    // from_random did not touch these
1868    let fix_time = Instant::now();
1869    test.creation_time = fix_time;
1870    data.creation_time = fix_time;
1871    for k in &mut data.rb_events {
1872      k.creation_time = None;
1873    }
1874    for k in &mut test.rb_events {
1875      k.creation_time = None;
1876    }
1877    for h in &mut test.hits {
1878      h.paddle_len       = 0.0; 
1879      h.coax_cable_time  = 0.0; 
1880      h.hart_cable_time  = 0.0; 
1881      h.x                = 0.0; 
1882      h.y                = 0.0; 
1883      h.z                = 0.0; 
1884      h.event_t0         = 0.0;
1885    }
1886    assert_eq!(data, test);
1887  }
1888}  
1889
1890#[test]
1891#[cfg(feature="random")]
1892fn packable_tofeventv2() {
1893  for _ in 0..500 {
1894    let mut data = TofEvent::from_random();
1895    if data.version != ProtocolVersion::V2 {
1896      continue;
1897    }
1898    let mut test : TofEvent = data.pack().unpack().unwrap();
1899    //println!("{}", data.hits[0]);
1900    //println!("{}", test.hits[0]);
1901    // Manually zero these fields, since comparison with nan will fail and 
1902    // from_random did not touch these
1903    let fix_time = Instant::now();
1904    test.creation_time = fix_time;
1905    data.creation_time = fix_time;
1906    for k in &mut data.rb_events {
1907      k.creation_time = None;
1908    }
1909    for k in &mut test.rb_events {
1910      k.creation_time = None;
1911    }
1912    for h in &mut test.hits {
1913      h.paddle_len       = 0.0; 
1914      h.coax_cable_time  = 0.0; 
1915      h.hart_cable_time  = 0.0; 
1916      h.x                = 0.0; 
1917      h.y                = 0.0; 
1918      h.z                = 0.0; 
1919      h.event_t0         = 0.0;
1920    }
1921    assert_eq!(data, test);
1922  }
1923}  
1924
1925#[test]
1926#[cfg(feature="random")]
1927fn packable_tofeventv3() {
1928  for _ in 0..500 {
1929    let mut data = TofEvent::from_random();
1930    if data.version != ProtocolVersion::V3 {
1931      continue;
1932    }
1933    let mut test : TofEvent = data.pack().unpack().unwrap();
1934    //println!("{}", data.hits[0]);
1935    //println!("{}", test.hits[0]);
1936    // Manually zero these fields, since comparison with nan will fail and 
1937    // from_random did not touch these
1938    let fix_time = Instant::now();
1939    test.creation_time = fix_time;
1940    data.creation_time = fix_time;
1941    for h in &mut test.hits {
1942      h.paddle_len       = 0.0; 
1943      h.coax_cable_time  = 0.0; 
1944      h.hart_cable_time  = 0.0; 
1945      h.x                = 0.0; 
1946      h.y                = 0.0; 
1947      h.z                = 0.0; 
1948      h.event_t0         = 0.0;
1949    }
1950    assert_eq!(data, test);
1951  }
1952}  
1953
1954/// An event with three hits in paddles 1, 2, 3 at the
1955/// times 10, 20 and 30 ns (no paddle length, cable delays
1956/// or phase, which TofHit::set_paddle would set)
1957#[cfg(test)]
1958#[cfg(feature="database")]
1959fn event_for_timing_offsets() -> TofEvent {
1960  let mut event = TofEvent::new();
1961  for (pid, t) in [(1u8, 10.0f32), (2, 20.0), (3, 30.0)] {
1962    let mut h  = TofHit::new();
1963    h.paddle_id = pid;
1964    h.time_a    = f16::from_f32(t);
1965    h.time_b    = f16::from_f32(t);
1966    h.paddle_len      = 0.0;
1967    h.coax_cable_time = 0.0;
1968    h.hart_cable_time = 0.0;
1969    event.hits.push(h);
1970  }
1971  event
1972}
1973
1974#[test]
1975#[cfg(feature="database")]
1976fn tofevent_timing_offsets_applied_once() {
1977  let mut event = event_for_timing_offsets();
1978  assert!(!event.hit_times_normalized);
1979  // a stale offset, paddle 3 is not in the map
1980  event.hits[2].timing_offset = 7.0;
1981  let offsets = HashMap::from([(1u8, 1.0f32), (2, 4.0)]);
1982  event.set_timing_offsets(&offsets);
1983  let set : Vec<f32> = event.hits.iter().map(|h| h.timing_offset).collect();
1984  assert_eq!(set, vec![1.0, 4.0, 0.0]);
1985  event.normalize_hit_times();
1986  assert!(event.hit_times_normalized);
1987  // (10 - 1, 20 - 4, 30 - 0) relative to the first hit
1988  let t0 : Vec<f32> = event.hits.iter().map(|h| h.event_t0).collect();
1989  assert_eq!(t0, vec![0.0, 7.0, 21.0]);
1990  // normalizing again does not change anything
1991  event.normalize_hit_times();
1992  let again : Vec<f32> = event.hits.iter().map(|h| h.event_t0).collect();
1993  assert_eq!(again, t0);
1994}
1995
1996#[test]
1997#[cfg(feature="database")]
1998fn tofevent_timing_offsets_after_normalization() {
1999  let mut event = event_for_timing_offsets();
2000  event.normalize_hit_times();
2001  let t0 : Vec<f32> = event.hits.iter().map(|h| h.event_t0).collect();
2002  assert_eq!(t0, vec![0.0, 10.0, 20.0]);
2003  // too late, nothing changes
2004  event.set_timing_offsets(&HashMap::from([(1u8, 1.0f32), (2, 4.0)]));
2005  assert!(event.hits.iter().all(|h| h.timing_offset == 0.0));
2006  event.normalize_hit_times();
2007  let again : Vec<f32> = event.hits.iter().map(|h| h.event_t0).collect();
2008  assert_eq!(again, t0);
2009}
2010
2011#[test]
2012#[cfg(feature="database")]
2013fn tofevent_normalize_with_offsets() {
2014  // the hits have NaN fields (no paddle information), so
2015  // compare only the times and offsets
2016  let times = |ev : &TofEvent| -> Vec<(f32, f32)> {
2017    ev.hits.iter().map(|h| (h.event_t0, h.timing_offset)).collect()
2018  };
2019  let offsets = HashMap::from([(1u8, 1.0f32), (2, 4.0)]);
2020  let mut separate = event_for_timing_offsets();
2021  separate.set_timing_offsets(&offsets);
2022  separate.normalize_hit_times();
2023  let mut together = event_for_timing_offsets();
2024  assert!(!together.timing_offsets_applied());
2025  together.normalize_hit_times_with_offsets(Some(&offsets));
2026  assert_eq!(times(&separate), times(&together));
2027  assert!(together.hit_times_normalized && together.timing_offsets_applied());
2028  // None uses the offsets set before
2029  let mut before = event_for_timing_offsets();
2030  before.set_timing_offsets(&offsets);
2031  before.normalize_hit_times_with_offsets(None);
2032  assert_eq!(times(&before), times(&separate));
2033  // without any offsets
2034  let mut none = event_for_timing_offsets();
2035  none.normalize_hit_times_with_offsets(None);
2036  assert!(none.hit_times_normalized && !none.timing_offsets_applied());
2037  // too late, as for set_timing_offsets
2038  none.normalize_hit_times_with_offsets(Some(&offsets));
2039  assert!(!none.timing_offsets_applied());
2040}
2041
2042#[test]
2043#[cfg(feature="database")]
2044fn tofevent_normalize_first_hit_at_zero() {
2045  // the first hit being at 0 before normalization does
2046  // not mean the hit times are already normalized
2047  let mut event = event_for_timing_offsets();
2048  event.hits[0].event_t0 = 0.0;
2049  event.set_timing_offsets(&HashMap::from([(2u8, 4.0f32)]));
2050  event.normalize_hit_times();
2051  let t0 : Vec<f32> = event.hits.iter().map(|h| h.event_t0).collect();
2052  assert_eq!(t0, vec![0.0, 6.0, 20.0]);
2053}
2054
2055#[test]
2056#[cfg(feature="random")]
2057fn tofevent_move_hits() {
2058  let mut event = TofEvent::from_random();
2059  let mut n_hits_exp = 0usize;
2060  for rb in &event.rb_events {
2061    n_hits_exp += rb.hits.len();
2062  }
2063  event.hits.clear();
2064  event.move_hits();
2065  for rb in &event.rb_events {
2066    assert_eq!(rb.hits.len(),0);
2067  }
2068  assert_eq!(n_hits_exp, event.hits.len());
2069
2070}
2071
2072#[test]
2073#[cfg(feature="random")] 
2074fn tofevent_striprbevents() {
2075  let mut event      = TofEvent::from_random();
2076  let mut n_hits_exp = 0usize;
2077  for rb in &event.rb_events {
2078    n_hits_exp += rb.hits.len();
2079  }
2080  event.hits.clear();
2081  event.strip_rbevents();
2082  assert_eq!(event.rb_events.len(),0);
2083  assert_eq!(n_hits_exp, event.hits.len());
2084}
2085
2086//#[test]
2087//#[cfg(feature = "random")]
2088//fn tofevent_sizes_header() {
2089//  for _ in 0..100 {
2090//    let data = TofEvent::from_random();
2091//    let mask = data.construct_sizes_header();
2092//    let size = TofEvent::decode_size_header(&mask);
2093//    assert_eq!(size.0, data.rb_events.len());
2094//    //assert_eq!(size.1, data.missing_hits.len());
2095//  }
2096//}
2097
2098//#[test]
2099//#[cfg(feature = "random")]
2100//fn packable_tofevent() {
2101//  for _ in 0..5 {
2102//    let data = TofEvent::from_random();
2103//    let test : TofEvent = data.pack().unpack().unwrap();
2104//    assert_eq!(data.header, test.header);
2105//    assert_eq!(data.compression_level, test.compression_level);
2106//    assert_eq!(data.quality, test.quality);
2107//    assert_eq!(data.mt_event, test.mt_event);
2108//    assert_eq!(data.rb_events.len(), test.rb_events.len());
2109//    //assert_eq!(data.missing_hits.len(), test.missing_hits.len());
2110//    //assert_eq!(data.missing_hits, test.missing_hits);
2111//    assert_eq!(data.rb_events, test.rb_events);
2112//    //assert_eq!(data, test);
2113//    //println!("{}", data);
2114//  }
2115//}
2116
2117
2118