Skip to main content

openreadout_intan/
lib.rs

1//! Reader for Intan Technologies RHD2000 (`.rhd`) and RHS2000 (`.rhs`) recordings in the
2//! traditional single-file format.
3//!
4//! Layout and vocabulary: `docs/formats/intan.md`. Provenance: `docs/provenance/intan.md` (Intan's
5//! public data-file-format application notes). The header lists signal groups and channels;
6//! samples follow in data blocks of 60 or 128 samples. Each stored signal kind (amplifier,
7//! auxiliary, supply, temperature, board ADC/DAC, digital, DC amplifier, stimulation) is one
8//! trace with a single sweep, scaled as the application notes specify.
9//!
10//! # Example
11//!
12//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
13//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
14//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
15//! access.
16//!
17//! ```
18//! use openreadout_core::FormatReader;
19//! use openreadout_intan::IntanReader;
20//!
21//! let format = IntanReader.descriptor();
22//! assert_eq!(format.id, openreadout_intan::FORMAT_ID);
23//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
24//! ```
25//!
26//! Reading a file:
27//!
28//! ```no_run
29//! use std::path::Path;
30//!
31//! use openreadout_core::FormatReader;
32//! use openreadout_intan::IntanReader;
33//!
34//! let mut dataset = IntanReader.open(Path::new("recording.rhd"))?;
35//! let info = dataset.info()?; // headers only
36//! let trace = &info.traces[0];
37//! println!("{} sweep(s) at {} Hz, {} channel(s)", trace.sweep_count, trace.sample_rate_hz, trace.channels.len());
38//! // The first 1000 samples of sweep 0, every channel, scaled to physical units.
39//! let samples = dataset.read_trace(0, 0, 0, 1000)?;
40//! for (channel, values) in trace.channels.iter().zip(&samples.channels) {
41//!     println!("{} ({}): {:?}", channel.name, channel.unit.as_deref().unwrap_or("?"), values.first());
42//! }
43//! # Ok::<(), openreadout_core::Error>(())
44//! ```
45//!
46//! Applications that accept any instrument file usually register every reader in an
47//! [`openreadout_core::Registry`] and let it detect the format; that is what the
48//! `openreadout` command-line tool does.
49//!
50//! # API stability
51//!
52//! The supported API is what this page documents. The parser modules are public only so that
53//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
54//! in any release.
55#![forbid(unsafe_code)]
56#![warn(missing_docs)]
57
58mod assurance;
59#[doc(hidden)]
60pub mod dataset;
61#[doc(hidden)]
62pub mod header;
63#[doc(hidden)]
64pub mod split;
65
66use std::path::Path;
67
68use openreadout_core::Result;
69use openreadout_core::bytes::le_u32;
70use openreadout_core::model::{DetectConfidence, FormatDescriptor};
71use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
72use openreadout_core::source::Input;
73
74#[doc(hidden)]
75pub use dataset::{IntanDataset, MAX_HEADER_LEN};
76#[doc(hidden)]
77pub use header::{
78    BlockPart, Cursor, Family, IntanChannel, IntanHeader, RHD_MAGIC, RHS_MAGIC, SignalKind,
79    block_layout, parse_header, scaling, stim_steps,
80};
81#[doc(hidden)]
82pub use split::{
83    SplitDataset, SplitLayout, SplitStream, StreamFiles, channel_file, info_file, signal_file,
84    split_scaling,
85};
86
87/// Format id used on the command line and in JSON.
88pub const FORMAT_ID: &str = "intan";
89
90/// Files a split-layout directory may hold besides `info.rhd`/`info.rhs` and the `.dat` files:
91/// the acquisition settings and notes.
92pub const SESSION_COMPANIONS: [&str; 5] = ["xml", "txt", "log", "json", "md"];
93
94/// The files of a "one file per signal type" or "one file per channel" Intan directory (its
95/// `info.rhd` / `info.rhs` and `.dat` files), or `None` when `dir` is not one.
96pub fn session_files(dir: &Path) -> Option<Vec<std::path::PathBuf>> {
97    session_files_in(&Input::local(dir))
98}
99
100fn session_files_in(input: &Input) -> Option<Vec<std::path::PathBuf>> {
101    let dir = input.path();
102    split::info_file_in(input.fs(), dir)?;
103    openreadout_core::session::session_files_in(
104        input.fs(),
105        dir,
106        &|p| has_extension(p, &["dat", "rhd", "rhs"]),
107        &SESSION_COMPANIONS,
108        0,
109    )
110}
111
112/// True for an `info.rhd` / `info.rhs` header file that has `time.dat` or other `.dat` files next
113/// to it and no data blocks of its own: opening it opens the split recording.
114pub fn is_split_header(path: &Path) -> bool {
115    is_split_header_input(&Input::local(path))
116}
117
118fn is_split_header_input(input: &Input) -> bool {
119    let path = input.path();
120    let fs = input.fs();
121    let named_info = path
122        .file_stem()
123        .and_then(|s| s.to_str())
124        .is_some_and(|s| s.eq_ignore_ascii_case("info"));
125    named_info
126        && path.parent().is_some_and(|d| {
127            fs.is_file(&d.join("time.dat"))
128                || split::info_file_in(fs, d).is_some_and(|_| {
129                    fs.read_dir(d).is_ok_and(|mut rd| {
130                        rd.any(|e| e.is_ok_and(|e| has_extension(&e.path(), &["dat"])))
131                    })
132                })
133        })
134}
135
136/// The Intan reader.
137#[derive(Debug, Default, Clone, Copy)]
138pub struct IntanReader;
139
140impl FormatReader for IntanReader {
141    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
142        Some(&assurance::INTAN)
143    }
144
145    fn descriptor(&self) -> FormatDescriptor {
146        FormatDescriptor {
147            id: FORMAT_ID.into(),
148            name: "Intan RHD2000/RHS2000".into(),
149            vendor: "Intan Technologies (RHD/RHS recording and stimulation systems)".into(),
150            extensions: vec!["rhd".into(), "rhs".into()],
151            family: "electrophysiology".into(),
152            can_read: true,
153            can_write: false,
154            confidence: assurance::INTAN.confidence,
155            known_gaps: vec![
156                "\"One file per signal type\" and \"one file per channel\" directories (info.rhd/info.rhs + .dat) are read as one recording; temperature sensors are not saved in those layouts".into(),
157                "Stimulation words return the signed current; the amp-settle, charge-recovery and compliance bits are not exposed".into(),
158                "Split recordings (one file per N minutes) are read file by file".into(),
159            ],
160        }
161    }
162
163    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
164        self.sniff_input(head, &Input::local(path))
165    }
166
167    fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
168        let path = input.path();
169        if input.is_dir() {
170            return session_files_in(input).map(|_| Detection {
171                format_id: FORMAT_ID,
172                confidence: DetectConfidence::Definite,
173                note: Some("Intan split-layout directory (info.rhd/info.rhs + .dat files)".into()),
174            });
175        }
176        let magic = le_u32(head, 0);
177        if matches!(magic, Some(RHD_MAGIC | RHS_MAGIC)) {
178            return Some(Detection {
179                format_id: FORMAT_ID,
180                confidence: DetectConfidence::Definite,
181                note: None,
182            });
183        }
184        // A longer file without the magic number is another kind of file (exit 3).
185        (has_extension(path, &["rhd", "rhs"]) && head.len() < 4).then(|| Detection {
186            format_id: FORMAT_ID,
187            confidence: DetectConfidence::ExtensionOnly,
188            note: Some("Intan extension but no RHD/RHS magic number".into()),
189        })
190    }
191
192    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
193        self.open_input(&Input::local(path))
194    }
195
196    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
197        if input.is_dir() || is_split_header_input(input) {
198            return Ok(Box::new(SplitDataset::open_input(input)?));
199        }
200        Ok(Box::new(IntanDataset::open_input(input)?))
201    }
202
203    fn reads_any_source(&self) -> bool {
204        true
205    }
206}