openreadout-plexon 0.4.0

Reader for Plexon PLX and PL2 electrophysiology files, part of OpenReadout
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! `PlxDataset`: continuous channels as traces (channels on one sample grid share a trace, gap-free
//! runs are sweeps), spike waveforms and events as two tables.

use openreadout_core::source::SourceFile as File;
use openreadout_core::source::{Fs, Input};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use openreadout_core::bytes::read_block;
use openreadout_core::model::{
    CheckReport, ColumnInfo, FileInfo, Finding, LsEntry, SignalChannelInfo, Table, TableInfo,
    Trace, TraceInfo,
};
use openreadout_core::provenance::{ProvenanceMap, Source};
use openreadout_core::reader::{Dataset, FormatReader, PlaneIndex};
use openreadout_core::{Error, Plane, Result};
use serde_json::{Value, json};

use crate::plx::{
    BLOCK_HEADER_LEN, BlockList, ContinuousChannel, PlxFile, Run, block_header, parse_plx, runs,
};
use crate::{FORMAT_ID, PlexonReader};

/// A sweep's blocks are read in one go when they lie within this many bytes of the file.
const READ_SPAN_MAX: u64 = 64 << 20;
/// Otherwise they are read through windows of this size.
const READ_WINDOW: u64 = 4 << 20;

/// Call `f(offset, samples)` for each stretch of samples `first_sample..first_sample + n` of
/// `run` covers in `blocks`, in order.
fn for_each_piece(
    blocks: &BlockList,
    run: &Run,
    first_sample: u64,
    n: u64,
    mut f: impl FnMut(u64, u64) -> Result<()>,
) -> Result<()> {
    let mut skip = first_sample;
    let mut done = 0u64;
    for b in blocks.range(run.first_block, run.block_count) {
        if done >= n {
            break;
        }
        let bs = u64::from(b.samples);
        if skip >= bs {
            skip -= bs;
            continue;
        }
        let take = (bs - skip).min(n - done);
        f(b.offset.saturating_add(2 * skip), take)?;
        done += take;
        skip = 0;
    }
    Ok(())
}

/// Rows decoded per `read_table` call at most.
pub const MAX_TABLE_READ: u64 = 1 << 20;

/// One trace: continuous channels (indices into the header list) on one sample grid.
#[derive(Debug, Clone)]
pub struct PlxTrace {
    /// Continuous-channel header indices, in header order.
    pub channels: Vec<usize>,
    /// Sampling rate, Hz.
    pub rate_hz: f64,
    /// Gap-free runs (sweeps), identical for every channel of the trace.
    pub runs: Vec<Run>,
}

/// An opened PLX file.
#[derive(Debug)]
pub struct PlxDataset {
    path: PathBuf,
    fs: Fs,
    plx: PlxFile,
    traces: Vec<PlxTrace>,
    /// Continuous channels with blocks but no header (channel numbers).
    orphans: Vec<u16>,
    handle: Option<File>,
}

fn not_images() -> Error {
    Error::unsupported(
        FORMAT_ID,
        "image planes",
        "Plexon files hold continuous signals, spikes and events: use `openreadout trace` for signals and `openreadout export --format csv --table N` for tables.",
    )
}

/// The alphabetic prefix of a channel name (`WB01` → `WB`).
fn prefix(name: &str) -> &str {
    name.trim_end_matches(|c: char| c.is_ascii_digit())
}

impl PlxDataset {
    /// Open and index a PLX file.
    pub fn open(path: &Path) -> Result<Self> {
        Self::open_input(&Input::local(path))
    }

    pub(crate) fn open_input(input: &Input) -> Result<Self> {
        let path = input.path();
        let fs = input.fs();
        let mut f = fs.open(path).map_err(|e| Error::io(path, e))?;
        let len = f.metadata().map_err(|e| Error::io(path, e))?.len();
        let plx = parse_plx(&mut f, path, len)?;
        let clock = f64::from(plx.header.clock_hz);
        let mut traces: Vec<PlxTrace> = Vec::new();
        for (i, c) in plx.continuous_channels.iter().enumerate() {
            let Some(blocks) = u16::try_from(c.channel)
                .ok()
                .and_then(|ch| plx.index.continuous.get(&ch))
            else {
                continue;
            };
            let rate = f64::from(c.rate_hz);
            let r = runs(blocks.iter(), clock, rate);
            let grid: Vec<(u64, u64)> = r.iter().map(|x| (x.timestamp, x.samples)).collect();
            match traces.iter_mut().find(|t| {
                t.rate_hz.to_bits() == rate.to_bits()
                    && t.runs
                        .iter()
                        .map(|x| (x.timestamp, x.samples))
                        .eq(grid.iter().copied())
            }) {
                Some(t) => t.channels.push(i),
                None => traces.push(PlxTrace {
                    channels: vec![i],
                    rate_hz: rate,
                    runs: r,
                }),
            }
        }
        let known: Vec<i32> = plx.continuous_channels.iter().map(|c| c.channel).collect();
        let orphans = plx
            .index
            .continuous
            .keys()
            .filter(|ch| !known.contains(&i32::from(**ch)))
            .copied()
            .collect();
        Ok(PlxDataset {
            path: path.to_path_buf(),
            fs: fs.clone(),
            plx,
            traces,
            orphans,
            handle: Some(f),
        })
    }

    /// The parsed file.
    pub fn plx(&self) -> &PlxFile {
        &self.plx
    }

    fn clock(&self) -> f64 {
        f64::from(self.plx.header.clock_hz.max(1))
    }

    fn handle(&mut self) -> Result<&mut File> {
        if self.handle.is_none() {
            self.handle = Some(
                self.fs
                    .open(&self.path)
                    .map_err(|e| Error::io(&self.path, e))?,
            );
        }
        Ok(self.handle.as_mut().expect("just opened"))
    }

    fn blocks(&self, c: &ContinuousChannel) -> &BlockList {
        static EMPTY: std::sync::LazyLock<BlockList> = std::sync::LazyLock::new(BlockList::default);
        u16::try_from(c.channel)
            .ok()
            .and_then(|ch| self.plx.index.continuous.get(&ch))
            .unwrap_or(&*EMPTY)
    }

    fn trace_info(&self, index: usize, t: &PlxTrace) -> TraceInfo {
        let h = &self.plx.header;
        let clock = self.clock();
        let channels: Vec<SignalChannelInfo> = t
            .channels
            .iter()
            .enumerate()
            .map(|(k, &i)| {
                let c = &self.plx.continuous_channels[i];
                let mut e = BTreeMap::new();
                e.insert("channel_number".into(), json!(c.channel));
                e.insert("gain".into(), json!(c.gain));
                e.insert("preamp_gain".into(), json!(c.preamp_gain));
                e.insert("enabled".into(), json!(c.enabled));
                if !c.comment.is_empty() {
                    e.insert("comment".into(), json!(c.comment));
                }
                SignalChannelInfo {
                    index: k as u32,
                    name: c.name.clone(),
                    unit: Some("mV".into()),
                    dtype: "int16".into(),
                    scale: h.continuous_scale(c),
                    offset: 0.0,
                    extra: e,
                }
            })
            .collect();
        let names: Vec<&str> = t
            .channels
            .iter()
            .map(|&i| prefix(&self.plx.continuous_channels[i].name))
            .collect();
        let name = names
            .first()
            .filter(|p| !p.is_empty() && names.iter().all(|x| x == *p))
            .map(|p| (*p).to_string());
        let mut extra = BTreeMap::new();
        let counts: Vec<u64> = t.runs.iter().map(|r| r.samples).collect();
        if counts.windows(2).any(|w| w[0] != w[1]) {
            extra.insert("sweep_sample_counts".into(), json!(counts));
        }
        extra.insert(
            "sweep_start_timestamps".into(),
            json!(t.runs.iter().map(|r| r.timestamp).collect::<Vec<_>>()),
        );
        extra.insert(
            "sweep_starts_s".into(),
            json!(
                t.runs
                    .iter()
                    .map(|r| r.timestamp as f64 / clock)
                    .collect::<Vec<_>>()
            ),
        );
        extra.insert("timestamp_clock_hz".into(), json!(h.clock_hz));
        TraceInfo {
            index: index as u32,
            name,
            sample_rate_hz: t.rate_hz,
            sample_count: counts.iter().copied().max().unwrap_or(0),
            sweep_count: t.runs.len() as u32,
            channels,
            start_s: t.runs.first().map(|r| r.timestamp as f64 / clock),
            extra,
        }
    }

    fn spike_columns(&self) -> Vec<ColumnInfo> {
        let col = |i: usize, name: String, dtype: &str, unit: Option<&str>| ColumnInfo {
            index: i as u32,
            name,
            label: None,
            dtype: dtype.into(),
            unit: unit.map(str::to_string),
            range: None,
            extra: BTreeMap::new(),
        };
        let mut v = vec![
            col(0, "time_s".into(), "float64", Some("s")),
            col(1, "timestamp".into(), "uint64", None),
            col(2, "channel".into(), "uint16", None),
            col(3, "unit".into(), "uint16", None),
        ];
        for i in 0..self.plx.index.max_waveform as usize {
            v.push(col(v.len(), format!("w{i}"), "float64", Some("mV")));
        }
        v
    }

    fn event_columns() -> Vec<ColumnInfo> {
        let col = |i: u32, name: &str, dtype: &str, unit: Option<&str>| ColumnInfo {
            index: i,
            name: name.into(),
            label: None,
            dtype: dtype.into(),
            unit: unit.map(str::to_string),
            range: None,
            extra: BTreeMap::new(),
        };
        vec![
            col(0, "time_s", "float64", Some("s")),
            col(1, "timestamp", "uint64", None),
            col(2, "channel", "uint16", None),
            col(3, "value", "uint16", None),
        ]
    }

    /// (spike table index, event table index).
    fn table_ids(&self) -> (Option<u32>, Option<u32>) {
        let spikes =
            (!self.plx.spike_channels.is_empty() || !self.plx.index.spikes.is_empty()).then_some(0);
        let events = (!self.plx.event_channels.is_empty() || !self.plx.index.events.is_empty())
            .then_some(u32::from(spikes.is_some()));
        (spikes, events)
    }

    fn tables(&self) -> Vec<TableInfo> {
        let h = &self.plx.header;
        let (s, e) = self.table_ids();
        let mut out = Vec::new();
        if let Some(i) = s {
            let mut extra = BTreeMap::new();
            extra.insert("timestamp_clock_hz".into(), json!(h.clock_hz));
            extra.insert("waveform_rate_hz".into(), json!(h.waveform_rate_hz));
            extra.insert("waveform_points".into(), json!(h.waveform_points));
            extra.insert("pre_threshold_points".into(), json!(h.pre_threshold_points));
            extra.insert(
                "channels".into(),
                json!(self.plx.spike_channels.iter().map(|c| json!({
                    "channel_number": c.channel, "name": c.name, "signal_name": c.signal_name,
                    "gain": c.gain, "mv_per_count": h.spike_scale(c), "threshold": c.threshold,
                    "filter": c.filter, "unit_count": c.unit_count,
                })).collect::<Vec<_>>()),
            );
            out.push(TableInfo {
                index: i,
                name: Some("spikes".into()),
                row_count: self.plx.index.spikes.len() as u64,
                columns: self.spike_columns(),
                extra,
            });
        }
        if let Some(i) = e {
            let mut extra = BTreeMap::new();
            extra.insert("timestamp_clock_hz".into(), json!(h.clock_hz));
            extra.insert(
                "channels".into(),
                json!(
                    self.plx
                        .event_channels
                        .iter()
                        .map(|c| json!({
                            "channel_number": c.channel, "name": c.name,
                        }))
                        .collect::<Vec<_>>()
                ),
            );
            out.push(TableInfo {
                index: i,
                name: Some("events".into()),
                row_count: self.plx.index.events.len() as u64,
                columns: Self::event_columns(),
                extra,
            });
        }
        out
    }

    fn read_spikes(&mut self, first: u64, n: u64) -> Result<Table> {
        let width = self.plx.index.max_waveform as usize;
        let mut cols: Vec<Vec<f64>> = (0..4 + width)
            .map(|_| Vec::with_capacity(n as usize))
            .collect();
        let clock = self.clock();
        let scales: BTreeMap<i32, f64> = self
            .plx
            .spike_channels
            .iter()
            .map(|c| (c.channel, self.plx.header.spike_scale(c)))
            .collect();
        let offsets: Vec<u64> =
            self.plx.index.spikes[first as usize..(first + n) as usize].to_vec();
        let (path, len) = (self.path.clone(), self.plx.file_len);
        let mut buf = openreadout_core::bytes::Block::default();
        let max_block = BLOCK_HEADER_LEN + 2 * u64::from(self.plx.index.max_waveform);
        for at in offsets {
            if at < buf.origin || at + max_block > buf.end() {
                buf = read_block(self.handle()?, &path, at, (4 << 20).max(max_block), len)?;
            }
            let (_, ts, ch, unit, waves, words) = block_header(&buf, at)
                .ok_or_else(|| Error::corrupt_at(FORMAT_ID, at, "spike block cut off"))?;
            let scale = scales.get(&i32::from(ch)).copied().unwrap_or(1.0);
            cols[0].push(ts as f64 / clock);
            cols[1].push(ts as f64);
            cols[2].push(f64::from(ch));
            cols[3].push(f64::from(unit));
            let k = usize::from(waves) * usize::from(words);
            for w in 0..width {
                let v = if w < k {
                    let raw = buf
                        .i16_at(at + BLOCK_HEADER_LEN + 2 * w as u64)
                        .ok_or_else(|| {
                            Error::corrupt_at(FORMAT_ID, at, "spike waveform cut off")
                        })?;
                    f64::from(raw) * scale
                } else {
                    f64::NAN
                };
                cols[4 + w].push(v);
            }
        }
        Ok(Table {
            table: 0,
            first_row: first,
            columns: cols,
        })
    }
}

impl Dataset for PlxDataset {
    fn info(&self) -> Result<FileInfo> {
        let h = &self.plx.header;
        let mut traces: Vec<TraceInfo> = self
            .traces
            .iter()
            .enumerate()
            .map(|(i, t)| self.trace_info(i, t))
            .collect();
        let mut tables = self.tables();
        let first = traces
            .first_mut()
            .map(|t| &mut t.extra)
            .or_else(|| tables.first_mut().map(|t| &mut t.extra));
        if let Some(e) = first {
            if let Some(d) = &h.recorded_at {
                e.insert("recorded_at".into(), json!(d));
            }
            if !h.acquired_with.is_empty() {
                e.insert("application".into(), json!(h.acquired_with));
            }
        }
        let mut notes = vec![format!(
            "PLX version {}: continuous channels on one sample grid form a trace (gap-free runs of blocks are sweeps; values in mV = raw × scale); spike waveforms and events are tables; timestamps count a {} Hz clock",
            h.version, h.clock_hz
        )];
        let empty = self
            .plx
            .continuous_channels
            .iter()
            .filter(|c| self.blocks(c).is_empty())
            .count();
        if empty > 0 {
            notes.push(format!(
                "{empty} continuous channel header(s) without data blocks are not listed as channels"
            ));
        }
        if self
            .plx
            .index
            .findings
            .iter()
            .any(|f| f.severity == openreadout_core::model::Severity::Error)
        {
            notes.push("structural problems found (e.g. truncation); run `check`".into());
        }
        Ok(FileInfo {
            path: self.path.display().to_string(),
            size_bytes: self.plx.file_len,
            format: PlexonReader.descriptor(),
            format_version: Some(format!("PLX {}", h.version)),
            images: Vec::new(),
            tables,
            spectra: Vec::new(),
            traces,
            plane_count: 0,
            notes,
        })
    }

    fn vendor_metadata(&self) -> Result<Value> {
        let p = &self.plx;
        let h = &p.header;
        Ok(json!({
            "container": "plx",
            "version": h.version, "comment": h.comment, "clock_hz": h.clock_hz,
            "waveform_points": h.waveform_points, "pre_threshold_points": h.pre_threshold_points,
            "recorded_at": h.recorded_at, "waveform_rate_hz": h.waveform_rate_hz,
            "last_timestamp": h.last_timestamp, "electrodes_per_channel": h.electrodes_per_channel,
            "data_electrodes_per_channel": h.data_electrodes_per_channel, "spike_bits": h.spike_bits,
            "continuous_bits": h.continuous_bits, "spike_max_mv": h.spike_max_mv,
            "continuous_max_mv": h.continuous_max_mv, "spike_preamp_gain": h.spike_preamp_gain,
            "acquired_with": h.acquired_with, "processed_with": h.processed_with,
            "spike_channels": p.spike_channels.iter().map(|c| json!({
                "name": c.name, "signal_name": c.signal_name, "channel": c.channel, "gain": c.gain,
                "filter": c.filter, "threshold": c.threshold, "unit_count": c.unit_count, "comment": c.comment,
            })).collect::<Vec<_>>(),
            "event_channels": p.event_channels.iter().map(|c| json!({
                "name": c.name, "channel": c.channel, "comment": c.comment,
            })).collect::<Vec<_>>(),
            "continuous_channels": p.continuous_channels.iter().map(|c| json!({
                "name": c.name, "channel": c.channel, "rate_hz": c.rate_hz, "gain": c.gain,
                "enabled": c.enabled, "preamp_gain": c.preamp_gain, "comment": c.comment,
                "blocks": self.blocks(c).len(),
            })).collect::<Vec<_>>(),
            "block_counts": p.index.block_counts,
            "data_start": p.data_start,
        }))
    }

    fn provenance(&self) -> ProvenanceMap {
        let mut p = ProvenanceMap::new();
        for (k, s) in [
            ("traces[].sample_rate_hz", Source::PriorArt),
            ("traces[].channels[].scale", Source::PriorArt),
            ("traces[].channels[].unit", Source::Inferred),
            ("traces[].sweep_count", Source::Inferred),
            ("traces[].start_s", Source::Inferred),
            ("tables[spikes].columns", Source::PriorArt),
            ("tables[events].columns", Source::PriorArt),
            ("traces[].extra.recorded_at", Source::PriorArt),
            ("tables[].extra.recorded_at", Source::PriorArt),
            ("traces[].extra.application", Source::PriorArt),
            ("tables[].extra.application", Source::PriorArt),
        ] {
            p.insert(k.into(), s);
        }
        p
    }

    fn entries(&self) -> Result<Vec<LsEntry>> {
        let p = &self.plx;
        let mut out = vec![LsEntry {
            kind: "header".into(),
            name: "PLX file header".into(),
            offset: Some(0),
            size: Some(crate::plx::FILE_HEADER_LEN),
            image: None,
            details: json!({"version": p.header.version}),
        }];
        out.push(LsEntry {
            kind: "header".into(),
            name: "channel headers".into(),
            offset: Some(crate::plx::FILE_HEADER_LEN),
            size: Some(p.data_start - crate::plx::FILE_HEADER_LEN),
            image: None,
            details: json!({"spike": p.spike_channels.len(), "event": p.event_channels.len(), "continuous": p.continuous_channels.len()}),
        });
        out.push(LsEntry {
            kind: "records".into(),
            name: "data blocks".into(),
            offset: Some(p.data_start),
            size: Some(p.index.data_end - p.data_start),
            image: None,
            details: json!({"blocks_by_type": p.index.block_counts}),
        });
        Ok(out)
    }

    fn read_plane(&mut self, _image: u32, _index: PlaneIndex) -> Result<Plane> {
        Err(not_images())
    }

    fn read_trace(
        &mut self,
        index: u32,
        sweep: u32,
        first_sample: u64,
        max_samples: u64,
    ) -> Result<Trace> {
        let t = self.traces.get(index as usize).cloned().ok_or_else(|| {
            Error::Usage(format!(
                "trace {index} out of range (file has {} traces)",
                self.traces.len()
            ))
        })?;
        let run = *t.runs.get(sweep as usize).ok_or_else(|| {
            Error::Usage(format!(
                "sweep {sweep} out of range (trace {index} has {} sweeps)",
                t.runs.len()
            ))
        })?;
        if first_sample > run.samples {
            return Err(Error::Usage(format!(
                "first sample {first_sample} is past the end of sweep {sweep} ({} samples)",
                run.samples
            )));
        }
        let n = max_samples.min(run.samples - first_sample).min(1 << 24);
        let (path, len) = (self.path.clone(), self.plx.file_len);
        // The blocks of one sweep interleave all channels (and spikes) in one stretch of the
        // file. When that stretch is small, read it once for every channel instead of one
        // read per block: blocks often hold only ten samples.
        let mut span: Option<(u64, u64)> = None;
        for &ci in &t.channels {
            let blocks = self.blocks(&self.plx.continuous_channels[ci]);
            for_each_piece(blocks, &run, first_sample, n, |at, take| {
                let end = at.saturating_add(2 * take);
                span = Some(span.map_or((at, end), |(lo, hi)| (lo.min(at), hi.max(end))));
                Ok(())
            })?;
        }
        let whole_span = span.filter(|(lo, hi)| hi - lo <= READ_SPAN_MAX);
        let mut win = openreadout_core::bytes::Block::default();
        let mut out = Vec::with_capacity(t.channels.len());
        for &ci in &t.channels {
            let c = self.plx.continuous_channels[ci].clone();
            let scale = self.plx.header.continuous_scale(&c);
            let mut v = Vec::with_capacity(n as usize);
            let handle = self.handle.take();
            let mut file = match handle {
                Some(file) => file,
                None => self.fs.open(&path).map_err(|e| Error::io(&path, e))?,
            };
            let blocks = self.blocks(&c);
            let res = for_each_piece(blocks, &run, first_sample, n, |at, take| {
                let end = at.saturating_add(2 * take);
                if at < win.origin || end > win.end() {
                    win = match whole_span {
                        Some((lo, hi)) => read_block(&mut file, &path, lo, hi - lo, len)?,
                        None => read_block(&mut file, &path, at, (2 * take).max(READ_WINDOW), len)?,
                    };
                }
                if end > win.end() {
                    return Err(Error::corrupt_at(FORMAT_ID, at, "continuous block cut off"));
                }
                for k in 0..take {
                    let raw = win
                        .i16_at(at + 2 * k)
                        .ok_or_else(|| Error::corrupt_at(FORMAT_ID, at, "sample cut off"))?;
                    v.push(f64::from(raw) * scale);
                }
                Ok(())
            });
            self.handle = Some(file);
            res?;
            out.push(v);
        }
        Ok(Trace {
            trace: index,
            sweep,
            first_sample,
            channels: out,
        })
    }

    fn read_table(&mut self, index: u32, first_row: u64, max_rows: u64) -> Result<Table> {
        let (s, e) = self.table_ids();
        let total = if Some(index) == s {
            self.plx.index.spikes.len() as u64
        } else if Some(index) == e {
            self.plx.index.events.len() as u64
        } else {
            return Err(Error::Usage(format!(
                "table {index} out of range (file has {} tables)",
                u32::from(s.is_some()) + u32::from(e.is_some())
            )));
        };
        if first_row > total {
            return Err(Error::Usage(format!(
                "first row {first_row} is past the last row ({total} rows)"
            )));
        }
        let n = max_rows.min(total - first_row).min(MAX_TABLE_READ);
        if Some(index) == s {
            let mut t = self.read_spikes(first_row, n)?;
            t.table = index;
            return Ok(t);
        }
        let clock = self.clock();
        let mut cols: Vec<Vec<f64>> = (0..4).map(|_| Vec::with_capacity(n as usize)).collect();
        for ev in &self.plx.index.events[first_row as usize..(first_row + n) as usize] {
            cols[0].push(ev.timestamp as f64 / clock);
            cols[1].push(ev.timestamp as f64);
            cols[2].push(f64::from(ev.channel));
            cols[3].push(f64::from(ev.value));
        }
        Ok(Table {
            table: index,
            first_row,
            columns: cols,
        })
    }

    fn check(&mut self) -> Result<CheckReport> {
        let mut r = CheckReport::new(self.path.display().to_string(), FORMAT_ID);
        r.performed("PLEX signature; file header and channel headers inside the file");
        r.performed("every data block: known type (spike, event, continuous) and its samples inside the file (truncation)");
        r.performed("continuous blocks: timestamps per channel never go backwards; gaps reported");
        for f in &self.plx.index.findings {
            r.push(f.clone());
        }
        let h = &self.plx.header;
        if h.clock_hz <= 0 {
            r.push(Finding::error(
                "bad_clock",
                format!("timestamp clock {} Hz", h.clock_hz),
            ));
        }
        if !(100..=107).contains(&h.version) {
            r.push(Finding::warning(
                "unknown_version",
                format!(
                    "PLX version {} (versions 100–106 are documented by prior art)",
                    h.version
                ),
            ));
        }
        for c in &self.plx.continuous_channels {
            let blocks = self.blocks(c);
            if blocks.is_empty() {
                continue;
            }
            if c.rate_hz <= 0 {
                r.push(Finding::error(
                    "bad_rate",
                    format!("continuous channel {} has rate {} Hz", c.name, c.rate_hz),
                ));
            }
            let back = blocks
                .iter()
                .zip(blocks.iter().skip(1))
                .filter(|(a, b)| b.timestamp < a.timestamp)
                .count();
            if back > 0 {
                r.push(Finding::warning(
                    "timestamps_decrease",
                    format!(
                        "continuous channel {}: {back} block timestamps go backwards",
                        c.name
                    ),
                ));
            }
        }
        for t in &self.traces {
            if t.runs.len() > 1 {
                r.push(Finding::info(
                    "segments",
                    format!(
                        "trace of {} channel(s) at {} Hz: {} gap-free sweeps (recording paused)",
                        t.channels.len(),
                        t.rate_hz,
                        t.runs.len()
                    ),
                ));
            }
        }
        if !self.orphans.is_empty() {
            r.push(Finding::warning(
                "unlisted_channel",
                format!(
                    "continuous blocks for channel number(s) {:?} that have no channel header (not read)",
                    self.orphans
                ),
            ));
        }
        let known: Vec<i32> = self.plx.spike_channels.iter().map(|c| c.channel).collect();
        let (path, len) = (self.path.clone(), self.plx.file_len);
        let mut unknown = 0u64;
        let offsets = self.plx.index.spikes.clone();
        let mut buf = openreadout_core::bytes::Block::default();
        for at in offsets {
            if at < buf.origin || at + BLOCK_HEADER_LEN > buf.end() {
                buf = read_block(self.handle()?, &path, at, 4 << 20, len)?;
            }
            if let Some((_, _, ch, ..)) = block_header(&buf, at)
                && !known.contains(&i32::from(ch))
            {
                unknown += 1;
            }
        }
        if unknown > 0 {
            r.push(Finding::warning(
                "unlisted_spike_channel",
                format!("{unknown} spike blocks name a channel without a header (waveforms left in counts)"),
            ));
        }
        Ok(r)
    }
}