Skip to main content

openreadout_gel/
lib.rs

1//! Clean-room readers for gel and blot documentation images.
2//!
3//! - **Bio-Rad Image Lab** (`biorad-scn`, `.scn`): the image files ChemiDoc, Gel Doc and other
4//!   imagers save through Image Lab (also scans imported into Image Lab): one 16-bit image per
5//!   scan with its pixel size, imager, application (chemiluminescence, IRDye, colorimetric,
6//!   stains), exposure, filters, user, dates and the audit log. Notes:
7//!   `docs/formats/biorad-scn.md`.
8//! - **Syngene GeneSys** (`syngene-sgd`, `.sgd`): the compound files G:Box and PXi imagers save
9//!   through GeneSys: one 8- or 16-bit image per capture (every exposure of a series and the
10//!   marker image) with the imager, camera, light, filter, application, exposure, time and user.
11//!   Notes: `docs/formats/syngene-sgd.md`.
12//!
13//! # Example
14//!
15//! ```
16//! use openreadout_core::FormatReader;
17//! use openreadout_gel::ImageLabReader;
18//!
19//! let format = ImageLabReader.descriptor();
20//! assert_eq!(format.id, openreadout_gel::IMAGE_LAB_FORMAT_ID);
21//! ```
22//!
23//! Reading a file:
24//!
25//! ```no_run
26//! use std::path::Path;
27//!
28//! use openreadout_core::{FormatReader, PlaneIndex};
29//! use openreadout_gel::ImageLabReader;
30//!
31//! let mut dataset = ImageLabReader.open(Path::new("blot.scn"))?;
32//! let info = dataset.info()?;
33//! let plane = dataset.read_plane(0, PlaneIndex::default())?; // 16-bit little-endian
34//! println!("{} × {}", info.images[0].size_x, info.images[0].size_y);
35//! # Ok::<(), openreadout_core::Error>(())
36//! ```
37//!
38//! # API stability
39//!
40//! The supported API is what this page documents: the readers, their format ids and
41//! [`ScnDataset`] and [`SgdDataset`] (returned boxed by `open`).
42#![forbid(unsafe_code)]
43#![warn(missing_docs)]
44
45mod assurance;
46mod mime;
47mod scn;
48mod sgd;
49
50use std::path::Path;
51
52use openreadout_core::model::{DetectConfidence, FormatDescriptor};
53use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
54use openreadout_core::source::Input;
55use openreadout_core::{Error, Result};
56
57pub use scn::ScnDataset;
58pub use sgd::SgdDataset;
59
60/// Format id of Bio-Rad Image Lab `.scn` files.
61pub const IMAGE_LAB_FORMAT_ID: &str = scn::FORMAT_ID;
62
63/// Format id of Syngene GeneSys `.sgd` files.
64pub const SYNGENE_FORMAT_ID: &str = sgd::FORMAT_ID;
65
66/// The Bio-Rad Image Lab `.scn` reader.
67#[derive(Debug, Default, Clone, Copy)]
68pub struct ImageLabReader;
69
70impl FormatReader for ImageLabReader {
71    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
72        Some(&assurance::BIORAD_SCN)
73    }
74
75    fn descriptor(&self) -> FormatDescriptor {
76        FormatDescriptor {
77            id: IMAGE_LAB_FORMAT_ID.into(),
78            name: "Bio-Rad Image Lab (.scn)".into(),
79            vendor: "Bio-Rad".into(),
80            extensions: vec!["scn".into()],
81            family: "gel-imaging".into(),
82            can_read: true,
83            can_write: false,
84            confidence: assurance::BIORAD_SCN.confidence,
85            known_gaps: vec![
86                "Validated on 13 development files from Image Lab 3.0.1 to 6.1.0 (ChemiDoc MP, ChemiDoc XRS+, Gel Doc XR+, a merged image); all hold one 16-bit scan. Scans imported from Typhoon/Molecular Dynamics `.gel` files carry a square-root encoding (`scaler/moldyn`) that is reported, not applied, and no corpus file exercises it".into(),
87                "Lane and band analyses, molecular-weight calibrations and volume tools are not stored in any file seen; other parts are listed by `info --view structure` and kept in the vendor tree".into(),
88                "Multi-channel (fluorescent multiplex) files have no public sample; each ScanImageTag would be its own image".into(),
89                "Scans imported from Molecular Dynamics .gel keep their stored square-root-encoded counts (the scale is reported, not applied)".into(),
90                "Leica SCN whole-slide files share the extension: they are TIFF and go to the TIFF reader".into(),
91            ],
92        }
93    }
94
95    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
96        let start = head.get(..head.len().min(512))?;
97        let text = String::from_utf8_lossy(start);
98        if text.starts_with("MIME-Version:") && text.contains("Image Lab") {
99            return Some(Detection {
100                format_id: IMAGE_LAB_FORMAT_ID,
101                confidence: DetectConfidence::Definite,
102                note: None,
103            });
104        }
105        (text.starts_with("MIME-Version:") && has_extension(path, &["scn"])).then_some(Detection {
106            format_id: IMAGE_LAB_FORMAT_ID,
107            confidence: DetectConfidence::Likely,
108            note: Some(
109                "a MIME document with the .scn extension that does not name Image Lab".into(),
110            ),
111        })
112    }
113
114    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
115        self.open_input(&Input::local(path))
116    }
117
118    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
119        let file = input.open()?;
120        let len = file.size().map_err(|e| Error::io(input.path(), e))?;
121        Ok(Box::new(ScnDataset::open(
122            self.descriptor(),
123            input.path().to_path_buf(),
124            file,
125            len,
126        )?))
127    }
128
129    fn reads_any_source(&self) -> bool {
130        true
131    }
132}
133
134/// The Syngene GeneSys `.sgd` reader.
135#[derive(Debug, Default, Clone, Copy)]
136pub struct SyngeneReader;
137
138/// Whether a compound file holds GeneSys captures: the capture list, or a capture's pixels.
139fn is_genesys(input: &Input) -> bool {
140    let Ok(mut f) = input.open() else {
141        return false;
142    };
143    openreadout_core::cfb::Cfb::open(&mut f, input.path(), SYNGENE_FORMAT_ID).is_ok_and(|c| {
144        c.entries.iter().any(|e| {
145            e.is_stream
146                && (e.path.eq_ignore_ascii_case("Detector/MultiImage/MultiData")
147                    || (e.path.starts_with("Detector/GeneSnap/") && e.path.ends_with("/PixelData")))
148        })
149    })
150}
151
152impl FormatReader for SyngeneReader {
153    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
154        Some(&assurance::SYNGENE_SGD)
155    }
156
157    fn descriptor(&self) -> FormatDescriptor {
158        FormatDescriptor {
159            id: SYNGENE_FORMAT_ID.into(),
160            name: "Syngene GeneSys (.sgd)".into(),
161            vendor: "Syngene".into(),
162            extensions: vec!["sgd".into()],
163            family: "gel-imaging".into(),
164            can_read: true,
165            can_write: false,
166            confidence: assurance::SYNGENE_SGD.confidence,
167            known_gaps: vec![
168                "Validated on two development files (GeneSys 1.5.6.0 on a PXi 6, 1.6.1.0 on a G:Box mini 6); no independent reader decodes the samples, so pixel values are checked only through the correlation with one depositor's TIFF export".into(),
169                "The exposure is reported in seconds, an inference from how the signal grows across one file's exposure series".into(),
170                "Annotations, band and spot-blot analyses, the view and rotation settings and the thumbnail are listed by `info --view structure`, not decoded".into(),
171            ],
172        }
173    }
174
175    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
176        (has_extension(path, &["sgd"]) && head.starts_with(&openreadout_core::cfb::CFB_MAGIC))
177            .then_some(Detection {
178                format_id: SYNGENE_FORMAT_ID,
179                confidence: DetectConfidence::Likely,
180                note: Some("compound file with the .sgd extension".into()),
181            })
182    }
183
184    fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
185        if head.starts_with(&openreadout_core::cfb::CFB_MAGIC) && is_genesys(input) {
186            return Some(Detection {
187                format_id: SYNGENE_FORMAT_ID,
188                confidence: DetectConfidence::Definite,
189                note: None,
190            });
191        }
192        self.sniff(head, input.path())
193    }
194
195    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
196        self.open_input(&Input::local(path))
197    }
198
199    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
200        let file = input.open()?;
201        let len = file.size().map_err(|e| Error::io(input.path(), e))?;
202        Ok(Box::new(SgdDataset::open(
203            self.descriptor(),
204            input.path().to_path_buf(),
205            file,
206            len,
207        )?))
208    }
209
210    fn reads_any_source(&self) -> bool {
211        true
212    }
213}
214
215/// Provenance for the experiment fields every reader of this crate sets from the format itself
216/// (vendor, instrument kind, technique) and for each measurement, where the builder did not
217/// record one.
218pub(crate) fn complete_provenance(e: &mut openreadout_core::experiment::Experiment) {
219    use openreadout_core::experiment::Origin;
220    use openreadout_core::provenance::Source;
221    let o = |from: &str| Origin {
222        source: Source::Inferred,
223        from: from.into(),
224    };
225    for k in 0..e.measurements.len() {
226        e.provenance
227            .entry(format!("measurements[{k}]"))
228            .or_insert_with(|| o("the reader's data layout (traces, tables, images)"));
229    }
230    if let Some(i) = &e.instrument {
231        if i.vendor.is_some() {
232            e.provenance
233                .entry("instrument.vendor".into())
234                .or_insert_with(|| o("the file format"));
235        }
236        if i.kind.is_some() {
237            e.provenance
238                .entry("instrument.kind".into())
239                .or_insert_with(|| o("the file format"));
240        }
241    }
242    if e.method.as_ref().is_some_and(|m| m.technique.is_some()) {
243        e.provenance
244            .entry("method.technique".into())
245            .or_insert_with(|| o("the file format and the recorded mode"));
246    }
247}