Skip to main content

gondola_core/calibration/
tracker.rs

1//! The following file is part of gaps-online-software and published 
2//! under the GPLv3 license
3//!
4//! Calibration routines for the GAPS tracker system
5
6use crate::prelude::*;
7
8#[cfg_attr(feature="pybindings", pyclass)] 
9pub struct TrackerOfflineCalibration {
10  pub mask_map      : HashMap<u32,TrackerStripMask>, 
11  pub tf_map        : HashMap<u32,TrackerStripTransferFunction>, 
12  pub ped_map       : HashMap<u32,TrackerStripPedestal>,
13  pub gain_map      : HashMap<u32,TrackerStripGain>,
14  pub pulse_map     : HashMap<u32,TrackerStripPulse>,
15  pub adc_sig_cut   : HashMap<u32,f32>,
16  pub remove_cmn    : bool,
17  pub ped_sigma_cut : f32,
18}
19
20impl TrackerOfflineCalibration {
21
22  pub fn new() -> Self {
23    Self {
24      mask_map      : HashMap::<u32, TrackerStripMask>::new(),
25      tf_map        : HashMap::<u32, TrackerStripTransferFunction>::new(), 
26      ped_map       : HashMap::<u32, TrackerStripPedestal>::new(),
27      adc_sig_cut   : HashMap::<u32,f32>::new(),
28      gain_map      : HashMap::<u32,TrackerStripGain>::new(),
29      pulse_map     : HashMap::<u32,TrackerStripPulse>::new(),
30      remove_cmn    : false,
31      ped_sigma_cut : 0.0,
32    }
33  }
34
35  /// Calculate the common noise level, according to the research of the GAPS tracker group
36  ///
37  /// General scheme is to find the pulsed channel on the strip, get the pulse value, 
38  /// subtract the pedestal and subtract it from the hit adc (taking gain into account)
39  pub fn get_common_noise(&self, hit : &TrackerHit, event_hits : &Vec<TrackerHit>) -> (f32, bool) {
40    let mut cmn_level     = 0.0f32;
41    // per default gains are 1 if they can not be looked up
42    let strip_gain     : f32;
43    let mut pulse_gain = 1.0f32; 
44    let mut pulse_avg  = 0.0f32;
45    let mut pulse_chn  = -1i32;
46    let mut pulse_adc  = 0.0f32;
47    let is_pulser      : bool;
48    //let mut pulse_is_mean = false;
49    if let Some(cmn_strip) = self.gain_map.get(&hit.get_stripid()) {
50      strip_gain = cmn_strip.gain;
51    } else {
52      debug!("There is no entry for the strip gain for {}, default is 1.0", &hit.get_stripid());
53      strip_gain = 1.0;
54    }
55    if let Some(pulse_chn_) = self.pulse_map.get(&hit.get_stripid()) { 
56      pulse_chn  = pulse_chn_.pulse_chn;  
57      pulse_avg  = pulse_chn_.pulse_avg;
58      //pulse_is_mean = pulse_chn_.pulse_is_mean;
59    }
60    is_pulser = pulse_chn == hit.channel as i32;
61    if pulse_chn < 0 || pulse_avg > 400.0 {
62      return (0.0, is_pulser) 
63    }
64    let pulse_id = TrackerStrip::create_stripid(hit.layer, hit.row, hit.module, pulse_chn as u8);
65    // now we need to find the hit in this event which is caused by the pulser 
66    let mut p_hit  = TrackerHit::new();
67    p_hit.layer    = hit.layer;
68    p_hit.row      = hit.row;
69    p_hit.module   = hit.module;
70    p_hit.channel  = pulse_chn as u8;
71    let mut found  = false;
72    for h in event_hits {
73      if h.get_stripid() == p_hit.get_stripid() {
74        pulse_adc = h.adc as f32;
75        found = true;
76        break; // FIXME - there might be multiple hits
77      }
78    }
79    if let Some(pulse_gain_) = self.gain_map.get(&pulse_id) {
80      pulse_gain = pulse_gain_.gain; 
81    } 
82    if found {
83      let adc_pulc_diff = pulse_adc - pulse_avg;
84      if adc_pulc_diff < 250.0 && pulse_avg > 0.0 {
85        cmn_level = adc_pulc_diff / pulse_gain;   
86      }
87    } 
88    debug!("Calculated common level of {} gain {}", cmn_level, strip_gain);
89    if cmn_level < 0.0 {
90      //error!("CMN is negative! {}", cmn_level);
91      //cmn_level = 0.0;
92    }
93    return (cmn_level * strip_gain, is_pulser);  
94  }
95
96  pub fn mask_hits(&self, event_hits : &mut Vec<TrackerHit>) {
97    let mut active_strips = Vec::<u32>::new();
98    for h in event_hits.iter() {
99      if let Some(mask) = self.mask_map.get(&h.get_stripid()) {
100        if mask.active {
101          active_strips.push(h.get_stripid());
102        }
103      } else {
104        warn!("No mask information for strip {}", h.get_stripid());
105      }
106    }
107    event_hits.retain(|x| active_strips.contains(&x.get_stripid()));
108  }
109
110  pub fn calibrate_event(&self, event : &mut TelemetryEvent, remove_pulsed : bool) -> Result<(),CalibrationError> {
111    self.calibrate(&mut event.tracker_hits, remove_pulsed)?;
112    Ok(())
113  }
114
115  /// The actual energy calibration of the individual tracker strips 
116  ///
117  /// This is a multistep process which includes 
118  /// 1) Pedestal subtraction
119  /// 2) Common noise reduction (if so desired) 
120  /// 3) ADC -> Energy (Transfer functions) 
121  /// 3) Deal with strips which had the pulser active 
122  ///
123  /// While this might not be the best way to do things, this 
124  /// function matches the implementation in SimpleDet very 
125  /// closely and produces the same results. 
126  ///
127  /// See also the compontents in the `database` related part 
128  /// of this code.
129  ///
130  /// # Arguments:
131  ///   * remove_pulsed: If true, remove pulser hits with adc > 400
132  pub fn calibrate(&self, event_hits : &mut Vec<TrackerHit>, remove_pulsed : bool) -> Result<(),CalibrationError> {
133    let mut calibrated_hits = Vec::<TrackerHit>::with_capacity(event_hits.len());
134    let mut c_hit : TrackerHit; //= TrackerHit::new();
135    let mv_2_kev = 0.841f32;// mV to keV
136    for hit in event_hits.iter() {
137      let mut hit_ped = 0.0f32;
138      let mut energy  = hit.adc as f32;
139      let hit_tf  : Option<&TrackerStripTransferFunction>;
140      if let Some(ped) = self.ped_map.get(&hit.get_stripid()) {
141        hit_ped = ped.pedestal_mean;
142        energy -= hit_ped;
143        //if energy < self.ped_sigma_cut * ped.pedestal_sigma {
144        //  // this basically means that the energy is within the given 
145        //  // range of the pedestal. In this case, we set it basiccally to 0 
146        //  //
147        //  // Note - we don't raise the error, because this simply means this 
148        //  // is a noisy strip!
149        //  //return Ok(());i
150        //  continue;
151        //}
152      } else {
153        error!("No entry for {} in pedestal map", hit);
154        //continue;
155        //return Err(CalibrationError::NoPedestalAvailable); 
156      }
157      let mut hit_is_pulser = false;
158      if self.remove_cmn {
159        let cmn = self.get_common_noise(hit, event_hits); 
160        energy -= cmn.0;
161        hit_is_pulser = cmn.1;
162      }
163      // apply transfer functions. They are only defined up to
164      // TrackerStripTransferFunction::MAX_ADC, so larger values
165      // saturate there
166      hit_tf = self.tf_map.get(&hit.get_stripid());
167      if let Some(tf) = hit_tf {
168        //println!("energy before : {}", energy);
169        energy = tf.evaluate(energy.min(TrackerStripTransferFunction::MAX_ADC));
170        //println!("energy after : {}", energy);
171      } else {
172        error!("Trying to calibrate {}, but we don't have a transfer function for that!", hit.get_stripid());
173        energy = 0.0;
174        //return Err(CalibrationError::NoTransferFnAvailable);
175      }
176      // now we need to check if this is a pulsed channel 
177      if hit_is_pulser {
178        if let Some(pulse) = self.pulse_map.get(&hit.get_stripid()) {
179          let mut p_avg = pulse.pulse_avg; 
180          if p_avg > 0.0 {
181            if p_avg > 400.0 && remove_pulsed {
182              continue;
183            }
184            p_avg -= hit_ped;
185            if let Some(tf) = hit_tf {
186              p_avg = tf.evaluate(p_avg.min(TrackerStripTransferFunction::MAX_ADC));
187              energy -= p_avg;
188            }
189          }
190        } else {
191          warn!("Hit is from the pulser, but we don't have any information about that strip in the cmn map!"); 
192        }
193      }
194      c_hit = hit.clone();
195      energy       *= mv_2_kev/1000.0; 
196      c_hit.energy = energy;
197      //println!("c_hit {}", c_hit);
198      calibrated_hits.push(c_hit);
199      //if energy < -0.13 {
200      //  error!("Small energy!");
201      //  error!("{}", c_hit);
202      //}
203    }
204    event_hits.clear(); 
205    *event_hits = calibrated_hits;
206    Ok(())
207  }
208}
209
210impl fmt::Display for TrackerOfflineCalibration {
211  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212    let mut repr = String::from("<TrackerOfflineCalibration:");
213    repr += &(format!("\n  N masks  : {}", self.mask_map.len()));
214    repr += &(format!("\n  N pedest : {}", self.ped_map.len()));
215    repr += &(format!("\n  N tf_fns : {}", self.tf_map.len()));
216    repr += &(format!("\n  N gains  : {}", self.gain_map.len()));
217    repr += &(format!("\n  N pulses : {}", self.pulse_map.len()));
218    repr += ">";
219    write!(f, "{}", repr)
220  }
221}
222
223#[cfg(feature="pybindings")] 
224#[pymethods]
225impl TrackerOfflineCalibration {
226 
227  #[pyo3(name="calibrate_hits")]
228  fn calibrate_hits_py(&self, mut hits : Vec<TrackerHit>, remove_pulsed : bool) -> Vec<TrackerHit> {
229    let _ = self.calibrate(&mut hits, remove_pulsed);
230    hits 
231  }
232   
233  // all the getters/setters are here because I did not get
234  // #[cfg_attr(feature="pybindings", pyo3(set,get)] 
235  // to work. If we find out how to use that, get rid 
236  // of all the getters/setters here
237
238  #[getter]
239  #[pyo3(name="remove_cmn")] 
240  fn get_remove_cmn_py(&self) -> bool {
241    self.remove_cmn
242  }
243  #[getter]
244  #[pyo3(name="ped_sigma_cut")] 
245  fn get_ped_sigma_cut_py(&self) -> f32 {
246    self.ped_sigma_cut
247  }
248 
249  #[setter]
250  #[pyo3(name="remove_cmn")] 
251  fn set_remove_cmn_py(&mut self, value : bool) {
252    self.remove_cmn = value;
253  }
254
255  #[setter]
256  #[pyo3(name="ped_sigma_cut")] 
257  fn set_ped_sigma_cut_py(&mut self, value : f32) {
258    self.ped_sigma_cut = value;
259  }
260
261  #[getter]
262  #[pyo3(name="mask_map")]
263  fn get_mask_map_py(&self) -> HashMap<u32,TrackerStripMask> {
264    self.mask_map.clone()
265  }
266  
267  #[setter]
268  #[pyo3(name="mask_map")]
269  fn set_mask_map_py(&mut self, value : HashMap<u32,TrackerStripMask>) {
270    self.mask_map = value;
271  }
272  
273  #[getter]
274  #[pyo3(name="tf_map")]
275  fn get_tf_map_py(&self) -> HashMap<u32,TrackerStripTransferFunction> {
276    self.tf_map.clone()
277  }
278  #[setter]
279  #[pyo3(name="tf_map")]
280  fn set_tf_map_py(&mut self, value : HashMap<u32, TrackerStripTransferFunction>) {
281    self.tf_map = value;
282  }
283
284  #[getter]
285  #[pyo3(name="ped_map")]
286  fn get_ped_map_py(&self) -> HashMap<u32,TrackerStripPedestal> {
287    self.ped_map.clone()
288  }
289  #[setter] 
290  #[pyo3(name="ped_map")]
291  fn set_ped_map_py(&mut self, value : HashMap<u32,TrackerStripPedestal>) {
292    self.ped_map = value;
293  }
294
295  #[getter]
296  #[pyo3(name="pulse_map")]
297  fn get_pulse_map_py(&self) -> HashMap<u32, TrackerStripPulse> {
298    self.pulse_map.clone()
299  }
300  
301  #[setter]
302  #[pyo3(name="pulse_map")]
303  fn set_pulse_map_py(&mut self, value : HashMap<u32,TrackerStripPulse>) {
304    self.pulse_map = value;
305  }
306  
307  #[getter]
308  #[pyo3(name="gain_map")]
309  fn get_gain_map_py(&self) -> HashMap<u32, TrackerStripGain> {
310    self.gain_map.clone()
311  }
312  #[setter]
313  #[pyo3(name="gain_map")]
314  fn set_gain_map_py(&mut self, value : HashMap<u32,TrackerStripGain>) {
315    self.gain_map = value;
316  }
317
318  #[getter]
319  #[pyo3(name="adc_sig_cut")]
320  fn get_adc_sig_cut_py(&self) -> HashMap<u32,f32> {
321    self.adc_sig_cut.clone()
322  }
323  #[setter]
324  #[pyo3(name="adc_sig_cut")]
325  fn set_adc_sig_cut_py(&mut self, value : HashMap<u32,f32>) {
326    self.adc_sig_cut = value;
327  }
328}
329
330#[cfg(feature="pybindings")]
331pythonize!(TrackerOfflineCalibration);
332
333#[cfg(test)]
334mod tests {
335  use super::*;
336
337  #[test]
338  fn tracker_calibration_saturates_at_max_adc() {
339    let mut cali = TrackerOfflineCalibration::new();
340    let mut hit  = TrackerHit::new();
341    (hit.layer, hit.row, hit.module, hit.channel) = (1, 2, 3, 4);
342    let sid = hit.get_stripid();
343    let mut ped = TrackerStripPedestal::new();
344    ped.pedestal_mean = 100.0;
345    cali.ped_map.insert(sid, ped);
346    let mut tf = TrackerStripTransferFunction::new();
347    (tf.pol_d3_0, tf.pol_d3_1) = (10.0, 2.0);
348    cali.tf_map.insert(sid, tf.clone());
349    // adc - pedestal = 1800 is beyond the transfer function
350    hit.adc = 1900;
351    let mut hits = vec![hit.clone()];
352    cali.calibrate(&mut hits, false).unwrap();
353    let at_max = tf.evaluate(TrackerStripTransferFunction::MAX_ADC)*0.841/1000.0;
354    assert!(at_max > 0.0);
355    assert!((hits[0].energy - at_max).abs() < 1e-6);
356    // within the range, the transfer function is used as it is
357    hit.adc = 1100;
358    let mut hits = vec![hit];
359    cali.calibrate(&mut hits, false).unwrap();
360    assert!((hits[0].energy - tf.evaluate(1000.0)*0.841/1000.0).abs() < 1e-6);
361  }
362}