Skip to main content

gondola_core/io/caraspace/
frame.rs

1//! Caraapace I/O system
2//!
3// The following file is part of gaps-online-software and published 
4// under the GPLv3 license
5
6use crate::prelude::*;
7
8/// The Caraspace object type determines the 
9/// kind of object we are able to put in 
10/// a frame and ultimate (de)serialize
11#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
12#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
13#[repr(u8)]
14pub enum CRFrameObjectType {
15  Unknown          =  0u8,
16  TofPacket        = 10u8,
17  TelemetryPacket  = 20u8,
18  McTree           = 30u8,
19  CRFrameHeader    = 40u8,
20  CRFileSummary    = 50u8,
21}
22
23expand_and_test_enum!(CRFrameObjectType, test_crframeobjecttype_repr);
24
25//---------------------------------------------------
26
27/// All possible merged event types in the context of 
28/// CRFrame. This can be used to check against if a frame 
29/// contains any kind of merged event
30pub const MERGED_EVENT_TYPES : [&'static str;4] = [
31  "TelemetryPacketType.NoGapsTriggerEvent",
32  "TelemetryPacketType.BoringEvent",
33  "TelemetryPacketType.InterestingEvent",
34  "TelemetryPacketType.NoTofDataEvent"];
35
36/// A registry of all possible names for TelemetryEvents (aka "MergedEvent") 
37/// which can be stored in CRFrames. This provides the keys they are stored 
38/// under
39#[cfg(feature="pybindings")]
40#[pyfunction]
41pub fn get_all_telemetry_event_names() -> [&'static str;4] {
42  MERGED_EVENT_TYPES
43}
44
45//---------------------------------------------------
46
47/// A Caraspace object, that can be stored
48/// within a frame.
49///
50/// _For the connaiseur_: This is basically a 
51/// TofPacket on steroids_
52///
53///
54#[derive(Debug, Clone)]
55#[cfg_attr(feature="pybindings", pyclass)] 
56pub struct CRFrameObject {
57  pub version : u8,
58  pub ftype   : CRFrameObjectType,
59  /// serialized representation of the 
60  /// content object
61  pub payload : Vec<u8>,
62}
63
64impl CRFrameObject {
65  pub fn new() -> Self {
66    Self {
67      version          : 0,
68      ftype            : CRFrameObjectType::Unknown,
69      payload          : Vec::<u8>::new(),
70    }
71  }
72
73  /// Size of the serialized object, including
74  /// header and footer in bytes
75  pub fn size(&self) -> usize {
76    let size = self.payload.len() + 2 + 4; 
77    size
78  }
79
80  /// Unpack the TofPacket and return its content
81  pub fn extract<T>(&self) -> Result<T, SerializationError>
82    where T: Frameable + Serialization {
83    if T::CRFRAMEOBJECT_TYPE != self.ftype {
84      error!("This bytestream is not for a {} packet!", self.ftype);
85      return Err(SerializationError::IncorrectPacketType);
86    }
87    let unpacked : T = T::from_bytestream(&self.payload, &mut 0)?;
88    Ok(unpacked)
89  }
90}
91
92impl Serialization for CRFrameObject {
93  
94  /// Decode a serializable from a bytestream  
95  fn from_bytestream(stream : &Vec<u8>, 
96                     pos    : &mut usize)
97    -> Result<Self, SerializationError>
98    where Self : Sized {
99    if stream.len() < 2 {
100      return Err(SerializationError::HeadInvalid {});
101    }
102    let head = parse_u16(stream, pos);
103    if Self::HEAD != head {
104      error!("Packet does not start with CRHEAD signature");
105      return Err(SerializationError::HeadInvalid {});
106    }
107      let mut f_obj    = CRFrameObject::new();
108      f_obj.version    = parse_u8(stream, pos);
109      let ftype        = parse_u8(stream, pos);
110      f_obj.ftype      = CRFrameObjectType::from(ftype);
111      let payload_size = parse_u32(stream, pos);
112      *pos += payload_size as usize; 
113      let tail = parse_u16(stream, pos);
114      if Self::TAIL != tail {
115        error!("Packet does not end with CRTAIL signature");
116        return Err(SerializationError::TailInvalid {});
117      }
118      *pos -= 2; // for tail parsing
119      *pos -= payload_size as usize;
120      f_obj.payload.extend_from_slice(&stream[*pos..*pos+payload_size as usize]);
121      Ok(f_obj)
122  }
123  
124  /// Encode a serializable to a bytestream  
125  fn to_bytestream(&self) -> Vec<u8> {
126    let mut stream = Vec::<u8>::new();
127    stream.extend_from_slice(&Self::HEAD.to_le_bytes());
128    stream.push(self.version);
129    stream.push(self.ftype as u8);
130    let size = self.payload.len() as u32;
131    stream.extend_from_slice(&size.to_le_bytes());
132    stream.extend_from_slice(&self.payload.as_slice());
133    stream.extend_from_slice(&Self::TAIL.to_le_bytes());
134    stream
135  }
136}
137
138impl fmt::Display for CRFrameObject {
139  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140    let p_len = self.payload.len();
141    write!(f, "<CRFrameObject: type {:?}, payload [ {} {} {} {} .. {} {} {} {}] of size {} >",
142           self.ftype,
143           self.payload[0], self.payload[1], self.payload[2], self.payload[3],
144           self.payload[p_len-4], self.payload[p_len-3], self.payload[p_len - 2], self.payload[p_len-1], p_len ) 
145  }
146}
147
148//---------------------------------------------------
149
150#[cfg(feature="pybindings")]
151pythonize!(CRFrameObject);
152
153//---------------------------------------------------
154
155/// The central data container of the 
156/// caraspace suite. 
157///
158/// A CRFrame can hold multiple CRFrameObjects
159/// and is basically a little sclerite of 
160/// the entire skeleton.
161#[derive(Debug, Clone)]
162#[cfg_attr(feature="pybindings", pyclass)]
163pub struct CRFrame {
164  // the index holds name, position in frame as well as the type of 
165  // object stored in the frame
166  // FIXME - this needs to be HashMap<&str, (u64, CRFrameObjectType)>
167  pub index            : HashMap<String, (u64, CRFrameObjectType)>,
168  pub bytestorage      : Vec<u8>,
169  pub tof_paddles      : Arc<HashMap<u8,  TofPaddle>>, 
170  pub trk_strips       : Arc<HashMap<u32, TrackerStrip>>,
171  pub trk_masks        : Arc<HashMap<u32, TrackerStripMask>>,
172  pub trk_ped          : Arc<HashMap<u32, TrackerStripPedestal>>,
173  pub trk_tf           : Arc<HashMap<u32, TrackerStripTransferFunction>>,
174  pub trk_cmn          : Arc<HashMap<u32, TrackerStripCmnNoise>>, 
175  /// TRK calibration - convert to energy
176  pub do_trk_calib     : bool,
177  /// TRK subtract CMN 
178  pub subtract_trk_cmn : bool,
179  // will not get serialized, just hold the 
180  // number for the writer in case it needs 
181  // to write files every x second interval 
182  pub timestamp : Option<f64>,
183  // will not get serialized either, the GPS time 
184  // of this frame for the file summary
185  pub gpstime   : Option<f64>,
186}
187
188impl CRFrame {
189  
190  pub fn new() -> Self {
191    Self {
192      index            : HashMap::<String, (u64, CRFrameObjectType)>::new(),
193      bytestorage      : Vec::<u8>::new(),
194      tof_paddles      : Arc::new(HashMap::<u8, TofPaddle>::new()),
195      trk_strips       : Arc::new(HashMap::<u32, TrackerStrip>::new()),
196      trk_masks        : Arc::new(HashMap::<u32, TrackerStripMask>::new()),
197      trk_ped          : Arc::new(HashMap::<u32, TrackerStripPedestal>::new()),
198      trk_tf           : Arc::new(HashMap::<u32, TrackerStripTransferFunction>::new()),
199      trk_cmn          : Arc::new(HashMap::<u32, TrackerStripCmnNoise>::new()), 
200      do_trk_calib     : false,
201      subtract_trk_cmn : false,
202      timestamp        : None,
203      gpstime          : None,
204    }
205  }
206
207  /// Extract trackerhits across the frame. 
208  ///
209  /// Sources for tracker hits can either be the regular 
210  /// TelemetryEvents, or all the different TrackerHits. 
211  ///
212  ///
213  // FIXME - this needs to return references with lifetimes, not 
214  // cloning the hits
215  pub fn get_tracker_hitseries(&self, source : TrackerHitSource, name : Option<String>) 
216    -> Result<Vec<TrackerHit>, SerializationError> {
217    let mut hits = Vec::<TrackerHit>::new();
218    let mut tracker_hit_name = String::from("Tracker");
219    if name.is_some() {
220      tracker_hit_name = name.unwrap();
221    }
222    match source {
223      TrackerHitSource::TelemetryEvent |
224      TrackerHitSource::Unknown => {
225      }
226      TrackerHitSource::TrackerPacket => {
227        for k in self.index.keys() {
228          if k.contains(&tracker_hit_name) {
229            let pack = self.get::<TelemetryPacket>(k)?;
230            let trk  = TrackerDAQEventPacket::from_telemetrypacket(&pack)?;
231            for ev in trk.events {
232              for h in ev.hits {
233                hits.push(h.clone());
234              }
235            }
236          }
237        }
238      }
239    }
240    Ok(hits) 
241  }
242
243  pub fn get_telemetrypacket_gcutime_range(&self) -> Option<(f64,f64,f64)> {
244    let mut times = Vec::<f64>::new();
245    for k in self.index.keys() {
246      let f_obj_idx = self.index.get(k).unwrap();
247      if f_obj_idx.1 == CRFrameObjectType::TelemetryPacket { 
248        // offset of 8 for serialzied CRFrameObject 
249        let ts = TelemetryPacket::get_gcutime_unpacked(&self.bytestorage[f_obj_idx.0 as usize + 8..].to_vec()); 
250        if ts.is_ok() {
251          times.push(ts.unwrap());
252        }
253      }
254    }
255    if times.len() > 0 {
256      let min_time = times.iter().min_by(|a, b| a.partial_cmp(b).unwrap()).unwrap();
257      let max_time = times.iter().max_by(|a, b| a.partial_cmp(b).unwrap()).unwrap();
258      let delta    = max_time - min_time;
259      return Some((*min_time,*max_time,delta));
260    }
261    None
262  }
263
264  pub fn serialize_index(&self) -> Vec<u8> {
265    let mut s_index  = Vec::<u8>::new();
266    // more than 255 frame items are not supported
267    let idx_size = self.index.len() as u8;
268    s_index.push(idx_size);
269    for k in &self.index {
270      let mut s_name  = Self::string_to_bytes(k.0.clone());
271      let s_pos   = k.1.0.to_le_bytes();
272      s_index.append(&mut s_name);
273      s_index.extend_from_slice(&s_pos);
274      s_index.push(k.1.1 as u8);
275    }
276    s_index
277  }
278
279  ///// Get the timestamp from the actual telemetry packet in the frame
280  //pub fn get_timestamp(&self) -> u64 {
281  //  todo!("Needs to be implemented!");
282  //  return 0
283  //}
284
285  pub fn string_to_bytes(value : String) -> Vec<u8> {
286    let mut stream  = Vec::<u8>::new();
287    let mut payload = value.into_bytes();
288    let string_size = payload.len() as u16; // limit size
289    stream.extend_from_slice(&string_size.to_le_bytes());
290    stream.append(&mut payload);
291    stream
292  }
293
294  pub fn parse_index(stream : &Vec<u8>, pos : &mut usize) -> HashMap<String, (u64, CRFrameObjectType)> {
295    let idx_size = parse_u8(stream, pos);
296    //println!("Found index of size {idx_size}");
297    let mut index    = HashMap::<String, (u64, CRFrameObjectType)>::new();
298    for _ in 0..idx_size as usize {
299      let name    = parse_string(stream, pos);
300      let obj_pos = parse_u64(stream, pos);
301      let obj_t   = CRFrameObjectType::from(stream[*pos]);
302      *pos += 1;
303      //println!("-- {} {} {}", name, obj_pos, obj_t);
304      index.insert(name.to_owned(), (obj_pos, obj_t));
305    }
306    index
307  }
308
309  /// Delete a CRFrameObject by this name from the frame
310  ///
311  /// To delete multiple objects, delete calls can be 
312  /// chained
313  /// 
314  /// # Arguments:
315  ///   * name : The name of the FrameObject to delte 
316  ///            (must be in index)
317  ///
318  /// # Returns:
319  ///   A complete copy of self, without the given object.
320  pub fn delete(&self, name : &str) -> Result<CRFrame, SerializationError> {
321    // a copy keeps everything which is not serialized as well
322    // (calibrations, timestamps, ...)
323    let mut new_frame = self.clone();
324    new_frame.remove(name)?;
325    Ok(new_frame)
326  }
327
328  /// Remove a CRFrameObject by this name from the frame (in place)
329  ///
330  /// The bytes of the object are removed as well, all 
331  /// other objects are kept unchanged.
332  pub fn remove(&mut self, name : &str) -> Result<(), SerializationError> {
333    if !self.has(name) {
334      error!("There is no object with name {} in this frame!", name);
335      return Err(SerializationError::ObjectNotFound);
336    }
337    let mut keep = Vec::<(String, CRFrameObject)>::with_capacity(self.index.len());
338    for objname in self.index.keys() {
339      if objname == name {
340        continue;
341      }
342      keep.push((objname.clone(), self.get_fobject(objname)?));
343    }
344    self.index.clear();
345    self.bytestorage.clear();
346    for (objname, obj) in keep {
347      self.put_fobject(obj, &objname);
348    }
349    Ok(())
350  }
351
352
353  /// Store any eligible object in the frame
354  ///
355  /// Eligible object must implement the "Frameable" trait
356  pub fn put<T: Serialization + Frameable>(&mut self, object : T, name : &str) {
357    let f_object = object.pack();
358    self.put_fobject(f_object, name);
359  }
360
361  fn put_fobject(&mut self, object : CRFrameObject, name : &str) {
362    let pos    = self.bytestorage.len() as u64;
363    self.index.insert(name.to_string(), (pos, object.ftype));
364    let mut stream = object.to_bytestream();
365    //self.put_stream(&mut stream, name);
366    //let pos    = self.bytestorage.len();
367    //self.index.insert(name, pos);
368    self.bytestorage.append(&mut stream);
369  }
370
371  /// Check if the frame contains an object with the given name
372  ///
373  /// # Arguments:
374  ///   * name : The name of the object as it appears in the index
375  pub fn has(&self, name : &str) -> bool {
376    self.index.contains_key(name)
377  }
378  
379  /// A list of TelemetryEvents (fka MergedEvent) in the frame
380  pub fn get_telemetry_event_names(&self) -> Vec<&str> {
381    let mut tevents = Vec::<&str>::new();
382    for k in MERGED_EVENT_TYPES {
383      if self.has(k) {
384        tevents.push(k);
385      }
386    }
387    tevents
388  }
389
390  //pub fn put_stream(&mut self, stream : &mut Vec<u8>, name : String) {
391  //  let pos    = self.bytestorage.len();
392  //  self.index.insert(name, pos);
393  //  self.bytestorage.append(stream);
394  //}
395
396  pub fn get_fobject(&self, name : &str) -> Result<CRFrameObject, SerializationError> {
397    let mut pos    : usize;
398    match self.index.get(name) {
399      None => {
400        error!("There is no object with name {} in this frame!", name);
401        return Err(SerializationError::ObjectNotFound);
402      }
403      Some(meta)  => {
404        //lookup = meta;
405        pos   = meta.0 as usize;
406      }
407    }
408    let cr_object = CRFrameObject::from_bytestream(&self.bytestorage, &mut pos)?;
409    Ok(cr_object)
410  }
411
412  /// A check if the frame contains anything which is a telemetrypacket. 
413  /// This can be used to check if we can get the time of the telemetrypacket 
414  /// directly
415  pub fn get_first_gcutime(&self) -> Option<f64> {
416    let times = self.get_telemetrypacket_gcutime_range()?; 
417    Some(times.0)
418  }
419
420  pub fn get<T : Serialization + Frameable>(&self, name : &str) -> Result<T, SerializationError> {
421    
422    //let mut lookup : (usize, CRFrameObjectType);
423    let mut pos    : usize;
424    match self.index.get(name) {
425      None => {
426        return Err(SerializationError::ValueNotFound);
427      }
428      Some(meta)  => {
429        //lookup = meta;
430        pos   = meta.0 as usize;
431      }
432    }
433    let cr_object = CRFrameObject::from_bytestream(&self.bytestorage, &mut pos)?;
434    let result    = cr_object.extract::<T>()?;
435    Ok(result)
436  }
437
438  /// A verbose display of the frame content
439  pub fn show_frame(&self) -> String {
440    let mut repr = String::from("");
441    for k in &self.index {
442      repr += &(format!("\n -- {}@{}:{} --", k.0, k.1.0, k.1.1));
443      //match k.1.1 {
444      //  CRFrameObjectType::TelemetryPacket => {
445      //    repr += &(format!("\n -- -- {}", self.get<TelemetryPacket>
446      //  }
447      //  CRFrameObjectType::TofPacket => {
448      //  }
449      //}
450    }
451    repr 
452  }
453  
454  /// The CRFrameHeader of this frame, if it has one 
455  /// (stored under CRFRAMEHEADER_NAME)
456  pub fn get_header(&self) -> Option<CRFrameHeader> {
457    if !self.has(CRFRAMEHEADER_NAME) {
458      return None;
459    }
460    match self.get::<CRFrameHeader>(CRFRAMEHEADER_NAME) {
461      Ok(header) => Some(header),
462      Err(err)   => {
463        error!("Unable to decode the CRFrameHeader of this frame! {err}");
464        None
465      }
466    }
467  }
468
469  /// An empty frame only contains a CRFrameHeader. It 
470  /// stands for an event which is missing in the data
471  pub fn is_empty_event(&self) -> bool {
472    self.index.len() == 1 && self.has(CRFRAMEHEADER_NAME)
473  }
474
475  /// Store a CRFrameHeader in this frame. An existing 
476  /// header is replaced (and its bytes removed)
477  pub fn put_header(&mut self, header : CRFrameHeader) {
478    if self.has(CRFRAMEHEADER_NAME) {
479      // can not fail, the header is there
480      let _ = self.remove(CRFRAMEHEADER_NAME);
481    }
482    self.put(header, CRFRAMEHEADER_NAME);
483  }
484
485  /// Add a data source to the CRFrameHeader of this frame. 
486  ///
487  /// Use this when adding packets of a new data source to 
488  /// a frame, so that the header (and the file summary) 
489  /// stay consistent with the content. 
490  /// A source which is already present is not added again.
491  pub fn add_datasource(&mut self, source : GapsDataSource) -> Result<(), SerializationError> {
492    let mut header = match self.get_header() {
493      None => {
494        error!("This frame does not have a CRFrameHeader, can not add data source {}!", source);
495        return Err(SerializationError::ObjectNotFound);
496      }
497      Some(h) => h
498    };
499    header.add_datasource(source);
500    self.put_header(header);
501    Ok(())
502  }
503}
504
505impl Default for CRFrame {
506  fn default() -> Self {
507    Self::new()
508  }
509}
510
511impl Serialization for CRFrame {
512  /// Decode a serializable from a bytestream  
513  fn from_bytestream(stream : &Vec<u8>, 
514                     pos    : &mut usize)
515    -> Result<Self, SerializationError> {
516    if stream.len() < 2 {
517      return Err(SerializationError::HeadInvalid {});
518    }
519    let head = parse_u16(stream, pos);
520    if Self::HEAD != head {
521      error!("FrameObject does not start with HEAD signature");
522      return Err(SerializationError::HeadInvalid {});
523    }
524    if stream.len() < *pos + 8 {
525      return Err(SerializationError::StreamTooShort);
526    }
527    // the size is the size of index + bytestorage
528    let fr_size   = parse_u64(stream, pos) as usize; 
529    let start     = *pos;
530    if stream.len() < start + fr_size + 2 {
531      return Err(SerializationError::StreamTooShort);
532    }
533    *pos = start + fr_size;
534    let tail = parse_u16(stream, pos);
535    if Self::TAIL != tail {
536      error!("FrameObject does not end with TAIL signature");
537      return Err(SerializationError::TailInvalid {});
538    }
539    // pos stays behind the TAIL, read the content from the start
540    let mut frame       = CRFrame::new();
541    let mut content_pos = start;
542    frame.index         = Self::parse_index(stream, &mut content_pos);
543    frame.bytestorage   = stream[content_pos..start + fr_size].to_vec();
544    Ok(frame)
545  }
546  
547  /// Encode a serializable to a bytestream  
548  fn to_bytestream(&self) -> Vec<u8> {
549    let mut stream  = Vec::<u8>::new();
550    stream.extend_from_slice(&Self::HEAD.to_le_bytes());
551    let mut s_index = self.serialize_index();
552    //let idx_size    = s_index.len() as u64;
553    let size = self.bytestorage.len() as u64 + s_index.len() as u64;
554    //println!("Will store frame with {size} bytes!");
555    stream.extend_from_slice(&size.to_le_bytes());
556    stream.append(&mut s_index);
557    stream.extend_from_slice(&self.bytestorage.as_slice());
558    stream.extend_from_slice(&Self::TAIL.to_le_bytes());
559    stream
560  }
561}
562
563impl fmt::Display for CRFrame {
564  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
565    let mut repr = String::from("<CRFrame : ");
566    repr += &self.show_frame();
567    repr += "\n>";
568    write!(f, "{}", repr)
569  }
570}
571
572//---------------------------------------------------
573
574#[cfg(feature="pybindings")]
575#[pymethods]
576impl CRFrame {
577  
578  /// Delete a CRFrameObject by this name from the frame
579  ///
580  /// To delete multiple objects, delete calls can be 
581  /// chained
582  /// 
583  /// # Arguments:
584  ///   * name : The name of the FrameObject to delte 
585  ///            (must be in index)
586  ///
587  /// # Returns:
588  ///   A complete copy of self, without the given object.
589  #[pyo3(name="delete")]
590  fn delete_py(&self, name : &str) -> PyResult<Self> {
591    if !self.has(name) {
592      let msg = format!("Frame does not contain {}", name);
593      return Err(PyKeyError::new_err(msg));
594    }
595    match self.delete(name) {
596      Ok(new_frame) => {
597        Ok(new_frame)
598      }
599      Err(err) => {
600        return Err(PyValueError::new_err(err.to_string()));
601      }
602    }
603  }
604  
605  #[getter]
606  /// A list of TelemetryEvents (fka MergedEvent) in the frame
607  fn telemetry_event_names(&self) -> Vec<&str> {
608    self.get_telemetry_event_names() 
609  }
610  
611  /// In case the frame contains at least one telemetrypacket, 
612  /// return the smallest of all gcutimes from all packets in the 
613  /// frame. 
614  ///
615  /// If there is no telemetrypacket in the frame, return None
616  #[pyo3(name="get_first_gcutime")]
617  fn get_first_gcutime_py(&self) -> Option<f64> {
618    self.get_first_gcutime()
619  }
620
621  /// The number of individual frame objects in the frame
622  #[getter] 
623  fn get_n_objects(&self) -> usize {
624    self.index.len()
625  }
626
627  /// For multiple telemetry packets in the frame, get the first and 
628  /// last gcu time, as well as the delta between them
629  #[pyo3(name="get_telemetrypacket_gcutime_range")]
630  fn get_telemetrypacket_gcutime_range_py(&self) -> Option<(f64,f64,f64)> {
631    self.get_telemetrypacket_gcutime_range()
632  }
633
634
635  /// Add a TelemetryPacket to the frame. 
636  ///
637  /// # Arguments:
638  ///   name : The name under which we store the TelemetryPacket within the index.
639  ///          If None given, use the default name, which is
640  ///          "TelemetryPacketType.<ValueOf(TelemetryPacketType)". This should be used in 
641  ///          all cases for which there is only a single TelemetryPacket within 
642  ///          the frame.
643  #[pyo3(signature = (packet, name = None, record_timestamp = false))]
644  fn put_telemetrypacket(&mut self, packet : TelemetryPacket, name : Option<&str>, record_timestamp : bool) -> PyResult<()> {
645    if record_timestamp { 
646      self.timestamp = Some(packet.header.get_gcutime());
647    }
648    if let Some(p_name) = name {
649      if self.has(p_name) {
650        let msg = format!("Frame already contains a TelemetryPacket named {}", p_name);
651        return Err(PyValueError::new_err(msg));
652      }
653      self.put(packet, p_name);
654      Ok(())
655    } else {
656      let name = format!("TelemetryPacketType.{}", packet.header.packet_type.as_ref());
657      let msg = format!("Frame already contains a TelemetryPacket named {}", name);
658      if self.has(&name) {
659        return Err(PyValueError::new_err(msg));
660      }
661      self.put(packet, name.as_str());
662      Ok(())
663    }
664  }
665  
666  /// Add a TofPacket to the frame. 
667  ///
668  /// # Arguments:
669  ///   name : The name under which we store the TofPacket within the index.
670  ///          If None given, use the default name, which is
671  ///          "TofPacketType.<ValueOf(TofPacketType)". This should be used in 
672  ///          all cases for which there is only a single TofPacket within 
673  ///          the frame.
674  #[pyo3(signature = (packet, name = None))]
675  fn put_tofpacket(&mut self, packet : TofPacket, name : Option<&str>) -> PyResult<()> {
676    if let Some(p_name) = name {
677      if self.has(p_name) {
678        let msg = format!("Frame already contains a TofPacket named {}", p_name);
679        return Err(PyValueError::new_err(msg));
680      }
681      self.put(packet, p_name);
682      Ok(())
683    } else {
684      let name = format!("TofPacketType.{}", packet.packet_type.as_ref());
685      let msg = format!("Frame already contains a TofPacket named {}", name);
686      if self.has(&name) {
687        return Err(PyValueError::new_err(msg));
688      }
689      self.put(packet, name.as_str());
690      Ok(())
691    }
692  }
693 
694  /// Retrieve a TofPacket from a frame
695  ///
696  /// # Arguments:
697  ///   * name : The name of the packet as it is stored in the 
698  ///            index
699  fn get_tofpacket(&mut self, name : &str) -> PyResult<TofPacket> {
700    let packet    = self.get::<TofPacket>(name).unwrap();
701    Ok(packet)
702  }
703  
704  /// Retrieve a TelemetryPacket from a frame
705  ///
706  /// # Arguments:
707  ///   * name : The name of the packet as it is stored in the 
708  ///            index
709  //#[pyo3(signature = (name = None))]
710  fn get_telemetrypacket(&mut self, name : &str) -> PyResult<TelemetryPacket> {
711    match self.get::<TelemetryPacket>(name) {
712      Err(err)   => Err(PyValueError::new_err(format!("Unable to get TelemetryPacket {} from frame! {}", name, err))),
713      Ok(packet) => Ok(packet)
714    }
715  }
716
717  fn get_mctree(&mut self, name : &str) -> PyResult<McEvent> {
718    match self.get::<McEvent>(name) {
719      Err(err)  => Err(PyValueError::new_err(format!("Unable to get McEvent {} from frame! {}", name, err))),
720      Ok(event) => Ok(event)
721    }
722  }
723
724  /// Get a tofevent from the frame directly
725  fn get_tofevent(&mut self, name : &str) -> PyResult<TofEvent> {
726    let packet    = self.get::<TofPacket>(name).unwrap();
727    let mut event = packet.unpack::<TofEvent>().unwrap();
728    event.set_paddles(&self.tof_paddles);
729    //event.set_paddles(&self.paddles);
730    //py_event.event  = event;
731    Ok(event)
732  }
733
734  /// Get a TelemetryEvent ("MergedEvent") from the frame
735  ///
736  /// This automatically unpacks the event 
737  ///
738  /// # Arugments:
739  ///   * name           : in case there are multiple telemetry events in the same 
740  ///                      frame, choose the one to return by name. In case there 
741  ///                      are multiple events and no name is given, a ValueError 
742  ///                      is raised. In case the one with the given name does not exist,
743  ///                      a ValueError is raised as well.
744  ///   * always_exclude : never return the name given to always_exclude. This can be useful 
745  ///                      in case there are multiple events and no name is given.
746  ///
747  /// # Returns:
748  ///   TelemetryEvent -> if a name is given and the corresponding packe
749  ///                     packet is found OR no name is given and the 
750  ///                     frame contains any TelemetryEvent
751  ///   None           -> if no name is given, but the frame does not
752  ///                     contain any TelemetryEvent
753  #[pyo3(signature = (name = None, always_exclude = None))]
754  fn get_telemetryevent(&mut self, name : Option<&str>, always_exclude : Option<Vec<String>>) -> PyResult<Option<TelemetryEvent>> {
755    let name_ : &str;
756    match name {
757      None => {
758        let mut names = self.get_telemetry_event_names();
759        if let Some(to_exclude) = always_exclude {
760          let exclusion_set: HashSet<_> = to_exclude.into_iter().collect();
761          names.retain(|&x| !exclusion_set.contains(x));
762        }
763        if names.len() != 1 {
764          let msg = format!("Frame contains multiple or no TelemetryEvents {:?}. Please specify a name!", names);
765          return Err(PyValueError::new_err(msg)); 
766        } else {
767          name_ = names[0];
768        }
769      }
770      Some(n_) => {
771        name_ = n_;
772      }
773    }
774    let packet = match self.get::<TelemetryPacket>(name_) {
775      Err(err)   => return Err(PyValueError::new_err(format!("Unable to get TelemetryPacket {} from frame! {}", name_, err))),
776      Ok(packet) => packet
777    };
778    match packet.unpack::<TelemetryEvent>() {
779      Err(err) => {
780        return Err(PyValueError::new_err(err.to_string())); 
781      }
782      Ok(mut event) => {
783        event.header  = packet.header;  
784        event.hydrate(&self.tof_paddles, &self.trk_strips);
785        if self.do_trk_calib {
786        //  event.mask_strips(&self.trk_masks);
787        //  event.calibrate_tracker(self.subtract_trk_cmn, 
788        //                          &self.trk_ped,
789        //                          &self.trk_tf,
790        //                          &self.trk_cmn);
791        error!("Tracker calibration not implemented!");
792        }
793        Ok(Some(event))
794      }
795    }
796  }
797
798  /// The serialized payload of the object with the given name, 
799  /// e.g. to deserialize it with the C++ library 
800  /// (gondola_cxx.McEvent.from_bytestream)
801  ///
802  /// # Arguments:
803  ///   * name : The name of the object as it appears in the index
804  #[pyo3(name="get_payload")]
805  fn get_payload_py<'py>(&self, py : Python<'py>, name : &str) -> PyResult<Bound<'py, PyBytes>> {
806    match self.get_fobject(name) {
807      Err(err) => {
808        Err(PyValueError::new_err(format!("Unable to get {} from frame! {}", name, err)))
809      }
810      Ok(fobject) => {
811        Ok(PyBytes::new(py, &fobject.payload))
812      }
813    }
814  }
815
816  /// Check if the frame contains an object with the given name
817  ///
818  /// # Arguments:
819  ///   * name : The name of the object as it appears in the index
820  #[pyo3(name="has")]
821  fn has_py(&self, name : &str) -> bool {
822    self.has(name)
823  }
824 
825
826  /// The index of the frame. This is a dictionary of name, 
827  /// to byte position in the file as well as its type
828  #[getter]
829  fn index(&self) -> HashMap<String, (u64, CRFrameObjectType)> {
830    self.index.clone()
831  }
832
833  #[getter]
834  #[pyo3(name="do_trk_calib")]
835  fn do_trk_calib_py(&self) -> bool {
836    self.do_trk_calib
837  }
838
839  /// For multiple telemetry packets in the frame, this allows to 
840  /// select a specific hitseries from a number of packets with 
841  /// the same name tag
842  #[pyo3(name="get_tracker_hitseries")]
843  #[pyo3(signature = (name = None))]
844  fn get_tracker_hitseries_py(&self, name : Option<String>) -> Vec<TrackerHit> {
845    self.get_tracker_hitseries(TrackerHitSource::TrackerPacket, name).unwrap()
846  }
847
848}
849
850
851
852#[cfg(feature="pybindings")]
853pythonize!(CRFrame);
854
855#[test]
856#[cfg(feature="random")]
857fn serialize_deserialize_crframe() {
858  for _ in 0..20 {
859    let mut frame = CRFrame::new();
860    frame.put(TofPacket::from_random(), "TofPacket");
861    frame.put(CRFrameHeader::from_random(), "header");
862    let mut stream = frame.to_bytestream();
863    // something after the frame must not be read
864    stream.extend_from_slice(&[1,2,3]);
865    let mut pos = 0;
866    let test    = CRFrame::from_bytestream(&stream, &mut pos).unwrap();
867    assert_eq!(pos, stream.len() - 3);
868    assert_eq!(test.index, frame.index);
869    assert_eq!(test.bytestorage, frame.bytestorage);
870    assert_eq!(test.get::<CRFrameHeader>("header").unwrap(), frame.get::<CRFrameHeader>("header").unwrap());
871  }
872  
873  #[test]
874  fn crframe_put_header_replaces() {
875    let mut frame = CRFrame::new();
876    frame.put(TofPacket::new(), "TofPacket");
877    frame.put_header(header_for(1));
878    let size = frame.bytestorage.len();
879    frame.put_header(header_for(2));
880    // the old header is gone, not only hidden
881    assert_eq!(frame.bytestorage.len(), size);
882    assert_eq!(frame.index.len(), 2);
883    assert_eq!(frame.get_header().unwrap().event_id, 2);
884    // the other objects are unchanged
885    assert_eq!(frame.get::<TofPacket>("TofPacket").unwrap(), TofPacket::new());
886  }
887
888  #[test]
889  fn crframe_add_datasource() {
890    // an empty frame, which gets data later on
891    let mut frame = CRFrame::new();
892    frame.put_header(header_for(7));
893    assert!(frame.is_empty_event());
894    frame.put(TofPacket::new(), "TofPacket");
895    frame.add_datasource(GapsDataSource::TOFCPU).unwrap();
896    frame.add_datasource(GapsDataSource::TOFCPU).unwrap();
897    assert!(!frame.is_empty_event());
898    let header = frame.get_header().unwrap();
899    assert_eq!(header.event_id, 7);
900    assert_eq!(header.data_sources, vec![GapsDataSource::TOFCPU]);
901    // without header, there is nothing to add to
902    let mut no_header = CRFrame::new();
903    assert!(no_header.add_datasource(GapsDataSource::GCU).is_err());
904    assert!(!no_header.has(CRFRAMEHEADER_NAME));
905  }
906
907  #[test]
908  fn crframe_delete_keeps_everything_else() {
909    let mut frame       = CRFrame::new();
910    frame.put(TofPacket::new(), "TofPacket");
911    frame.put_header(header_for(3));
912    frame.timestamp        = Some(12.5);
913    frame.gpstime          = Some(30.5);
914    frame.do_trk_calib     = true;
915    frame.subtract_trk_cmn = true;
916    let new_frame = frame.delete("TofPacket").unwrap();
917    assert!(!new_frame.has("TofPacket"));
918    assert_eq!(new_frame.get_header().unwrap().event_id, 3);
919    assert_eq!((new_frame.timestamp, new_frame.gpstime), (Some(12.5), Some(30.5)));
920    assert!(new_frame.do_trk_calib && new_frame.subtract_trk_cmn);
921    assert!(Arc::ptr_eq(&new_frame.trk_masks, &frame.trk_masks));
922    assert!(Arc::ptr_eq(&new_frame.trk_ped,   &frame.trk_ped));
923    assert!(Arc::ptr_eq(&new_frame.trk_tf,    &frame.trk_tf));
924    assert!(Arc::ptr_eq(&new_frame.trk_cmn,   &frame.trk_cmn));
925    // the original frame is unchanged
926    assert!(frame.has("TofPacket"));
927    assert!(frame.delete("NotThere").is_err());
928  }
929}