1use crate::prelude::*;
9
10use crate::database::schema;
11use diesel::prelude::*;
12
13use std::io::{
14 self,
15 BufRead,
16 BufReader
17};
18
19#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
21#[diesel(table_name = schema::tof_db_trackerstriptransferfunction)]
22#[diesel(primary_key(data_id))]
23#[allow(non_snake_case)]
24#[cfg_attr(feature="pybindings", pyclass)]
25pub struct TrackerStripTransferFunction {
26 pub data_id : i32,
27 pub strip_id : i32,
28 pub volume_id : i64,
29 pub utc_timestamp_start: i64,
30 pub utc_timestamp_stop : i64,
31 pub name : Option<String>,
32 pub pol_a2_0 : f32,
33 pub pol_a2_1 : f32,
34 pub pol_a2_2 : f32,
35 pub pol_b3_0 : f32,
36 pub pol_b3_1 : f32,
37 pub pol_b3_2 : f32,
38 pub pol_b3_3 : f32,
39 pub pol_c3_0 : f32,
40 pub pol_c3_1 : f32,
41 pub pol_c3_2 : f32,
42 pub pol_c3_3 : f32,
43 pub pol_d3_0 : f32,
44 pub pol_d3_1 : f32,
45 pub pol_d3_2 : f32,
46 pub pol_d3_3 : f32,
47}
48
49impl TrackerStripTransferFunction {
50
51 pub const MAX_ADC : f32 = 1600.0;
54
55 pub fn new() -> Self {
56 Self {
57 data_id : 0,
58 strip_id : 0,
59 volume_id : 0,
60 utc_timestamp_start : 0,
61 utc_timestamp_stop : 0,
62 name : None,
63 pol_a2_0 : 0.0,
64 pol_a2_1 : 0.0,
65 pol_a2_2 : 0.0,
66 pol_b3_0 : 0.0,
67 pol_b3_1 : 0.0,
68 pol_b3_2 : 0.0,
69 pol_b3_3 : 0.0,
70 pol_c3_0 : 0.0,
71 pol_c3_1 : 0.0,
72 pol_c3_2 : 0.0,
73 pol_c3_3 : 0.0,
74 pol_d3_0 : 0.0,
75 pol_d3_1 : 0.0,
76 pol_d3_2 : 0.0,
77 pol_d3_3 : 0.0,
78 }
79 }
80
81 pub fn parse_from_file<P: AsRef<Path>>(path: P) -> io::Result<Vec<Self>> {
82 let file = File::open(path)?;
83 let reader = BufReader::new(file);
84 let mut transfer_fns = Vec::<Self>::new();
85 let hid_vid_map = get_hid_vid_maps().unwrap().1;
86 for line in reader.lines() {
87 let line = line?;
88 if line.starts_with("#") || line.starts_with("Layer") || line.starts_with("layer") {
89 continue;
90 }
91 let mut trfn = Self::new();
92 let parts: Vec<&str> = line.split(",").collect();
93 if parts.len() == 19 {
94 let layer = parts[0].parse::<u8>()
96 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
97 let row = parts[1].parse::<u8>()
98 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
99 let module = parts[2].parse::<u8>()
100 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
101 let channel = parts[3].parse::<u8>()
102 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
103 trfn.strip_id = TrackerStrip::create_stripid(layer, row, module, channel) as i32;
104 trfn.volume_id = *hid_vid_map.get(&(trfn.strip_id as u32)).unwrap() as i64; trfn.pol_a2_0 = parts[4].parse::<f32>()
106 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
107 trfn.pol_a2_1 = parts[5].parse::<f32>()
108 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
109 trfn.pol_a2_2 = parts[6].parse::<f32>()
110 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
111 trfn.pol_b3_0 = parts[7].parse::<f32>()
112 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
113 trfn.pol_b3_1 = parts[8].parse::<f32>()
114 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
115 trfn.pol_b3_2 = parts[9].parse::<f32>()
116 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
117 trfn.pol_b3_3 = parts[10].parse::<f32>()
118 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
119 trfn.pol_c3_0 = parts[11].parse::<f32>()
120 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
121 trfn.pol_c3_1 = parts[12].parse::<f32>()
122 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
123 trfn.pol_c3_2 = parts[13].parse::<f32>()
124 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
125 trfn.pol_c3_3 = parts[14].parse::<f32>()
126 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
127 trfn.pol_d3_0 = parts[15].parse::<f32>()
128 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
129 trfn.pol_d3_1 = parts[16].parse::<f32>()
130 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
131 trfn.pol_d3_2 = parts[17].parse::<f32>()
132 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
133 trfn.pol_d3_3 = parts[18].parse::<f32>()
134 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
135 transfer_fns.push(trfn);
136 }
137 }
138 Ok(transfer_fns)
139 }
140
141 pub fn as_dict_by_name(fname : &str) -> Result<HashMap<u32,Self>, ConnectionError> {
146 use schema::tof_db_trackerstriptransferfunction::dsl::*;
147 let mut strips = HashMap::<u32, Self>::new();
148 if fname == "" {
149 match Self::all() {
150 None => {
151 error!("Unable to retrive ANY TrackerStripTransferFunction");
152 return Ok(strips);
153 }
154 Some(_strips) => {
155 for k in _strips {
156 strips.insert(k.strip_id as u32, k);
157 }
158 return Ok(strips);
159 }
160 }
161 }
162 let mut conn = connect_to_db()?;
163 match tof_db_trackerstriptransferfunction.filter(
164 schema::tof_db_trackerstriptransferfunction::name.eq(fname)).load::<Self>(&mut conn) {
165 Err(err) => {
166 error!("We can't find any tracker strip transferfunction in the database! {err}");
167 return Ok(strips);
168 }
169 Ok(peds_) => {
170 for s in peds_ {
171 strips.insert(s.strip_id as u32, s );
172 }
173 }
174 }
175 return Ok(strips);
176 }
177
178 pub fn all_names() -> Result<Vec<String>, ConnectionError> {
179 let mut conn = connect_to_db()?;
180 let mut names = Vec::<String>::new();
181 let unique_names =
182 schema::tof_db_trackerstriptransferfunction::table.select(
183 schema::tof_db_trackerstriptransferfunction::name)
184 .distinct()
185 .load::<Option<String>>(&mut conn).expect("Error getting names from db!");
186 for k in unique_names {
187 if let Some(n) = k {
188 names.push(n);
189 }
190 }
191 Ok(names)
192 }
193
194 pub fn all() -> Option<Vec<Self>> {
199 use schema::tof_db_trackerstriptransferfunction::dsl::*;
200 let mut conn = connect_to_db().ok()?;
201 match tof_db_trackerstriptransferfunction.load::<Self>(&mut conn) {
202 Err(err) => {
203 error!("Unable to load tracker transfer functions from db! {err}");
204 return None;
205 }
206 Ok(strips) => {
207 return Some(strips);
208 }
209 }
210 }
211
212 pub fn evaluate(&self, adc : f32) -> f32 {
215 if adc < 0.0 {
216 return 0.0;
217 }
218 if adc <= 190.0 {
219 return self.pol_a2_0 + self.pol_a2_1*adc + self.pol_a2_2*(adc.powi(2));
220 }
221 if 190.0 < adc && adc <= 500.0 {
222 return self.pol_b3_0 + self.pol_b3_1*adc + self.pol_b3_2*(adc.powi(2)) + self.pol_b3_3*(adc.powi(3));
223 }
224 if 500.0 < adc && adc <= 900.0 {
225 return self.pol_c3_0 + self.pol_c3_1*adc + self.pol_c3_2*(adc.powi(2)) + self.pol_c3_3*(adc.powi(3));
226 }
227 if 900.0 < adc && adc <= 1600.0 {
229 return self.pol_d3_0 + self.pol_d3_1*adc + self.pol_d3_2*(adc.powi(2)) + self.pol_d3_3*(adc.powi(3));
230 }
231 0.0
232 }
233
234 pub fn derivative(&self, adc : f32) -> f32 {
236 if adc < 0.0 {
237 return 0.0;
238 }
239 if adc <= 190.0 {
240 return self.pol_a2_1 + 2.0*self.pol_a2_2*adc;
241 }
242 if 190.0 < adc && adc <= 500.0 {
243 return self.pol_b3_1 + 2.0*self.pol_b3_2*adc + 3.0*self.pol_b3_3*(adc.powi(2));
244 }
245 if 500.0 < adc && adc <= 900.0 {
246 return self.pol_c3_1 + 2.0*self.pol_c3_2*adc + 3.0*self.pol_c3_3*(adc.powi(2));
247 }
248 if 900.0 < adc && adc <= 1600.0 {
250 return self.pol_d3_1 + 2.0*self.pol_d3_2*adc + 3.0*self.pol_d3_3*(adc.powi(2));
251 }
252 0.0
253 }
254
255 pub fn invert(&self, y : f64, epsilon_opt : Option<f64>) -> Result<f64, AnalysisError> {
259 let x_min = 0.0f32;
260 let x_max = 1600.0f32;
261 let y_min = self.evaluate(x_min);
262 let y_max = self.evaluate(x_max);
263 if y < y_min as f64 || y > y_max as f64 {
264 error!("y value of {} is out of bounds for 0 <= x <= 1600", y);
265 return Err(AnalysisError::OutOfBounds);
266 }
267 let max_iterations = 50;
268 let epsilon : f64;
269 if epsilon_opt.is_some() {
270 epsilon = epsilon_opt.unwrap();
271 } else {
272 epsilon = 1e-12; }
274
275 let mut low = x_min;
276 let mut high = x_max;
277 let mut x = 0.5 * (low + high);
278
279 for _ in 0..max_iterations {
280 let f_x = self.evaluate(x) as f64 - y;
281 let df_x = self.derivative(x) as f64;
282 if f_x.abs() < epsilon {
284 return Ok(x as f64);
285 }
286 if f_x > 0.0 {
288 high = x;
289 } else {
290 low = x;
291 }
292 if df_x.abs() > 1e-9 {
294 let next_x = x as f64 - f_x / df_x;
295 if next_x > low as f64 && next_x < high as f64 {
298 x = next_x as f32;
299 continue;
300 }
301 }
302 x = 0.5 * (low + high);
304 }
305 error!("We couldn't find a solution which is epsilon {} away! The transfer function might not be continuous or monotonic, try a larger epsilon!", epsilon);
306 Err(AnalysisError::DidNotConverge)
307 }
308}
309
310impl fmt::Display for TrackerStripTransferFunction {
311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
312 let mut repr = format!("<TrackerStripTransferFunction [{}]:", self.strip_id);
313 repr += &(format!("\n vid : {}", self.volume_id));
314 repr += "\n UTC Timestamps (Begin/End):";
315 repr += &(format!("\n {}/{}", self.utc_timestamp_start, self.utc_timestamp_stop));
316 if self.name.is_some() {
317 repr += &(format!("\n name : {}", self.name.clone().unwrap()));
318 }
319 repr += &(format!("\n Poly A {}*adc + {}*adc + {}*(adc**2) for adc < 190", self.pol_a2_0, self.pol_a2_1, self.pol_a2_2));
320 repr += &(format!("\n Poly B :{}*adc + {}*adc + {}*(adc**2) + {}*(adc**3) for 190 < adc <= 500", self.pol_b3_0, self.pol_b3_1, self.pol_b3_2, self.pol_b3_3));
321 repr += &(format!("\n Poly C :{}*adc + {}*adc + {}*(adc**2) + {}*(adc**3) for 500 < adc <= 900", self.pol_c3_0, self.pol_c3_1, self.pol_c3_2, self.pol_c3_3));
322 repr += &(format!("\n Poly D :{}*adc + {}*adc + {}*(adc**2) + {}*(adc**3) for 900 < adc <= 1600>", self.pol_d3_0, self.pol_d3_1, self.pol_d3_2, self.pol_d3_3));
323 write!(f, "{}", repr)
324 }
325}
326
327#[cfg(feature="pybindings")]
328#[pymethods]
329impl TrackerStripTransferFunction {
330
331 #[staticmethod]
332 #[pyo3(name="all")]
333 pub fn all_py() -> Option<Vec<Self>> {
334 Self::all()
335 }
336
337 #[staticmethod]
338 #[pyo3(name="all_names")]
339 pub fn all_names_py() -> Option<Vec<String>> {
343 match Self::all_names() {
344 Err(_) => {
345 return None;
346 }
347 Ok(names) => {
348 return Some(names);
349 }
350 }
351 }
352
353 #[staticmethod]
354 #[pyo3(name="as_dict_by_name")]
355 pub fn all_as_dict_py(name : &str) -> Option<HashMap<u32,Self>> {
356 match Self::as_dict_by_name(name) {
357 Err(err) => {
358 error!("Unable to retrieve tracker strip transfer fn dictionary. {err}. Did you laod the setup-env.sh shell?");
359 return None;
360 }
361 Ok(_data) => {
362 return Some(_data);
363 }
364 }
365 }
366
367 #[getter]
368 fn get_strip_id (&self) -> i32 {
369 self.strip_id
370 }
371
372 #[getter]
373 fn get_volume_id (&self) -> i64 {
374 self.volume_id
375 }
376
377 #[getter]
378 fn get_utc_timestamp_start(&self) -> i64 {
379 self.utc_timestamp_start
380 }
381
382 #[getter]
383 fn get_utc_timestamp_stop(&self) -> i64 {
384 self.utc_timestamp_stop
385 }
386
387 #[setter]
388 fn set_utc_timestamp_start(&mut self, value : i64) {
389 self.utc_timestamp_start = value;
390 }
391
392 #[setter]
393 fn set_utc_timestamp_stop(&mut self, value : i64) {
394 self.utc_timestamp_stop = value;
395 }
396
397 #[getter]
398 fn get_name(&self) -> Option<String> {
399 self.name.clone()
400 }
401
402 #[setter]
403 fn set_name(&mut self, value : String) {
404 self.name = Some(value);
405 }
406
407 #[pyo3(name="transfer_fn")]
408 fn transfer_fn_py(&self, adc : f32) -> f32 {
409 if adc > 1600.0 {
410 warn!("ADC value larger than 1600! {}. Transfer fn not defined beyond 1600.", adc);
411 }
412 return self.evaluate(adc);
413 }
414
415 #[pyo3(name="derivative")]
416 fn derivative_py(&self, adc : f32) -> f32 {
417 if adc > 1600.0 {
418 warn!("ADC value larger than 1600! {}. Transfer fn not defined beyond 1600.", adc);
419 }
420 return self.derivative(adc);
421 }
422
423 #[pyo3(signature = (mv , epsilon = None))]
430 #[pyo3(name="invert")]
431 fn invert_py(&self, mv : f64, epsilon : Option<f64>) -> PyResult<f64> {
432 Ok(self.invert(mv, epsilon)?)
433 }
434
435 #[staticmethod]
436 #[pyo3(name="parse_from_file")]
437 fn parse_from_file_py(fname : &str) -> Option<Vec<Self>> {
438 let result = Self::parse_from_file(fname);
439 if result.is_ok() {
440 return Some(result.unwrap());
441 } else {
442 error!("An error occured when parsing {} : '{}'", fname, result.unwrap_err());
443 return None;
444 }
445 }
446}
447
448#[cfg(feature="pybindings")]
449pythonize!(TrackerStripTransferFunction);
450
451#[derive(Debug,PartialEq, Clone, Insertable)]
454#[diesel(table_name = schema::tof_db_trackerstriptransferfunction)]
455#[allow(non_snake_case)]
456#[cfg_attr(feature="pybindings", pyclass)]
457struct NewTrackerStripTransferFunction {
458 pub strip_id : i32,
459 pub volume_id : i64,
460 pub utc_timestamp_start: i64,
461 pub utc_timestamp_stop : i64,
462 pub name : Option<String>,
463 pub pol_a2_0 : f32,
464 pub pol_a2_1 : f32,
465 pub pol_a2_2 : f32,
466 pub pol_b3_0 : f32,
467 pub pol_b3_1 : f32,
468 pub pol_b3_2 : f32,
469 pub pol_b3_3 : f32,
470 pub pol_c3_0 : f32,
471 pub pol_c3_1 : f32,
472 pub pol_c3_2 : f32,
473 pub pol_c3_3 : f32,
474 pub pol_d3_0 : f32,
475 pub pol_d3_1 : f32,
476 pub pol_d3_2 : f32,
477 pub pol_d3_3 : f32,
478}
479
480impl NewTrackerStripTransferFunction {
481 pub fn from(tf : &TrackerStripTransferFunction) -> Self {
482 Self {
483 strip_id : tf.strip_id ,
484 volume_id : tf.volume_id ,
485 utc_timestamp_start : tf.utc_timestamp_start ,
486 utc_timestamp_stop : tf.utc_timestamp_stop ,
487 name : tf.name.clone() ,
488 pol_a2_0 : tf.pol_a2_0 ,
489 pol_a2_1 : tf.pol_a2_1 ,
490 pol_a2_2 : tf.pol_a2_2 ,
491 pol_b3_0 : tf.pol_b3_0 ,
492 pol_b3_1 : tf.pol_b3_1 ,
493 pol_b3_2 : tf.pol_b3_2 ,
494 pol_b3_3 : tf.pol_b3_3 ,
495 pol_c3_0 : tf.pol_c3_0 ,
496 pol_c3_1 : tf.pol_c3_1 ,
497 pol_c3_2 : tf.pol_c3_2 ,
498 pol_c3_3 : tf.pol_c3_3 ,
499 pol_d3_0 : tf.pol_d3_0 ,
500 pol_d3_1 : tf.pol_d3_1 ,
501 pol_d3_2 : tf.pol_d3_2 ,
502 pol_d3_3 : tf.pol_d3_3 ,
503 }
504 }
505}
506
507#[cfg_attr(feature="pybindings", pyfunction)]
508pub fn create_trk_transfer_fn_table( db_path: &str, transfer_fns: Vec<TrackerStripTransferFunction>) {
509 use schema::tof_db_trackerstriptransferfunction::dsl::*;
510 let mut conn = SqliteConnection::establish(db_path).ok().unwrap();
511 let mut _query_result = diesel::sql_query("
512 CREATE TABLE IF NOT EXISTS tof_db_trackerstriptransferfunction (
513 data_id INTEGER PRIMARY KEY AUTOINCREMENT,
514 strip_id INTEGER NOT NULL,
515 volume_id BIGINT NOT NULL,
516 utc_timestamp_start BIGINT NOT NULL,
517 utc_timestamp_stop BIGINT NOT NULL,
518 name TEXT,
519 pol_a2_0 FLOAT NOT NULL,
520 pol_a2_1 FLOAT NOT NULL,
521 pol_a2_2 FLOAT NOT NULL,
522 pol_b3_0 FLOAT NOT NULL,
523 pol_b3_1 FLOAT NOT NULL,
524 pol_b3_2 FLOAT NOT NULL,
525 pol_b3_3 FLOAT NOT NULL,
526 pol_c3_0 FLOAT NOT NULL,
527 pol_c3_1 FLOAT NOT NULL,
528 pol_c3_2 FLOAT NOT NULL,
529 pol_c3_3 FLOAT NOT NULL,
530 pol_d3_0 FLOAT NOT NULL,
531 pol_d3_1 FLOAT NOT NULL,
532 pol_d3_2 FLOAT NOT NULL,
533 pol_d3_3 FLOAT NOT NULL
534 )
535 ").execute(&mut conn);
536 let mut new_data = Vec::<NewTrackerStripTransferFunction>::new();
537 for p in transfer_fns {
538 let np = NewTrackerStripTransferFunction::from(&p);
539 new_data.push(np);
540 }
541 println!("Will insert {} tfns!", new_data.len());
542 _query_result = diesel::insert_into(tof_db_trackerstriptransferfunction)
543 .values(&new_data)
544 .execute(&mut conn);
545 println!("Inserted {}", _query_result.unwrap());
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[test]
553 fn trk_transfer_fn_derivative() {
554 let mut tf = TrackerStripTransferFunction::new();
556 (tf.pol_a2_0, tf.pol_a2_1, tf.pol_a2_2) = (1.97, 1.098, 0.0018);
557 (tf.pol_b3_0, tf.pol_b3_1, tf.pol_b3_2, tf.pol_b3_3) = (-853.71, 10.29, -0.0322, 4.48e-5);
558 (tf.pol_c3_0, tf.pol_c3_1, tf.pol_c3_2, tf.pol_c3_3) = (5585.65, -13.69, -0.0104, 4.6e-5);
559 (tf.pol_d3_0, tf.pol_d3_1, tf.pol_d3_2, tf.pol_d3_3) = (-29596.45, 25.56, 0.028, 2.1e-6);
560 for adc in [50.0f32, 150.0, 300.0, 450.0, 600.0, 800.0, 1000.0, 1500.0] {
562 let h = 0.5f32;
563 let numeric = (tf.evaluate(adc + h) - tf.evaluate(adc - h))/(2.0*h);
564 let exact = tf.derivative(adc);
565 assert!((numeric - exact).abs() < 1e-3*exact.abs().max(1.0), "adc {adc}: {numeric} != {exact}");
566 }
567 }
568}