Skip to main content

openreadout_plexon/
lib.rs

1//! Reader for Plexon PLX ("Plexon 1") and PL2 electrophysiology recordings.
2//!
3//! Layout and vocabulary: `docs/formats/plexon.md`. Provenance: `docs/provenance/plexon.md` (PLX
4//! from Neo, BSD-3, read as documentation; PL2 from hex dumps of corpus files only — Plexon's own
5//! PL2 reader is a DLL that is neither opened nor run). Continuous channels are traces (channels
6//! sampled on one grid share a trace; recording pauses split sweeps); spike waveforms and events
7//! are tables.
8//!
9//! # Example
10//!
11//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
12//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
13//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
14//! access.
15//!
16//! ```
17//! use openreadout_core::FormatReader;
18//! use openreadout_plexon::PlexonReader;
19//!
20//! let format = PlexonReader.descriptor();
21//! assert_eq!(format.id, openreadout_plexon::FORMAT_ID);
22//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
23//! ```
24//!
25//! Reading a file:
26//!
27//! ```no_run
28//! use std::path::Path;
29//!
30//! use openreadout_core::FormatReader;
31//! use openreadout_plexon::PlexonReader;
32//!
33//! let mut dataset = PlexonReader.open(Path::new("session.plx"))?;
34//! let info = dataset.info()?;
35//! for t in &info.traces {
36//!     println!("trace {}: {} channel(s) at {} Hz", t.index, t.channels.len(), t.sample_rate_hz);
37//! }
38//! // The first 100 spikes: time, channel, unit and waveform samples in mV.
39//! let spikes = dataset.read_table(0, 0, 100)?;
40//! println!("{} spike rows", spikes.columns[0].len());
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 dataset;
59#[doc(hidden)]
60pub mod pl2;
61#[doc(hidden)]
62pub mod pl2_dataset;
63#[doc(hidden)]
64pub mod plx;
65
66use openreadout_core::source::Input;
67use std::path::Path;
68
69use openreadout_core::Result;
70use openreadout_core::model::{DetectConfidence, FormatDescriptor};
71use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
72
73#[doc(hidden)]
74pub use dataset::{MAX_TABLE_READ, PlxDataset, PlxTrace};
75#[doc(hidden)]
76pub use pl2::{
77    EventRun, MAX_PL2_CHANNELS, PL2_FILE_HEADER_LEN, PL2_MAGIC, PL2_MAGIC_AT, Pl2Channel, Pl2File,
78    Pl2Header, Pl2Index, REC_ANALOG, REC_ANALOG_HEADER, REC_DIGITAL_HEADER, REC_END, REC_EVENTS,
79    REC_SPIKE_HEADER, REC_SPIKES, RECORD_HEADER_LEN, SpikeRun, UNIT_SLOTS, looks_like_pl2,
80    parse_pl2, parse_pl2_header, record_len, walk_records,
81};
82#[doc(hidden)]
83pub use pl2_dataset::{Pl2Dataset, Pl2Trace};
84#[doc(hidden)]
85pub use plx::{
86    BLOCK_CONTINUOUS, BLOCK_EVENT, BLOCK_HEADER_LEN, BLOCK_SPIKE, BlockList, CONTINUOUS_HEADER_LEN,
87    ContinuousChannel, EVENT_HEADER_LEN, EventChannel, EventRecord, FILE_HEADER_LEN,
88    MAX_CHANNEL_HEADERS, PLX_MAGIC, PlxFile, PlxHeader, PlxIndex, Run, SPIKE_HEADER_LEN,
89    SampleBlock, SpikeChannel, block_header, parse_file_header, parse_plx, runs, walk_blocks,
90};
91
92/// Format id used on the command line and in JSON.
93pub const FORMAT_ID: &str = "plexon";
94
95/// Extensions this reader opens.
96pub const EXTENSIONS: [&str; 2] = ["plx", "pl2"];
97
98/// The Plexon reader.
99#[derive(Debug, Default, Clone, Copy)]
100pub struct PlexonReader;
101
102impl FormatReader for PlexonReader {
103    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
104        Some(&assurance::PLEXON)
105    }
106
107    fn descriptor(&self) -> FormatDescriptor {
108        FormatDescriptor {
109            id: FORMAT_ID.into(),
110            name: "Plexon PLX/PL2".into(),
111            vendor: "Plexon (MAP, OmniPlex)".into(),
112            extensions: EXTENSIONS.iter().map(|e| (*e).to_string()).collect(),
113            family: "electrophysiology".into(),
114            can_read: true,
115            can_write: false,
116            confidence: assurance::PLEXON.confidence,
117            known_gaps: vec![
118                "PLX has no index: `info` walks every data-block header (fast, but proportional to the file size)".into(),
119                "PLX values are in mV by the gain formulas Neo documents; version 100/101 files assume a preamplifier gain of 1000".into(),
120                "PL2 is derived from hex dumps of public files (Plexon's reader is a DLL); spike waveforms and events are confirmed against Neo on a PLX of the same recording, PL2 continuous records only for internal consistency".into(),
121                "PLX version 107 (and continuous channels of unequal length) are read but have no oracle-confirmed continuous data".into(),
122                "PL2 footer index and device settings are not read; `info` walks the data-record headers".into(),
123            ],
124        }
125    }
126
127    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
128        if head.get(..4) == Some(&PLX_MAGIC[..]) || looks_like_pl2(head) {
129            return Some(Detection {
130                format_id: FORMAT_ID,
131                confidence: DetectConfidence::Definite,
132                note: None,
133            });
134        }
135        // A longer file with neither start is another kind of file (exit 3).
136        (has_extension(path, &EXTENSIONS) && (head.len() < 4 || head.first() == Some(&0xFE))).then(
137            || Detection {
138                format_id: FORMAT_ID,
139                confidence: DetectConfidence::ExtensionOnly,
140                note: Some("Plexon extension but no PLX/PL2 signature".into()),
141            },
142        )
143    }
144
145    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
146        self.open_input(&Input::local(path))
147    }
148
149    fn reads_any_source(&self) -> bool {
150        true
151    }
152
153    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
154        let path = input.path();
155        let mut head = [0u8; 16];
156        let n = input
157            .fs()
158            .open(path)
159            .and_then(|mut f| std::io::Read::read(&mut f, &mut head))
160            .map_err(|e| openreadout_core::Error::io(path, e))?;
161        if looks_like_pl2(&head[..n]) {
162            return Ok(Box::new(Pl2Dataset::open_input(input)?));
163        }
164        Ok(Box::new(PlxDataset::open_input(input)?))
165    }
166}