Skip to main content

openreadout_epr/
lib.rs

1//! Clean-room readers for electron paramagnetic resonance (EPR/ESR) data.
2//!
3//! - **Bruker BES3T** (`bruker-bes3t`, `.DSC` descriptor + `.DTA` data, optionally `.XGF`/`.YGF`/
4//!   `.ZGF` axis files; written by Xepr on ELEXSYS, EMX and EMXplus spectrometers): cw and pulse
5//!   spectra, 1D, 2D and 3D, real or complex, with the field or time axis, the sweep axis and the
6//!   standard parameters (microwave frequency and power, modulation, gain, time constant, scans,
7//!   temperature).
8//! - **Bruker ESP / WinEPR** (`bruker-esp`, `.par` parameters + `.spc` data): WinEPR and ESP
9//!   300/380 spectra (1D and 2D) with the field axis and acquisition parameters.
10//!
11//! Every data set is one trace per data value of a point (almost always one): one sweep per
12//! slice of the second and third dimensions, channel `intensity` (real data) or `real` and
13//! `imaginary` (complex data), the abscissa in `extra.axis` (`magnetic_field` in G or mT, `time`
14//! in ns, …; an axis file is channel 0). Notes: `docs/formats/bruker-epr.md`.
15//!
16//! # Example
17//!
18//! ```
19//! use openreadout_core::FormatReader;
20//! use openreadout_epr::Bes3tReader;
21//!
22//! assert_eq!(Bes3tReader.descriptor().id, openreadout_epr::BES3T_FORMAT_ID);
23//! ```
24//!
25//! # API stability
26//!
27//! The supported API is what this page documents: the readers and their format ids.
28#![forbid(unsafe_code)]
29#![warn(missing_docs)]
30
31mod assurance;
32mod bes3t;
33mod common;
34mod esp;
35mod params;
36
37use std::path::Path;
38
39use openreadout_core::Result;
40use openreadout_core::model::{DetectConfidence, FormatDescriptor};
41use openreadout_core::reader::{Dataset, Detection, FormatReader};
42use openreadout_core::series::SeriesDataset;
43use openreadout_core::source::Input;
44
45/// Format id of Bruker BES3T (`.DSC`/`.DTA`) data sets.
46pub const BES3T_FORMAT_ID: &str = bes3t::FORMAT_ID;
47/// Format id of Bruker ESP/WinEPR (`.par`/`.spc`) data sets.
48pub const ESP_FORMAT_ID: &str = esp::FORMAT_ID;
49
50/// The Bruker BES3T reader (`.DSC` + `.DTA`).
51#[derive(Debug, Default, Clone, Copy)]
52pub struct Bes3tReader;
53
54impl FormatReader for Bes3tReader {
55    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
56        Some(&assurance::BRUKER_BES3T)
57    }
58
59    fn descriptor(&self) -> FormatDescriptor {
60        FormatDescriptor {
61            id: BES3T_FORMAT_ID.into(),
62            name: "Bruker BES3T EPR (.DSC/.DTA)".into(),
63            vendor: "Bruker".into(),
64            extensions: vec!["dsc".into(), "dta".into()],
65            family: "epr".into(),
66            can_read: true,
67            can_write: false,
68            confidence: assurance::BRUKER_BES3T.confidence,
69            known_gaps: vec![
70                "ASCII data sets (IRFMT A), N-tuple axes (NTUP) and points whose values have different number formats are refused (exit 6)".into(),
71                "Values are returned as stored: no normalization by scans, gain, power or conversion time (Xepr's and EasySpin's optional scalings)".into(),
72                "The manipulation history layer (#MHL) is counted, not interpreted; processed data sets are read like acquired ones".into(),
73                "Only the standard parameters are normalized; device parameters (#DSL) are in the vendor tree as text".into(),
74            ],
75        }
76    }
77
78    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
79        let ext = path.extension()?.to_str()?.to_ascii_lowercase();
80        if ext == "dsc" && params::is_descriptor(head) {
81            return Some(Detection {
82                format_id: BES3T_FORMAT_ID,
83                confidence: DetectConfidence::Definite,
84                note: None,
85            });
86        }
87        None
88    }
89
90    fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
91        if let Some(d) = self.sniff(head, input.path()) {
92            return Some(d);
93        }
94        let ext = input.path().extension()?.to_str()?.to_ascii_lowercase();
95        (ext == "dta" && bes3t::has_descriptor(input)).then_some(Detection {
96            format_id: BES3T_FORMAT_ID,
97            confidence: DetectConfidence::Definite,
98            note: None,
99        })
100    }
101
102    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
103        self.open_input(&Input::local(path))
104    }
105
106    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
107        let p = bes3t::open(input)?;
108        Ok(Box::new(SeriesDataset::new(
109            self.descriptor(),
110            input.path().to_path_buf(),
111            p.size,
112            p.file,
113        )))
114    }
115
116    fn reads_any_source(&self) -> bool {
117        true
118    }
119}
120
121/// The Bruker ESP/WinEPR reader (`.par` + `.spc`).
122#[derive(Debug, Default, Clone, Copy)]
123pub struct EspReader;
124
125impl FormatReader for EspReader {
126    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
127        Some(&assurance::BRUKER_ESP)
128    }
129
130    fn descriptor(&self) -> FormatDescriptor {
131        FormatDescriptor {
132            id: ESP_FORMAT_ID.into(),
133            name: "Bruker ESP/WinEPR EPR (.par/.spc)".into(),
134            vendor: "Bruker".into(),
135            extensions: vec!["par".into(), "spc".into()],
136            family: "epr".into(),
137            can_read: true,
138            can_write: false,
139            confidence: assurance::BRUKER_ESP.confidence,
140            known_gaps: vec![
141                "The .spc file has no header: its layout (little-endian float32 for WinEPR, big-endian int32 for ESP) and point count come from the .par file; a data set without its .par file is not recognised".into(),
142                "Values are returned as stored: no normalization by scans, gain or conversion time".into(),
143            ],
144        }
145    }
146
147    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
148        // a .spc file has no header: only a .par whose lines are ESP/WinEPR parameters is
149        // recognised from its bytes (the sibling decides for the other inputs)
150        if !path
151            .extension()
152            .is_some_and(|e| e.eq_ignore_ascii_case("par"))
153        {
154            return None;
155        }
156        let text = String::from_utf8_lossy(&head[..head.len().min(4096)]);
157        let keys = text
158            .split(['\r', '\n'])
159            .filter_map(|l| l.split_whitespace().next())
160            .filter(|k| {
161                matches!(
162                    *k,
163                    "JSS"
164                        | "JDA"
165                        | "JTM"
166                        | "JON"
167                        | "GST"
168                        | "GSI"
169                        | "HCF"
170                        | "HSW"
171                        | "RES"
172                        | "MF"
173                        | "ANZ"
174                        | "RCT"
175                        | "RTC"
176                        | "RRG"
177                        | "MPS"
178                        | "MP"
179                        | "TE"
180                )
181            })
182            .count();
183        (keys >= 3).then_some(Detection {
184            format_id: ESP_FORMAT_ID,
185            confidence: DetectConfidence::Likely,
186            note: None,
187        })
188    }
189
190    fn sniff_input(&self, _head: &[u8], input: &Input) -> Option<Detection> {
191        esp::sibling_par(input).map(|_| Detection {
192            format_id: ESP_FORMAT_ID,
193            confidence: DetectConfidence::Likely,
194            note: None,
195        })
196    }
197
198    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
199        self.open_input(&Input::local(path))
200    }
201
202    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
203        let p = esp::open(input)?;
204        Ok(Box::new(SeriesDataset::new(
205            self.descriptor(),
206            input.path().to_path_buf(),
207            p.size,
208            p.file,
209        )))
210    }
211
212    fn reads_any_source(&self) -> bool {
213        true
214    }
215}