Skip to main content

nereids_io/
live.rs

1//! Live fractions of a Timepix-1 frame-mode run.
2//!
3//! A pixel records one count per shutter, so a neutron in bin `k` is recorded
4//! only if the pixel had no count earlier in that shutter:
5//! `L_k = 1 − Σ_{j<k} C_j / S`, with `C_j` the pixel's counts in bin `j` of the
6//! shutter and `S` its triggers that carried beam.
7//!
8//! # References
9//! A. S. Tremsin et al., JINST 9 (2014) C05026;
10//! K. Watanabe et al., Nucl. Instrum. Methods A 861 (2017) 55, Eqs. 1–5.
11
12use ndarray::{Array3, ArrayView3, Axis, Zip};
13
14use crate::error::IoError;
15use crate::fits_stack::Shutter;
16
17/// Each frame's shutter: the last one opening by the frame's start, within rounding.
18///
19/// A frame that ends after the next shutter opens is refused: its counts mix
20/// two shutters.
21fn shutter_of_frames(edges_us: &[f64], shutters: &[Shutter]) -> Result<Vec<usize>, IoError> {
22    let width = edges_us
23        .windows(2)
24        .map(|w| w[1] - w[0])
25        .fold(f64::INFINITY, f64::min);
26    let slack = 1e-6 * width;
27    edges_us
28        .windows(2)
29        .enumerate()
30        .map(|(k, w)| {
31            let i = shutters
32                .iter()
33                .rposition(|s| s.start_us - slack <= w[0])
34                .filter(|&i| w[0] < shutters[i].end_us)
35                .ok_or_else(|| {
36                    IoError::InvalidParameter(format!(
37                        "frame {k} starts at {} µs, outside every shutter",
38                        w[0]
39                    ))
40                })?;
41            match shutters.get(i + 1) {
42                Some(next) if w[1] > next.start_us + slack => {
43                    Err(IoError::InvalidParameter(format!(
44                        "frame {k} ends at {} µs, after shutter {} opens at {} µs",
45                        w[1],
46                        i + 1,
47                        next.start_us
48                    )))
49                }
50                _ => Ok(i),
51            }
52        })
53        .collect()
54}
55
56/// Live fractions of each pixel in each bin, by the counts before it in its shutter.
57///
58/// `shutters[i].triggers` should count the pulses that reached the detector
59/// while shutter `i` was open; triggers without beam make `L` too large.
60///
61/// # Arguments
62/// * `counts` — Raw counts in (time bin, row, column), finite and 0 or more.
63/// * `edges_us` — Time-bin edges in µs, ascending, one more than the bins.
64/// * `shutters` — The run's shutters; each bin starts inside one and ends by the next.
65///
66/// # Returns
67/// `L` in (time bin, row, column), each in (0, 1].
68///
69/// # Errors
70/// [`IoError::ShapeMismatch`] if `counts` is empty or `edges_us` does not fit it;
71/// [`IoError::InvalidParameter`] if a count is invalid, a bin starts outside
72/// every shutter or ends after the next opens, shutters overlap, or a pixel's
73/// counts in a shutter reach its triggers.
74pub fn live_fractions(
75    counts: ArrayView3<f64>,
76    edges_us: &[f64],
77    shutters: &[Shutter],
78) -> Result<Array3<f64>, IoError> {
79    let bins = counts.len_of(Axis(0));
80    if edges_us.len() != bins + 1 || counts.is_empty() {
81        return Err(IoError::ShapeMismatch(format!(
82            "{} time-bin edges for {bins} bins",
83            edges_us.len()
84        )));
85    }
86    if let Some(v) = counts.iter().find(|v| !(v.is_finite() && **v >= 0.0)) {
87        return Err(IoError::InvalidParameter(format!(
88            "counts must be finite and 0 or more, got {v}"
89        )));
90    }
91    if edges_us.iter().any(|t| !t.is_finite()) || edges_us.windows(2).any(|w| w[1] <= w[0]) {
92        return Err(IoError::InvalidParameter(
93            "time-bin edges must be finite and ascending".into(),
94        ));
95    }
96    if let Some(s) = shutters.iter().find(|s| {
97        !(s.start_us.is_finite()
98            && s.end_us.is_finite()
99            && s.start_us < s.end_us
100            && s.triggers.is_finite()
101            && s.triggers > 0.0)
102    }) {
103        return Err(IoError::InvalidParameter(format!(
104            "a shutter needs finite times, start before end, and triggers, got {s:?}"
105        )));
106    }
107    if shutters.windows(2).any(|w| w[1].start_us < w[0].end_us) {
108        return Err(IoError::InvalidParameter(
109            "shutters must be in time order and must not overlap".into(),
110        ));
111    }
112    let owner = shutter_of_frames(edges_us, shutters)?;
113
114    let mut live = Array3::zeros(counts.raw_dim());
115    let mut before = ndarray::Array2::<f64>::zeros((counts.shape()[1], counts.shape()[2]));
116    for k in 0..bins {
117        let shutter = &shutters[owner[k]];
118        if k > 0 && owner[k] != owner[k - 1] {
119            before.fill(0.0);
120        }
121        Zip::from(live.index_axis_mut(Axis(0), k))
122            .and(&before)
123            .for_each(|l, &b| *l = 1.0 - b / shutter.triggers);
124        if let Some(((row, column), l)) = live
125            .index_axis(Axis(0), k)
126            .indexed_iter()
127            .find(|(_, l)| **l <= 0.0)
128        {
129            return Err(IoError::InvalidParameter(format!(
130                "pixel row {row}, column {column} has live fraction {l} in bin {k}: \
131                 its counts before the bin reach the shutter's {} triggers",
132                shutter.triggers
133            )));
134        }
135        before += &counts.index_axis(Axis(0), k);
136        if let Some(((row, column), b)) =
137            before.indexed_iter().find(|(_, b)| **b > shutter.triggers)
138        {
139            return Err(IoError::InvalidParameter(format!(
140                "pixel row {row}, column {column} has {b} counts by bin {k}, \
141                 more than the shutter's {} triggers",
142                shutter.triggers
143            )));
144        }
145    }
146    Ok(live)
147}
148
149/// The standard deviation of a live fraction `L` from a binomial count of hits.
150///
151/// # References
152/// K. Watanabe et al., Nucl. Instrum. Methods A 861 (2017) 55, Eqs. 4–5.
153pub fn live_fraction_sigma(live: f64, triggers: f64) -> f64 {
154    (live * (1.0 - live) / triggers).sqrt()
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use ndarray::Array3;
161
162    fn shutter(start_us: f64, end_us: f64, triggers: f64) -> Shutter {
163        Shutter {
164            start_us,
165            end_us,
166            triggers,
167        }
168    }
169
170    #[test]
171    fn a_bin_sees_the_counts_before_it_in_its_shutter() {
172        let counts = Array3::from_shape_vec((4, 1, 1), vec![2.0, 3.0, 5.0, 4.0]).unwrap();
173        let shutters = [shutter(0.0, 3.0, 10.0), shutter(3.0, 4.0, 8.0)];
174        let live = live_fractions(counts.view(), &[0.0, 1.0, 2.0, 3.0, 4.0], &shutters).unwrap();
175        assert_eq!(live.as_slice().unwrap(), &[1.0, 0.8, 0.5, 1.0]);
176
177        let near = [shutter(0.0, 1.0, 10.0), shutter(1.0, 2.0, 10.0)];
178        let two = Array3::from_shape_vec((2, 1, 1), vec![2.0, 3.0]).unwrap();
179        assert!(live_fractions(two.view(), &[0.0, 0.9995, 1.9995], &near).is_err());
180
181        let with_gap = [shutter(0.0, 0.9, 10.0), shutter(1.0, 2.0, 10.0)];
182        let live = live_fractions(two.view(), &[0.0, 0.9999995, 1.9999995], &with_gap).unwrap();
183        assert_eq!(live[[1, 0, 0]], 1.0);
184    }
185
186    #[test]
187    fn counts_that_reach_the_triggers_or_a_bin_outside_the_shutters_are_refused() {
188        let counts = Array3::from_shape_vec((2, 1, 1), vec![10.0, 1.0]).unwrap();
189        let edges = [0.0, 1.0, 2.0];
190        assert!(live_fractions(counts.view(), &edges, &[shutter(0.0, 2.0, 10.0)]).is_err());
191        assert!(live_fractions(counts.view(), &edges, &[shutter(0.0, 1.0, 20.0)]).is_err());
192        assert!(live_fractions(counts.view(), &edges[..2], &[shutter(0.0, 2.0, 20.0)]).is_err());
193        let last = Array3::from_shape_vec((2, 1, 1), vec![6.0, 6.0]).unwrap();
194        assert!(live_fractions(last.view(), &edges, &[shutter(0.0, 2.0, 10.0)]).is_err());
195        let overlap = [shutter(0.0, 2.0, 10.0), shutter(1.0, 3.0, 100.0)];
196        assert!(live_fractions(counts.view(), &edges, &overlap).is_err());
197    }
198
199    /// Recorded counts of a pixel that keeps the first neutron of each shutter.
200    fn first_hits(rates: &[f64], shutters: &[(usize, usize, u64)], seed: u64) -> Vec<f64> {
201        let mut state = seed;
202        let mut uniform = move || {
203            state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
204            let mut z = state;
205            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
206            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
207            ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64
208        };
209        let mut counts = vec![0.0; rates.len()];
210        for &(first, end, triggers) in shutters {
211            let cumulative: Vec<f64> = rates[first..end]
212                .iter()
213                .scan(0.0, |sum, r| {
214                    *sum += r;
215                    Some(*sum)
216                })
217                .collect();
218            for _ in 0..triggers {
219                let arrival = -(1.0 - uniform()).ln();
220                let k = cumulative.partition_point(|&c| c <= arrival);
221                if k < cumulative.len() {
222                    counts[first + k] += 1.0;
223                }
224            }
225        }
226        counts
227    }
228
229    #[test]
230    fn the_live_fraction_recovers_the_arrivals_of_first_hit_counts() {
231        let bins = 400;
232        let rates: Vec<f64> = (0..bins)
233            .map(|k| match k {
234                0..5 => 0.01,
235                5..200 => 1.2e-3,
236                _ => 1.5e-3,
237            })
238            .collect();
239        let triggers = [400_000_u64, 300_000];
240        let recorded = first_hits(
241            &rates,
242            &[(0, 200, triggers[0]), (200, bins, triggers[1])],
243            7,
244        );
245        let shutters = [
246            shutter(0.0, 200.0, triggers[0] as f64),
247            shutter(200.0, bins as f64, triggers[1] as f64),
248        ];
249        let edges: Vec<f64> = (0..=bins).map(|k| k as f64).collect();
250        let counts = Array3::from_shape_vec((bins, 1, 1), recorded.clone()).unwrap();
251        let live = live_fractions(counts.view(), &edges, &shutters).unwrap();
252        assert_eq!(live[[200, 0, 0]], 1.0);
253
254        // A recorded count in bin k needs one arrival there, P = 1 − exp(−r_k).
255        for group in (0..bins).step_by(20) {
256            let range = group..group + 20;
257            let s = if group < 200 {
258                triggers[0]
259            } else {
260                triggers[1]
261            } as f64;
262            let truth: f64 = range.clone().map(|k| s * -(-rates[k]).exp_m1()).sum();
263            let found: f64 = range.clone().map(|k| recorded[k] / live[[k, 0, 0]]).sum();
264            let raw: f64 = range.clone().map(|k| recorded[k]).sum();
265            let sigma = raw.sqrt() * found / raw;
266            assert!(
267                (found - truth).abs() < 4.0 * sigma,
268                "bins {range:?}: {found} arrivals found, {truth} expected, σ {sigma}"
269            );
270            if (60..200).contains(&group) || group >= 260 {
271                assert!(
272                    (raw - truth).abs() > 5.0 * sigma,
273                    "bins {range:?} lose too little"
274                );
275            }
276        }
277    }
278}