Skip to main content

gondola_core/database/
tof_paddle_temps.rs

1// This file is part of gaps-online-software and published 
2// under the GPLv3 license
3
4use crate::prelude::*;
5use crate::database::schema;
6
7use diesel::prelude::*;
8
9#[cfg_attr(feature="pybindings", pyfunction)]
10pub fn create_tof_paddle_temp_table( db_path: &str, paddle_temps: Vec<TofPaddleTemp>) { 
11  use schema::tof_db_tofpaddletemp::dsl::*;
12  let mut conn = SqliteConnection::establish(db_path).ok().unwrap();
13  
14  let mut _query_result = diesel::sql_query("
15      CREATE TABLE IF NOT EXISTS tof_db_tofpaddletemp (
16          data_id INTEGER PRIMARY KEY AUTOINCREMENT,
17          paddle_id SMALLINT NOT NULL, 
18          utc_timestamp BIGINT NOT NULL,
19          temp_a FLOAT NOT NULL,
20          temp_b FLOAT NOT NULL,
21          meta TEXT
22      )
23  ").execute(&mut conn);
24  match _query_result {
25    Ok(_) => {
26      println!("Created table successfully!");
27    }
28    Err(err) => {
29      println!("Error occured when creating tof_db_tofpaddletemp table! {err}");
30    }
31  }
32  _query_result = diesel::insert_into(tof_db_tofpaddletemp)
33    .values(&paddle_temps)
34    .execute(&mut conn);
35  match _query_result {
36    Ok(_) => {
37      println!("Entered data into db successfully!");
38    }
39    Err(err) => {
40      println!("Error occured when entering data in the db! {err}");
41    }
42  }
43}
44
45#[derive(Debug, PartialEq, Clone)]
46#[allow(non_snake_case)]
47#[cfg_attr(feature="pybindings", pyclass)]
48pub struct TofPaddleTempDataSeries {
49  pub temp_a         : Vec<f32>,
50  pub temp_b         : Vec<f32>,
51  pub utc_timestamps : Vec<u64>,
52  pub paddle_id      : u8
53}
54
55impl TofPaddleTempDataSeries {
56  pub fn new() -> Self {
57    Self {
58      temp_a         : Vec::<f32>::new(),
59      temp_b         : Vec::<f32>::new(),
60      utc_timestamps : Vec::<u64>::new(),
61      paddle_id      : 0
62    }
63  }
64
65  pub fn add(&mut self, pdl_t : &TofPaddleTemp) {
66    if pdl_t.paddle_id == self.paddle_id as i16 {
67      self.temp_a.push(pdl_t.temp_a);
68      self.temp_b.push(pdl_t.temp_b);
69      self.utc_timestamps.push(pdl_t.utc_timestamp as u64);
70    }
71  }
72
73  pub fn get_for_ts(&self, utc_timestamp : u64) -> (f32, f32) {
74    let mut result = (-273.0, -273.0); 
75    let idx_opt = self.utc_timestamps.partition_point(|&t| t < utc_timestamp)
76        .checked_sub(1);
77    if let Some(idx) = idx_opt {
78      if self.temp_a.len() > idx as usize && self.temp_b.len() > idx {
79        result.0 = self.temp_a[idx]; 
80        result.1 = self.temp_b[idx];
81      }
82    }
83    result
84  }
85
86  pub fn sort(&mut self) {
87    let mut indices: Vec<usize> = (0..self.utc_timestamps.len()).collect();
88    indices.sort_unstable_by_key(|&i| self.utc_timestamps[i]);
89    let timestamps_sorted: Vec<u64> =
90      indices.iter().map(|&i| self.utc_timestamps[i]).collect();
91    let values_a_sorted: Vec<f32> =
92      indices.iter().map(|&i| self.temp_a[i]).collect();
93    let values_b_sorted: Vec<f32> =
94      indices.iter().map(|&i| self.temp_b[i]).collect();
95    self.utc_timestamps = timestamps_sorted;
96    self.temp_a = values_a_sorted;
97    self.temp_b = values_b_sorted;
98    //self.utc_timestamps.sort_unstable();
99  }
100}
101
102impl fmt::Display for TofPaddleTempDataSeries {
103  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104    let mut repr = String::from("<TofPaddleTempDataSeries:");
105    repr += &(format!("\n  Paddle ID : {}", self.paddle_id));
106    repr += &(format!("\n  Values    : {}", self.temp_a.len()));
107    repr += ">";
108    write!(f, "{}", repr)
109  }
110}
111
112/// Recorded Temperature of each paddle end. The SiPM preamp board 
113/// is equipped with a temeperature sensor, which allows to calibrate 
114/// the gain of the SiPm
115#[derive(Debug,PartialEq, Clone, Queryable, Selectable, Insertable, serde::Serialize, serde::Deserialize)]
116#[diesel(table_name = schema::tof_db_tofpaddletemp)]
117#[diesel(primary_key(data_id))]
118#[allow(non_snake_case)]
119#[cfg_attr(feature="pybindings", pyclass)]
120pub struct TofPaddleTemp {
121  #[diesel(deserialize_as = i32)]
122  pub data_id             : Option<i32>,
123  pub paddle_id           : i16, 
124  pub utc_timestamp       : i64,
125  pub temp_a              : f32,
126  pub temp_b              : f32,
127  pub meta                : Option<String>, 
128}
129
130impl TofPaddleTemp {
131
132  pub fn new() -> Self {
133    Self {
134      data_id             : None,
135      paddle_id           : 0,
136      utc_timestamp       : 0,
137      temp_a              : 0.0,
138      temp_b              : 0.0,
139      meta                : None, 
140    }
141  }
142 
143  /// Retrieve all paddle temperatures
144  /// stroed in the database
145  ///
146  /// # Returns:
147  ///   * Vec<Self>  : All paddle temperatures as they are 
148  ///                  stored in the db
149  pub fn all() -> Option<Vec<Self>> {
150    use schema::tof_db_tofpaddletemp::dsl::*;
151    let mut conn = connect_to_db().ok()?;
152    match tof_db_tofpaddletemp.load::<Self>(&mut conn) {
153      Err(err) => {
154        error!("Unable to load TOF paddle temperature data from db! {err}");
155        return None;
156      }
157      Ok(tpts) => {
158        return Some(tpts);
159      }
160    }
161  }
162  
163  /// Retrieve all paddle temperatures for a specific paddle id
164  ///
165  /// # Returns:
166  ///   * Vec<Self>  : All paddle tempereaturs as they are 
167  ///                  stored in the db for this paddle id
168  pub fn all_data() -> Option<HashMap<u8,TofPaddleTempDataSeries>> {
169    use schema::tof_db_tofpaddletemp::dsl::*;
170    let mut conn = connect_to_db().ok()?;
171    let results = tof_db_tofpaddletemp
172      //.filter(paddle_id.eq(pid as i16))
173      .load::<Self>(&mut conn);
174    let mut all_ds = HashMap::<u8, TofPaddleTempDataSeries>::new();
175    for k in 1..161u8 {
176      let mut new_series = TofPaddleTempDataSeries::new();
177      new_series.paddle_id = k;
178      all_ds.insert(k, new_series); 
179    }
180    
181    match results {
182      Err(err) => {
183        error!("Unable to load TOF paddle temperature data from db! {err}");
184        return None;
185      }
186      Ok(tpts) => {
187        for tp in tpts {
188          all_ds.get_mut(&(tp.paddle_id as u8)).unwrap().add(&tp);
189          //ds.add(&tp);
190        }
191      }
192    }
193    for k in 1..161 {
194      all_ds.get_mut(&k).unwrap().sort(); 
195    }
196    //return Some(tpts);
197    return Some(all_ds);
198  }
199
200  //pub fn from_telemetry_packet(pack : &TelemetryPacket) -> Self { 
201  //  let mut tpt = Self::new();
202  //  tpt.utc_timestamp = pack.header.get_gcutime() as i64;
203  //  return tpt;
204  //}
205
206
207  //pub fn from_pa_monidata(&PAMoniData) -> Self {
208  //  let mut tpt = Self::new();  
209  //  tpt
210  //  return tpt;
211  //}
212}
213
214impl Default for TofPaddleTemp {
215  fn default() -> Self {
216    Self::new()
217  }
218}
219
220impl fmt::Display for TofPaddleTemp {
221  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222    let mut repr = String::from("<TofPaddleTemp:");
223    repr += &(format!("\n  Paddle ID     : {}", self.paddle_id));
224    repr += &(format!("\n  UTC Timstamp  : {} [{}|]", self.utc_timestamp, get_utc_timestamp_from_unix(self.utc_timestamp as f64).unwrap_or(String::from("0"))));    
225    repr += &(format!("\n  Temp [C]      : A {} // B {}", self.temp_a, self.temp_b)); 
226    if self.meta.is_some() {
227      repr += &(format!("\n  meta info     : {}", self.meta.clone().unwrap())); 
228    }
229    repr += ">";
230    write!(f, "{}", repr)
231  }
232}
233
234#[cfg(feature="pybindings")]
235#[pymethods]
236impl TofPaddleTempDataSeries {
237  #[pyo3(name="get_for_ts")]
238  pub fn get_for_ts_py(&self, timestamp : u64) -> (f32, f32) {
239    self.get_for_ts(timestamp)
240  }
241  
242  #[getter]
243  fn get_first_ts(&self) -> Option<&u64> {
244    self.utc_timestamps.first() 
245  }
246  
247  #[getter]
248  fn get_last_ts(&self) -> Option<&u64> {
249    self.utc_timestamps.last() 
250  }
251}
252
253#[cfg(feature="pybindings")]
254pythonize!(TofPaddleTempDataSeries);
255
256#[cfg(feature="pybindings")]
257#[pymethods]
258impl TofPaddleTemp {
259  
260  #[staticmethod]
261  #[pyo3(name="all")]
262  pub fn all_py() -> Option<Vec<Self>> {
263    Self::all()
264  } 
265  
266  /// Retrieve all paddle temperatures for a specific paddle id
267  ///
268  /// # Returns:
269  ///   * Vec<Self>  : All paddle tempereaturs as they are 
270  ///                  stored in the db for this paddle id
271  #[staticmethod]
272  #[pyo3(name="all_data")]
273  fn all_data_py() -> Option<HashMap<u8,TofPaddleTempDataSeries>> {
274    Self::all_data()
275  } 
276
277  #[getter]
278  fn get_utc_timestamp(&self) -> i64 {
279    self.utc_timestamp
280  }
281  
282  #[setter]
283  fn set_utc_timestamp(&mut self, ts : i64) {
284    self.utc_timestamp = ts;
285  }
286   
287  #[getter]
288  fn get_meta    (&self) -> Option<String> {
289    self.meta.clone()
290  }  
291  
292  #[getter]
293  fn get_paddle_id(&self) -> i16 { 
294    self.paddle_id 
295  }
296  
297  #[getter]
298  fn get_temp_a(&self)    -> f32 { 
299    self.temp_a 
300  }
301  
302  #[getter]
303  fn get_temp_b(&self)    -> f32 {
304    self.temp_b
305  }
306  
307  #[setter]
308  fn set_paddle_id(&mut self, pid : i16) { 
309    self.paddle_id = pid;
310  }
311  
312  #[setter]
313  fn set_temp_a(&mut self, t : f32) { 
314    self.temp_a = t;
315  }
316  
317  #[setter]
318  fn set_temp_b(&mut self, t : f32) {
319    self.temp_b = t;
320  }
321}
322
323#[cfg(feature="pybindings")]
324pythonize!(TofPaddleTemp);
325