Skip to main content

openreadout_abf/
lib.rs

1//! Reader for Axon Binary Format (ABF 1 and ABF 2) electrophysiology recordings.
2//!
3//! Layout and vocabulary: `docs/formats/abf.md`. Provenance: `docs/provenance/abf.md` (derived
4//! from the public, MIT-licensed pyABF documentation and the corpus; the Axon SDK was never
5//! consulted). A file is exposed as one trace: `sweep_count` sweeps × input channels, samples
6//! scaled to physical units with the per-channel gain chain recorded in the header.
7//!
8//! # Example
9//!
10//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
11//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
12//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
13//! access.
14//!
15//! ```
16//! use openreadout_core::FormatReader;
17//! use openreadout_abf::AbfReader;
18//!
19//! let format = AbfReader.descriptor();
20//! assert_eq!(format.id, openreadout_abf::FORMAT_ID);
21//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
22//! ```
23//!
24//! Reading a file:
25//!
26//! ```no_run
27//! use std::path::Path;
28//!
29//! use openreadout_core::FormatReader;
30//! use openreadout_abf::AbfReader;
31//!
32//! let mut dataset = AbfReader.open(Path::new("cell.abf"))?;
33//! let info = dataset.info()?; // headers only
34//! let trace = &info.traces[0];
35//! println!("{} sweep(s) at {} Hz, {} channel(s)", trace.sweep_count, trace.sample_rate_hz, trace.channels.len());
36//! // The first 1000 samples of sweep 0, every channel, scaled to physical units.
37//! let samples = dataset.read_trace(0, 0, 0, 1000)?;
38//! for (channel, values) in trace.channels.iter().zip(&samples.channels) {
39//!     println!("{} ({}): {:?}", channel.name, channel.unit.as_deref().unwrap_or("?"), values.first());
40//! }
41//! # Ok::<(), openreadout_core::Error>(())
42//! ```
43//!
44//! Applications that accept any instrument file usually register every reader in an
45//! [`openreadout_core::Registry`] and let it detect the format; that is what the
46//! `openreadout` command-line tool does.
47//!
48//! # API stability
49//!
50//! The supported API is what this page documents. The parser modules are public only so that
51//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
52//! in any release.
53#![forbid(unsafe_code)]
54#![warn(missing_docs)]
55
56mod assurance;
57#[doc(hidden)]
58pub mod atf;
59#[doc(hidden)]
60pub mod command;
61#[doc(hidden)]
62pub mod dataset;
63#[doc(hidden)]
64pub mod file;
65
66use std::path::Path;
67
68use openreadout_core::Result;
69use openreadout_core::model::{DetectConfidence, FormatDescriptor};
70use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
71use openreadout_core::source::Input;
72
73pub use atf::{ATF_FORMAT_ID, AtfReader};
74#[doc(hidden)]
75pub use atf::{
76    AtfColumn, AtfDataset, MAX_ATF_LEN, MAX_COLUMNS, MAX_HEADER_RECORDS, looks_like_atf,
77};
78#[doc(hidden)]
79pub use command::{CommandPlan, command_plan, command_sweep};
80#[doc(hidden)]
81pub use dataset::{AbfDataset, MAX_READ_SAMPLES, command_trace_info, trace_info};
82#[doc(hidden)]
83pub use file::{
84    ABF1_BASIC_LEN, ABF1_EXTENDED_LEN, AbfFile, AcquisitionMode, BLOCK_LEN, DigitalEpoch, Epoch,
85    EpochKind, Generation, InputChannel, MAX_RECORDS, MAX_STRINGS_LEN, OutputChannel,
86    SECTION_ENTRY_LEN, SECTION_MAP_OFFSET, SECTION_NAMES, SampleFormat, SectionEntry, Sweep, Tag,
87    Telegraph, channel_scaling, guid_text, iso_datetime, parse_string_table, usable_factor,
88};
89
90/// Format id used on the command line and in JSON.
91pub const FORMAT_ID: &str = "abf";
92
93/// The ABF reader.
94#[derive(Debug, Default, Clone, Copy)]
95pub struct AbfReader;
96
97impl FormatReader for AbfReader {
98    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
99        Some(&assurance::ABF)
100    }
101
102    fn descriptor(&self) -> FormatDescriptor {
103        FormatDescriptor {
104            id: FORMAT_ID.into(),
105            name: "Axon Binary Format (ABF)".into(),
106            vendor: "Molecular Devices (Axon Instruments) pCLAMP".into(),
107            extensions: vec!["abf".into()],
108            family: "electrophysiology".into(),
109            can_read: true,
110            can_write: false,
111            confidence: assurance::ABF.confidence,
112            known_gaps: vec![
113                "Command (DAC) waveforms are synthesized (trace 1) for episodic files with step, ramp and pulse-train epochs only; stimulus files, user lists, alternating outputs, conditioning trains, triangle/cosine/biphasic epochs, ABF 1 files before 1.6 and ABF 1 files with epoch tables on both DACs keep the epoch table only".into(),
114                "User lists, statistics, math, scope and voice-tag sections are listed but not decoded".into(),
115                "Pre-1.6 ABF 1 files: telegraph, protocol path and 20-entry epoch tables are not in the header and are not reported".into(),
116                "Old pCLAMP/Axotape files without an `ABF ` signature (CLPX, FTCX) are not read".into(),
117            ],
118        }
119    }
120
121    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
122        match head.get(..4) {
123            Some(b"ABF2") => Some(Detection {
124                format_id: FORMAT_ID,
125                confidence: DetectConfidence::Definite,
126                note: None,
127            }),
128            Some(b"ABF ") => Some(Detection {
129                format_id: FORMAT_ID,
130                confidence: DetectConfidence::Definite,
131                note: None,
132            }),
133            // a longer file without the signature is another kind of file (exit 3)
134            _ if has_extension(path, &["abf"]) && head.len() < 4 => Some(Detection {
135                format_id: FORMAT_ID,
136                confidence: DetectConfidence::ExtensionOnly,
137                note: Some("ABF extension but no `ABF ` or `ABF2` signature at byte 0".into()),
138            }),
139            _ => None,
140        }
141    }
142
143    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
144        Ok(Box::new(AbfDataset::open(path)?))
145    }
146
147    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
148        Ok(Box::new(AbfDataset::open_input(input)?))
149    }
150
151    fn reads_any_source(&self) -> bool {
152        true
153    }
154}