Skip to main content

gondola_core/events/
telemetry_event.rs

1//! The TelemetryEvent or former "MergedEvent" is that what gets 
2//! sent over telemetry during flight
3// The following file is part of gaps-online-software and published 
4// under the GPLv3 license
5
6use crate::prelude::*;
7
8use std::collections::HashSet;
9
10/// The basic event type as sent over telemetry, often 
11/// also dubbed as "merged event".
12///
13/// This event type contains tof as well as tracker 
14/// hits, and comes in several flavors, depending 
15/// on the suspected signalness of the online system
16/// determined by a specific algorith.
17/// For that, please see the TelemetryPacketHeader, 
18/// which identifiers these different flavors. 
19///
20/// For most purposes, this event is the to-go data 
21/// to start any analysis.
22#[cfg_attr(feature="pybindings", pyclass)]
23#[derive(Debug, Clone, PartialEq)]
24pub struct TelemetryEvent {
25  pub header              : TelemetryPacketHeader,
26  pub creation_time       : u64,
27  pub event_id            : u32,
28  pub tracker_hits        : Vec<TrackerHit>,
29  pub tracker_oscillators : Vec<u64>,
30  pub tof_event           : TofEvent,
31  //#[cfg(feature = "pybindings")]
32  //pub tof_event: pyo3::Py<TofEvent>,
33  //#[cfg(not(feature = "pybindings"))]
34  //pub tof_event           : TofEvent,
35  pub raw_data            : Vec<u8>,
36  pub flags0              : u8,
37  pub flags1              : u8,
38  pub version             : u8,
39  pub osc_flags           : u8,
40  pub oscillator_idx      : Vec<u8>,
41  // this is for re-merging and does not get serialized to disk 
42  pub expected_tr_hits    : u8,
43}
44
45impl TelemetryEvent {
46
47  pub fn new() -> Self {
48    let mut tracker_oscillators = Vec::<u64>::new();
49    for _ in 0..10 {
50      tracker_oscillators.push(0);
51    }
52    Self {
53      header              : TelemetryPacketHeader::new(),
54      creation_time       : 0,
55      event_id            : 0,
56      tracker_hits        : Vec::<TrackerHit>::new(),
57      tracker_oscillators : tracker_oscillators,
58      tof_event           : TofEvent::new(),
59      raw_data            : Vec::<u8>::new(),
60      flags0              : 0,
61      flags1              : 1,
62      version             : 0, 
63      osc_flags           : 0,
64      oscillator_idx      : Vec::<u8>::new(),
65      expected_tr_hits    : 0,
66    }
67  }
68
69  /// The tracker hits as (x, y, z, t, adc), with the
70  /// coordinates in mm. Tracker hits do not have a time,
71  /// so t is NaN.
72  pub fn get_tracker_pointcloud(&self) -> Vec<(f32, f32, f32, f32, f32)> {
73    let mut pts = Vec::<(f32,f32,f32,f32,f32)>::new();
74    for h in &self.tracker_hits {
75      // uses adc
76      // FIXME - factor 10!
77      let pt = (10.0*h.x, 10.0*h.y, 10.0*h.z, f32::NAN, h.adc as f32);
78      pts.push(pt);
79    }
80    pts
81  }
82
83  /// This can be useful for single track analysis 
84  pub fn has_only_one_hit_per_tlayer(&self) -> bool { 
85    let mut layers = HashSet::<u8>::new();
86    for h in &self.tracker_hits {
87      if !layers.insert(h.layer) {
88        return false; // we found a duplicate! 
89      }
90    } 
91    return true;
92  }
93
94  /// Create a TelemetryPacket from the 
95  /// TelemetryEvent.
96  ///
97  /// CAVEAT: Currently the checksum does 
98  /// not get re-evaluated
99  pub fn pack(&self) -> TelemetryPacket {
100    let mut tp = TelemetryPacket::new();
101    // this is bad, but currently I am not 
102    // sure how to make this better
103    tp.header  = self.header.clone();
104    tp.payload = self.to_bytestream();
105    tp
106  }
107
108  pub fn calibrate_trk_hits(&mut self, cali : &TrackerOfflineCalibration, remove_pulsed : bool) 
109    -> Result<(), CalibrationError> {
110    cali.mask_hits(&mut self.tracker_hits);
111    cali.calibrate(&mut self.tracker_hits, remove_pulsed)?;
112    Ok(())
113  }
114
115  /// Restore position information from database
116  #[cfg(feature="database")]
117  pub fn hydrate(&mut self, tof_paddles : &HashMap<u8,TofPaddle>, trk_strips : &HashMap<u32, TrackerStrip>) {
118    self.tof_event.set_paddles(tof_paddles);
119    for h in &mut self.tracker_hits {  
120      h.set_coordinates(trk_strips);
121    }
122  }
123  
124  /// Delete tracker hits (e.g. in case they are supposed to 
125  /// be replaced by packet type 80 tracker hits)
126  pub fn delete_all_tracker_hits(&mut self) {
127    self.tracker_hits.clear();
128  }
129
130  /// Add tracker hits (e.g. hits from packet type 80)
131  pub fn add_tracker_hits(&mut self, hits:  &Vec<TrackerHit>) {
132    self.tracker_hits.extend_from_slice(hits);
133    // for each tracker hits, the packet length extends by 4 bytes 
134    self.header.length += (4*hits.len()) as u16;
135  }
136
137  #[cfg(feature="database")]
138  pub fn mask_strips(&mut self, masks : &HashMap<u32, TrackerStripMask>) {
139    let mut clean_hits = Vec::<TrackerHit>::with_capacity(self.tracker_hits.len());
140    for h in &self.tracker_hits {
141      if !masks.contains_key(&h.get_stripid()) {
142        warn!("We don't have a mask information for strip id {}", h.get_stripid());
143        continue;
144      }
145      if masks[&h.get_stripid()].active {
146        clean_hits.push(h.clone());
147      }
148    }
149    self.tracker_hits = clean_hits;
150  }
151
152
153  ///// Applies a cut based on adc values
154  //#[cfg(feature="database")]
155  //pub fn apply_signal_cut(&mut self, cut : f32, pedestals : &HashMap<u32, TrackerStripPedestal>) {
156  //  let mut clean_hits = Vec::<TrackerHit>::with_capacity(self.tracker_hits.len());
157  //  for h in &self.tracker_hits {
158  //    if !pedestals.contains_key(&h.get_stripid()) {
159  //      warn!("We don't have pedestal information for strip id {}", h.get_stripid());
160  //      continue;
161  //    }
162  //    let ped = &pedestals[&h.get_stripid()];
163  //    if (h.adc as f32) - ped.pedestal_mean > (cut * ped.pedestal_sigma){
164  //      clean_hits.push(h.clone());
165  //    }
166  //  }
167  //  self.tracker_hits = clean_hits;
168  //}
169 
170  ///// Calculate the absolute common noise (adc)
171  //#[cfg(feature="database")]
172  //pub fn cmn_noise(hit       : &TrackerHit, 
173  //                 pedestals : &HashMap<u32, TrackerStripPedestal>,
174  //                 cmn_noise : &HashMap<u32, TrackerStripCmnNoise>) -> Option<f32> {
175  //  let stripid = hit.get_stripid();
176  //  if !cmn_noise.contains_key(&stripid) {
177  //    warn!("We don't have pedestal information for strip id {}", stripid);
178  //    return None;
179  //  }
180  //  if !pedestals.contains_key(&stripid) {
181  //    warn!("We don't have pedestal information for strip id {}", stripid);
182  //    return None;
183  //  }
184  //  let mut cmn_level = 0.0f32;
185  //  let adc_ped_sub   = hit.adc as f32 - pedestals[&stripid].pedestal_mean; 
186  //  if adc_ped_sub < 400.0 {
187  //    cmn_level = cmn_noise[&stripid].common_level(hit.adc as f32);
188  //  }
189  //  return Some(adc_ped_sub - cmn_noise[&stripid].gain * cmn_level);
190  //}
191
192  ///// Calculate the energy deposition
193  //#[cfg(feature="database")]
194  //pub fn get_trk_energy(adc : f32, tf : &TrackerStripTransferFunction) -> f32 {
195  //  let mut energy = 0.0f32;
196  //  let mut adc_m  = adc; 
197  //  if adc_m <= 0.0 {
198  //    return energy;
199  //  }
200  //  if adc_m > 1600.0 {
201  //    adc_m = 1600.0;
202  //  }
203  //  #[allow(non_snake_case)]
204  //  let mV2keV  = 0.841f32;
205  //  // the max and min range are basically defined by the 
206  //  // polynominal [0-1600]
207  //  let voltage = tf.transfer_fn(adc_m);
208  //  println!("voltage {}", voltage);
209  //  energy  = voltage*mV2keV;
210  //  energy /= 1000.0;
211  //  println!("adc : {} , energy {}", adc_m, energy);
212  //  return energy;
213  //}
214
215  //#[cfg(feature="database")]
216  //pub fn calibrate_tracker(&mut self, 
217  //                         remove_cmn_noise : bool,
218  //                         pedestals        : &HashMap<u32, TrackerStripPedestal>,
219  //                         transfer_fn      : &HashMap<u32, TrackerStripTransferFunction>,
220  //                         cmn_noise        : &HashMap<u32, TrackerStripCmnNoise>) {
221  //  //println!("Will remove CMN noise {}", remove_cmn_noise);
222  //  for h in &mut self.tracker_hits {
223  //    let stripid = h.get_stripid();
224  //    //println!("Running TRK calibration for strip {}", stripid);
225  //    if !pedestals.contains_key(&stripid) {
226  //      warn!("Pedestal map does not contain strip {}. Will not calculate energy!", stripid);
227  //      continue;
228  //    }
229  //    if !transfer_fn.contains_key(&stripid) {
230  //      warn!("Transfer fn for strip {} not available. Will not calculate energy!", stripid);
231  //      continue;
232  //    }
233  //    let adc_no_ped = h.adc as f32 - pedestals[&stripid].pedestal_mean;
234  //    //println!("ADC NO PED {}", adc_no_ped);
235  //    if remove_cmn_noise {
236  //      match Self::cmn_noise(&h, pedestals, cmn_noise) { 
237  //        None => {
238  //          h.energy = Self::get_trk_energy(adc_no_ped, &transfer_fn[&stripid]); 
239  //        }
240  //        Some(cmn) => {
241  //          h.energy = Self::get_trk_energy(cmn, &transfer_fn[&stripid]);
242  //        }
243  //      }    
244  //    } else {
245  //      h.energy = Self::get_trk_energy(adc_no_ped, &transfer_fn[&stripid]);
246  //    }
247  //  }
248  //}
249}
250
251
252impl TelemetryPackable for TelemetryEvent {
253  // trivial for TelemetryEvent, since the default 
254  // already contains the packet types
255}
256
257impl Serialization for TelemetryEvent {
258  
259  fn from_bytestream(stream : &Vec<u8>,
260                     pos    : &mut usize)
261    -> Result<Self, SerializationError> {
262    let mut me       = Self::new();
263    let version      = parse_u8(stream, pos);
264    me.version       = version;
265    me.flags0        = parse_u8(stream, pos);
266    // skip a bunch of Alex newly implemented things
267    // FIXME
268    if version == 0 {
269      me.flags1      = parse_u8(stream, pos);
270    } else {
271      *pos += 8;
272    }
273
274    me.event_id       = parse_u32(stream, pos);
275    //println!("EVENT ID {}", me.event_id);
276    let _tof_delim    = parse_u8(stream, pos);
277    //println!("TOF delim : {}", _tof_delim);
278    if stream.len() <= *pos + 2 {
279      error!("Not able to parse merged event!");
280      return Err(SerializationError::StreamTooShort);
281    }
282    let num_tof_bytes = parse_u16(stream, pos) as usize;
283    //println!("Num TOF bytes : {}", num_tof_bytes);
284    if stream.len() < *pos+num_tof_bytes {
285      error!("Not enough bytes for TOF packet with {} bytes! Only {} bytes remaining in input", num_tof_bytes, stream.len() - *pos);
286      return Err(SerializationError::StreamTooShort); 
287    }
288    let pos_before = *pos;
289    //println!("Expecting {} tof bytes", num_tof_bytes);
290    if num_tof_bytes != 0 {
291      let tof_pack   = TofPacket::from_bytestream(stream, pos)?;
292      //println!("Retrieved packet with {} bytes", tof_pack.payload.len());
293      let ts         = tof_pack.unpack::<TofEvent>()?;
294    // sanity check - is tofpacket as long as num_tof_bytes lets us believe?
295      me.tof_event = ts;
296    }
297    if pos_before + num_tof_bytes != *pos {
298      error!("Byte misalignment. Expected {num_tof_bytes}, got {pos} - {pos_before}"); 
299      return Err(SerializationError::WrongByteSize);
300    }
301    let trk_delim    = parse_u8(stream, pos);
302
303    //println!("TRK delim {}", trk_delim);
304    if trk_delim != 0xbb {
305      error!("The TRK delim is incorrect! {trk_delim} instead of 0xbb!");
306      return Err(SerializationError::HeadInvalid);
307    }
308    if version == 1 {
309      let num_trk_hits = parse_u16(stream, pos);
310      if (*pos + (num_trk_hits as usize)*4 ) > stream.len() {
311        let expected_s = *pos + (num_trk_hits as usize)*4 - stream.len();
312        let actual = stream.len() - *pos;
313        error!("We expect {} more bytes, but see only {}", expected_s, actual);
314        error!("Not enough bytes ({}) for {} tracker hits!", stream.len(), num_trk_hits);
315        //println!("{}", &me);
316        return Err(SerializationError::StreamTooShort);
317      }
318      for _ in 0..num_trk_hits { 
319        let mut hit  = TrackerHit::new();
320        let strip_id = parse_u16(stream, pos);
321        let adc      = parse_u16(stream, pos);
322        hit.channel  = (strip_id & 0b11111) as u8;
323        hit.module   = ((strip_id >> 5) & 0b111) as u8;
324        hit.row      = ((strip_id >> 8) & 0b111) as u8;
325        hit.layer    = ((strip_id >> 11) & 0b1111) as u8;
326        hit.adc      = adc;
327        me.tracker_hits.push(hit);
328      }
329      // oscillators
330      let oscillators_delimiter = parse_u8(stream, pos);
331      if oscillators_delimiter != 0xcc {
332        error!("Oscillators_delimiter is incorrect {oscillators_delimiter} instead of 0xcc");
333        return Err(SerializationError::HeadInvalid);
334      }
335      me.osc_flags = parse_u8(stream, pos);
336      let mut oscillator_idx = Vec::<u8>::new();
337      for j in 0..8 {
338        if (me.osc_flags >> j & 0b1) > 0 {
339          oscillator_idx.push(j)
340        }
341      }
342      if (*pos + oscillator_idx.len()*6) > stream.len() {
343        error!("Not enough bytes to parse tracker oscillators!");
344        return Err(SerializationError::StreamTooShort);
345      }
346      for idx in oscillator_idx.iter() {
347        let lower = parse_u32(stream, pos);
348        let upper = parse_u16(stream, pos);
349        let osc : u64 = (upper as u64) << 32 | (lower as u64);
350        //println!("FROM: IDX {}, LOWER {}, UPPER {}, OSC {}", idx, lower, upper, osc);
351        me.tracker_oscillators[*idx as usize] = osc;
352      }
353      me.oscillator_idx = oscillator_idx;
354    } else if version == 0 {
355      error!("Version {version} found, which is currently not supported!");
356      return Err(SerializationError::UnsupportedVersion);
357    } else {
358      error!("Unsuported and unknown version : {version}!");
359      return Err(SerializationError::UnsupportedVersion);
360    } 
361    me.expected_tr_hits = me.tracker_hits.len() as u8;
362    Ok(me)
363  }
364  
365  fn to_bytestream(&self) -> Vec<u8> {
366    let mut stream = Vec::<u8>::new();
367    stream.push(self.version);
368    stream.push(self.flags0);
369    if self.version == 0 {
370      stream.push(self.flags1);
371    } else {
372      stream.extend_from_slice(&[0u8;8]);
373    }
374    stream.extend_from_slice(&self.event_id.to_le_bytes());
375    stream.push(0xaa); // tof delimiter
376    let tof           = self.tof_event.pack();
377    let tof_bytes     = tof.to_bytestream();
378    let num_tof_bytes = tof_bytes.len() as u16;
379    debug!("Will write {} bytes for tef event to stream!", num_tof_bytes);
380    stream.extend_from_slice(&num_tof_bytes.to_le_bytes());
381    stream.extend_from_slice(&tof_bytes);
382    stream.push(0xbb);
383    stream.extend_from_slice(&(self.tracker_hits.len() as u16).to_le_bytes());
384    //println!("Will add bytes for {} tracker hits!", self.tracker_hits.len());
385    for h in &self.tracker_hits { 
386      let mut strip_id: u16 = 0;
387      // Shift each value to its respective position and OR them together
388      strip_id |= (h.channel as u16) & 0b11111;       // Bits 0-4
389      strip_id |= ((h.module as u16) & 0b111) << 5;   // Bits 5-7
390      strip_id |= ((h.row as u16) & 0b111) << 8;      // Bits 8-10
391      strip_id |= ((h.layer as u16) & 0b1111) << 11; 
392      stream.extend_from_slice(&strip_id.to_le_bytes());
393      stream.extend_from_slice(&h.adc.to_le_bytes());
394    }
395    stream.push(0xcc); // oscillators delimiter
396    stream.push(self.osc_flags);
397    for idx in &self.oscillator_idx { 
398    //for osc in &self.tracker_oscillators {
399      //deconstruct the timestamps    
400      let osc   = self.tracker_oscillators[*idx as usize];
401      let upper = ((osc >> 32) & (u16::MAX as u64)) as u16;
402      let lower = (osc & (u32::MAX as u64)) as u32; 
403      //println!("TO: OSC {}, upper {}, lower {}", osc, upper, lower);
404      stream.extend_from_slice(&lower.to_le_bytes());
405      stream.extend_from_slice(&upper.to_le_bytes());
406    }
407    return stream;
408  }
409}
410
411impl fmt::Display for TelemetryEvent {
412  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
413    let mut repr     = String::from("<TelemetryEvent:");
414    let mut te = self.tof_event.clone();
415    te.calc_gcu_variables();
416    let tof_str  = format!("\n  {}", self.tof_event);
417    let mut good_hits = 0;
418    
419    if self.version == 0 {
420      repr += "\n VERSION 0 NOT SUPPORTED!!";
421    } else if self.version == 1 {
422      for _ in &self.tracker_hits {
423        good_hits += 1;
424      }
425    }
426    repr += &(format!("  {}", self.header));
427    repr += "\n  ** ** ** MERGED  ** ** **";
428    repr += &(format!("\n  version      {}", self.version));
429    repr += &(format!("\n  event ID     {}", self.event_id));  
430    repr += "\n  ** ** ** TOF GCU VARIABLES  ** ** **";
431    repr += &(format!("\n  n_hits_umb   {}", te.n_hits_umb));
432    repr += &(format!("\n  n_hits_cbe   {}", te.n_hits_cbe));
433    repr += &(format!("\n  n_hits_cor   {}", te.n_hits_cor));
434    repr += &(format!("\n  tot_edep_umb {}", te.tot_edep_umb));  
435    repr += &(format!("\n  tot_edep_cbe {}", te.tot_edep_cbe));  
436    repr += &(format!("\n  tot_edep_cor {}", te.tot_edep_cor));  
437    if self.version == 0 {
438      repr += "\n VERSION 0 NOT SUPPORTED!!"; 
439    }
440    repr += "\n  ** ** ** TRACKER ** ** **";
441    if self.version == 0 {
442      repr += "\n VERSION 0 NOT SUPPORTED!!"; 
443    } else if self.version == 1 {
444      repr += &(format!("\n  Trk oscillators {:?}", self.tracker_oscillators)); 
445    }
446    repr += &(format!("\n  N Good Trk Hits {}", good_hits));
447    repr += &tof_str;
448    write!(f,"{}", repr)
449  }
450}
451
452//----------------------------------------
453
454#[cfg(feature="pybindings")]
455#[pymethods]
456impl TelemetryEvent {
457
458  #[getter]
459  #[pyo3(name="exptected_tracker_hits")]
460  fn expected_trk_hits_py(&self) -> u8 {
461    self.expected_tr_hits
462  }
463
464  #[getter]
465  #[pyo3(name="has_only_one_hit_per_tlayer")] 
466  fn has_only_one_hit_per_tlayer_py(&self) -> bool {
467    self.has_only_one_hit_per_tlayer()
468  }
469
470  #[getter]
471  #[pyo3(name="has_at_least_expected_trk_hits")]
472  fn has_at_least_expected_trk_hits(&self) -> bool {
473    return self.tracker_hits.len() as u8 >= self.expected_tr_hits
474  }
475
476  #[getter]
477  #[pyo3(name="version")]
478  fn version_py(&self) -> u8 {
479    self.version
480  }
481 
482  #[getter] 
483  #[pyo3(name="flags0")]
484  fn flags0_py(&self) -> u8 {
485    self.flags0
486  }
487  
488  #[getter] 
489  #[pyo3(name="flags1")]
490  fn flags1_py(&self) -> u8 {
491    self.flags1
492  }
493
494  //#[staticmethod]
495  //#[pyo3(name = "get_trk_energy")]
496  //fn get_trk_energy_py(adc : f32, tf : &TrackerStripTransferFunction) -> f32 {
497  //  Self::get_trk_energy(adc, tf)
498  //}
499
500  #[getter]
501  fn get_header(&self) -> TelemetryPacketHeader {
502    self.header
503  }
504
505  #[getter]
506  fn tracker(&self) -> PyResult<Vec<TrackerHit>> {
507    Ok(self.tracker_hits.clone())
508  }
509
510  #[getter]
511  fn get_event_id(&self) -> u32 {
512    self.event_id
513  }
514 
515  /// If available parse the run id from 
516  /// the TOF part of the event 
517  ///
518  /// Returns None if the run id is not 
519  /// set or 0
520  #[getter]
521  fn get_run_id(&self) -> Option<u16> {
522    if self.tof_event.run_id == 0 {
523      return None;
524    }
525    Some(self.tof_event.run_id) 
526  }
527  
528  /// Remove all TOF hits from the event's hit series which 
529  /// do NOT obey causality. that is where the timings
530  /// measured at ends A and B can not be correlated
531  /// by the assumed speed of light in the paddle
532  #[pyo3(name="tof_remove_non_causal_hits")]
533  fn tof_remove_non_causal_hits_py(&mut self) -> Vec<u16> {
534    // return Vec<u16> here so that python does not 
535    // interpret it as a byte
536    let mut pids = Vec::<u16>::new();
537    for pid in self.tof_event.remove_non_causal_hits() {
538      pids.push(pid as u16);
539    }
540    pids
541  }
542  
543  /// Remove the hits from the event which are not passing 
544  /// Elena's cuts. This has a large overlap with "non-causal"
545  /// hit, but is stricter 
546  ///
547  /// # Arguments:
548  ///   * no_return : If true, don't return anything, which 
549  ///                 will make the execution time shorter
550  ///
551  pub fn tof_remove_elena_hits(&mut self, no_return : bool) -> Option<Vec<TofHit>> {
552    return self.tof_event.remove_elena_hits(no_return);
553  } 
554  
555  /// Remove TOF hits from the hitseries which can not 
556  /// be caused by the same particle, which means 
557  /// that for these two specific hits beta with 
558  /// respect to the first hit in the event is 
559  /// larger than one
560  /// That this works, first hits need to be 
561  /// "normalized" by calling normalize_hit_times
562  #[pyo3(name="tof_lightspeed_cleaning")]
563  pub fn tof_lightspeed_cleaning_py(&mut self, t_err : f32) -> (Vec<u16>, Vec<f32>) {
564    // return Vec<u16> here so that python does not 
565    // interpret it as a byte
566    let mut pids = Vec::<u16>::new();
567    let (pids_rm, twindows) = self.tof_event.lightspeed_cleaning(t_err);
568    for pid in pids_rm {
569      pids.push(pid as u16);
570    }
571    (pids, twindows)
572  }
573
574  /// One shot function for a simple calculation of the tof time of flight 
575  /// as calucated by first inner - first outer time. 
576  /// Depending on the event topology, this might or might not be very useful.
577  ///
578  /// That this yields something reasonable, the systematic timing offsets 
579  /// have to be set before, see `set_tof_timing_offsets` 
580  ///
581  /// Returns: 
582  ///   time-of-flight, beta, phase differenc, distance, harting cable time difference 
583  #[getter]
584  fn get_tof_time_of_flight(&mut self) -> Option<(f32,f32,f32,f32,f32)> {
585    self.tof_event.get_tof()
586  }
587
588  /// Set per-paddle timing constant offsets 
589  /// for the TOF
590  ///
591  /// # Arguments:
592  ///   * timing_offsetes : A map of paddle id to timin
593  ///                       timing offset constant
594  #[pyo3(name="set_tof_timing_offsets")]
595  pub fn set_tof_timing_offsets_py(&mut self, timing_offsets : HashMap<u8, f32>) {
596    self.tof_event.set_timing_offsets(&timing_offsets);
597  }
598  
599  /// Normalize the hit times so that the first 
600  /// hit is at 0. This includes application 
601  /// of the phase correction
602  ///
603  /// This is only done once per event, further calls
604  /// do nothing (see tof.hit_times_normalized)
605  ///
606  /// # Arguments:
607  ///   * offsets : a dict paddle id -> timing offset. If
608  ///               None, the offsets which have been set
609  ///               before with set_tof_timing_offsets (by
610  ///               default none) are used
611  #[pyo3(name="tof_normalize_hit_times", signature = (offsets = None))]
612  fn tof_normalize_hit_times_py(&mut self, offsets : Option<HashMap<u8, f32>>) {
613    self.tof_event.normalize_hit_times_with_offsets(offsets.as_ref());
614  }
615
616  /// TOF hits in two overlapping paddles at the same time come
617  /// from a particle going through the overlap: move both hits
618  /// across the paddles to the middle of the overlap. Needs
619  /// normalized hit times (tof_normalize_hit_times).
620  ///
621  /// # Arguments:
622  ///   * overlaps : TofPaddleOverlaps
623  ///   * max_dt   : largest time difference of the two hits (ns)
624  ///
625  /// # Returns:
626  ///   * the number of merged pairs
627  #[cfg(feature="database")]
628  #[pyo3(name="tof_merge_overlapping_hits", signature = (overlaps, max_dt = TofPaddleOverlaps::DEFAULT_MAX_DT))]
629  fn tof_merge_overlapping_hits_py(&mut self, overlaps : &TofPaddleOverlaps, max_dt : f32) -> usize {
630    self.tof_event.merge_overlapping_hits(overlaps, max_dt)
631  }
632
633  /// Apply a set of per-paddle timing constants 
634  ///
635  /// # Arguments:
636  ///   * constants : A map of paddle id -> constant (in ns) 
637  fn tof_set_timing_constants(&mut self, constants:  HashMap<u8, f32>) {
638    for h in &mut self.tof_event.hits {
639      h.event_t0 -= constants[&h.paddle_id];
640    }
641  }
642
643  
644  /// Returns a COPY of the TofEvent associated 
645  /// with this event id
646  #[getter]
647  fn get_tof(&self) -> PyResult<TofEvent> {
648    Ok(self.tof_event.clone())
649  }
650  //#[getter]
651  //fn get_tof(&self, py: Python<'_>) -> Py<TofEvent> {
652  //    // This returns a reference-counted pointer to the same object
653  //    // Python can now call .timestamp = 123 on it
654  //  self.tof_event.clone_ref(py)
655  //}
656
657 // #[getter]``
658 // fn get_tof<'_py>(&self, py: Python<'_py>) -> PyResult<Bound<'_py, PyArray1<f32>>> {
659 // fn get_tof(slf: Bound<'_, Self>) -> PyResult<Bound<'_, TofEvent>> {
660      // 1. Borrow the parent (slf)
661      // 2. Map the borrow to the internal field
662      // 3. Return a Bound that points to that specific memory
663      
664  //    let py = slf.py();
665  //    let py_ref = slf.borrow_mut(); // This is a PyRef<'_, MyLibrary>
666  //    
667  //    // Use PyRef::map to project the reference to the internal field
668  //    // In PyO3 0.23+, this is often used via 'into_bound'
669  //    //let mapped = pyo3::PyRef::map(py_ref, |s| &s.tof_event);
670  //    
671  //    //Ok(mapped.into_bound(py))
672  //    Ok(py_ref)
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  #[pyo3(name="tof_set_paddles")]
685  fn tof_set_paddles_py(&mut self, paddles : HashMap<u8, TofPaddle>) {
686    self.tof_event.set_paddles(&paddles); 
687  }
688
689  #[getter]
690  fn tracker_pointcloud(&self) -> Vec<(f32, f32, f32, f32, f32)> {
691    self.get_tracker_pointcloud()
692  }
693  
694  /// Add tracker hits to the merged event (e.g. with hits from packet type 80
695  #[pyo3(name="add_tracker_hits")]
696  pub fn add_tracker_hits_py(&mut self, mut hits: Vec<TrackerHit>, dedup : bool) { 
697    if dedup {
698      hits.sort();
699      hits.dedup();
700    }
701    let n_hits_before = self.tracker_hits.len();
702    self.tracker_hits.extend_from_slice(&hits);
703    self.tracker_hits.sort(); 
704    self.tracker_hits.dedup();
705    let delta_hits = self.tracker_hits.len() - n_hits_before; 
706    // for each tracker hits, the packet length extends by 4 bytes 
707    self.header.length += (4*delta_hits) as u16;
708  }
709  
710  /// Delete tracker hits (e.g. in case they are supposed to 
711  /// be replaced by packet type 80 tracker hits)
712  #[pyo3(name="delete_all_tracker_hits")]
713  pub fn delete_all_tracker_hits_py(&mut self) {
714    self.tracker_hits.clear();
715  }
716
717  /// Populate a merged event from a TelemetryPacket.
718  ///
719  /// Telemetry packet type should be 90 (MergedEvent)
720  #[staticmethod]
721  fn from_telemetrypacket(packet : TelemetryPacket) -> PyResult<Self> {
722    match Self::from_bytestream(&packet.payload, &mut 0) {
723      Ok(mut event) => {
724        event.header = packet.header.clone();
725        #[cfg(feature="database")]
726        event.hydrate(&packet.tof_paddles, &packet.trk_strips);
727        return Ok(event);
728      }
729      Err(err) => {
730        return Err(PyValueError::new_err(err.to_string()));
731      }  
732    }
733  }
734
735  #[pyo3(name="pack")]
736  fn pack_py(&self) -> TelemetryPacket {
737    self.pack()
738  }
739
740  #[pyo3(name="calibrate_trk_hits")]
741  fn calibrate_trk_hits_py(&mut self, cali : Bound<'_, TrackerOfflineCalibration> , remove_pulsed : bool) -> PyResult<()> {
742    let cali_ref = cali.borrow();
743    self.calibrate_trk_hits(&*cali_ref, remove_pulsed)?;
744    Ok(())
745  }
746}
747
748#[cfg(feature="random")]
749impl FromRandom for TelemetryEvent {
750
751  fn from_random() -> Self {
752    let mut rng    = rand::rng();
753    let mut ev     = Self::new();
754    ev.header      = TelemetryPacketHeader::from_random();
755    ev.tof_event   = TofEvent::from_random();
756    //let n_trk_hits = rng.random::<u8>();
757    let n_trk_hits = 1u8;
758    for _ in 0..n_trk_hits {
759      let mut h = TrackerHit::from_random();
760      h.oscillator = 0;
761      h.asic_event_code = 0;
762      ev.tracker_hits.push(h);
763    }
764    //ev.creation_time      = rng.random::<u64>();
765    ev.creation_time      = 0;
766    ev.event_id           = rng.random::<u32>();
767    ev.flags0             = 3;
768    ev.flags1             = 1;
769    ev.version            = 1;
770    // tracker oscillators are one by layer - set 
771    // layers active by random choice 
772    for idx in 0..10usize {
773      let active = rng.random::<bool>();
774      if idx < 8 && active {
775        ev.osc_flags = ev.osc_flags | (0b1 << idx);
776        let osc  = rng.random::<u64>() & 0x0000FFFFFFFFFFFF;
777        ev.tracker_oscillators[idx] = osc;
778        ev.oscillator_idx.push(idx as u8);
779        //ev.tracker_oscillators[idx] = u32::MAX as u64 + 1;
780      }
781    }
782    return ev;
783  }
784}
785
786#[test]
787#[cfg(feature="random")]
788fn serialize_deserialize_telemetryevent() {
789  for _ in 0..10 {
790    let mut ev        = TelemetryEvent::from_random();  
791    let bytes         = ev.to_bytestream();
792    let mut test      = TelemetryEvent::from_bytestream(&bytes, &mut 0).unwrap();
793    let creation_time = Instant::now();
794    ev.tof_event.creation_time   = creation_time;
795    test.tof_event.creation_time = creation_time;
796    ev.tof_event.rb_events.clear();
797    test.tof_event.rb_events.clear();
798    for h in &mut ev.tof_event.hits {
799      h.coax_cable_time = 0.0;
800      h.hart_cable_time = 0.0;
801      h.event_t0 = 0.0;
802      h.paddle_len = 0.0;
803      h.x = 0.0; 
804      h.y = 0.0; 
805      h.z = 0.0; 
806    }
807    for h in &mut test.tof_event.hits {
808      h.coax_cable_time = 0.0;
809      h.hart_cable_time = 0.0;
810      h.event_t0 = 0.0;
811      h.paddle_len = 0.0;
812      h.x = 0.0; 
813      h.y = 0.0; 
814      h.z = 0.0; 
815    }
816    // the header will not be the same, since it is not  
817    // deserialized with from_bytestream, but just attached 
818    assert_eq!(ev.creation_time      , test.creation_time); 
819    assert_eq!(ev.event_id           , test.event_id); 
820    assert_eq!(ev.osc_flags          , test.osc_flags); 
821    assert_eq!(ev.tracker_oscillators, test.tracker_oscillators); 
822    assert_eq!(ev.raw_data           , test.raw_data); 
823    assert_eq!(ev.flags0             , test.flags0); 
824    assert_eq!(ev.flags1             , test.flags1); 
825    assert_eq!(ev.version            , test.version); 
826    assert_eq!(ev.oscillator_idx     , test.oscillator_idx); 
827    assert_eq!(ev.tracker_hits       , test.tracker_hits); 
828    assert_eq!(ev.tof_event          , test.tof_event); 
829    //assert_eq!(ev, test);
830  }
831}
832
833#[cfg(feature="pybindings")]
834pythonize!(TelemetryEvent);
835