Skip to main content

gondola_core/
lib.rs

1//! Dataclasses provides structures to facilitate the work with data drom 
2//! the GAPS experiment. Most noticeably, there are
3//!
4//! * events       - TOF/Tracker data, TOF events on disk, MergedEvents send over telemetry
5//!
6//! * packets      - containers to serialize/deserialize the described structures so that 
7//!                  these can be stored on disk or send over the network
8//!
9//! * calibration  - TOF/Tracker related calibration routines and containers to hold results
10//! 
11//! * io           - read/write packets to/from disk or receive them over the network
12//! 
13//! * random       - random numbers for software tests
14//! 
15//! * tof          - Very specific TOF related code which does not fall under a different 
16//!                  category
17//! 
18//! * tracker      - Very specific TRK related code which does not fall under any other 
19//!                  category
20//!
21//! * geometry     - The GAPS detector geometry, read from GDML
22//!
23//! # features:
24//!
25//! * random              - allow random number generated data classes for 
26//!                         testing
27//!
28//! * database            - access a data base for advanced paddle
29//!                         mapping, readoutboard and ltb information etc.
30//!                         This will introduce a dependency on sqlite and 
31//!                         diesel
32//! * tof-control         - allows to control LTB & Powerboard from the RBs 
33//!                         over i2c. Since the i2c protocoll is not supported 
34//!                         on Mac, code with this feature enable won't build 
35//!                         on Apple systems. 
36//! * advanced-algorithms - allows to use a different algorithm for pulse extraction 
37//! * pybindings          - build the python library "gondola". Most of the entitities 
38//!                         within "gondola-core" have pybindings, e.g. events, hits.
39//! * tof-liftof          - build the code which is required to build liftof, the flight
40//!                         code utiilizing this library 
41// This file is part of gaps-online-software and published 
42// under the GPLv3 license
43
44#[macro_use] extern crate log; 
45
46pub mod prelude;
47#[cfg(feature="random")]
48pub mod random;
49pub mod constants;
50pub mod events;
51pub mod packets;
52pub mod version;
53pub mod io;
54pub mod calibration;
55pub mod errors;
56pub mod tof;
57pub mod tracker;
58pub mod monitoring;
59pub mod stats;
60pub mod physics;
61pub mod geometry;
62#[cfg(feature="pybindings")]
63pub mod python;
64#[cfg(feature="database")]
65pub mod database;
66
67// python convention
68pub const VERSION: &str = env!("CARGO_PKG_VERSION"); 
69pub const VERSION_MAJ: &str = env!("CARGO_PKG_VERSION_MAJOR");
70pub const VERSION_MIN: &str = env!("CARGO_PKG_VERSION_MINOR");
71pub const VERSION_PCH: &str = env!("CARGO_PKG_VERSION_PATCH");
72
73#[cfg(feature="pybindings")]
74use crate::errors::*;
75
76/// A simple helper macro adding an as_str function 
77/// as well as the Display method to any enum.
78///
79/// Avoids writing boilerplate
80#[macro_export]
81macro_rules! expand_and_test_enum {
82  ($name:ident, $test_name:ident) => {
83    impl fmt::Display for $name {
84      fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85        write!(f, "<{}: {}>",stringify!($name), self.as_ref())
86      }
87    }
88
89    impl From<u8> for $name {
90      fn from(value: u8) -> Self {
91        match Self::from_repr(value)  {
92          None => {
93            return Self::Unknown;
94          }
95          Some(variant) => {
96            return variant;
97          }
98        }
99      }
100    }
101
102    #[cfg(feature="random")]
103    impl FromRandom for $name {
104      fn from_random() -> Self {
105        let mut choices = Vec::<Self>::new();
106        for k in Self::iter() {
107          choices.push(k);
108        }
109        let mut rng  = rand::rng();
110        let idx = rng.random_range(0..choices.len());
111        choices[idx]
112      }
113    }
114
115    #[test]
116    fn $test_name() {
117      for _ in 0..100 {
118        let data = $name::from_random();
119        assert_eq!($name::from(data as u8), data);
120      }
121    }
122
123    #[cfg(feature="pybindings")]
124    #[pymethods]
125    impl $name {
126    
127      #[staticmethod]  
128      #[pyo3(name = "from_u8")]
129      fn from_py(byte : u8) -> Self {
130        Self::from(byte) 
131      }
132    }
133  };
134}
135
136//---------------------------------------
137// helpers to init the logging system
138//
139
140use colored::{
141    Colorize,
142    ColoredString
143};
144use chrono::Utc;
145use log::Level;
146use std::io::Write;
147
148/// Make sure that the loglevel is in color, even though not using pretty_env logger
149pub fn color_log(level : &Level) -> ColoredString {
150  match level {
151    Level::Error    => String::from(" ERROR!").red(),
152    Level::Warn     => String::from(" WARN  ").yellow(),
153    Level::Info     => String::from(" Info  ").green(),
154    Level::Debug    => String::from(" debug ").blue(),
155    Level::Trace    => String::from(" trace ").cyan(),
156  }
157}
158
159/// Set up the environmental (env) logger
160/// with our format
161///
162/// Ensure that the lines and module paths
163/// are printed in the logging output
164pub fn init_env_logger() {
165  env_logger::builder()
166    .format(|buf, record| {
167    writeln!( buf, "[{ts} - {level}][{module_path}:{line}] {args}",
168      ts    = Utc::now().format("%Y/%m/%d-%H:%M:%SUTC"), 
169      level = color_log(&record.level()),
170      module_path = record.module_path().unwrap_or("<unknown>"),
171      line  = record.line().unwrap_or(0),
172      args  = record.args()
173      )
174    }).init();
175}
176
177//-------------------------------------------------
178// Build the python library
179
180#[cfg(feature="pybindings")]
181pub use pyo3::prelude::*; 
182#[cfg(feature="pybindings")]
183pub use pyo3::wrap_pymodule; 
184#[cfg(feature="pybindings")]
185pub use pyo3::wrap_pyfunction; 
186
187#[cfg(feature="pybindings")]
188#[pymodule]
189#[pyo3(name = "tof")]
190fn tof_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
191  use crate::tof::*;
192  m.add_class::<RBPaddleID>()?;
193  m.add_class::<TofDetectorStatus>()?;
194  m.add_class::<TofCommandCode>()?;
195  m.add_class::<TofCommand>()?;
196  m.add_class::<TofOperationMode>()?;
197  m.add_class::<BuildStrategy>()?;
198  m.add_class::<PreampBiasConfig>()?;
199  m.add_class::<RBChannelMaskConfig>()?;
200  m.add_class::<TriggerConfig>()?;
201  m.add_class::<TofRunConfig>()?;
202  m.add_class::<TofCuts>()?;
203  m.add_class::<TofAnalysis>()?;
204  m.add_class::<TofAnalysisCache>()?;
205  m.add_class::<TofAnalysisPaddleCache>()?;
206  m.add_class::<AnalysisEngineSettings>()?;
207  m.add_class::<TofPulseTemplate>()?;
208  #[cfg(feature="tof-liftof")]
209  m.add_class::<PyMasterTrigger>()?;
210  m.add_function(wrap_pyfunction!(waveform_analysis, m)?)?;
211  m.add_function(wrap_pyfunction!(to_board_id_string, m)?)?;
212  // the commands
213  m.add_function(wrap_pyfunction!(start_run, m)?)?;
214  m.add_function(wrap_pyfunction!(stop_run, m)?)?;
215  m.add_function(wrap_pyfunction!(restart_liftofrb, m)?)?;
216  m.add_function(wrap_pyfunction!(enable_verification_run, m)?)?;
217  m.add_function(wrap_pyfunction!(shutdown_all_rbs, m)?)?;
218  m.add_function(wrap_pyfunction!(shutdown_rat, m)?)?;
219  m.add_function(wrap_pyfunction!(shutdown_ratpair, m)?)?;
220  m.add_function(wrap_pyfunction!(shutdown_rb, m)?)?;
221  m.add_function(wrap_pyfunction!(shutdown_tofcpu, m)?)?;
222  m.add_function(wrap_pyfunction!(run_action_alfa, m)?)?;
223  m.add_function(wrap_pyfunction!(run_action_bravo, m)?)?;
224  m.add_function(wrap_pyfunction!(run_action_charlie, m)?)?;
225  m.add_function(wrap_pyfunction!(run_action_whiskey, m)?)?;
226  m.add_function(wrap_pyfunction!(run_action_tango, m)?)?;
227  m.add_function(wrap_pyfunction!(run_action_foxtrott, m)?)?;
228  m.add_function(wrap_pyfunction!(request_liftof_settings, m)?)?;
229  m.add_function(wrap_pyfunction!(restore_default_config, m)?)?;
230  m.add_function(wrap_pyfunction!(apply_settings_diff, m)?)?;
231  Ok(())
232}
233
234#[cfg(feature="pybindings")]
235#[pymodule]
236#[pyo3(name = "tracker")]
237fn tracker_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
238  use crate::tracker::*;
239  //m.add_function(wrap_pyfunction!(mt_event_get_timestamp_abs48,m)?)?;
240  m.add_function(wrap_pyfunction!(strip_lines, m)?)?;
241  m.add_class::<TrackerOnlineCalibration>()?;
242  Ok(())
243}
244
245#[cfg(feature="pybindings")]
246#[pymodule]
247#[pyo3(name = "calibration")]
248fn calibration_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
249  use crate::calibration::*;
250  m.add_class::<RBCalibrations>()?;
251  m.add_class::<TrackerOfflineCalibration>()?;
252  Ok(())
253}
254
255#[cfg(feature="pybindings")]
256#[pymodule]
257#[pyo3(name = "events")]
258fn events_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
259  use crate::events::*;
260  m.add_class::<McHit>()?;
261  m.add_class::<McEvent>()?;
262  m.add_class::<McTrack>()?;
263  m.add_class::<McTree>()?;
264  m.add_class::<TofHit>()?;
265  m.add_class::<TrackerHit>()?;
266  m.add_class::<RBEventHeader>()?;
267  m.add_class::<RBEvent>()?;
268  m.add_class::<RBWaveform>()?;
269  m.add_class::<EventStatus>()?;
270  m.add_class::<DataType>()?;
271  m.add_class::<TofEvent>()?;
272  m.add_class::<TrackerDAQEvent>()?;
273  m.add_class::<TrackerDAQEventPacket>()?;
274  m.add_class::<TelemetryEvent>()?;
275  m.add_function(wrap_pyfunction!(strip_id, m)?)?;
276  m.add_class::<HitQuality>()?;
277  m.add_class::<EventQuality>()?;
278  m.add_class::<TriggerType>()?;
279  m.add_class::<LTBThreshold>()?;
280  m.add_function(wrap_pyfunction!(mt_event_get_timestamp_abs48,m)?)?;
281  Ok(())
282}
283
284#[cfg(feature="pybindings")]
285#[pymodule]
286#[pyo3(name = "packets")]
287fn packets_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
288  use crate::packets::*;
289  m.add_class::<TofPacketType>()?;
290  m.add_class::<TofPacket>()?;
291  m.add_class::<TelemetryPacketType>()?;
292  m.add_class::<TelemetryPacket>()?;
293  m.add_class::<TelemetryPacketHeader>()?;
294  m.add_class::<TrackerHeader>()?;
295  // FIXME - this is monitoring data, we should 
296  // move this over to the monitoring part of the 
297  // code and they should become MoniData/Series 
298  m.add_class::<PduChannel>()?;
299  m.add_class::<Pac1934>()?;
300  m.add_class::<PduHKPacket>()?;
301  m.add_function(wrap_pyfunction!(make_systime,m)?)?;
302  m.add_class::<TrackerEventIDEchoPacket>()?;
303  m.add_class::<TrackerTempLeakPacket>()?;
304  m.add_class::<TrackerDAQTempPacket>()?;
305  m.add_class::<TrackerDAQHSKPacket>()?;
306  Ok(())
307}
308
309#[cfg(feature="pybindings")]
310#[pymodule]
311#[pyo3(name = "io")]
312fn io_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
313  use crate::io::*;
314  use crate::io::caraspace::*;
315  #[cfg(feature="root")]
316  use crate::io::root_reader::read_example;
317  use crate::io::caraspace::frame::get_all_telemetry_event_names;
318  #[cfg(feature="root")]
319  m.add_function(wrap_pyfunction!(read_example, m)?)?;
320  m.add_function(wrap_pyfunction!(get_all_telemetry_event_names, m)?)?;
321  m.add_function(wrap_pyfunction!(get_runfilename, m)?)?;
322  m.add_function(wrap_pyfunction!(get_califilename, m)?)?;
323  m.add_function(wrap_pyfunction!(list_path_contents_sorted_py, m)?)?;
324  m.add_function(wrap_pyfunction!(get_utc_timestamp, m)?)?;
325  m.add_function(wrap_pyfunction!(get_utc_date, m)?)?;
326  m.add_function(wrap_pyfunction!(get_rundata_from_file, m)?)?;
327  m.add_function(wrap_pyfunction!(get_datetime, m)?)?;
328  m.add_function(wrap_pyfunction!(get_utc_timestamp_from_unix, m)?)?;
329  m.add_function(wrap_pyfunction!(get_unix_timestamp, m)?)?;
330  m.add_function(wrap_pyfunction!(get_unix_timestamp_from_telemetry, m)?)?;
331  // these are the config file manipulators
332  m.add_function(wrap_pyfunction!(apply_diff_to_file_py, m)?)?;
333  m.add_function(wrap_pyfunction!(compress_toml_py, m)?)?;
334  m.add_function(wrap_pyfunction!(decompress_toml_py, m)?)?;
335  m.add_function(wrap_pyfunction!(create_compressed_diff_py, m)?)?;
336
337  m.add_class::<CRFrameObject>()?;
338  m.add_class::<CRFrameObjectType>()?;
339  m.add_class::<CRFrameHeader>()?;
340  m.add_class::<CRFileSummary>()?;
341  m.add_class::<CRFrameType>()?;
342  m.add_class::<GapsDataSource>()?;
343  m.add_class::<CRFrame>()?;
344  m.add_class::<DataSourceKind>()?;
345  m.add_class::<CRReader>()?;
346  m.add_class::<CRWriter>()?;
347  m.add_class::<TofPacketReader>()?;
348  m.add_class::<TofPacketWriter>()?;
349  m.add_class::<TelemetryPacketReader>()?;
350  m.add_class::<TelemetryPacketWriter>()?;
351  //m.add_class::<PyDataSource>()?;
352  Ok(())
353}
354
355#[cfg(feature="pybindings")]
356#[pymodule]
357#[pyo3(name = "monitoring")]
358fn monitoring_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
359  use crate::monitoring::*;
360  m.add_class::<EventBuilderHB>()?;
361  m.add_class::<EventBuilderHBSeries>()?;
362  m.add_class::<DataSinkHB>()?;
363  m.add_class::<DataSinkHBSeries>()?;
364  m.add_class::<MasterTriggerHB>()?;
365  m.add_class::<MasterTriggerHBSeries>()?;
366  m.add_class::<PAMoniData>()?;
367  m.add_class::<PAMoniDataSeries>()?;
368  m.add_class::<PBMoniData>()?;
369  m.add_class::<PBMoniDataSeries>()?;
370  m.add_class::<MtbMoniData>()?;
371  m.add_class::<MtbMoniDataSeries>()?;
372  m.add_class::<LTBMoniData>()?;
373  m.add_class::<LTBMoniDataSeries>()?;
374  m.add_class::<RBMoniData>()?;
375  m.add_class::<RBMoniDataSeries>()?;
376  m.add_class::<CPUMoniData>()?;
377  m.add_class::<CPUMoniDataSeries>()?;
378  m.add_class::<SipPresMoniData>()?;
379  m.add_class::<SipPresMoniDataSeries>()?;
380  m.add_class::<SipPosMoniData>()?;
381  m.add_class::<SipPosMoniDataSeries>()?;
382  m.add_class::<SipTimeMoniData>()?;
383  m.add_class::<SipTimeMoniDataSeries>()?;
384  m.add_class::<TrackerGpsMoniData>()?;
385  m.add_class::<TrackerGpsMoniDataSeries>()?;
386  m.add_class::<GcuEvBldStatsMoniData>()?;
387  m.add_class::<GcuEvBldStatsMoniDataSeries>()?;
388  m.add_class::<CoolingMoniData>()?;
389  m.add_class::<CoolingMoniDataSeries>()?;
390  m.add_class::<RunStatistics>()?;
391  m.add_class::<WastieMoniData>()?;
392  m.add_class::<WastieMoniDataSeries>()?;
393  Ok(())
394}
395
396#[cfg(feature="pybindings")]
397#[pymodule]
398#[pyo3(name = "stats")]
399fn stats_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
400  //use crate::io::*;
401  use crate::stats::gamma_pdf_py;
402  use crate::stats::mean_py;
403  m.add_function(wrap_pyfunction!(gamma_pdf_py, m)?)?;
404  m.add_function(wrap_pyfunction!(mean_py, m)?)?;
405  Ok(())
406}
407
408#[cfg(feature="pybindings")]
409#[pymodule]
410#[pyo3(name = "algo")]
411fn algo_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
412  //use crate::io::*;
413  use crate::tof::algorithms::*;
414  m.add_function(wrap_pyfunction!(get_max_value_idx_py, m)?)?;
415  m.add_function(wrap_pyfunction!(interpolate_time_py, m)?)?;
416  m.add_function(wrap_pyfunction!(fit_sine_simple_py, m)?)?;
417  Ok(())
418}
419
420#[cfg(feature="pybindings")]
421#[pymodule]
422#[pyo3(name = "reconstruction")]
423fn reconstruction_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
424  use crate::physics::reconstruction::*;
425  m.add_class::<FitStatus>()?;
426  m.add_class::<LineFit>()?;
427  m.add_class::<LineFitCost>()?;
428  m.add_class::<LineFitCleaning>()?;
429  m.add_class::<CleanedLineFit>()?;
430  #[cfg(feature="database")]
431  m.add_class::<TofPaddleOverlaps>()?;
432  #[cfg(feature="database")]
433  {
434    use crate::physics::searchlight::*;
435    m.add_class::<Searchlight>()?;
436    m.add_class::<SearchlightGeometry>()?;
437    m.add_class::<SearchlightSettings>()?;
438    m.add_class::<SearchlightResult>()?;
439    m.add_class::<SearchlightCandidate>()?;
440  }
441  m.add("LINEFIT_DEFAULT_ERR_XY", LINEFIT_DEFAULT_ERR_XY)?;
442  m.add("TOF_INNER_MAX_PADDLE_ID", TOF_INNER_MAX_PADDLE_ID)?;
443  Ok(())
444}
445
446#[cfg(feature="pybindings")]
447#[pymodule]
448#[pyo3(name = "geometry")]
449fn geometry_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
450  use crate::geometry::*;
451  m.add_class::<Geometry>()?;
452  m.add_class::<Material>()?;
453  m.add_class::<Solid>()?;
454  m.add_class::<SolidKind>()?;
455  m.add_class::<Volume>()?;
456  m.add_class::<Placement>()?;
457  m.add_class::<WorldPlacement>()?;
458  m.add_class::<Transform>()?;
459  m.add_class::<Crossing>()?;
460  m.add_class::<TrackPath>()?;
461  Ok(())
462}
463
464#[cfg(feature="database")]
465#[cfg(feature="pybindings")]
466#[pymodule]
467#[pyo3(name = "db")]
468fn db_py<'_py>(m: &Bound<'_py, PyModule>) -> PyResult<()> {
469  use crate::database::*;
470  m.add_class::<ReadoutBoard>()?;
471  m.add_class::<RAT>()?;
472  m.add_class::<TofPaddle>()?;
473  m.add_class::<TrackerStrip>()?;
474  m.add_class::<TrackerStripMask>()?;
475  m.add_class::<TrackerStripPedestal>()?;
476  m.add_class::<TrackerStripTransferFunction>()?;
477  m.add_class::<TrackerStripCmnNoise>()?;
478  m.add_class::<TrackerStripGain>()?;
479  m.add_class::<TrackerStripPulse>()?;
480  m.add_class::<TofPaddleTimingConstant>()?;
481  m.add_class::<TrackerCalibrationFile>()?;
482  m.add_class::<TrackerCalibrationFileType>()?;
483  m.add_class::<TrackerCaliTimeWindow>()?;
484  m.add_class::<TofPaddleTemp>()?;
485  m.add_class::<TofPaddleTempDataSeries>()?;
486  m.add_function(wrap_pyfunction!(load_calibration_db_elena, m)?)?;
487  m.add_function(wrap_pyfunction!(get_all_rbids_in_db, m)?)?;
488  m.add_function(wrap_pyfunction!(get_all_pbids_in_db, m)?)?;
489  m.add_function(wrap_pyfunction!(get_hid_vid_maps, m)?)?;
490  m.add_function(wrap_pyfunction!(get_vid_hid_maps, m)?)?;
491  m.add_function(wrap_pyfunction!(get_rbids_for_pbid, m)?)?;
492  m.add_function(wrap_pyfunction!(get_dsi_j_ch_pid_map_py, m)?)?;
493  m.add_function(wrap_pyfunction!(get_rbid_pbchannel_pid_map_py, m)?)?;
494  m.add_function(wrap_pyfunction!(load_calibration_db_elena, m)?)?;
495  m.add_function(wrap_pyfunction!(create_trk_mask_table, m)?)?;
496  m.add_function(wrap_pyfunction!(create_trk_pedestal_table, m)?)?;
497  m.add_function(wrap_pyfunction!(create_trk_transfer_fn_table, m)?)?;
498  m.add_function(wrap_pyfunction!(create_trk_pulse_table, m)?)?;
499  m.add_function(wrap_pyfunction!(create_trk_gain_table, m)?)?;
500  m.add_function(wrap_pyfunction!(is_in_tracker_cali_window, m)?)?;
501  m.add_function(wrap_pyfunction!(create_trk_cali_tw_table, m)?)?;
502  m.add_function(wrap_pyfunction!(create_tof_paddle_temp_table, m)?)?;
503  Ok(())
504}
505
506#[cfg(feature="pybindings")]
507#[pyfunction]
508fn get_version() -> &'static str {
509  return VERSION;
510}
511
512/// Major version of the package 
513/// from the version string
514/// (Major.Minor.Patch)
515#[cfg(feature="pybindings")]
516#[pyfunction]
517fn get_version_major() -> u8 {
518  return VERSION_MAJ.parse().unwrap();
519}
520
521/// Minor version of the package 
522/// from the version string
523/// (Major.Minor.Patch)
524#[cfg(feature="pybindings")]
525#[pyfunction]
526fn get_version_minor() -> u8 {
527  return VERSION_MIN.parse().unwrap();
528}
529
530/// Patch level of the package 
531/// from the version string
532/// (Major.Minor.Patch)
533#[cfg(feature="pybindings")]
534#[pyfunction]
535fn get_version_patch() -> u8 {
536  return VERSION_PCH.parse().unwrap();
537}
538
539/// Check if the version is at least the 
540/// required, given string following the 
541/// format MAJOR.MINOR.PATCH 
542#[cfg(feature="pybindings")]
543#[pyfunction]
544fn version_at_least(version_string : String) -> bool {
545  let parts: Vec<u32> = version_string.split('.')
546    .map(|s| s.parse().expect("Input is not a valid version string. Please follow the MAJOR.MINOR.PATCH format!"))
547    .collect();
548  let major : u8 = parts[0] as u8;
549  let minor : u8 = parts[1] as u8;
550  let patch : u8 = parts[2] as u8;
551  if major < get_version_major() {
552    return true;
553  }
554  if major > get_version_major() {
555    println!("Required major version of {} is larger than current version {}", major, VERSION);
556    return false;
557  }
558  if major == get_version_major() {
559    if minor < get_version_minor() {
560      return true;
561    }
562    if minor > get_version_minor() {
563      println!("Required minor version of {} is larger than current version {}", minor, VERSION);
564      return false;
565    }
566    if minor == get_version_minor() {
567      if patch > get_version_patch() {
568        println!("Required patch version of {} is larger than current version {}", patch, VERSION);
569        return false 
570      }
571    }
572  } 
573  true
574}
575
576#[cfg(feature="pybindings")]
577pyo3::create_exception!(gondola_core_py, PyMasterTriggerError, pyo3::exceptions::PyException);
578#[cfg(feature="pybindings")]
579pyo3::create_exception!(gondola_core_py, PyRunError, pyo3::exceptions::PyException);
580#[cfg(feature="pybindings")]
581pyo3::create_exception!(gondola_core_py, PyTofError, pyo3::exceptions::PyException);
582#[cfg(feature="pybindings")]
583pyo3::create_exception!(gondola_core_py, PyStagingError, pyo3::exceptions::PyException);
584#[cfg(feature="pybindings")]
585pyo3::create_exception!(gondola_core_py, PySensorError, pyo3::exceptions::PyException);
586#[cfg(feature="pybindings")]
587pyo3::create_exception!(gondola_core_py, PyUserError, pyo3::exceptions::PyException);
588#[cfg(feature="pybindings")]
589pyo3::create_exception!(gondola_core_py, PyCalibrationError, pyo3::exceptions::PyException);
590#[cfg(feature="pybindings")]
591pyo3::create_exception!(gondola_core_py, PyWaveformError, pyo3::exceptions::PyException);
592#[cfg(feature="pybindings")]
593pyo3::create_exception!(gondola_core_py, PyIPBusError, pyo3::exceptions::PyException);
594#[cfg(feature="pybindings")]
595pyo3::create_exception!(gondola_core_py, PySerializationError, pyo3::exceptions::PyException);
596#[cfg(feature="pybindings")]
597pyo3::create_exception!(gondola_core_py, PyAnalysisError, pyo3::exceptions::PyException); 
598#[cfg(feature="pybindings")]
599pyo3::create_exception!(gondola_core_py, PyGeometryError, pyo3::exceptions::PyException);
600
601#[macro_export]
602macro_rules! pythonize_error {
603  ($name:ident, $pyname:ident) => {
604
605    impl From<$name> for PyErr {
606      fn from(err: $name) -> PyErr {
607        // You can use a standard Python exception if you prefer, 
608        // e.g., pyo3::exceptions::PyValueError::new_err(...)
609        // But mapping to your custom PyAnalysisError is usually better. 
610        $pyname::new_err(format!("<GondolaCoreException: {}>", err))
611      }
612    }
613  }
614}
615
616#[cfg(feature="pybindings")]
617pythonize_error!(SerializationError, PySerializationError);
618#[cfg(feature="pybindings")]
619pythonize_error!(AnalysisError, PyAnalysisError);
620#[cfg(feature="pybindings")]
621pythonize_error!(CalibrationError, PyCalibrationError);
622#[cfg(feature="pybindings")]
623pythonize_error!(UserError, PyUserError);
624#[cfg(feature="pybindings")]
625pythonize_error!(GeometryError, PyGeometryError);
626
627/// Python API to rust version of tof-dataclasses.
628///
629/// Currently, this contains only the analysis 
630/// functions
631#[cfg(feature="pybindings")]
632#[pymodule]
633#[pyo3(name = "gondola_core")]
634fn gondola_core_py<'_py>(m : &Bound<'_py, PyModule>) -> PyResult<()> { //: Python<'_>, m: &PyModule) -> PyResult<()> {
635  pyo3_log::init();
636  m.add_function(wrap_pyfunction!(get_version, m)?)?;
637  m.add_function(wrap_pyfunction!(get_version_major, m)?)?;
638  m.add_function(wrap_pyfunction!(get_version_minor, m)?)?;
639  m.add_function(wrap_pyfunction!(get_version_patch, m)?)?;
640  m.add_function(wrap_pyfunction!(version_at_least, m)?)?;
641  m.add_wrapped(wrap_pymodule!(events_py))?;
642  m.add_wrapped(wrap_pymodule!(monitoring_py))?;
643  m.add_wrapped(wrap_pymodule!(packets_py))?;
644  m.add_wrapped(wrap_pymodule!(tof_py))?;
645  m.add_wrapped(wrap_pymodule!(tracker_py))?;
646  m.add_wrapped(wrap_pymodule!(io_py))?;
647  m.add_wrapped(wrap_pymodule!(db_py))?;
648  m.add_wrapped(wrap_pymodule!(stats_py))?;
649  m.add_wrapped(wrap_pymodule!(algo_py))?;
650  m.add_wrapped(wrap_pymodule!(calibration_py))?;
651  m.add_wrapped(wrap_pymodule!(geometry_py))?;
652  m.add_wrapped(wrap_pymodule!(reconstruction_py))?;
653  //m.add("SerializationError",  pyo3::types::PyAnyMethods::<PySerializationError>::get_type(m))?;
654  //m.add("AnalysisError",  pyo3::types::PyAnyMethods::<PyAnalysisError>::get_type(m))?;
655  Ok(())
656}
657
658
659
660