Skip to main content

gondola_core/io/caraspace/
frame_header.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//---------------------------------------------------
9
10/// GAPS specific - gaps data source. This can be data 
11/// from various disks or telemetry 
12/// FIXME - this should go somehwere else  
13#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
14#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
15#[repr(u8)]
16pub enum GapsDataSource {
17  /// default/unknown (usually fallback for issues)
18  Unknown          =  0u8,
19  /// In-flight general computer 
20  GCU              = 10u8,
21  /// In-flight tracker computer 
22  AUXGCU           = 20u8,
23  /// In-flight tof computer 
24  TOFCPU           = 30u8,
25  /// Data sent over starlink (in general all telemetry, but we only used 
26  /// starlink) 
27  TELEMETRY        = 40u8,
28}
29
30expand_and_test_enum!(GapsDataSource, test_gapsdatasource_repr);
31
32//---------------------------------------------------
33
34/// The Caraspace object type determines the 
35/// kind of object we are able to put in 
36/// a frame and ultimate (de)serialize
37#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
38#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
39#[repr(u8)]
40pub enum CRFrameType {
41  /// default/unknown (usually fallback for issues)
42  Unknown          =  0u8,
43  /// Information about the current run 
44  RunInfo          = 10u8,
45  /// special representation of .gdml geometry 
46  Geometry         = 20u8,
47  /// calibration data - either tracker, tof or both
48  Calibration      = 30u8,
49  /// Status - special information about detector status 
50  DetectorStatus   = 40u8,
51  /// monitoring data, this frame does not contain any 
52  /// physics events/packets 
53  Monitoring       = 50u8,
54  /// regular (good physics data) 
55  Physics          = 100u8,
56}
57
58expand_and_test_enum!(CRFrameType, test_crframetype_repr);
59
60//---------------------------------------------------
61
62/// The name under which the CRFrameHeader is stored 
63/// in a frame
64pub const CRFRAMEHEADER_NAME : &str = "header";
65
66//---------------------------------------------------
67
68/// A specific type of CRFrameObject, which holds 
69/// meta information concerning what this frame containes 
70#[derive(Debug, Clone, PartialEq)]
71#[cfg_attr(feature="pybindings", pyclass)] 
72pub struct CRFrameHeader { 
73  /// The version of this frame, needs to be compatible with 
74  /// CRReader/Writer 
75  pub version      : u8,
76  /// Does this frame contain (physics/calibration) event data?
77  pub is_event     : bool,
78  /// Run id (if applicable) 
79  pub run_id       : u16,
80  /// Event id (if applicable) 
81  pub event_id     : u32, 
82  /// Frame id - that is a number which is increasing per each frame 
83  /// by design, no frame id shall be missing. If it is, something 
84  /// might actually be wrong 
85  pub frame_id     : u32,
86  /// What kind of data is stored in this frame? 
87  /// - see CRFrameType reference 
88  pub frame_type   : CRFrameType, 
89  /// What data sources does this frame contain? 
90  pub data_sources : Vec<GapsDataSource> 
91}
92
93impl CRFrameHeader {
94  pub fn new() -> Self {
95    Self {
96      version      : 0,
97      is_event     : false,
98      run_id       : 0,
99      event_id     : 0,
100      frame_id     : 0,
101      frame_type   : CRFrameType::Unknown,
102      data_sources : Vec::<GapsDataSource>::new(),
103    }
104  }
105
106  /// Append a data source to the data sources of this frame.
107  ///
108  /// Each data source can only be present once. If the 
109  /// source is already present, a warning is issued and 
110  /// it is not added again.
111  pub fn add_datasource(&mut self, source : GapsDataSource) {
112    if self.data_sources.contains(&source) {
113      debug!("Data source {} is already present in this frame, not adding it again!", source);
114      return;
115    }
116    self.data_sources.push(source);
117  }
118}
119
120impl CRFrame {
121
122}
123
124#[cfg(feature="pybindings")]
125#[pymethods]
126impl CRFrame {
127
128  /// Add a CRFrameHeader to this frame (stored under "header"). 
129  /// An existing header is replaced.
130  #[pyo3(name="put_header")]
131  fn put_header_py(&mut self, header : CRFrameHeader) {
132    self.put_header(header);
133  }
134
135  /// Add a data source to the CRFrameHeader of this frame. 
136  /// Use this when adding packets of a new data source.
137  #[pyo3(name="add_datasource")]
138  fn add_datasource_py(&mut self, source : GapsDataSource) -> PyResult<()> {
139    match self.add_datasource(source) {
140      Ok(_)    => Ok(()),
141      Err(err) => Err(PyKeyError::new_err(format!("Can not add data source {}! {}", source, err)))
142    }
143  }
144
145  /// The CRFrameHeader of this frame, None if it does not have one
146  #[getter]
147  #[pyo3(name="header")]
148  fn get_header_py(&self) -> Option<CRFrameHeader> {
149    self.get_header()
150  }
151
152  /// True if this frame only contains a CRFrameHeader 
153  /// (an event which is missing in the data)
154  #[getter]
155  #[pyo3(name="is_empty_event")]
156  fn is_empty_event_py(&self) -> bool {
157    self.is_empty_event()
158  }
159
160  /// The GPS time of this frame. It is not stored in 
161  /// the frame itself, but used by the CRWriter for 
162  /// the file summary
163  #[getter]
164  fn get_gpstime(&self) -> Option<f64> {
165    self.gpstime
166  }
167
168  #[setter]
169  fn set_gpstime(&mut self, gpstime : Option<f64>) {
170    self.gpstime = gpstime;
171  }
172}
173
174impl Default for CRFrameHeader {
175  fn default() -> Self {
176    Self::new()
177  }
178}
179
180impl fmt::Display for CRFrameHeader {
181  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182    let mut repr = format!("<CRFrameHeader (version:{}) [{}]:", self.version, self.frame_type);
183    repr += &(format!("\n  Frame id // Run/Event id: {} // {}/{}", self.frame_id, self.run_id, self.event_id));
184    //if self.is_event {
185    //  repr += &(format!("\n  Run/Event id: {}/{}", self.run_id, self.event_id)); 
186    //}
187    if self.data_sources.len() > 0 { 
188      repr += "\n  data sources : [";
189    }
190    for k in &self.data_sources {
191      repr += &(format!(" {} ", k));
192    }
193    if self.data_sources.len() > 0 { 
194      repr += "]";
195    }
196    repr += ">";
197    write!(f, "{}", repr)
198  }
199}
200
201
202//---------------------------------------------------
203
204impl Serialization for CRFrameHeader {
205  
206  /// Decode a CRFrameHeader from a bytestream
207  ///
208  /// Layout (little endian): 
209  ///   HEAD (2) | version (1) | is_event (1) | run_id (2) | event_id (4) |
210  ///   frame_id (4) | frame_type (1) | n_sources (1) | sources (n_sources) | TAIL (2)
211  fn from_bytestream(stream : &Vec<u8>,
212                     pos    : &mut usize)
213    -> Result<Self, SerializationError> {
214    // fixed part of the header, including HEAD and TAIL
215    // (= size of a header without any data sources)
216    if stream.len() < *pos + 18 {
217      return Err(SerializationError::StreamTooShort);
218    }
219    let head = parse_u16(stream, pos);
220    if head != Self::HEAD {
221      error!("Got wrong head bytes! Found {} instead of {}", head, Self::HEAD);
222      return Err(SerializationError::HeadInvalid);
223    }
224    let mut header      = Self::new();
225    header.version      = parse_u8  (stream, pos);
226    header.is_event     = parse_bool(stream, pos);
227    header.run_id       = parse_u16 (stream, pos);
228    header.event_id     = parse_u32 (stream, pos);
229    header.frame_id     = parse_u32 (stream, pos);
230    header.frame_type   = CRFrameType::from(parse_u8(stream, pos));
231    let n_sources       = parse_u8  (stream, pos) as usize;
232    if stream.len() < *pos + n_sources + 2 {
233      return Err(SerializationError::StreamTooShort);
234    }
235    for _ in 0..n_sources {
236      header.data_sources.push(GapsDataSource::from(parse_u8(stream, pos)));
237    }
238    let tail = parse_u16(stream, pos);
239    if tail != Self::TAIL {
240      error!("Got wrong tail bytes! Found {} instead of {}", tail, Self::TAIL);
241      return Err(SerializationError::TailInvalid);
242    }
243    Ok(header)
244  }
245  
246  /// Encode a CRFrameHeader to a bytestream 
247  fn to_bytestream(&self) -> Vec<u8> {
248    let mut stream = Vec::<u8>::with_capacity(18 + self.data_sources.len());
249    stream.extend_from_slice(&Self::HEAD.to_le_bytes());
250    stream.push(self.version);
251    stream.push(self.is_event as u8);
252    stream.extend_from_slice(&self.run_id.to_le_bytes());
253    stream.extend_from_slice(&self.event_id.to_le_bytes());
254    stream.extend_from_slice(&self.frame_id.to_le_bytes());
255    stream.push(self.frame_type as u8);
256    // the number of sources is stored as u8 - there are only 
257    // a handful of GapsDataSources, so this is plenty
258    if self.data_sources.len() > u8::MAX as usize {
259      error!("Too many data sources ({}), only the first {} will be serialized!", self.data_sources.len(), u8::MAX);
260    }
261    let n_sources = self.data_sources.len().min(u8::MAX as usize);
262    stream.push(n_sources as u8);
263    for k in &self.data_sources[0..n_sources] {
264      stream.push(*k as u8);
265    }
266    stream.extend_from_slice(&Self::TAIL.to_le_bytes());
267    stream
268  }
269}
270
271impl Frameable for CRFrameHeader {
272  const CRFRAMEOBJECT_TYPE : CRFrameObjectType = CRFrameObjectType::CRFrameHeader;
273}
274
275//---------------------------------------------------
276
277#[cfg(feature="pybindings")]
278#[pymethods]
279impl CRFrameHeader {
280
281  /// The version of this frame
282  #[getter]
283  fn get_version(&self) -> u8 {
284    self.version
285  }
286
287  #[setter]
288  fn set_version(&mut self, version : u8) {
289    self.version = version;
290  }
291
292  /// Does this frame contain (physics/calibration) event data?
293  #[getter]
294  fn get_is_event(&self) -> bool {
295    self.is_event
296  }
297
298  #[setter]
299  fn set_is_event(&mut self, is_event : bool) {
300    self.is_event = is_event;
301  }
302
303  /// Run id (if applicable)
304  #[getter]
305  fn get_run_id(&self) -> u16 {
306    self.run_id
307  }
308
309  #[setter]
310  fn set_run_id(&mut self, run_id : u16) {
311    self.run_id = run_id;
312  }
313
314  /// Event id (if applicable)
315  #[getter]
316  fn get_event_id(&self) -> u32 {
317    self.event_id
318  }
319
320  #[setter]
321  fn set_event_id(&mut self, event_id : u32) {
322    self.event_id = event_id;
323  }
324
325  /// Frame id - increasing per frame, no frame id shall be missing
326  #[getter]
327  fn get_frame_id(&self) -> u32 {
328    self.frame_id
329  }
330
331  #[setter]
332  fn set_frame_id(&mut self, frame_id : u32) {
333    self.frame_id = frame_id;
334  }
335
336  /// What kind of data is stored in this frame?
337  #[getter]
338  fn get_frame_type(&self) -> CRFrameType {
339    self.frame_type
340  }
341
342  #[setter]
343  fn set_frame_type(&mut self, frame_type : CRFrameType) {
344    self.frame_type = frame_type;
345  }
346
347  /// What data sources does this frame contain? (read-only)
348  ///
349  /// Note: this returns a copy, appending to the returned 
350  /// list does not change the header. Use add_datasource instead.
351  #[getter]
352  fn get_data_sources(&self) -> Vec<GapsDataSource> {
353    self.data_sources.clone()
354  }
355
356  /// Append a data source to the data sources of this frame.
357  /// If the source is already present, a warning is issued 
358  /// and it is not added again.
359  #[pyo3(name="add_datasource")]
360  fn add_datasource_py(&mut self, source : GapsDataSource) {
361    self.add_datasource(source);
362  }
363
364  #[cfg(feature="random")]
365  #[staticmethod]
366  #[pyo3(name="from_random")]
367  fn from_random_py() -> Self {
368    Self::from_random()
369  }
370}
371
372#[cfg(feature="pybindings")]
373pythonize!(CRFrameHeader);
374
375//---------------------------------------------------
376
377#[cfg(feature="random")]
378impl FromRandom for CRFrameHeader {
379
380  fn from_random() -> Self {
381    let mut h      = Self::new();
382    let mut rng    = rand::rng();
383    h.version      = rng.random::<u8>();
384    h.is_event     = rng.random::<bool>();
385    h.run_id       = rng.random::<u16>();
386    h.event_id     = rng.random::<u32>();
387    h.frame_id     = rng.random::<u32>();
388    h.frame_type   = CRFrameType::from_random();
389    // a random subset of the data sources, without duplicates
390    for source in GapsDataSource::iter() {
391      if rng.random::<bool>() {
392        h.add_datasource(source);
393      }
394    }
395    h
396  }
397}
398
399//---------------------------------------------------
400
401#[cfg(test)]
402mod tests {
403  use super::*;
404  
405  #[test]
406  #[cfg(feature="random")]
407  fn serialize_deserialize_crframeheader() {
408    for _ in 0..100 {
409      let h       = CRFrameHeader::from_random();
410      let stream  = h.to_bytestream();
411      assert_eq!(stream.len(), 18 + h.data_sources.len());
412      let mut pos = 0;
413      let test    = CRFrameHeader::from_bytestream(&stream, &mut pos).unwrap();
414      assert_eq!(h, test);
415      assert_eq!(pos, stream.len());
416    }
417  }
418  
419  #[test]
420  fn crframeheader_add_datasource_no_duplicates() {
421    let mut h = CRFrameHeader::new();
422    h.add_datasource(GapsDataSource::TOFCPU);
423    h.add_datasource(GapsDataSource::GCU);
424    h.add_datasource(GapsDataSource::TOFCPU);
425    assert_eq!(h.data_sources, vec![GapsDataSource::TOFCPU, GapsDataSource::GCU]);
426  }
427  
428  #[test]
429  #[cfg(feature="random")]
430  fn pack_crframeheader() {
431    for _ in 0..100 {
432      let h    = CRFrameHeader::from_random();
433      let test : CRFrameHeader = h.pack().extract().unwrap();
434      assert_eq!(h, test);
435    }
436  }
437  
438  #[test]
439  #[cfg(feature="random")]
440  fn crframeheader_stream_too_short() {
441    let h      = CRFrameHeader::from_random();
442    let stream = h.to_bytestream();
443    for k in 0..stream.len() {
444      let short = stream[0..k].to_vec();
445      assert!(CRFrameHeader::from_bytestream(&short, &mut 0).is_err());
446    }
447  }
448
449  fn header_for(evid : u32) -> CRFrameHeader {
450    let mut h  = CRFrameHeader::new();
451    h.event_id = evid;
452    h
453  }
454
455}