Skip to main content

openreadout_core/
model.rs

1//! The normalized metadata model. Field names follow the OME data model wherever one
2//! exists, so agents can rely on a single vocabulary across vendors.
3
4use std::collections::BTreeMap;
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::pixel::PixelType;
10use crate::provenance::{Confidence, ProvenanceMap};
11
12/// Static description of a format as the tool understands it.
13#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
14pub struct FormatDescriptor {
15    /// Short id used on the command line, e.g. `czi`.
16    pub id: String,
17    /// Human name, e.g. `Zeiss CZI`.
18    pub name: String,
19    /// Vendor (nominative use only).
20    pub vendor: String,
21    /// File extensions, lowercase, without the dot.
22    pub extensions: Vec<String>,
23    /// Family: `microscopy`, `mass-spectrometry`, `flow-cytometry`, ...
24    pub family: String,
25    /// True when the tool can read this format.
26    pub can_read: bool,
27    /// True when `export` can also write this format (e.g. mzML, OME-Zarr).
28    pub can_write: bool,
29    /// Overall confidence in this reader.
30    pub confidence: Confidence,
31    /// Things this reader knowingly does not handle yet.
32    pub known_gaps: Vec<String>,
33}
34
35/// Physical pixel size in micrometres (the OME default unit). Every present value is > 0.
36#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
37pub struct PhysicalSize {
38    /// Pixel width in µm (the distance between neighbouring columns).
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub x: Option<f64>,
41    /// Pixel height in µm (the distance between neighbouring rows).
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub y: Option<f64>,
44    /// Spacing between Z planes (focal slices) in µm.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub z: Option<f64>,
47    /// Always `µm` in this schema version.
48    pub unit: String,
49}
50
51impl PhysicalSize {
52    /// Sizes in µm. A size that is not a positive finite number (files store 0 for an axis
53    /// that was never calibrated, e.g. Y of a line scan or Z of a single plane) is dropped:
54    /// missing information is omitted, never encoded as 0 (`book/src/guides/metadata.md`).
55    pub fn micrometres(x: Option<f64>, y: Option<f64>, z: Option<f64>) -> Self {
56        let keep = |v: Option<f64>| v.filter(|v| v.is_finite() && *v > 0.0);
57        PhysicalSize {
58            x: keep(x),
59            y: keep(y),
60            z: keep(z),
61            unit: "µm".into(),
62        }
63    }
64    /// True when no axis is calibrated.
65    pub fn is_empty(&self) -> bool {
66        self.x.is_none() && self.y.is_none() && self.z.is_none()
67    }
68}
69
70/// One acquisition channel.
71#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
72pub struct ChannelInfo {
73    /// Zero-based channel index (the `c` of a plane).
74    pub index: u32,
75    /// Channel name as the acquisition software shows it.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub name: Option<String>,
78    /// Fluorescent dye or protein imaged in this channel (e.g. `DAPI`, `GFP`), if recorded.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub fluorophore: Option<String>,
81    /// Excitation wavelength in nanometres: the light used to make the sample fluoresce.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub excitation_nm: Option<f64>,
84    /// Emission wavelength in nanometres: the light collected from the sample. What the file
85    /// records varies by format (a dye's emission peak, a filter's centre, the start of a
86    /// spectral detection window for Leica λ scans); `docs/formats/<fmt>.md` says which. When
87    /// a detection band is known, `emission_band_*_nm` give it explicitly.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub emission_nm: Option<f64>,
90    /// Detection band `[start_nm, end_nm]` when the instrument records a range instead of a single emission wavelength.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub emission_range_nm: Option<[f64; 2]>,
93    /// Short-wavelength edge of the detection band in nanometres (spectral detector window or
94    /// emission filter), when the file records the band.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub emission_band_start_nm: Option<f64>,
97    /// Long-wavelength edge of the detection band in nanometres.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub emission_band_end_nm: Option<f64>,
100    /// Centre of the detection band in nanometres: (start + end) / 2.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub emission_band_center_nm: Option<f64>,
103    /// Display colour as `#RRGGBB` if the file records one.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub color: Option<String>,
106    /// Acquisition mode as a readable label, `<technique>[ <contrast>]` (e.g. `Laser Scanning
107    /// Confocal`, `Widefield Fluorescence`, `Brightfield`, `Phase Contrast`); OME enumeration
108    /// tokens (`WideField`) are turned into these labels, other vendor wording is kept.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub acquisition_mode: Option<String>,
111    /// Exposure (integration) time of the detector in milliseconds.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub exposure_ms: Option<f64>,
114}
115
116/// The objective lens.
117#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
118pub struct ObjectiveInfo {
119    /// Objective model name as the vendor records it.
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub model: Option<String>,
122    /// Nominal magnification (e.g. `63` for a 63× lens).
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub nominal_magnification: Option<f64>,
125    /// Numerical aperture.
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub lens_na: Option<f64>,
128    /// Immersion medium between lens and sample (`Oil`, `Water`, `Air`, ...).
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub immersion: Option<String>,
131}
132
133/// The instrument and software that produced the file.
134#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
135pub struct InstrumentInfo {
136    /// Instrument manufacturer.
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub manufacturer: Option<String>,
139    /// Instrument model (e.g. microscope stand or mass spectrometer).
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub model: Option<String>,
142    /// Acquisition software.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub software: Option<String>,
145    /// Version of the acquisition software.
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub software_version: Option<String>,
148    /// Detector (camera or photomultiplier) name.
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub detector: Option<String>,
151}
152
153/// Mosaic (tiled/stitched) acquisition summary.
154#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
155pub struct MosaicInfo {
156    /// Number of tiles (fields of view) in the mosaic.
157    pub tile_count: u32,
158    /// Width of one tile in pixels, when all tiles share it.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub tile_width: Option<u32>,
161    /// Height of one tile in pixels, when all tiles share it.
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub tile_height: Option<u32>,
164    /// Whether the reader stitches tiles into a single plane on read.
165    pub stitched_on_read: bool,
166}
167
168/// One image (a scene, series, or position) inside the file.
169#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
170pub struct ImageInfo {
171    /// Zero-based index used by `--image`.
172    pub index: u32,
173    /// Image (scene, series or position) name, if recorded.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub name: Option<String>,
176    /// Width in pixels.
177    pub size_x: u32,
178    /// Height in pixels.
179    pub size_y: u32,
180    /// Number of Z planes (focal slices).
181    pub size_z: u32,
182    /// Number of channels.
183    pub size_c: u32,
184    /// Number of time points.
185    pub size_t: u32,
186    /// Storage order of planes, e.g. `XYCZT` (X and Y always first).
187    pub dimension_order: String,
188    /// Sample type of every plane.
189    pub pixel_type: PixelType,
190    /// 1 for grayscale channels, 3 for interleaved RGB.
191    pub samples_per_pixel: u32,
192    /// Physical size of one pixel (and the Z step).
193    pub physical_size: PhysicalSize,
194    /// Interval between time points in seconds.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub time_increment_s: Option<f64>,
197    /// One entry per channel, in channel order.
198    pub channels: Vec<ChannelInfo>,
199    /// The objective lens, if recorded.
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub objective: Option<ObjectiveInfo>,
202    /// Instrument and software, if recorded.
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub instrument: Option<InstrumentInfo>,
205    /// ISO-8601 acquisition start, if recorded.
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub acquired_at: Option<String>,
208    /// Tile layout when the image was acquired as a mosaic.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub mosaic: Option<MosaicInfo>,
211    /// Number of resolution levels stored (1 = no pyramid).
212    pub pyramid_levels: u32,
213    /// Size, downsampling and stored tile size of every resolution level, level 0 first. Filled
214    /// by readers of pyramidal or tiled images (read a level with `--level N`, a rectangle
215    /// with `--region X,Y,W,H`); empty otherwise.
216    #[serde(default, skip_serializing_if = "Vec::is_empty")]
217    pub resolution_levels: Vec<crate::region::ResolutionLevel>,
218    /// `size_z * size_c * size_t`.
219    pub plane_count: u64,
220    /// Format-specific extras that have no OME equivalent, in our own vocabulary.
221    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
222    pub extra: BTreeMap<String, serde_json::Value>,
223}
224
225impl ImageInfo {
226    /// A blank image with the given geometry; callers fill the rest.
227    pub fn new(index: u32, size_x: u32, size_y: u32, pixel_type: PixelType) -> Self {
228        ImageInfo {
229            index,
230            name: None,
231            size_x,
232            size_y,
233            size_z: 1,
234            size_c: 1,
235            size_t: 1,
236            dimension_order: "XYCZT".into(),
237            pixel_type,
238            samples_per_pixel: 1,
239            physical_size: PhysicalSize::micrometres(None, None, None),
240            time_increment_s: None,
241            channels: Vec::new(),
242            objective: None,
243            instrument: None,
244            acquired_at: None,
245            mosaic: None,
246            pyramid_levels: 1,
247            resolution_levels: Vec::new(),
248            plane_count: 1,
249            extra: BTreeMap::new(),
250        }
251    }
252
253    /// Recompute `plane_count` from the dimensions, and fill each channel's explicit
254    /// detection band (`emission_band_*_nm`) from `emission_range_nm`.
255    pub fn finish(mut self) -> Self {
256        // Saturating: a corrupt header can declare sizes whose product exceeds u64.
257        self.plane_count = u64::from(self.size_z)
258            .saturating_mul(u64::from(self.size_c))
259            .saturating_mul(u64::from(self.size_t));
260        for c in &mut self.channels {
261            c.fill_band();
262            // One readable vocabulary for every reader (OME tokens → labels).
263            c.acquisition_mode = c
264                .acquisition_mode
265                .as_deref()
266                .and_then(crate::acquisition_mode::label);
267        }
268        // Unit conversions leave binary noise (1e-7 m × 1e6 = 0.09999999999999999 µm): keep
269        // 15 significant digits, which no instrument records more precisely.
270        for v in [
271            &mut self.physical_size.x,
272            &mut self.physical_size.y,
273            &mut self.physical_size.z,
274            &mut self.time_increment_s,
275        ] {
276            *v = v.map(round_noise);
277        }
278        if let Some(o) = &mut self.objective {
279            o.lens_na = o.lens_na.map(round_noise);
280            o.nominal_magnification = o.nominal_magnification.map(round_noise);
281        }
282        // Text fields are compared and exported as values: no padding, no blanks.
283        if let Some(o) = &mut self.objective {
284            o.model = trimmed(o.model.take());
285            o.immersion = o.immersion.as_deref().and_then(immersion_label);
286        }
287        if let Some(i) = &mut self.instrument {
288            for s in [
289                &mut i.manufacturer,
290                &mut i.model,
291                &mut i.software,
292                &mut i.software_version,
293                &mut i.detector,
294            ] {
295                *s = trimmed(s.take());
296            }
297        }
298        self
299    }
300}
301
302/// `v` to 15 significant digits: removes the last-bit noise of decimal conversions
303/// (`0.30000000000000004` → `0.3`). Non-finite values are returned unchanged.
304pub fn round_noise(v: f64) -> f64 {
305    if !v.is_finite() || v == 0.0 {
306        return v;
307    }
308    format!("{v:.14e}").parse().unwrap_or(v)
309}
310
311fn trimmed(s: Option<String>) -> Option<String> {
312    let s = s?;
313    let t = s.trim();
314    if t.is_empty() {
315        None
316    } else if t.len() == s.len() {
317        Some(s)
318    } else {
319        Some(t.to_string())
320    }
321}
322
323/// An objective's immersion medium in one spelling for every reader: `Oil`, `Water`, `Air`
324/// (also for `dry`), `Glycerol`, `Multi` or `Other`, matched without case (`DRY` → `Air`);
325/// other media (`Silicone`) are kept as written, trimmed. `None` for blank text.
326pub(crate) fn immersion_label(raw: &str) -> Option<String> {
327    let t = raw.trim();
328    if t.is_empty() {
329        return None;
330    }
331    Some(
332        match t.to_ascii_lowercase().as_str() {
333            "oil" => "Oil",
334            "water" => "Water",
335            "air" | "dry" => "Air",
336            "glycerol" | "glycerin" | "glycerine" => "Glycerol",
337            "multi" => "Multi",
338            "other" => "Other",
339            _ => t,
340        }
341        .to_string(),
342    )
343}
344
345impl ChannelInfo {
346    /// Set the detection band: `emission_range_nm` and `emission_band_{start,end,center}_nm`.
347    /// Ignored unless both edges are finite, positive and ordered.
348    pub fn set_band(&mut self, start_nm: f64, end_nm: f64) {
349        if start_nm.is_finite() && end_nm.is_finite() && start_nm > 0.0 && end_nm >= start_nm {
350            self.emission_range_nm = Some([start_nm, end_nm]);
351            self.emission_band_start_nm = Some(start_nm);
352            self.emission_band_end_nm = Some(end_nm);
353            self.emission_band_center_nm = Some(f64::midpoint(start_nm, end_nm));
354        }
355    }
356
357    /// Fill `emission_band_*_nm` from `emission_range_nm` when a reader set only the range.
358    pub fn fill_band(&mut self) {
359        if self.emission_band_start_nm.is_none()
360            && let Some([a, b]) = self.emission_range_nm
361        {
362            let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
363            if lo.is_finite() && hi.is_finite() {
364                self.emission_band_start_nm = Some(lo);
365                self.emission_band_end_nm = Some(hi);
366                self.emission_band_center_nm = Some(f64::midpoint(lo, hi));
367            }
368        }
369    }
370}
371
372/// Output of `info` (and the `file` part of `info --view full`).
373#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
374pub struct FileInfo {
375    /// The path as given by the caller.
376    pub path: String,
377    /// Size in bytes (for directory formats such as Bruker `.d`, the files that were read).
378    pub size_bytes: u64,
379    /// The format that read the file.
380    pub format: FormatDescriptor,
381    /// Version of the container format as written in the file, if any.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub format_version: Option<String>,
384    /// Images in the file (empty for tables, spectra and traces).
385    pub images: Vec<ImageInfo>,
386    /// Tabular datasets (flow cytometry events, ...). Empty for image formats.
387    #[serde(default, skip_serializing_if = "Vec::is_empty")]
388    pub tables: Vec<TableInfo>,
389    /// Mass-spectrometry runs. Empty for other formats.
390    #[serde(default, skip_serializing_if = "Vec::is_empty")]
391    pub spectra: Vec<SpectraInfo>,
392    /// Sampled-signal blocks (electrophysiology, chromatography, NMR). Empty for other formats.
393    #[serde(default, skip_serializing_if = "Vec::is_empty")]
394    pub traces: Vec<TraceInfo>,
395    /// Total planes across all images.
396    pub plane_count: u64,
397    /// Notes the reader wants the caller to see (e.g. "pyramid levels skipped").
398    #[serde(default, skip_serializing_if = "Vec::is_empty")]
399    pub notes: Vec<String>,
400}
401
402/// Output of `info --view full`.
403#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
404pub struct Dump {
405    /// What `info` reports, including the derived `experiment`.
406    pub file: crate::experiment::InfoOutput,
407    /// The vendor's own metadata tree, converted to JSON without renaming anything.
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub vendor: Option<serde_json::Value>,
410    /// Where each normalized field came from. Keys are JSON paths into `file`.
411    pub provenance: ProvenanceMap,
412}
413
414/// A file embedded in the container (thumbnail, label image, time stamps, ...).
415#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
416pub struct AttachmentInfo {
417    /// Zero-based index, usable with `extract FILE #<index>`.
418    pub index: u32,
419    /// Name as stored in the container (e.g. `Thumbnail`, `Label`).
420    pub name: String,
421    /// Content type as the file declares it (e.g. `JPG`, `CZI`, `CZTIMS`).
422    pub content_type: String,
423    /// Suggested file extension for the extracted bytes, without the dot.
424    pub extension: String,
425    /// Byte offset of the attachment payload in its file.
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub offset: Option<u64>,
428    /// Payload size in bytes.
429    pub size: u64,
430    /// Format-specific details in the reader's documented vocabulary.
431    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
432    pub extra: BTreeMap<String, serde_json::Value>,
433}
434
435/// Output of `extract`.
436#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
437pub struct ExtractOutput {
438    /// The input file.
439    pub path: String,
440    /// Format id of the input file.
441    pub format: String,
442    /// The attachment that was extracted.
443    pub attachment: AttachmentInfo,
444    /// Where the bytes were written.
445    pub output: String,
446    /// Number of bytes written.
447    pub bytes_written: u64,
448    /// xxh3-128 of the written bytes, 32 hex chars.
449    pub xxh3: String,
450    /// True once the output was read back and matched.
451    pub verified: bool,
452}
453
454/// One row of `info --view structure`: a structural element of the container.
455#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
456pub struct LsEntry {
457    /// `image`, `plane`, `segment`, `chunk`, `block`, `attachment`, `metadata`, `pyramid-level`, ...
458    pub kind: String,
459    /// Element name (an id, a chunk name or a path inside the container).
460    pub name: String,
461    /// Byte offset of the element in the file, when it has one.
462    #[serde(skip_serializing_if = "Option::is_none")]
463    pub offset: Option<u64>,
464    /// Size of the element in bytes, when known.
465    #[serde(skip_serializing_if = "Option::is_none")]
466    pub size: Option<u64>,
467    /// Which image this element belongs to, if any.
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub image: Option<u32>,
470    /// Format-specific details (JSON), omitted when empty.
471    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
472    pub details: serde_json::Value,
473}
474
475/// Output of `info --view structure`.
476#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
477pub struct Listing {
478    /// The input file.
479    pub path: String,
480    /// Format id of the input file.
481    pub format: String,
482    /// Container elements in file order.
483    pub entries: Vec<LsEntry>,
484    /// Present when the file is not finished: still being written (`in_progress`) or
485    /// stopped before the end (`interrupted`). See `book/src/guides/lab-shares.md`.
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub acquisition: Option<crate::live::Acquisition>,
488    /// How many elements of each kind the container holds, when `entries` lists only some.
489    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
490    pub entries_total: BTreeMap<String, u64>,
491    /// What was left out of `entries` and how to list it.
492    #[serde(default, skip_serializing_if = "Vec::is_empty")]
493    pub notes: Vec<String>,
494}
495
496impl Listing {
497    /// Keep the answer small: list at most `max` elements of each kind (`0`: all), or, with
498    /// `kind`, only elements of that kind, from the `first`-th one on. Large mosaics hold tens
499    /// of thousands of tiles, while the attachments a caller looks for come after them in file
500    /// order, so the cap applies per kind. What was left out is said in `entries_total` and
501    /// `notes`.
502    pub fn cap(&mut self, max: usize, kind: Option<&str>, first: usize) {
503        let mut totals: BTreeMap<String, u64> = BTreeMap::new();
504        for e in &self.entries {
505            *totals.entry(e.kind.clone()).or_default() += 1;
506        }
507        let total = self.entries.len();
508        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
509        self.entries.retain(|e| {
510            let n = seen.entry(e.kind.clone()).or_default();
511            let i = *n;
512            *n += 1;
513            match kind {
514                Some(k) => e.kind == k && i >= first && (max == 0 || i - first < max),
515                None => max == 0 || i < max,
516            }
517        });
518        if self.entries.len() == total {
519            return;
520        }
521        let left_out: Vec<String> = totals
522            .iter()
523            .filter_map(|(k, &n)| {
524                let shown = self.entries.iter().filter(|e| &e.kind == k).count() as u64;
525                (shown < n).then(|| format!("{k} {shown} of {n}"))
526            })
527            .collect();
528        self.notes.push(format!(
529            "entries lists part of the {total} elements ({}); pass kind and first_entry to page through one kind, or max_entries 0 for all",
530            left_out.join(", ")
531        ));
532        self.entries_total = totals;
533    }
534}
535
536/// Severity of a `check` finding.
537#[derive(
538    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
539)]
540#[serde(rename_all = "lowercase")]
541#[non_exhaustive]
542pub enum Severity {
543    /// Worth knowing; the file is fine.
544    Info,
545    /// Something unusual that does not stop the file from being read.
546    Warning,
547    /// The file is damaged or inconsistent; some data may be unreadable.
548    Error,
549}
550
551impl Severity {
552    /// The lowercase name used in JSON (`info`, `warning`, `error`).
553    pub fn as_str(self) -> &'static str {
554        match self {
555            Severity::Info => "info",
556            Severity::Warning => "warning",
557            Severity::Error => "error",
558        }
559    }
560}
561
562/// One `check` finding.
563#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
564pub struct Finding {
565    /// How serious the finding is.
566    pub severity: Severity,
567    /// Stable code, e.g. `truncated`, `bad_offset`, `missing_planes`, `directory_mismatch`.
568    pub code: String,
569    /// Plain-English description.
570    pub message: String,
571    /// Byte offset the finding refers to, if any.
572    #[serde(skip_serializing_if = "Option::is_none")]
573    pub offset: Option<u64>,
574}
575
576impl Finding {
577    /// A finding of severity `error` with a stable `code`.
578    pub fn error(code: &str, message: impl Into<String>) -> Self {
579        Finding {
580            severity: Severity::Error,
581            code: code.into(),
582            message: message.into(),
583            offset: None,
584        }
585    }
586    /// A finding of severity `warning` with a stable `code`.
587    pub fn warning(code: &str, message: impl Into<String>) -> Self {
588        Finding {
589            severity: Severity::Warning,
590            code: code.into(),
591            message: message.into(),
592            offset: None,
593        }
594    }
595    /// A finding of severity `info` with a stable `code`.
596    pub fn info(code: &str, message: impl Into<String>) -> Self {
597        Finding {
598            severity: Severity::Info,
599            code: code.into(),
600            message: message.into(),
601            offset: None,
602        }
603    }
604    /// Attach the byte offset the finding refers to.
605    pub fn at(mut self, offset: u64) -> Self {
606        self.offset = Some(offset);
607        self
608    }
609}
610
611/// Output of `check`.
612#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
613pub struct CheckReport {
614    /// The input file.
615    pub path: String,
616    /// Format id of the input file.
617    pub format: String,
618    /// True when no finding has severity `error`.
619    pub ok: bool,
620    /// What was verified, in plain words, so the caller knows what "ok" covers.
621    pub checks_performed: Vec<String>,
622    /// Everything found, in the order checked.
623    pub findings: Vec<Finding>,
624    /// Present when the file is not finished: still being written (`in_progress`: findings
625    /// about the unfinished tail are warnings and `ok` covers the complete part) or stopped
626    /// before the end (`interrupted`). See `book/src/guides/lab-shares.md`.
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub acquisition: Option<crate::live::Acquisition>,
629    /// Whether the file lies inside what its reader has been validated on (the same block as
630    /// `info` → `assurance`). `ok` says the file is intact; `assurance` says whether its values
631    /// can be trusted. Filled by the `check` command when the header can be read.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub assurance: Option<crate::assurance::Assurance>,
634}
635
636impl CheckReport {
637    /// An empty report that is `ok` until an error finding is pushed.
638    pub fn new(path: impl Into<String>, format: impl Into<String>) -> Self {
639        CheckReport {
640            path: path.into(),
641            format: format.into(),
642            ok: true,
643            checks_performed: Vec::new(),
644            findings: Vec::new(),
645            acquisition: None,
646            assurance: None,
647        }
648    }
649    /// Record a check that was carried out (shown under `checks_performed`).
650    pub fn performed(&mut self, what: impl Into<String>) {
651        self.checks_performed.push(what.into());
652    }
653    /// Add a finding; an `error` finding makes the report not `ok`.
654    pub fn push(&mut self, f: Finding) {
655        if f.severity == Severity::Error {
656            self.ok = false;
657        }
658        self.findings.push(f);
659    }
660}
661
662/// Output of `self formats`.
663#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
664pub struct FormatsOutput {
665    /// Every registered format, in detection order.
666    pub formats: Vec<FormatDescriptor>,
667}
668
669/// Output of `info --view format`.
670#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
671pub struct DetectOutput {
672    /// The input file.
673    pub path: String,
674    /// Format id, e.g. `czi`.
675    pub format: String,
676    /// Human name of the format, e.g. `Zeiss CZI`.
677    pub name: String,
678    /// How the format was recognised.
679    pub confidence: DetectConfidence,
680    /// Why detection is less than definite, if it is.
681    #[serde(skip_serializing_if = "Option::is_none")]
682    pub note: Option<String>,
683}
684
685/// How sure detection is.
686#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
687#[serde(rename_all = "kebab-case")]
688#[non_exhaustive]
689pub enum DetectConfidence {
690    /// A format-specific signature matched.
691    Definite,
692    /// Structure looks right but no unique signature exists.
693    Likely,
694    /// Only the file extension matched.
695    ExtensionOnly,
696}
697
698/// One row of `planes`.
699#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
700pub struct PlaneHash {
701    /// Image index.
702    pub image: u32,
703    /// Pyramid level (0 = full resolution); omitted when 0.
704    #[serde(default, skip_serializing_if = "is_zero")]
705    pub level: u32,
706    /// The rectangle read (level pixel coordinates) when `--region` was given; the hash and
707    /// `width`/`height` are then those of the region. Absent = the whole plane.
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    pub region: Option<crate::region::Region>,
710    /// Channel index.
711    pub c: u32,
712    /// Z index (focal plane).
713    pub z: u32,
714    /// Time index.
715    pub t: u32,
716    /// Plane width in pixels.
717    pub width: u32,
718    /// Plane height in pixels.
719    pub height: u32,
720    /// Sample type.
721    pub pixel_type: PixelType,
722    /// 1 for grayscale, 3 for interleaved RGB.
723    pub samples_per_pixel: u32,
724    /// xxh3-128 of the raw little-endian sample bytes, 32 hex chars.
725    pub xxh3: String,
726}
727
728#[allow(clippy::trivially_copy_pass_by_ref)]
729fn is_zero(v: &u32) -> bool {
730    *v == 0
731}
732
733/// Output of `planes`.
734#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
735pub struct PlanesOutput {
736    /// The input file.
737    pub path: String,
738    /// Format id of the input file.
739    pub format: String,
740    /// One row per plane, in the order read.
741    pub planes: Vec<PlaneHash>,
742    /// Present when the file is not finished; while it is `in_progress` only complete planes
743    /// are read. See `book/src/guides/lab-shares.md`.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub acquisition: Option<crate::live::Acquisition>,
746}
747
748// ---------- non-image data (flow cytometry events, mass-spectrometry spectra, ...) ----------
749
750/// A column of a tabular dataset (e.g. an FCS parameter).
751#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
752pub struct ColumnInfo {
753    /// Zero-based column index.
754    pub index: u32,
755    /// Short name (FCS `$PnN`).
756    pub name: String,
757    /// Descriptive label (FCS `$PnS`), if any.
758    #[serde(skip_serializing_if = "Option::is_none")]
759    pub label: Option<String>,
760    /// NumPy-style dtype of the values as returned by `read_table` (`float32`, `float64`, `uint32`, ...).
761    pub dtype: String,
762    /// Physical unit of the values, if the format records one.
763    #[serde(skip_serializing_if = "Option::is_none")]
764    pub unit: Option<String>,
765    /// Nominal `[min, max]` range when the format declares one.
766    #[serde(skip_serializing_if = "Option::is_none")]
767    pub range: Option<[f64; 2]>,
768    /// Format-specific column metadata in the reader's documented vocabulary.
769    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
770    pub extra: BTreeMap<String, serde_json::Value>,
771}
772
773/// A tabular dataset inside the file (rows × columns), e.g. FCS events.
774#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
775pub struct TableInfo {
776    /// Zero-based table index.
777    pub index: u32,
778    /// Table name, if the format has one.
779    #[serde(skip_serializing_if = "Option::is_none")]
780    pub name: Option<String>,
781    /// Number of rows (e.g. recorded events).
782    pub row_count: u64,
783    /// One entry per column.
784    pub columns: Vec<ColumnInfo>,
785    /// Format-specific table metadata in the reader's documented vocabulary.
786    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
787    pub extra: BTreeMap<String, serde_json::Value>,
788}
789
790/// Rows of a table, column-major: `columns[c][r]` as f64 (lossless for ≤ 32-bit inputs).
791#[derive(Debug, Clone, Default)]
792pub struct Table {
793    /// Table index.
794    pub table: u32,
795    /// Zero-based index of the first row in `columns`.
796    pub first_row: u64,
797    /// Column-major values: `columns[c][r]`.
798    pub columns: Vec<Vec<f64>>,
799}
800
801/// A slice of a table as rows, for JSON consumers (`openreadout_table`).
802#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
803pub struct TableSlice {
804    /// The input file.
805    pub path: String,
806    /// Format id of the input file.
807    pub format: String,
808    /// Table index (see `info` → `tables[]`).
809    pub table: u32,
810    /// Zero-based index of the first row returned.
811    pub first_row: u64,
812    /// Rows in the whole table.
813    pub total_rows: u64,
814    /// Column names (FCS `$PnN`).
815    pub columns: Vec<String>,
816    /// Column labels (FCS `$PnS`), `null` where absent.
817    pub labels: Vec<Option<String>>,
818    /// Row-major values; `rows[r][c]`. Non-finite values serialize as `null`. A text column
819    /// holds codes here; `texts` has its text.
820    pub rows: Vec<Vec<f64>>,
821    /// Text columns (`info` → `tables[].columns[].extra.categories`) by column name: the text
822    /// of each returned row, so `texts[name][r]` is what `rows[r][c]` codes. Absent when the
823    /// table has no text column.
824    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
825    pub texts: BTreeMap<String, Vec<String>>,
826    /// True when more rows follow the returned slice.
827    pub truncated: bool,
828    /// Present when the values were processed (FCS scale values, compensation, transforms,
829    /// population membership columns); absent for raw values.
830    #[serde(default, skip_serializing_if = "Option::is_none")]
831    pub processing: Option<crate::flow::TableProcessing>,
832    /// Present with `--where`/`--count`: the row conditions and how many rows of the whole
833    /// table meet them. `rows`, `first_row` and `truncated` then page through the matching rows.
834    #[serde(default, skip_serializing_if = "Option::is_none")]
835    pub filter: Option<TableFilterSummary>,
836}
837
838impl TableSlice {
839    /// Fill `texts` from the category lists of `table`'s text columns (codes past a list's end
840    /// read as empty text).
841    pub fn attach_texts(&mut self, table: &TableInfo) {
842        for (c, col) in table.columns.iter().enumerate() {
843            let Some(cats) = col.extra.get("categories").and_then(|v| v.as_array()) else {
844                continue;
845            };
846            let text = |v: f64| -> String {
847                if v.is_finite() && v >= 0.0 {
848                    cats.get(v as usize)
849                        .and_then(|t| t.as_str())
850                        .unwrap_or_default()
851                        .to_string()
852                } else {
853                    String::new()
854                }
855            };
856            let values = self
857                .rows
858                .iter()
859                .map(|r| r.get(c).copied().map(text).unwrap_or_default())
860                .collect();
861            self.texts.insert(col.name.clone(), values);
862        }
863    }
864}
865
866/// Rows of a whole table that meet every condition (`table --where`, `--count`).
867#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
868pub struct TableFilterSummary {
869    /// The conditions as parsed (`FITC-A > 1000`), all of which a row must meet. Empty with
870    /// `--count` alone (every row counts).
871    pub conditions: Vec<String>,
872    /// Rows of the whole table that meet every condition (not only the returned page).
873    pub matched_rows: u64,
874    /// Rows in the whole table.
875    pub total_rows: u64,
876    /// `matched_rows / total_rows × 100` (0 for an empty table).
877    pub percent: f64,
878    /// The values the conditions were tested on: `raw` (as stored) or `processed` (FCS scale
879    /// values after compensation/transforms; see `processing`).
880    pub values: String,
881}
882
883/// Output of `export --format csv`.
884#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
885pub struct TableExportReport {
886    /// The input file.
887    pub input: String,
888    /// The CSV file written.
889    pub output: String,
890    /// Always `csv` in this schema version.
891    pub format: String,
892    /// Table index written.
893    pub table: u32,
894    /// First row written (zero-based).
895    pub first_row: u64,
896    /// Data rows written.
897    pub rows_written: u64,
898    /// Columns written.
899    pub columns_written: u32,
900    /// Header lines before the data (1, or 2 with `--labels`).
901    pub header_lines: u32,
902    /// Size of the written file in bytes.
903    pub bytes_written: u64,
904    /// True when the written file was read back and every value parsed equal to the source.
905    pub verified: bool,
906}
907
908/// Output of `export --format csv` for a trace (one sweep: a time column plus one column per channel).
909#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
910pub struct TraceExportReport {
911    /// The input file.
912    pub input: String,
913    /// The CSV file written.
914    pub output: String,
915    /// Always `csv` in this schema version.
916    pub format: String,
917    /// Trace index written.
918    pub trace: u32,
919    /// Sweep index written.
920    pub sweep: u32,
921    /// First sample of the sweep written (zero-based).
922    pub first_sample: u64,
923    /// Samples (rows) written.
924    pub samples_written: u64,
925    /// Signal channels written (the time column is not counted).
926    pub channels_written: u32,
927    /// Size of the written file in bytes.
928    pub bytes_written: u64,
929    /// True when the written file was read back and every value parsed equal to the source.
930    pub verified: bool,
931}
932
933/// A collection of mass spectra (one acquisition run).
934#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
935pub struct SpectraInfo {
936    /// Zero-based run index.
937    pub index: u32,
938    /// Run name, if the file records one.
939    #[serde(skip_serializing_if = "Option::is_none")]
940    pub name: Option<String>,
941    /// Number of spectra (scans) in the run.
942    pub scan_count: u64,
943    /// MS levels present (1 = full scans, 2 = MS/MS, ...).
944    pub ms_levels: Vec<u32>,
945    /// Retention-time range in seconds.
946    #[serde(skip_serializing_if = "Option::is_none")]
947    pub rt_range_s: Option<[f64; 2]>,
948    /// Instrument and software, if recorded.
949    #[serde(skip_serializing_if = "Option::is_none")]
950    pub instrument: Option<InstrumentInfo>,
951    /// Format-specific run metadata in the reader's documented vocabulary.
952    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
953    pub extra: BTreeMap<String, serde_json::Value>,
954}
955
956/// One mass spectrum.
957#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
958pub struct Spectrum {
959    /// Zero-based spectrum index within its run.
960    pub index: u64,
961    /// Scan number as the instrument counts it (1-based in most formats).
962    pub scan_number: u64,
963    /// MS level: 1 for a full scan, 2 for a fragment (MS/MS) scan, and so on.
964    pub ms_level: u32,
965    /// Retention time in seconds; null when the file states none for this spectrum (never an
966    /// invented 0).
967    #[serde(default)]
968    pub rt_s: Option<f64>,
969    /// `positive`, `negative` or `unknown`.
970    pub polarity: String,
971    /// True when the peaks are centroids (one point per peak) rather than a sampled profile.
972    pub centroided: bool,
973    /// m/z of the precursor ion that was isolated and fragmented (MS2 and above).
974    #[serde(skip_serializing_if = "Option::is_none")]
975    pub precursor_mz: Option<f64>,
976    /// Charge state of the precursor, when the instrument determined it.
977    #[serde(skip_serializing_if = "Option::is_none")]
978    pub precursor_charge: Option<i32>,
979    /// Instrument scan filter or scan description string (e.g. Thermo `FTMS + p ESI Full ms`).
980    #[serde(skip_serializing_if = "Option::is_none")]
981    pub scan_filter: Option<String>,
982    /// Sum of all intensities in the spectrum (TIC).
983    #[serde(skip_serializing_if = "Option::is_none")]
984    pub total_ion_current: Option<f64>,
985    /// The spectrum's identifier in its file (mzML `id`, e.g. `controllerType=0 controllerNumber=1 scan=17`).
986    #[serde(default, skip_serializing_if = "Option::is_none")]
987    pub native_id: Option<String>,
988    /// m/z of the most intense peak.
989    #[serde(default, skip_serializing_if = "Option::is_none")]
990    pub base_peak_mz: Option<f64>,
991    /// Intensity of the most intense peak.
992    #[serde(default, skip_serializing_if = "Option::is_none")]
993    pub base_peak_intensity: Option<f64>,
994    /// Intensity of the selected precursor ion, when recorded.
995    #[serde(default, skip_serializing_if = "Option::is_none")]
996    pub precursor_intensity: Option<f64>,
997    /// Precursor isolation window `[lower, upper]` in m/z.
998    #[serde(default, skip_serializing_if = "Option::is_none")]
999    pub isolation_window_mz: Option<[f64; 2]>,
1000    /// Dissociation method: `CID`, `HCD`, `ETD`, `ECD`, `ETHCD`, `UVPD`, ... (upper case).
1001    #[serde(default, skip_serializing_if = "Option::is_none")]
1002    pub activation: Option<String>,
1003    /// Collision energy as recorded (usually eV, or % normalized for Thermo `@hcd35.00`).
1004    #[serde(default, skip_serializing_if = "Option::is_none")]
1005    pub collision_energy: Option<f64>,
1006    /// Ion mobility of the precursor or scan, as inverse reduced mobility 1/K0 in V·s/cm².
1007    #[serde(default, skip_serializing_if = "Option::is_none")]
1008    pub inverse_reduced_mobility: Option<f64>,
1009    /// Scan (acquisition) window `[lower, upper]` in m/z.
1010    #[serde(default, skip_serializing_if = "Option::is_none")]
1011    pub scan_window_mz: Option<[f64; 2]>,
1012    /// Format-specific scan metadata in the reader's documented vocabulary.
1013    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1014    pub extra: BTreeMap<String, serde_json::Value>,
1015    /// Mass-to-charge ratios of the points, ascending.
1016    pub mz: Vec<f64>,
1017    /// Intensity of each point (same length as `mz`).
1018    pub intensity: Vec<f32>,
1019}
1020
1021/// Output of `spectrum`: one spectrum with its arrays.
1022#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1023pub struct SpectrumOutput {
1024    /// The input file.
1025    pub path: String,
1026    /// Format id of the input file.
1027    pub format: String,
1028    /// Run index the spectrum belongs to.
1029    pub run: u32,
1030    /// `primary` (profile when recorded) or `centroid` (the instrument's centroid list).
1031    pub view: String,
1032    /// Number of points in the full spectrum (the arrays may be shortened by `max_points`).
1033    pub point_count: u64,
1034    /// True when `mz`/`intensity` were shortened to `max_points` (the most intense points are
1035    /// kept, in m/z order).
1036    pub truncated: bool,
1037    /// The most intense peaks of the whole spectrum, with charges from their isotope patterns.
1038    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1039    pub peaks: Vec<crate::scans::MsPeak>,
1040    /// The spectrum, with its arrays.
1041    pub spectrum: Spectrum,
1042}
1043
1044// ---------- sampled signals (electrophysiology sweeps, chromatograms, NMR FIDs) ----------
1045
1046/// One channel of a sampled-signal dataset.
1047#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1048pub struct SignalChannelInfo {
1049    /// Zero-based channel index.
1050    pub index: u32,
1051    /// Channel name as recorded.
1052    pub name: String,
1053    /// Physical unit of the scaled values (`pA`, `mV`, `AU`, ...).
1054    #[serde(skip_serializing_if = "Option::is_none")]
1055    pub unit: Option<String>,
1056    /// NumPy-style dtype of the raw stored samples.
1057    pub dtype: String,
1058    /// `value = raw * scale + offset` when the file stores integers.
1059    pub scale: f64,
1060    /// Added after scaling; see `scale`.
1061    pub offset: f64,
1062    /// Format-specific channel metadata in the reader's documented vocabulary.
1063    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1064    pub extra: BTreeMap<String, serde_json::Value>,
1065}
1066
1067/// A block of uniformly sampled signals (a sweep, a chromatogram run, an FID).
1068#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
1069pub struct TraceInfo {
1070    /// Zero-based trace index.
1071    pub index: u32,
1072    /// Trace name, if the format has one.
1073    #[serde(skip_serializing_if = "Option::is_none")]
1074    pub name: Option<String>,
1075    /// Samples per second.
1076    pub sample_rate_hz: f64,
1077    /// Samples per sweep (the longest sweep when sweeps differ; see `extra.sweep_sample_counts`).
1078    pub sample_count: u64,
1079    /// Number of sweeps/episodes stored back to back (1 for continuous recordings).
1080    pub sweep_count: u32,
1081    /// One entry per channel.
1082    pub channels: Vec<SignalChannelInfo>,
1083    /// Time of the first sample relative to the recording start, seconds.
1084    #[serde(skip_serializing_if = "Option::is_none")]
1085    pub start_s: Option<f64>,
1086    /// Format-specific trace metadata in the reader's documented vocabulary.
1087    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1088    pub extra: BTreeMap<String, serde_json::Value>,
1089}
1090
1091/// Samples of one trace: `channels[c][i]`, scaled to physical units as f64.
1092#[derive(Debug, Clone, Default)]
1093pub struct Trace {
1094    /// Trace index.
1095    pub trace: u32,
1096    /// Sweep index.
1097    pub sweep: u32,
1098    /// Index of the first sample in `channels` within the sweep.
1099    pub first_sample: u64,
1100    /// Scaled samples: `channels[c][i]`.
1101    pub channels: Vec<Vec<f64>>,
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::*;
1107
1108    fn listing(tiles: usize) -> Listing {
1109        let entry = |kind: &str, i: usize| LsEntry {
1110            kind: kind.into(),
1111            name: format!("{kind} {i}"),
1112            offset: Some(i as u64),
1113            size: None,
1114            image: None,
1115            details: serde_json::Value::Null,
1116        };
1117        let mut entries = vec![entry("header", 0)];
1118        entries.extend((0..tiles).map(|i| entry("tile", i)));
1119        entries.push(entry("attachment", 0));
1120        Listing {
1121            entries,
1122            ..Listing::default()
1123        }
1124    }
1125
1126    #[test]
1127    fn structure_listings_are_capped_per_kind() {
1128        // Few elements: nothing to say.
1129        let mut l = listing(3);
1130        l.cap(50, None, 0);
1131        assert_eq!(l.entries.len(), 5);
1132        assert!(l.entries_total.is_empty() && l.notes.is_empty());
1133        // Many tiles: the attachment after them is still listed.
1134        let mut l = listing(1000);
1135        l.cap(50, None, 0);
1136        assert_eq!(l.entries.len(), 52);
1137        assert_eq!(l.entries.last().unwrap().kind, "attachment");
1138        assert_eq!(l.entries_total["tile"], 1000);
1139        assert!(l.notes[0].contains("tile 50 of 1000"), "{:?}", l.notes);
1140        // Paging through one kind.
1141        let mut l = listing(1000);
1142        l.cap(10, Some("tile"), 995);
1143        let names: Vec<&str> = l.entries.iter().map(|e| e.name.as_str()).collect();
1144        assert_eq!(
1145            names,
1146            ["tile 995", "tile 996", "tile 997", "tile 998", "tile 999"]
1147        );
1148        // 0 lists everything.
1149        let mut l = listing(1000);
1150        l.cap(0, None, 0);
1151        assert_eq!(l.entries.len(), 1002);
1152    }
1153
1154    #[test]
1155    #[allow(clippy::float_cmp)]
1156    fn finish_removes_conversion_noise() {
1157        let mut im = ImageInfo::new(0, 1, 1, PixelType::Uint8);
1158        im.physical_size = PhysicalSize::micrometres(Some(1e-7 * 1e6), Some(0.1 + 0.2), None);
1159        im.objective = Some(ObjectiveInfo {
1160            lens_na: Some(0.1 * 3.0),
1161            ..ObjectiveInfo::default()
1162        });
1163        let im = im.finish();
1164        assert_eq!(im.physical_size.x, Some(0.1));
1165        assert_eq!(im.physical_size.y, Some(0.3));
1166        assert_eq!(im.objective.unwrap().lens_na, Some(0.3));
1167        assert_eq!(round_noise(0.123_456_789_012_345_67), 0.123_456_789_012_346);
1168        assert!(round_noise(f64::NAN).is_nan());
1169    }
1170
1171    #[test]
1172    fn finish_normalizes_modes_immersion_and_padding() {
1173        let mut im = ImageInfo::new(0, 1, 1, PixelType::Uint8);
1174        im.channels = vec![ChannelInfo {
1175            acquisition_mode: Some("LaserScanningConfocalMicroscopy".into()),
1176            ..ChannelInfo::default()
1177        }];
1178        im.objective = Some(ObjectiveInfo {
1179            model: Some("HC PL APO 10x/0.40 DRY ".into()),
1180            immersion: Some("DRY".into()),
1181            ..ObjectiveInfo::default()
1182        });
1183        im.instrument = Some(InstrumentInfo {
1184            software: Some(" LAS X".into()),
1185            detector: Some("  ".into()),
1186            ..InstrumentInfo::default()
1187        });
1188        let im = im.finish();
1189        assert_eq!(
1190            im.channels[0].acquisition_mode.as_deref(),
1191            Some("Laser Scanning Confocal")
1192        );
1193        let o = im.objective.unwrap();
1194        assert_eq!(o.model.as_deref(), Some("HC PL APO 10x/0.40 DRY"));
1195        assert_eq!(o.immersion.as_deref(), Some("Air"));
1196        let i = im.instrument.unwrap();
1197        assert_eq!(i.software.as_deref(), Some("LAS X"));
1198        assert_eq!(i.detector, None);
1199        assert_eq!(immersion_label("water").as_deref(), Some("Water"));
1200        assert_eq!(immersion_label("Silicone").as_deref(), Some("Silicone"));
1201    }
1202
1203    #[test]
1204    fn physical_size_drops_uncalibrated_axes() {
1205        let p = PhysicalSize::micrometres(Some(0.5), Some(0.0), Some(f64::NAN));
1206        assert_eq!(p.x, Some(0.5));
1207        assert_eq!(p.y, None);
1208        assert_eq!(p.z, None);
1209        assert!(
1210            PhysicalSize::micrometres(None, Some(-1.0), None)
1211                .y
1212                .is_none()
1213        );
1214    }
1215}