Skip to main content

nereids_io/
fits_stack.rs

1//! Raw Timepix-1 frame-mode runs: FITS frames, frame times and shutters.
2//!
3//! A run folder holds `<prefix>_<chunk>_<frame>.fits`, one image of raw
4//! counts per time bin, and per chunk the sidecars `_Spectra.txt` (frame
5//! start times in s), `_ShutterTimes.txt` (index, gap before the shutter
6//! and its length, in s) and `_ShutterCount.txt` (index, triggers).
7
8use std::path::{Path, PathBuf};
9
10use ndarray::{Array2, Array3};
11
12use crate::error::IoError;
13use crate::spectrum::{MICROSECONDS_PER_SECOND, read_tof_sidecar};
14
15const BLOCK: usize = 2880;
16const CARD: usize = 80;
17
18/// One shutter of a frame-mode run.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Shutter {
21    /// Opening time after the trigger, in µs.
22    pub start_us: f64,
23    /// Closing time after the trigger, in µs.
24    pub end_us: f64,
25    /// Times the shutter opened.
26    pub triggers: f64,
27}
28
29/// One chunk of a raw frame-mode run.
30#[derive(Debug, Clone)]
31pub struct FitsRun {
32    /// Raw counts in (time bin, row, column), rows in file order.
33    pub counts: Array3<f64>,
34    /// Time-bin edges in µs, one more than the bins.
35    pub edges_us: Vec<f64>,
36    /// The run's shutters in time order.
37    pub shutters: Vec<Shutter>,
38}
39
40impl FitsRun {
41    /// Limits each shutter's triggers to the pulses that carried beam.
42    ///
43    /// The camera triggers on every pulse, with or without protons, so a run
44    /// paused with the beam off has more triggers than neutron pulses.
45    ///
46    /// # Errors
47    /// [`IoError::InvalidParameter`] unless `pulses` is a whole number above 0.
48    pub fn limit_to_beam_pulses(&mut self, pulses: f64) -> Result<(), IoError> {
49        if !(pulses > 0.0 && pulses.is_finite() && pulses.fract() == 0.0) {
50            return Err(IoError::InvalidParameter(format!(
51                "beam pulses must be a whole number above 0, got {pulses}"
52            )));
53        }
54        for shutter in &mut self.shutters {
55            shutter.triggers = shutter.triggers.min(pulses);
56        }
57        Ok(())
58    }
59}
60
61/// Read the primary image of a FITS file as counts in (row, column).
62///
63/// # Errors
64/// [`IoError::FileNotFound`] if the file cannot be read;
65/// [`IoError::InvalidParameter`] if the primary image is not 2-D with an
66/// integer `BITPIX` of 8, 16 or 32, `BZERO` or `BSCALE` is not whole, the
67/// file is short, or a count is not within 0 to 2^53.
68pub fn read_fits_image(path: &Path) -> Result<Array2<f64>, IoError> {
69    let name = path.to_string_lossy();
70    let bytes =
71        std::fs::read(path).map_err(|e| IoError::FileNotFound(name.clone().into_owned(), e))?;
72    let bad = |what: String| IoError::InvalidParameter(format!("FITS file {name}: {what}"));
73
74    let mut cards = bytes.as_chunks::<CARD>().0.iter();
75    let mut keys: Vec<(String, String)> = Vec::new();
76    let mut header = 0;
77    loop {
78        let card = cards.next().ok_or_else(|| bad("no END card".into()))?;
79        header += CARD;
80        let text = std::str::from_utf8(card.as_slice())
81            .ok()
82            .filter(|t| t.is_ascii())
83            .ok_or_else(|| bad(format!("header card {} is not ASCII", header / CARD)))?;
84        let key = text[..8].trim().to_string();
85        if key == "END" {
86            break;
87        }
88        if text.get(8..10) == Some("= ") {
89            let value = text[10..]
90                .split('/')
91                .next()
92                .unwrap_or("")
93                .trim()
94                .to_string();
95            keys.push((key, value));
96        }
97    }
98    let header = header.div_ceil(BLOCK) * BLOCK;
99    let number = |key: &str| -> Result<Option<f64>, IoError> {
100        keys.iter()
101            .find(|(k, _)| k == key)
102            .map(|(_, v)| {
103                v.parse::<f64>()
104                    .map_err(|_| bad(format!("{key} = {v} is not a number")))
105            })
106            .transpose()
107    };
108    let required = |key: &str| number(key)?.ok_or_else(|| bad(format!("no {key}")));
109
110    if keys.first().map(|(k, v)| (k.as_str(), v.as_str())) != Some(("SIMPLE", "T")) {
111        return Err(bad("first card is not SIMPLE = T".into()));
112    }
113    if required("NAXIS")? != 2.0 {
114        return Err(bad("the primary image is not 2-D".into()));
115    }
116    let axis = |key: &str| -> Result<usize, IoError> {
117        let v = required(key)?;
118        if v >= 1.0 && v <= f64::from(u32::MAX) && v.fract() == 0.0 {
119            Ok(v as usize)
120        } else {
121            Err(bad(format!("{key} = {v} is not a positive whole number")))
122        }
123    };
124    let (width, height) = (axis("NAXIS1")?, axis("NAXIS2")?);
125    let size = match required("BITPIX")? {
126        8.0 => 1,
127        16.0 => 2,
128        32.0 => 4,
129        b => return Err(bad(format!("BITPIX {b} is not raw integer counts"))),
130    };
131    // Counts are whole, so whole scaling gives them exactly.
132    const EXACT: f64 = (1u64 << 53) as f64;
133    // Read from the text, since a decimal near a whole number rounds to it in f64.
134    let whole = |key: &str, default: i128| -> Result<i128, IoError> {
135        let Some((_, text)) = keys.iter().find(|(k, _)| k == key) else {
136            return Ok(default);
137        };
138        let (int, frac) = text.split_once('.').unwrap_or((text, ""));
139        let digits = int.trim_start_matches(['+', '-']);
140        let v = (!digits.is_empty()
141            && digits.bytes().all(|b| b.is_ascii_digit())
142            && frac.bytes().all(|b| b == b'0'))
143        .then(|| int.parse::<i128>().ok())
144        .flatten()
145        .filter(|v| (-(EXACT as i128)..=EXACT as i128).contains(v));
146        v.ok_or_else(|| bad(format!("{key} = {text} is not a whole number up to 2^53")))
147    };
148    let (zero, scale) = (whole("BZERO", 0)?, whole("BSCALE", 1)?);
149    let data = width
150        .checked_mul(height)
151        .and_then(|n| n.checked_mul(size))
152        .and_then(|n| bytes.get(header..header.checked_add(n)?))
153        .ok_or_else(|| bad(format!("shorter than its {width} × {height} image")))?;
154
155    let mut values = Vec::with_capacity(width * height);
156    for (i, b) in data.chunks_exact(size).enumerate() {
157        let raw = match size {
158            1 => i128::from(b[0]),
159            2 => i128::from(i16::from_be_bytes([b[0], b[1]])),
160            _ => i128::from(i32::from_be_bytes([b[0], b[1], b[2], b[3]])),
161        };
162        let v = zero + scale * raw;
163        if !(0..=EXACT as i128).contains(&v) {
164            return Err(bad(format!(
165                "count {v} at row {}, column {} is not within 0 to 2^53",
166                i / width,
167                i % width
168            )));
169        }
170        values.push(v as f64);
171    }
172    let image = Array2::from_shape_vec((height, width), values).map_err(|e| bad(e.to_string()))?;
173    Ok(image)
174}
175
176/// The `(prefix, chunk, frame)` of a file named `<prefix>_<chunk>_<frame>.fits`.
177fn name_parts(path: &Path) -> Option<(String, String, usize)> {
178    let stem = path.file_name()?.to_str()?.strip_suffix(".fits")?;
179    let (rest, frame) = stem.rsplit_once('_')?;
180    let (prefix, chunk) = rest.rsplit_once('_')?;
181    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
182    if !(digits(chunk) && digits(frame)) {
183        return None;
184    }
185    Some((prefix.to_string(), chunk.to_string(), frame.parse().ok()?))
186}
187
188fn sidecar(dir: &Path, prefix: &str, chunk: &str, suffix: &str) -> Result<PathBuf, IoError> {
189    let path = dir.join(format!("{prefix}_{chunk}_{suffix}"));
190    if path.is_file() {
191        Ok(path)
192    } else {
193        Err(IoError::InvalidParameter(format!(
194            "no sidecar {}",
195            path.display()
196        )))
197    }
198}
199
200fn rows(path: &Path, columns: usize) -> Result<Vec<Vec<f64>>, IoError> {
201    let text = std::fs::read_to_string(path)
202        .map_err(|e| IoError::FileNotFound(path.to_string_lossy().into_owned(), e))?;
203    text.lines()
204        .filter(|l| !l.trim().is_empty())
205        .map(|l| {
206            let row: Option<Vec<f64>> = l
207                .split_whitespace()
208                .map(|v| v.parse().ok().filter(|v: &f64| v.is_finite()))
209                .collect();
210            if let Some(row) = row.filter(|r| r.len() == columns) {
211                Ok(row)
212            } else {
213                Err(IoError::InvalidParameter(format!(
214                    "{}: '{l}' is not {columns} numbers",
215                    path.display()
216                )))
217            }
218        })
219        .collect()
220}
221
222/// Shutters from `_ShutterTimes.txt` and `_ShutterCount.txt`.
223///
224/// Rows are indexed 0 to n − 1; rows with no triggers and no length are
225/// unused shutters. Shutter `i`
226/// opens its gap after shutter `i − 1` closes; the first gap is from the
227/// trigger.
228fn read_shutters(times: &Path, count: &Path) -> Result<Vec<Shutter>, IoError> {
229    let times = rows(times, 3)?;
230    let count = rows(count, 2)?;
231    let mut shutters = Vec::new();
232    let mut closed = 0.0;
233    for (i, (t, c)) in times.iter().zip(&count).enumerate() {
234        let (gap, length, triggers) = (t[1], t[2], c[1]);
235        if t[0] != i as f64 || c[0] != i as f64 {
236            return Err(IoError::InvalidParameter(format!(
237                "shutter row {i} has index {} and {}",
238                t[0], c[0]
239            )));
240        }
241        if length == 0.0 && triggers == 0.0 {
242            continue;
243        }
244        if !(gap >= 0.0 && length > 0.0 && triggers > 0.0 && triggers.fract() == 0.0) {
245            return Err(IoError::InvalidParameter(format!(
246                "shutter row {i}: gap {gap} s, length {length} s and {triggers} triggers \
247                 do not describe a used shutter"
248            )));
249        }
250        let start = closed + gap;
251        closed = start + length;
252        let shutter = Shutter {
253            start_us: start * MICROSECONDS_PER_SECOND,
254            end_us: closed * MICROSECONDS_PER_SECOND,
255            triggers,
256        };
257        if !shutter.end_us.is_finite() {
258            return Err(IoError::InvalidParameter(format!(
259                "shutter row {i} closes at {} µs",
260                shutter.end_us
261            )));
262        }
263        shutters.push(shutter);
264    }
265    if times.len() != count.len() || shutters.is_empty() {
266        return Err(IoError::InvalidParameter(format!(
267            "{} shutter times and {} shutter counts with {} used shutters",
268            times.len(),
269            count.len(),
270            shutters.len()
271        )));
272    }
273    Ok(shutters)
274}
275
276/// Load one chunk of a single-shutter raw frame-mode run folder.
277///
278/// A last frame whose bin ends at the shutter's close is left out: in the
279/// VENUS runs of this kind it holds several times its neighbours' counts.
280///
281/// # Arguments
282/// * `dir` — The run folder.
283/// * `chunk` — The chunk to load; `None` when the folder holds one chunk.
284///
285/// # Errors
286/// [`IoError::NoMatchingFiles`] if no frames are found;
287/// [`IoError::InvalidParameter`] if `chunk` is `None` and the folder holds
288/// several chunks, the run has more than one shutter, the chunk's frames
289/// have two prefixes or are not numbered
290/// 0 to n − 1, a sidecar is missing or disagrees with the frames, or a frame
291/// is unreadable;
292/// [`IoError::DimensionMismatch`] if frame sizes differ.
293pub fn load_fits_run(dir: &Path, chunk: Option<&str>) -> Result<FitsRun, IoError> {
294    let mut frames: Vec<(String, String, usize, PathBuf)> = std::fs::read_dir(dir)
295        .map_err(|e| IoError::FileNotFound(dir.to_string_lossy().into_owned(), e))?
296        .filter_map(|e| e.ok().map(|e| e.path()))
297        .filter_map(|p| name_parts(&p).map(|(prefix, c, f)| (prefix, c, f, p)))
298        .collect();
299    let mut chunks: Vec<&str> = frames.iter().map(|(_, c, _, _)| c.as_str()).collect();
300    chunks.sort_unstable();
301    chunks.dedup();
302    let chunk = match (chunk, chunks.as_slice()) {
303        (Some(c), _) => c.to_string(),
304        (None, [one]) => one.to_string(),
305        (None, []) => {
306            return Err(IoError::NoMatchingFiles {
307                directory: dir.to_string_lossy().into_owned(),
308                pattern: "<prefix>_<chunk>_<frame>.fits".into(),
309            });
310        }
311        (None, many) => {
312            return Err(IoError::InvalidParameter(format!(
313                "{} holds chunks {many:?}; name the one to load",
314                dir.display()
315            )));
316        }
317    };
318    frames.retain(|(_, c, _, _)| *c == chunk);
319    frames.sort_by_key(|(_, _, f, _)| *f);
320    if frames.is_empty() {
321        return Err(IoError::NoMatchingFiles {
322            directory: dir.to_string_lossy().into_owned(),
323            pattern: format!("<prefix>_{chunk}_<frame>.fits"),
324        });
325    }
326    if let Some((i, (_, _, f, _))) = frames.iter().enumerate().find(|(i, (_, _, f, _))| f != i) {
327        return Err(IoError::InvalidParameter(format!(
328            "chunk {chunk} frame {f} is at position {i}; frames must be numbered 0 to n − 1"
329        )));
330    }
331    let prefix = frames[0].0.clone();
332    if let Some((other, _, f, _)) = frames.iter().find(|(p, _, _, _)| *p != prefix) {
333        return Err(IoError::InvalidParameter(format!(
334            "chunk {chunk} frame {f} is named {other}, not {prefix}"
335        )));
336    }
337
338    let mut edges_us = read_tof_sidecar(
339        &sidecar(dir, &prefix, &chunk, "Spectra.txt")?,
340        Some(frames.len()),
341    )?;
342    let shutters = read_shutters(
343        &sidecar(dir, &prefix, &chunk, "ShutterTimes.txt")?,
344        &sidecar(dir, &prefix, &chunk, "ShutterCount.txt")?,
345    )?;
346    if let [_, _, ..] = shutters.as_slice() {
347        return Err(IoError::InvalidParameter(format!(
348            "{} shutters: the fit's contiguous bins cannot yet skip the closed time between \
349             shutters",
350            shutters.len()
351        )));
352    }
353    // A last frame ending at the shutter's close holds several times its neighbours' counts.
354    let bins = frames.len();
355    let width = edges_us[bins] - edges_us[bins - 1];
356    let kept = if bins > 1 && edges_us[bins] >= shutters[0].end_us - 1e-6 * width {
357        edges_us.pop();
358        bins - 1
359    } else {
360        bins
361    };
362
363    let first = read_fits_image(&frames[0].3)?;
364    let (height, width) = first.dim();
365    let mut counts = Array3::zeros((kept, height, width));
366    counts.index_axis_mut(ndarray::Axis(0), 0).assign(&first);
367    for (k, (_, _, _, path)) in frames.iter().enumerate().take(kept).skip(1) {
368        let image = read_fits_image(path)?;
369        if image.dim() != (height, width) {
370            return Err(IoError::DimensionMismatch {
371                expected: (width as u32, height as u32),
372                got: (image.ncols() as u32, image.nrows() as u32),
373                frame: k,
374            });
375        }
376        counts.index_axis_mut(ndarray::Axis(0), k).assign(&image);
377    }
378
379    Ok(FitsRun {
380        counts,
381        edges_us,
382        shutters,
383    })
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    fn card(text: &str) -> String {
391        format!("{text:<80}")
392    }
393
394    /// A FITS file of 16-bit values `raw` stored with `BZERO = zero`.
395    fn fits(width: usize, raw: &[i16], zero: f64) -> Vec<u8> {
396        let mut header = [
397            card("SIMPLE  =                    T"),
398            card("BITPIX  =                   16"),
399            card("NAXIS   =                    2"),
400            card(&format!("NAXIS1  = {width:>20}")),
401            card(&format!("NAXIS2  = {:>20}", raw.len() / width)),
402            card(&format!("BZERO   = {zero:>20} / offset")),
403            card("END"),
404        ]
405        .concat()
406        .into_bytes();
407        header.resize(BLOCK, b' ');
408        header.extend(raw.iter().flat_map(|v| v.to_be_bytes()));
409        header.resize(header.len().div_ceil(BLOCK) * BLOCK, 0);
410        header
411    }
412
413    #[test]
414    fn a_fits_image_reads_in_row_order_with_its_offset() {
415        let dir = tempfile::tempdir().unwrap();
416        let path = dir.path().join("a.fits");
417        std::fs::write(&path, fits(3, &[0, 1, 2, -32768, 5, 7], 32768.0)).unwrap();
418        let image = read_fits_image(&path).unwrap();
419        assert_eq!(image.dim(), (2, 3));
420        assert_eq!(image.row(0).to_vec(), vec![32768.0, 32769.0, 32770.0]);
421        assert_eq!(image.row(1).to_vec(), vec![0.0, 32773.0, 32775.0]);
422
423        std::fs::write(&path, fits(2, &[3, -1], 0.0)).unwrap();
424        assert!(read_fits_image(&path).is_err());
425
426        std::fs::write(&path, fits(1, &[1], 0.5)).unwrap();
427        assert!(read_fits_image(&path).is_err());
428
429        let mut scaled = fits(1, &[100], 0.0);
430        scaled[5 * 80..6 * 80].copy_from_slice(card("BSCALE  =                 0.07").as_bytes());
431        std::fs::write(&path, scaled).unwrap();
432        assert!(read_fits_image(&path).is_err());
433
434        let mut near = fits(1, &[-1], 1e15);
435        near[6 * 80..8 * 80]
436            .copy_from_slice((card("BSCALE  =   999999999999999.99") + &card("END")).as_bytes());
437        std::fs::write(&path, near).unwrap();
438        assert!(read_fits_image(&path).is_err());
439
440        let mut least = fits(1, &[2], 0.0);
441        least[6 * 80..8 * 80].copy_from_slice(
442            (card("BSCALE  = -170141183460469231731687303715884105728") + &card("END")).as_bytes(),
443        );
444        std::fs::write(&path, least).unwrap();
445        assert!(read_fits_image(&path).is_err());
446
447        let mut cancel = fits(1, &[-1], 1e15);
448        cancel[6 * 80..8 * 80]
449            .copy_from_slice((card("BSCALE  =    999999999999999.5") + &card("END")).as_bytes());
450        std::fs::write(&path, cancel).unwrap();
451        assert!(read_fits_image(&path).is_err());
452
453        let mut doubled = fits(1, &[3], 1.0);
454        doubled[6 * 80..8 * 80]
455            .copy_from_slice((card("BSCALE  =                    2") + &card("END")).as_bytes());
456        std::fs::write(&path, doubled).unwrap();
457        assert_eq!(read_fits_image(&path).unwrap()[[0, 0]], 7.0);
458
459        let mut large = fits(1, &[1], 1e9);
460        large[6 * 80..8 * 80]
461            .copy_from_slice((card("BSCALE  =                  0.5") + &card("END")).as_bytes());
462        std::fs::write(&path, large).unwrap();
463        assert!(read_fits_image(&path).is_err());
464
465        let mut half = fits(3, &[0, 1, 2, 3, 4, 5], 0.0);
466        half[3 * 80 + 27..3 * 80 + 30].copy_from_slice(b"1.5");
467        std::fs::write(&path, half).unwrap();
468        assert!(read_fits_image(&path).is_err());
469    }
470
471    fn write_run(dir: &Path, chunk: &str, frames: &[[i16; 2]]) {
472        for (k, f) in frames.iter().enumerate() {
473            let name = format!("run_0_{chunk}_{k:05}.fits");
474            std::fs::write(dir.join(name), fits(2, f, 0.0)).unwrap();
475        }
476        std::fs::write(
477            dir.join(format!("run_0_{chunk}_SummedImg.fits")),
478            fits(2, &[9, 9], 0.0),
479        )
480        .unwrap();
481        let spectra = "1e-06\t5\r\n2e-06\t6\r\n3e-06\t7\r\n4.5e-06\t1\r\n";
482        std::fs::write(dir.join(format!("run_0_{chunk}_Spectra.txt")), spectra).unwrap();
483        let times = "0\t1e-06\t6e-06\r\n1\t0\t0\r\n";
484        std::fs::write(dir.join(format!("run_0_{chunk}_ShutterTimes.txt")), times).unwrap();
485        let count = "0\t100\r\n1\t0\r\n";
486        std::fs::write(dir.join(format!("run_0_{chunk}_ShutterCount.txt")), count).unwrap();
487    }
488
489    #[test]
490    fn a_run_loads_its_frames_edges_and_shutters() {
491        let dir = tempfile::tempdir().unwrap();
492        write_run(dir.path(), "114", &[[1, 2], [3, 4], [5, 6], [7, 8]]);
493        let run = load_fits_run(dir.path(), None).unwrap();
494        assert_eq!(run.counts.shape(), &[4, 1, 2]);
495        assert_eq!(run.counts[[3, 0, 1]], 8.0);
496        assert_eq!(run.edges_us.len(), 5);
497        let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
498        for (&edge, expected) in run.edges_us.iter().zip([1.0, 2.0, 3.0, 4.5, 6.0]) {
499            assert!(close(edge, expected));
500        }
501        let [s] = run.shutters[..] else {
502            panic!("one shutter")
503        };
504        assert!(close(s.start_us, 1.0) && close(s.end_us, 7.0) && s.triggers == 100.0);
505
506        let mut paused = run.clone();
507        paused.limit_to_beam_pulses(95.0).unwrap();
508        assert_eq!(paused.shutters[0].triggers, 95.0);
509        assert!(paused.limit_to_beam_pulses(0.5).is_err());
510    }
511
512    #[test]
513    fn a_last_frame_ending_at_the_close_is_left_out_and_two_shutters_are_refused() {
514        let dir = tempfile::tempdir().unwrap();
515        write_run(dir.path(), "114", &[[1, 2], [3, 4], [5, 6], [7, 8]]);
516        let times = dir.path().join("run_0_114_ShutterTimes.txt");
517        std::fs::write(&times, "0\t1e-06\t5e-06\r\n1\t0\t0\r\n").unwrap();
518        std::fs::write(
519            dir.path().join("run_0_114_00003.fits"),
520            fits(2, &[-1, 8], 0.0),
521        )
522        .unwrap();
523        let run = load_fits_run(dir.path(), None).unwrap();
524        assert_eq!(run.counts.shape(), &[3, 1, 2]);
525        assert_eq!(run.edges_us.len(), 4);
526        assert!((run.edges_us[3] - 4.5).abs() < 1e-9);
527
528        std::fs::write(&times, "0\t1e-06\t2.5e-06\r\n1\t5e-07\t2e-06\r\n").unwrap();
529        let count = dir.path().join("run_0_114_ShutterCount.txt");
530        std::fs::write(&count, "0\t100\r\n1\t90\r\n").unwrap();
531        assert!(load_fits_run(dir.path(), None).is_err());
532    }
533
534    #[test]
535    fn a_folder_of_two_chunks_needs_the_chunk_named() {
536        let dir = tempfile::tempdir().unwrap();
537        write_run(dir.path(), "118", &[[1, 2], [3, 4], [5, 6], [7, 8]]);
538        write_run(dir.path(), "119", &[[1, 2], [3, 4], [5, 6], [7, 8]]);
539        assert!(load_fits_run(dir.path(), None).is_err());
540        assert_eq!(
541            load_fits_run(dir.path(), Some("119"))
542                .unwrap()
543                .counts
544                .shape()[0],
545            4
546        );
547
548        std::fs::remove_file(dir.path().join("run_0_118_00002.fits")).unwrap();
549        assert!(load_fits_run(dir.path(), Some("118")).is_err());
550        std::fs::write(
551            dir.path().join("other_0_118_00002.fits"),
552            fits(2, &[1, 1], 0.0),
553        )
554        .unwrap();
555        assert!(load_fits_run(dir.path(), Some("118")).is_err());
556    }
557
558    #[test]
559    fn shutter_rows_need_every_index_and_whole_triggers() {
560        let dir = tempfile::tempdir().unwrap();
561        write_run(dir.path(), "114", &[[1, 2], [3, 4], [5, 6], [7, 8]]);
562        let count = dir.path().join("run_0_114_ShutterCount.txt");
563        let times = dir.path().join("run_0_114_ShutterTimes.txt");
564        std::fs::write(&count, "0\t100.5\r\n1\t0\r\n").unwrap();
565        assert!(load_fits_run(dir.path(), None).is_err());
566        std::fs::write(&count, "0\t100\r\n2\t90\r\n").unwrap();
567        std::fs::write(&times, "0\t1e-06\t2.5e-06\r\n2\t5e-07\t2e-06\r\n").unwrap();
568        assert!(load_fits_run(dir.path(), None).is_err());
569    }
570}