Skip to main content

gondola_core/io/caraspace/
reader.rs

1//! Caraspace provides a system to read files 
2//! for the GAPS experiment comprising different sources, specifically 
3//! files from the TOF system written to disk as well as telemetry file
4//!
5//! While written for the GAPS experiment, the caraspace library is 
6//! designed in a form that it should be easily adaptable for other 
7//! purposes.
8//!
9//! This file contains the source for CRReader, a device to read a number
10//! of "caraspace" files from a given source.
11//
12// This file is part of gaps-online-software and published 
13// under the GPLv3 license
14
15use crate::prelude::*;
16
17/// Read binaries written through the caraspace i/o system
18///
19/// The file needs to contain subsequent CRFrames.
20#[derive(Debug)] // deliberatly don't have a default() method, reader should fail in that case
21#[cfg_attr(feature="pybindings", pyclass)]
22pub struct CRReader {
23  /// Read from this file
24  pub filenames        : Vec<String>,
25  /// The position of the current worked on file 
26  /// in the filenames vector
27  pub file_idx       : usize,
28  /// A simple BufReader for reading generic binary
29  /// files
30  file_reader          : BufReader<File>,
31  /// Current (byte) position in the current file
32  /// This gets reset when we switch to a new file
33  cursor               : usize,
34  /// Number of read packets
35  n_packs_read         : usize,
36  /// Number of skipped packets
37  n_packs_skipped      : usize,
38  /// Number of deserialization errors occured
39  /// since the beginning of the file
40  pub n_errors         : usize,
41  /// Skip the first n packets
42  pub skip_ahead       : usize,
43  /// Stop reading after n packets
44  pub stop_after       : usize,
45  /// Geometry of each TOF paddle
46  /// e.g. paddles 
47  pub tof_paddles      : Arc<HashMap<u8,TofPaddle>>,
48  /// Geometry of each tracker strip
49  pub trk_strips       : Arc<HashMap<u32, TrackerStrip>>,
50  /// Mask tracker strips 
51  pub trk_masks        : Arc<HashMap<u32, TrackerStripMask>>,
52  /// Tracker pedestal values
53  pub trk_ped          : Arc<HashMap<u32, TrackerStripPedestal>>,
54  /// Transfer functions for tracker (adc -> energy)
55  pub trk_tf           : Arc<HashMap<u32, TrackerStripTransferFunction>>,
56  /// Common noise data for tracker
57  pub trk_cmn          : Arc<HashMap<u32, TrackerStripCmnNoise>>, 
58  /// did paddle loading work
59  pub db_loaded        : bool,
60  /// TRK calibration - convert to energy
61  pub do_trk_calib     : bool,
62  /// TRK subtract CMN 
63  pub do_trk_cmn_noise : bool,
64  /// The summaries from the footers of the files, in the 
65  /// same order as filenames (None for files without footer)
66  pub summaries        : Vec<Option<CRFileSummary>>,
67  /// Where the footer starts in each file. Reading of a 
68  /// file stops there, so the footer is not returned as a frame
69  footer_starts        : Vec<Option<u64>>,
70}
71
72
73impl CRReader {
74
75  /// Create a new CRReader
76  ///
77  /// # Arguments:
78  ///   * filename_or_directory : Can be either the name of a single file, or a directory with 
79  ///                             caraspace files in it.
80  ///   
81  pub fn new(filename_or_directory : String) -> Result<Self, io::Error> {
82    #[cfg(feature="database")]
83    let mut paddles = HashMap::<u8, TofPaddle>::new();
84    #[cfg(not(feature="database"))]
85    let paddles = HashMap::<u8, TofPaddle>::new();
86    #[cfg(feature="database")]
87    let mut strips  = HashMap::<u32, TrackerStrip>::with_capacity(11520);
88    #[cfg(not(feature="database"))]
89    let strips  = HashMap::<u32, TrackerStrip>::with_capacity(11520);
90    let trk_mask    = HashMap::<u32, TrackerStripMask>::with_capacity(11520);
91    let trk_ped     = HashMap::<u32, TrackerStripPedestal>::with_capacity(11520);
92    let trk_tf      = HashMap::<u32, TrackerStripTransferFunction>::with_capacity(11520);
93    let trk_cmn     = HashMap::<u32, TrackerStripCmnNoise>::with_capacity(11520);
94    //let db_path       = env::var("DATABASE_URL").unwrap_or_else(|_| "".to_string());
95    #[cfg(feature="database")]
96    let mut db_loaded = false;
97    #[cfg(not(feature="database"))]
98    let db_loaded = false;
99    #[cfg(feature="database")]
100    match TofPaddle::all_as_dict() {
101      Err(err) => {
102        error!("Unable to retrieve paddle information from DB! {err}");
103      }
104      Ok(pdls) => {
105        db_loaded = true;
106        paddles   = pdls;         
107      }
108    }
109    #[cfg(feature="database")]
110    match TrackerStrip::all_as_dict() {
111      Err(err) => {
112        error!("Unable to retrieve tracker strip information from DB! {err}");
113        // if strips and paddles do not work, something is utterly fisy
114        db_loaded = false;
115      }
116      Ok(strips_) => {
117        strips   = strips_;         
118      }
119    }
120    // check the input argument and get the filelist
121    let infiles   = list_path_contents_sorted(&filename_or_directory, None)?;
122    if infiles.len() == 0 {
123      error!("Unable to read files from {filename_or_directory}. Is this a valid path?");
124      return Err(io::Error::new(io::ErrorKind::NotFound, "Unable to find given path!"))
125    }
126    // read the footers first, before anything else
127    let (summaries, footer_starts) = Self::read_summaries(&infiles)?;
128    let firstfile = infiles[0].clone(); 
129    let file = OpenOptions::new().create(false).append(false).read(true).open(&firstfile).expect("Unable to open file {filename}");
130    let packet_reader = Self { 
131      filenames        : infiles,
132      file_idx         : 0,
133      //file_reader      : BufReader::new(file),
134      // we exploit the fact here that a file is typically ~500Mb
135      // (tof file only is 420MB)
136      file_reader      : BufReader::with_capacity(500*1024*1024,file),
137      cursor           : 0,
138      n_packs_read     : 0,
139      n_errors         : 0,
140      skip_ahead       : 0,
141      stop_after       : 0,
142      n_packs_skipped  : 0,
143      tof_paddles      : Arc::new(paddles),
144      trk_strips       : Arc::new(strips),
145      trk_masks        : Arc::new(trk_mask),
146      trk_ped          : Arc::new(trk_ped),
147      trk_tf           : Arc::new(trk_tf),
148      trk_cmn          : Arc::new(trk_cmn),
149      db_loaded        : db_loaded,
150      do_trk_calib     : false,
151      do_trk_cmn_noise : false,
152      summaries        : summaries,
153      footer_starts    : footer_starts,
154    };
155    Ok(packet_reader)
156  } 
157
158  /// Read the summary from the footer of a file 
159  ///
160  /// # Returns:
161  ///   * Ok(None)                       : the file does not have a footer
162  ///   * Ok(Some((summary, footer_pos))) : the summary and the position 
163  ///                                       where the footer starts
164  ///   * Err                            : the file has a footer, but it 
165  ///                                       is broken
166  pub fn read_summary(filename : &str) -> Result<Option<(CRFileSummary, u64)>, io::Error> {
167    let broken = |reason : String| {
168      let msg = format!("Broken footer in {}: {}", filename, reason);
169      error!("{}", msg);
170      io::Error::new(io::ErrorKind::InvalidData, msg)
171    };
172    let mut file = File::open(filename)?;
173    let file_len = file.metadata()?.len();
174    if file_len < CRFileSummary::TRAILER_SIZE as u64 {
175      return Ok(None);
176    }
177    let mut trailer = vec![0u8; CRFileSummary::TRAILER_SIZE];
178    file.seek(SeekFrom::End(-(CRFileSummary::TRAILER_SIZE as i64)))?;
179    file.read_exact(&mut trailer)?;
180    if trailer[0..4] != CRFILESUMMARY_MAGIC {
181      // no footer, e.g. an older file
182      return Ok(None);
183    }
184    // from here on, the file claims to have a footer
185    let footer_len = match CRFileSummary::footer_len_from_trailer(&trailer) {
186      None      => return Err(broken(String::from("found the magic bytes, but the trailer is invalid"))),
187      Some(len) => len
188    };
189    if footer_len > file_len {
190      return Err(broken(format!("footer size {} is larger than the file ({} bytes)", footer_len, file_len)));
191    }
192    let footer_pos = file_len - footer_len;
193    let mut footer = vec![0u8; footer_len as usize];
194    file.seek(SeekFrom::Start(footer_pos))?;
195    file.read_exact(&mut footer)?;
196    let mut pos = 0usize;
197    let frame = match CRFrame::from_bytestream(&footer, &mut pos) {
198      Err(err) => return Err(broken(format!("no valid frame at byte {}: {}", footer_pos, err))),
199      Ok(f)    => f
200    };
201    if pos != footer.len() {
202      return Err(broken(format!("the footer frame has {} bytes, expected {}", pos, footer.len())));
203    }
204    let summary = match frame.get::<CRFileSummary>(CRFILESUMMARY_NAME) {
205      Err(err) => return Err(broken(format!("no {} in the footer frame: {}", CRFILESUMMARY_NAME, err))),
206      Ok(s)    => s
207    };
208    if summary.footer_len != footer_len {
209      return Err(broken(format!("footer size in summary ({}) and trailer ({}) differ", summary.footer_len, footer_len)));
210    }
211    Ok(Some((summary, footer_pos)))
212  }
213
214  /// Read the summaries of all files 
215  fn read_summaries(filenames : &Vec<String>) 
216    -> Result<(Vec<Option<CRFileSummary>>, Vec<Option<u64>>), io::Error> {
217    let mut summaries     = Vec::<Option<CRFileSummary>>::with_capacity(filenames.len());
218    let mut footer_starts = Vec::<Option<u64>>::with_capacity(filenames.len());
219    for fname in filenames {
220      match Self::read_summary(fname)? {
221        None => {
222          summaries.push(None);
223          footer_starts.push(None);
224        }
225        Some((summary, footer_pos)) => {
226          summaries.push(Some(summary));
227          footer_starts.push(Some(footer_pos));
228        }
229      }
230    }
231    Ok((summaries, footer_starts))
232  }
233
234  /// Has the reader reached the footer of the current file?
235  fn at_footer(&self) -> bool {
236    match self.footer_starts.get(self.file_idx) {
237      Some(Some(footer_pos)) => self.cursor as u64 >= *footer_pos,
238      _                      => false
239    }
240  }
241
242  /// The summary of the file which is currently read
243  pub fn get_current_summary(&self) -> Option<CRFileSummary> {
244    match self.summaries.get(self.file_idx) {
245      Some(Some(summary)) => Some(summary.clone()),
246      _                   => None
247    }
248  }
249    
250  #[cfg(feature="database")]
251  pub fn set_tracker_calibrations_from_fnames(&mut self,
252                                              mask        : Option<String>,
253                                              pedestal    : Option<String>,
254                                              transfer_fn : Option<String>,
255                                              cmn_noise   : Option<String>) {
256    // Tracker calibration parameters
257    if let Some(maskname) = mask {
258      match TrackerStripMask::as_dict_by_name(&maskname) {
259        Err(err) => {
260          error!("Unable to retrieve Trk strip mask information from DB! {err}");
261          // if strips and paddles do not work, something is utterly fisy
262          self.db_loaded = false;
263        }
264        Ok(strips_) => {
265          self.trk_masks = Arc::new(strips_);
266        }
267      }
268    }
269    if let Some(pedname) = pedestal {
270      match TrackerStripPedestal::as_dict_by_name(&pedname) {
271        Err(err) => {
272          error!("Unable to retrieve TRK pedestal information from DB! {err}");
273          // if strips and paddles do not work, something is utterly fisy
274          self.db_loaded = false;
275        }
276        Ok(strips_) => {
277          self.trk_ped = Arc::new(strips_);
278        }
279      }
280    }
281    if let Some(trafoname) = transfer_fn { 
282      match TrackerStripTransferFunction::as_dict_by_name(&trafoname) {
283        Err(err) => {
284          error!("Unable to retrieve TRK Transfer fn information from DB! {err}");
285          // if strips and paddles do not work, something is utterly fisy
286          self.db_loaded = false;
287        }
288        Ok(trafo_fns_) => {
289          self.trk_tf = Arc::new(trafo_fns_);
290          self.do_trk_calib = true;
291        }
292      }
293    }
294    if let Some(cmnname) = cmn_noise { 
295      match TrackerStripCmnNoise::as_dict_by_name(&cmnname) {
296        Err(err) => {
297          error!("Unable to retrieve TRK common noise from DB! {err}");
298          // if strips and paddles do not work, something is utterly fisy
299          self.db_loaded = false;
300        }
301        Ok(cmn_) => {
302          self.trk_cmn = Arc::new(cmn_);
303          self.do_trk_cmn_noise = true;
304        }
305      }
306    }
307  }
308
309  //  
310  /// This is the file the current cursor is located 
311  /// in and frames are currently read out from 
312  pub fn get_current_filename(&self) -> Option<String> {
313    // should only happen when it is empty
314    if self.filenames.len() <= self.file_idx {
315      return None;
316    }
317    Some(self.filenames[self.file_idx].clone())
318  }
319//  
320//  
321//  ///// Use the associated database to enrich paddle information
322//  //fn add_paddleinfo(&self, event : &mut TofEventSummary) {
323//  //  event.set_paddles(&self.paddles);
324//  //}
325//  
326//
327  /// Preview the number of frames in this reader
328  pub fn count_frames(&mut self) -> usize {
329    let _ = self.rewind();
330    let mut nframes = 0usize;
331    let mut buffer  = [0];
332    let bar_template : &str = "[{elapsed_precise}] {prefix} {msg} {spinner} {bar:60.blue/grey} {pos:>7}/{len:7}";
333    let bar_style  = ProgressStyle::with_template(bar_template).expect("Unable to set progressbar style!");
334    let bar = ProgressBar::new(self.filenames.len() as u64);
335    bar.set_position(0);
336    bar.set_message (String::from("Counting frames.."));
337    bar.set_prefix  ("\u{2728}");
338    bar.set_style   (bar_style);
339    bar.set_position(self.file_idx as u64);
340    loop {
341      if self.at_footer() {
342        // the footer is not a frame, go to the next file
343        match self.prime_next_file() {
344          None    => break,
345          Some(_) => {
346            bar.set_position(self.file_idx as u64);
347            continue;
348          }
349        }
350      }
351      match self.file_reader.read_exact(&mut buffer) {
352        Err(err) => {
353          debug!("Unable to read from file! {err}");
354          match self.prime_next_file() {
355            None    => break,
356            Some(_) => {
357              bar.set_position(self.file_idx as u64);
358              continue;
359            }
360          };
361        }
362        Ok(_) => {
363          self.cursor += 1;
364        }
365      }
366      if buffer[0] != 0xAA {
367        continue;
368      } else {
369        match self.file_reader.read_exact(&mut buffer) {
370          Err(err) => {
371            debug!("Unable to read from file! {err}");
372            match self.prime_next_file() {
373              None    => break,
374              Some(_) => {
375                bar.set_position(self.file_idx as u64);
376                continue;
377              }
378            };
379          }
380          Ok(_) => {
381            self.cursor += 1;
382          }
383        }
384        // check if the second byte of the header
385        if buffer[0] != 0xAA { 
386          continue;
387        } else {
388          // read the the size of the packet
389          let mut buffer_psize = [0,0,0,0,0,0,0,0];
390          match self.file_reader.read_exact(&mut buffer_psize) {
391            Err(_err) => {
392              match self.prime_next_file() {
393                None    => break,
394                Some(_) => {
395                  bar.set_position(self.file_idx as u64);
396                  continue;
397                }
398              }
399            }
400            Ok(_) => {
401              self.cursor += 8;
402            }
403          }
404          let vec_data = buffer_psize.to_vec();
405          let size     = parse_u64(&vec_data, &mut 0);
406          let mut temp_buffer = vec![0; size as usize];
407          match self.file_reader.read_exact(&mut temp_buffer) { 
408          //match self.file_reader.seek(SeekFrom::Current(size as i64)) {
409          //match self.file_reader.seek_relative(size as i64) {
410            Err(err) => {
411              error!("Unable to read {size} bytes from {}! {err}", self.get_current_filename().unwrap());
412              match self.prime_next_file() {
413                None    => break,
414                Some(_) => {
415                  bar.set_position(self.file_idx as u64);
416                  continue;
417                }
418              }
419            }
420            Ok(_) => {
421              self.cursor += size as usize;
422              nframes += 1;
423            }
424          }
425        }
426      } // if no 0xAA found
427    } // end loop
428    bar.finish_with_message("Done!");
429    let _ = self.rewind();
430    nframes
431  } // end fn
432
433  /// Return the next frame for the current files
434  ///
435  /// Will return none if the file has been exhausted.
436  /// Use ::rewind to start reading from the beginning
437  /// again.
438  pub fn read_next_item(&mut self) -> Option<CRFrame> {
439    // filter::Unknown corresponds to allowing any
440  
441    let mut buffer = [0];
442    loop {
443      if self.at_footer() {
444        // the footer is not a frame, go to the next file
445        self.prime_next_file()?;
446        return self.read_next_item();
447      }
448      match self.file_reader.read_exact(&mut buffer) {
449        Err(err) => {
450          debug!("Unable to read from file! {err}");
451          // this is ok in case we are out of files
452          self.prime_next_file()?;
453          return self.read_next_item();
454        }
455        Ok(_) => {
456          self.cursor += 1;
457        }
458      }
459      if buffer[0] != 0xAA {
460        continue;
461      } else {
462        match self.file_reader.read_exact(&mut buffer) {
463          Err(err) => {
464            debug!("Unable to read from file! {err}");
465            self.prime_next_file()?;
466            return self.read_next_item();
467          }
468          Ok(_) => {
469            self.cursor += 1;
470          }
471        }
472  
473        if buffer[0] != 0xAA { 
474          continue;
475        } else {
476          // read the the size of the packet
477          let mut buffer_psize = [0,0,0,0,0,0,0,0];
478          match self.file_reader.read_exact(&mut buffer_psize) {
479            Err(err) => {
480              debug!("Unable to read from file! {err}");
481              self.prime_next_file()?;
482              return self.read_next_item();
483            }
484            Ok(_) => {
485              self.cursor += 8;
486            }
487          }
488          
489          let vec_data = buffer_psize.to_vec();
490          //println!("vec_data {:?}", vec_data);
491          let size     = parse_u64(&vec_data, &mut 0);
492          //println!("Will read {size} bytes for payload!");
493          // now at this point, we want the packet!
494          // except we skip ahead or stop earlier
495          if self.skip_ahead > 0 && self.n_packs_skipped < self.skip_ahead {
496            // we don't want it
497            match self.file_reader.seek(SeekFrom::Current(size as i64)) {
498              Err(err) => {
499                debug!("Unable to read more data! {err}");
500                self.prime_next_file()?;
501                return self.read_next_item();
502              }
503              Ok(_) => {
504                self.n_packs_skipped += 1;
505                self.cursor += size as usize;
506              }
507            }
508            continue; // this is just not the packet we want
509          }
510          if self.stop_after > 0 && self.n_packs_read >= self.stop_after {
511            // we don't want it
512            match self.file_reader.seek(SeekFrom::Current(size as i64)) {
513              Err(err) => {
514                debug!("Unable to read more data! {err}");
515                self.prime_next_file()?;
516                return self.read_next_item();
517              }
518              Ok(_) => {
519                self.cursor += size as usize;
520              }
521            }
522            continue; // this is just not the packet we want
523          }
524  
525          let mut frame = CRFrame::new();
526          let mut payload = vec![0u8;size as usize];
527  
528          match self.file_reader.read_exact(&mut payload) {
529            Err(err) => {
530              debug!("Unable to read from file! {err}");
531              self.prime_next_file()?;
532              return self.read_next_item();
533            }
534            Ok(_) => {
535              self.cursor += size as usize;
536            }
537          }
538          let mut in_frame_pos = 0usize;
539          frame.index = CRFrame::parse_index(&payload, &mut in_frame_pos);
540          frame.bytestorage = payload[in_frame_pos..].to_vec();
541  
542          //tp.payload = payload;
543          // we don't filter, so we like this packet
544          let mut tail = vec![0u8; 2];
545          match self.file_reader.read_exact(&mut tail) {
546            Err(err) => {
547              debug!("Unable to read from file! {err}");
548              self.prime_next_file()?;
549              return self.read_next_item();
550            }
551            Ok(_) => {
552              self.cursor += 2;
553            }
554          }
555          let tail = parse_u16(&tail,&mut 0);
556          if tail != CRFrame::TAIL {
557            debug!("CRFrame TAIL signature wrong!");
558            return None;
559          }
560          self.n_packs_read += 1;
561          // hand the database poitners over to the frame 
562          frame.tof_paddles  = Arc::clone(&self.tof_paddles);
563          frame.trk_strips   = Arc::clone(&self.trk_strips);
564          frame.trk_masks    = Arc::clone(&self.trk_masks);
565          frame.trk_ped      = Arc::clone(&self.trk_ped);
566          frame.trk_tf       = Arc::clone(&self.trk_tf);
567          frame.trk_cmn      = Arc::clone(&self.trk_cmn);
568          frame.do_trk_calib = self.do_trk_calib;
569          frame.subtract_trk_cmn = self.do_trk_cmn_noise;
570          return Some(frame);
571        }
572      } // if no 0xAA found
573    } // end loop
574  } // end fn
575}
576
577impl fmt::Display for CRReader {
578  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579    let mut range_repr = String::from("");
580    if self.skip_ahead > 0 {
581      range_repr += &(format!("({}", self.skip_ahead));
582    } else {
583      range_repr += "(";
584    }
585    if self.stop_after > 0 {
586      range_repr += &(format!("..{})", self.stop_after));
587    } else {
588      range_repr += "..)";
589    }
590    let mut repr = String::from("<CRReader :");
591    repr += "\n -- files:";
592    for k in &self.filenames {
593      repr += &format!("\n     -- {k}");
594    }
595    if self.filenames.len() > 0 {
596      repr += &format!("\n  current : {}", self.get_current_filename().unwrap());
597    }
598    repr += &String::from("\n -- -- -- -- -- -- -- -- -- -- -- --");
599    repr += &format!("\n  read {} packets, {} errors, range {}>", self.n_packs_read, self.n_errors, range_repr);
600    write!(f, "{}", repr)
601  }
602}
603
604reader!(CRReader,CRFrame);
605
606//--------------------------------------
607
608#[cfg(feature="pybindings")]
609#[pymethods]
610impl CRReader {
611
612  #[new]
613  fn new_py(filenames_or_directory : &Bound<'_,PyAny>) -> PyResult<Self> {
614    let mut string_value = String::from("foo");
615    let mut fnames       = Vec::<String>::new();
616    if let Ok(s) = filenames_or_directory.extract::<String>() {
617       string_value = s;
618    } //else if let Ok(p) = filename_or_directory.extract::<&Path>() {
619    if let Ok(fspath_method) = filenames_or_directory.getattr("__fspath__") {
620      if let Ok(fspath_result) = fspath_method.call0() {
621        if let Ok(py_string) = fspath_result.extract::<String>() {
622          string_value = py_string;
623        }
624      }
625    }
626    if let Ok(list) = filenames_or_directory.extract::<Vec<String>>() {
627      for k in list {
628        fnames.push(k);
629      } 
630    }
631    if fnames.len() > 0 {
632      string_value = fnames[0].clone();
633    }
634    
635
636    match Self::new(string_value) {
637      Err(err) => {
638        return Err(PyValueError::new_err(err.to_string()));
639      }
640      Ok(mut reader) => {
641        if fnames.len() > 0 {
642          // the summaries have to be read for all given files
643          match Self::read_summaries(&fnames) {
644            Err(err) => return Err(PyValueError::new_err(err.to_string())),
645            Ok((summaries, footer_starts)) => {
646              reader.summaries     = summaries;
647              reader.footer_starts = footer_starts;
648            }
649          }
650          reader.filenames = fnames;
651        }
652        return Ok(reader);
653      }
654    }
655  }
656
657  /// The summaries from the footers of all files, in the 
658  /// same order as the files (None for files without footer)
659  #[getter]
660  #[pyo3(name="summaries")]
661  fn get_summaries_py(&self) -> Vec<Option<CRFileSummary>> {
662    self.summaries.clone()
663  }
664
665  /// The summary of the file which is currently read 
666  /// (None if it does not have a footer)
667  #[getter]
668  #[pyo3(name="summary")]
669  fn get_current_summary_py(&self) -> Option<CRFileSummary> {
670    self.get_current_summary()
671  }
672
673  #[pyo3(name="set_tracker_calibrations_from_fnames")]
674  #[pyo3(signature = (mask = None, pedestal = None, transfer_fn = None, cmn_noise = None))]
675  fn set_tracker_calibrations_from_fnames_py(&mut self,
676                                              mask        : Option<String>,
677                                              pedestal    : Option<String>,
678                                              transfer_fn : Option<String>,
679                                              cmn_noise   : Option<String>) {
680    self.set_tracker_calibrations_from_fnames(mask, pedestal, transfer_fn, cmn_noise);
681  }
682
683  /// This is the filename we are currently 
684  /// extracting frames from 
685  #[getter]
686  #[pyo3(name="current_filename")]
687  fn get_current_filename_py(&self) -> Option<String> {
688    self.get_current_filename()
689  }
690
691  /// All filenames this reader is primed with 
692  #[getter] 
693  #[pyo3(name="filenames")] 
694  fn get_filenames_py(&self) -> Vec<String> {
695    self.filenames.clone()
696  }
697
698  /// Start the reader from the beginning
699  /// This is equivalent to a re-initialization
700  /// of that reader.
701  #[pyo3(name="rewind")]
702  fn rewind_py(&mut self) -> PyResult<()> {
703    match self.rewind() {
704      Err(err) => {
705        return Err(PyValueError::new_err(err.to_string()));
706      }
707      Ok(_) => Ok(())
708    }
709  }
710
711  #[pyo3(name="count_frames")]
712  fn count_frames_py(&mut self) -> usize {
713    self.count_frames()
714  }
715
716  fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
717    slf 
718  }
719  
720  fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<CRFrame> {
721    match slf.next() { 
722      Some(frame) => {
723        return Some(frame)
724      }   
725      None => {
726        return None;
727      }   
728    }   
729  }
730}
731
732#[cfg(feature="pybindings")]
733pythonize_display!(CRReader);
734
735//---------------------------------------------------
736
737#[cfg(test)]
738mod tests {
739  use super::*;
740
741  fn event_frame(evid : u32) -> CRFrame {
742    let mut frame   = CRFrame::new();
743    let mut header  = CRFrameHeader::new();
744    header.event_id = evid;
745    header.add_datasource(GapsDataSource::TOFCPU);
746    frame.put(header, CRFRAMEHEADER_NAME);
747    frame.put(TofPacket::new(), "TofPacket");
748    frame
749  }
750
751  /// A file written by CRWriter, with footer
752  fn write_with_footer(dir : &Path, subrun : u64, ts : &str, evids : std::ops::Range<u32>) -> String {
753    let mut wr = CRWriter::new(dir.to_str().unwrap().to_string(), 42, Some(subrun), Some(String::from(ts)), None);
754    for evid in evids {
755      wr.add_frame(&event_frame(evid));
756    }
757    wr.close();
758    wr.file_name.clone()
759  }
760
761  /// A file without footer (as written before there were footers)
762  fn write_without_footer(dir : &Path, subrun : u64, ts : &str, evids : std::ops::Range<u32>) -> String {
763    let fname = format!("{}/Run42_{}.{}.gaps", dir.display(), subrun, ts);
764    let mut bytes = Vec::<u8>::new();
765    for evid in evids {
766      bytes.extend_from_slice(&event_frame(evid).to_bytestream());
767    }
768    fs::write(&fname, bytes).unwrap();
769    fname
770  }
771
772  /// All event ids the reader returns
773  fn read_all(reader : &mut CRReader) -> Vec<u32> {
774    let mut evids = Vec::<u32>::new();
775    while let Some(frame) = reader.read_next_item() {
776      assert!(!frame.has(CRFILESUMMARY_NAME), "the footer must not be returned as a frame");
777      evids.push(frame.get_header().unwrap().event_id);
778    }
779    evids
780  }
781
782  #[test]
783  fn crreader_footer_is_not_a_frame() {
784    let dir    = tempfile::tempdir().unwrap();
785    let fname  = write_with_footer(dir.path(), 0, "231114_221320", 10..20);
786    let mut rd = CRReader::new(fname).unwrap();
787    // the summary is there before anything is read
788    let s = rd.summaries[0].clone().unwrap();
789    assert_eq!((s.n_frames, s.min_evid, s.max_evid), (10, 10, 19));
790    assert_eq!(rd.get_current_summary(), Some(s));
791    assert_eq!(read_all(&mut rd), (10..20).collect::<Vec<u32>>());
792    assert_eq!(rd.count_frames(), 10);
793    // and again after counting (count_frames rewinds)
794    assert_eq!(read_all(&mut rd).len(), 10);
795  }
796
797  #[test]
798  fn crreader_file_without_footer() {
799    let dir    = tempfile::tempdir().unwrap();
800    let fname  = write_without_footer(dir.path(), 0, "231114_221320", 0..5);
801    let mut rd = CRReader::new(fname).unwrap();
802    assert_eq!(rd.summaries, vec![None]);
803    assert_eq!(read_all(&mut rd), vec![0, 1, 2, 3, 4]);
804    assert_eq!(rd.count_frames(), 5);
805  }
806
807  #[test]
808  fn crreader_directory_with_and_without_footers() {
809    let dir = tempfile::tempdir().unwrap();
810    write_without_footer(dir.path(), 0, "231114_221320", 0..3);
811    write_with_footer   (dir.path(), 1, "231114_221321", 3..7);
812    write_without_footer(dir.path(), 2, "231114_221322", 7..9);
813    let mut rd = CRReader::new(dir.path().to_str().unwrap().to_string()).unwrap();
814    assert_eq!(rd.filenames.len(), 3);
815    let has_summary : Vec<bool> = rd.summaries.iter().map(|s| s.is_some()).collect();
816    assert_eq!(has_summary, vec![false, true, false]);
817    assert_eq!(rd.summaries[1].clone().unwrap().n_frames, 4);
818    assert_eq!(read_all(&mut rd), (0..9).collect::<Vec<u32>>());
819    assert_eq!(rd.count_frames(), 9);
820  }
821
822  #[test]
823  fn crreader_skip_ahead_with_footer() {
824    let dir    = tempfile::tempdir().unwrap();
825    let fname  = write_with_footer(dir.path(), 0, "231114_221320", 0..10);
826    let mut rd = CRReader::new(fname).unwrap();
827    rd.skip_ahead = 3;
828    assert_eq!(read_all(&mut rd), (3..10).collect::<Vec<u32>>());
829  }
830
831  #[test]
832  fn crreader_broken_footers() {
833    let dir   = tempfile::tempdir().unwrap();
834    let fname = write_with_footer(dir.path(), 0, "231114_221320", 0..5);
835    let good  = fs::read(&fname).unwrap();
836    let n     = good.len();
837    let footer_len = parse_u64(&good[n - 14..n - 6].to_vec(), &mut 0);
838    let set_len = |bytes : &mut Vec<u8>, len : u64| {
839      bytes[n - 14..n - 6].copy_from_slice(&len.to_le_bytes());
840    };
841    let mut cases = Vec::<(&str, Vec<u8>)>::new();
842    // footer size larger than the file
843    let mut b = good.clone();
844    set_len(&mut b, n as u64 + 1);
845    cases.push(("larger than the file", b));
846    // footer size points to the wrong position
847    let mut b = good.clone();
848    set_len(&mut b, footer_len + 1);
849    cases.push(("no valid frame", b));
850    // magic bytes, but the tails are wrong
851    let mut b = good.clone();
852    b[n - 1] = 0;
853    cases.push(("trailer is invalid", b));
854    // a valid frame, but without the summary in it
855    let mut b = good.clone();
856    let name  = CRFILESUMMARY_NAME.as_bytes();
857    let at    = (n - footer_len as usize..n - name.len()).find(|k| &b[*k..*k + name.len()] == name).unwrap();
858    b[at] = b'g';
859    cases.push(("no file_summary", b));
860    for (reason, bytes) in cases {
861      fs::write(&fname, &bytes).unwrap();
862      let err = CRReader::new(fname.clone()).unwrap_err();
863      let msg = err.to_string();
864      assert!(msg.contains("Broken footer") && msg.contains(&fname) && msg.contains(reason), "{}", msg);
865    }
866  }
867}