edfarray 1.2.2__tar.gz → 1.2.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {edfarray-1.2.2 → edfarray-1.2.3}/Cargo.lock +2 -3
- {edfarray-1.2.2 → edfarray-1.2.3}/PKG-INFO +1 -1
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/Cargo.toml +1 -2
- edfarray-1.2.3/crates/edfarray-core/src/alloc.rs +53 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/annotation.rs +99 -47
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/edit.rs +35 -10
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/epoch.rs +33 -2
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/file.rs +57 -2
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/group.rs +57 -2
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/header.rs +32 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/lib.rs +1 -1
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/mmap.rs +16 -20
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/proxy.rs +36 -6
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/proxy_2d.rs +1 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/proxy_3d.rs +4 -2
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/signal.rs +26 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/writer.rs +119 -8
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/Cargo.toml +1 -1
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/aio.rs +23 -14
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/annotations.rs +3 -2
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/epoch.rs +3 -1
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/file.rs +11 -6
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/indexing.rs +27 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/proxy_2d.rs +6 -4
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/proxy_3d.rs +18 -8
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/signal.rs +10 -10
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/writer.rs +5 -3
- edfarray-1.2.2/crates/edfarray-core/src/alloc.rs +0 -33
- {edfarray-1.2.2 → edfarray-1.2.3}/Cargo.toml +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/LICENSE +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/README.md +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/README.md +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/error.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/grid.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-core/src/record.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/README.md +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/bin/gen_stubs.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/edit.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/errors.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/group.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/lib.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/crates/edfarray-python/src/numpy_util.rs +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/edfarray/__init__.py +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/edfarray/_core/__init__.pyi +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/edfarray/aio/__init__.py +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/edfarray/aio/__init__.pyi +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/edfarray/py.typed +0 -0
- {edfarray-1.2.2 → edfarray-1.2.3}/pyproject.toml +0 -0
|
@@ -196,7 +196,7 @@ dependencies = [
|
|
|
196
196
|
|
|
197
197
|
[[package]]
|
|
198
198
|
name = "edfarray"
|
|
199
|
-
version = "1.2.
|
|
199
|
+
version = "1.2.3"
|
|
200
200
|
dependencies = [
|
|
201
201
|
"chrono",
|
|
202
202
|
"edfarray-core",
|
|
@@ -209,12 +209,11 @@ dependencies = [
|
|
|
209
209
|
|
|
210
210
|
[[package]]
|
|
211
211
|
name = "edfarray-core"
|
|
212
|
-
version = "1.2.
|
|
212
|
+
version = "1.2.3"
|
|
213
213
|
dependencies = [
|
|
214
214
|
"chrono",
|
|
215
215
|
"hmac",
|
|
216
216
|
"libc",
|
|
217
|
-
"log",
|
|
218
217
|
"memmap2",
|
|
219
218
|
"proptest",
|
|
220
219
|
"rayon",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "edfarray-core"
|
|
3
|
-
version = "1.2.
|
|
3
|
+
version = "1.2.3"
|
|
4
4
|
edition = "2024"
|
|
5
5
|
description = "EDF/EDF+/BDF file parsing with memory-mapped and streaming reads"
|
|
6
6
|
license = "MIT"
|
|
@@ -12,7 +12,6 @@ categories = ["parser-implementations", "science::neuroscience"]
|
|
|
12
12
|
[dependencies]
|
|
13
13
|
chrono = { version = "0.4", default-features = false }
|
|
14
14
|
hmac = "0.13.0"
|
|
15
|
-
log = { version = "0.4.29", default-features = false }
|
|
16
15
|
memmap2 = { version = "0.9.10", default-features = false }
|
|
17
16
|
rayon = "1.11.0"
|
|
18
17
|
regex = "1.12.3"
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
use crate::error::{EdfError, Result};
|
|
2
|
+
|
|
3
|
+
/// Fill a `Vec` with `len` copies of `value`, or return [`EdfError::MemoryRequest`] naming
|
|
4
|
+
/// `name` if the allocator refuses.
|
|
5
|
+
pub fn filled_vec<T: Clone>(len: usize, value: T, name: &'static str) -> Result<Vec<T>> {
|
|
6
|
+
let bytes = len as u128 * std::mem::size_of::<T>() as u128;
|
|
7
|
+
let mut buf: Vec<T> = Vec::new();
|
|
8
|
+
if buf.try_reserve_exact(len).is_err() {
|
|
9
|
+
return Err(EdfError::MemoryRequest {
|
|
10
|
+
name,
|
|
11
|
+
elements: len,
|
|
12
|
+
bytes,
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
buf.resize(len, value);
|
|
16
|
+
Ok(buf)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// Multiply buffer dimensions, or return [`EdfError::MemoryRequest`] naming `name` on overflow.
|
|
20
|
+
pub fn checked_len(dims: &[usize], name: &'static str) -> Result<usize> {
|
|
21
|
+
dims.iter()
|
|
22
|
+
.try_fold(1usize, |acc, &d| acc.checked_mul(d))
|
|
23
|
+
.ok_or_else(|| EdfError::MemoryRequest {
|
|
24
|
+
name,
|
|
25
|
+
elements: usize::MAX,
|
|
26
|
+
bytes: dims
|
|
27
|
+
.iter()
|
|
28
|
+
.fold(1u128, |acc, &d| acc.saturating_mul(d as u128)),
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
#[cfg(test)]
|
|
33
|
+
mod tests {
|
|
34
|
+
use super::*;
|
|
35
|
+
|
|
36
|
+
#[test]
|
|
37
|
+
fn small_allocation_succeeds() {
|
|
38
|
+
let buf = filled_vec(4, 1.0f64, "test").unwrap();
|
|
39
|
+
assert_eq!(buf, vec![1.0; 4]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#[test]
|
|
43
|
+
fn checked_len_overflow_is_memory_request() {
|
|
44
|
+
assert_eq!(checked_len(&[2, 3, 4], "test").unwrap(), 24);
|
|
45
|
+
let err = checked_len(&[usize::MAX, 2], "test").unwrap_err();
|
|
46
|
+
assert!(matches!(err, EdfError::MemoryRequest { .. }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#[test]
|
|
50
|
+
fn empty_allocation_succeeds() {
|
|
51
|
+
assert!(filled_vec(0, 1.0f64, "test").unwrap().is_empty());
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -22,7 +22,8 @@ pub struct AnnotationIndex {
|
|
|
22
22
|
/// Non-timekeeping annotations, sorted by onset.
|
|
23
23
|
pub annotations: Vec<Annotation>,
|
|
24
24
|
|
|
25
|
-
/// Onset time (seconds from file start) for each data record.
|
|
25
|
+
/// Onset time (seconds from file start) for each data record. Empty unless the variant is
|
|
26
|
+
/// `+D`, because other variants use `record_index * record_duration`.
|
|
26
27
|
pub record_onsets: Vec<f64>,
|
|
27
28
|
|
|
28
29
|
/// Subsecond part of the recording start time, taken from the first timekeeping TAL.
|
|
@@ -57,7 +58,7 @@ impl AnnotationIndex {
|
|
|
57
58
|
cancel: &AtomicBool,
|
|
58
59
|
) -> Result<Self> {
|
|
59
60
|
let mut annotations = Vec::new();
|
|
60
|
-
let mut
|
|
61
|
+
let mut onsets = OnsetTracker::new(header);
|
|
61
62
|
let mut warnings = Vec::new();
|
|
62
63
|
|
|
63
64
|
let annotation_indices: Vec<usize> = header
|
|
@@ -69,13 +70,9 @@ impl AnnotationIndex {
|
|
|
69
70
|
.collect();
|
|
70
71
|
|
|
71
72
|
if annotation_indices.is_empty() {
|
|
72
|
-
let num_records = header.num_records.max(0) as usize;
|
|
73
|
-
for i in 0..num_records {
|
|
74
|
-
record_onsets.push(i as f64 * header.record_duration_secs);
|
|
75
|
-
}
|
|
76
73
|
return Ok(AnnotationIndex {
|
|
77
74
|
annotations,
|
|
78
|
-
record_onsets,
|
|
75
|
+
record_onsets: uniform_onsets(header),
|
|
79
76
|
starttime_subsecond: 0.0,
|
|
80
77
|
warnings,
|
|
81
78
|
});
|
|
@@ -111,7 +108,7 @@ impl AnnotationIndex {
|
|
|
111
108
|
// EDF+ puts the record's time-keeping TAL first in the first annotation
|
|
112
109
|
// signal. If a later signal supplied it, the scan will consume a real event.
|
|
113
110
|
if sig_pos == 0 && tal_idx == 0 && ann.text.is_empty() {
|
|
114
|
-
|
|
111
|
+
onsets.push(rec_idx, ann.onset, &mut warnings);
|
|
115
112
|
found_timekeeping = true;
|
|
116
113
|
continue;
|
|
117
114
|
}
|
|
@@ -134,7 +131,11 @@ impl AnnotationIndex {
|
|
|
134
131
|
"missing time-keeping annotation in record {rec_idx}, using calculated onset"
|
|
135
132
|
));
|
|
136
133
|
}
|
|
137
|
-
|
|
134
|
+
onsets.push(
|
|
135
|
+
rec_idx,
|
|
136
|
+
rec_idx as f64 * header.record_duration_secs,
|
|
137
|
+
&mut warnings,
|
|
138
|
+
);
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
progress.store(rec_idx + 1, Ordering::Relaxed);
|
|
@@ -144,7 +145,8 @@ impl AnnotationIndex {
|
|
|
144
145
|
// start time, so it is in [0, 1). Subtracting it makes every onset relative to the file
|
|
145
146
|
// start. A value outside that range means the file is not compliant (pyedflib rejects
|
|
146
147
|
// such files outright), so normalizing by it will silently shift every annotation.
|
|
147
|
-
let first_onset =
|
|
148
|
+
let first_onset = onsets.first.unwrap_or(0.0);
|
|
149
|
+
let mut record_onsets = onsets.kept;
|
|
148
150
|
let starttime_subsecond = if (0.0..1.0).contains(&first_onset) {
|
|
149
151
|
first_onset
|
|
150
152
|
} else {
|
|
@@ -164,13 +166,6 @@ impl AnnotationIndex {
|
|
|
164
166
|
}
|
|
165
167
|
}
|
|
166
168
|
|
|
167
|
-
validate_record_onsets(
|
|
168
|
-
&record_onsets,
|
|
169
|
-
header.record_duration_secs,
|
|
170
|
-
header.variant,
|
|
171
|
-
&mut warnings,
|
|
172
|
-
);
|
|
173
|
-
|
|
174
169
|
annotations.sort_by(|a, b| {
|
|
175
170
|
a.onset
|
|
176
171
|
.partial_cmp(&b.onset)
|
|
@@ -312,6 +307,7 @@ fn parse_onset(s: &str) -> std::result::Result<f64, String> {
|
|
|
312
307
|
|
|
313
308
|
s.parse::<f64>()
|
|
314
309
|
.map_err(|e| format!("onset parse error: {e}"))
|
|
310
|
+
.and_then(|v| finite(v, "onset", s))
|
|
315
311
|
}
|
|
316
312
|
|
|
317
313
|
/// Parse a duration. It must contain only digits and at most one dot, with no sign.
|
|
@@ -322,6 +318,15 @@ fn parse_duration(s: &str) -> std::result::Result<f64, String> {
|
|
|
322
318
|
validate_number(s, "duration")?;
|
|
323
319
|
s.parse::<f64>()
|
|
324
320
|
.map_err(|e| format!("duration parse error: {e}"))
|
|
321
|
+
.and_then(|v| finite(v, "duration", s))
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
fn finite(v: f64, label: &str, s: &str) -> std::result::Result<f64, String> {
|
|
325
|
+
if v.is_finite() {
|
|
326
|
+
Ok(v)
|
|
327
|
+
} else {
|
|
328
|
+
Err(format!("{label} {s:?} is too large to represent"))
|
|
329
|
+
}
|
|
325
330
|
}
|
|
326
331
|
|
|
327
332
|
fn validate_number(s: &str, label: &str) -> std::result::Result<(), String> {
|
|
@@ -376,37 +381,68 @@ fn skip_to_next_tal(data: &[u8], pos: &mut usize) {
|
|
|
376
381
|
}
|
|
377
382
|
}
|
|
378
383
|
|
|
379
|
-
///
|
|
380
|
-
fn
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
variant: EdfVariant,
|
|
384
|
-
warnings: &mut Vec<String>,
|
|
385
|
-
) {
|
|
386
|
-
if onsets.len() < 2 || record_duration <= 0.0 {
|
|
387
|
-
return;
|
|
384
|
+
/// Uniform record onsets for a `+D` file, and an empty table for any other variant.
|
|
385
|
+
pub(crate) fn uniform_onsets(header: &EdfHeader) -> Vec<f64> {
|
|
386
|
+
if !header.variant.is_plus_d() {
|
|
387
|
+
return Vec::new();
|
|
388
388
|
}
|
|
389
|
+
let num_records = header.num_records.max(0) as usize;
|
|
390
|
+
(0..num_records)
|
|
391
|
+
.map(|i| i as f64 * header.record_duration_secs)
|
|
392
|
+
.collect()
|
|
393
|
+
}
|
|
389
394
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
395
|
+
/// Running check of the record onsets against the file variant. It keeps the table only for `+D`.
|
|
396
|
+
struct OnsetTracker {
|
|
397
|
+
variant: EdfVariant,
|
|
398
|
+
record_duration: f64,
|
|
399
|
+
keep: bool,
|
|
400
|
+
kept: Vec<f64>,
|
|
401
|
+
first: Option<f64>,
|
|
402
|
+
prev: Option<f64>,
|
|
403
|
+
}
|
|
393
404
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
405
|
+
impl OnsetTracker {
|
|
406
|
+
fn new(header: &EdfHeader) -> Self {
|
|
407
|
+
Self {
|
|
408
|
+
variant: header.variant,
|
|
409
|
+
record_duration: header.record_duration_secs,
|
|
410
|
+
keep: header.variant.is_plus_d(),
|
|
411
|
+
kept: Vec::new(),
|
|
412
|
+
first: None,
|
|
413
|
+
prev: None,
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
fn push(&mut self, rec_idx: usize, onset: f64, warnings: &mut Vec<String>) {
|
|
418
|
+
if let Some(prev) = self.prev
|
|
419
|
+
&& self.record_duration > 0.0
|
|
420
|
+
{
|
|
421
|
+
let gap = onset - prev;
|
|
422
|
+
let expected = self.record_duration;
|
|
423
|
+
match self.variant {
|
|
424
|
+
EdfVariant::EdfPlusC | EdfVariant::BdfPlusC => {
|
|
425
|
+
if (gap - expected).abs() > 0.001 {
|
|
426
|
+
warnings.push(format!(
|
|
427
|
+
"EDF+C record {rec_idx}: expected onset gap {expected}s, got {gap:.6}s"
|
|
428
|
+
));
|
|
429
|
+
}
|
|
400
430
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
431
|
+
EdfVariant::EdfPlusD | EdfVariant::BdfPlusD => {
|
|
432
|
+
if gap < expected - 0.001 {
|
|
433
|
+
warnings.push(format!(
|
|
434
|
+
"EDF+D record {rec_idx}: onset gap {gap:.6}s is less than record \
|
|
435
|
+
duration {expected}s"
|
|
436
|
+
));
|
|
437
|
+
}
|
|
407
438
|
}
|
|
439
|
+
EdfVariant::Edf | EdfVariant::Bdf => {}
|
|
408
440
|
}
|
|
409
|
-
|
|
441
|
+
}
|
|
442
|
+
self.first.get_or_insert(onset);
|
|
443
|
+
self.prev = Some(onset);
|
|
444
|
+
if self.keep {
|
|
445
|
+
self.kept.push(onset);
|
|
410
446
|
}
|
|
411
447
|
}
|
|
412
448
|
}
|
|
@@ -562,8 +598,7 @@ mod tests {
|
|
|
562
598
|
let index = AnnotationIndex::build(&full_data, &header, &layout).unwrap();
|
|
563
599
|
|
|
564
600
|
assert!(index.annotations.is_empty());
|
|
565
|
-
|
|
566
|
-
assert!((index.record_onsets[0]).abs() < f64::EPSILON);
|
|
601
|
+
assert!(index.record_onsets.is_empty());
|
|
567
602
|
}
|
|
568
603
|
|
|
569
604
|
#[test]
|
|
@@ -572,13 +607,30 @@ mod tests {
|
|
|
572
607
|
let layout = RecordLayout::from_header(&header);
|
|
573
608
|
let index = AnnotationIndex::build(&full_data, &header, &layout).unwrap();
|
|
574
609
|
|
|
575
|
-
|
|
576
|
-
assert!(
|
|
577
|
-
assert!((index.record_onsets[1] - 1.0).abs() < f64::EPSILON);
|
|
610
|
+
assert!(index.record_onsets.is_empty());
|
|
611
|
+
assert!(index.warnings.is_empty());
|
|
578
612
|
assert_eq!(index.annotations.len(), 1);
|
|
579
613
|
assert_eq!(index.annotations[0].text, "TestEvent");
|
|
580
614
|
}
|
|
581
615
|
|
|
616
|
+
#[test]
|
|
617
|
+
fn build_index_keeps_onsets_for_plus_d() {
|
|
618
|
+
let (full_data, mut header) = build_file_with_annotations();
|
|
619
|
+
header.variant = EdfVariant::EdfPlusD;
|
|
620
|
+
let layout = RecordLayout::from_header(&header);
|
|
621
|
+
let index = AnnotationIndex::build(&full_data, &header, &layout).unwrap();
|
|
622
|
+
|
|
623
|
+
assert_eq!(index.record_onsets, vec![0.0, 1.0]);
|
|
624
|
+
assert_eq!(index.annotations.len(), 1);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
#[test]
|
|
628
|
+
fn huge_onset_and_duration_are_rejected() {
|
|
629
|
+
let huge = "9".repeat(400);
|
|
630
|
+
assert!(parse_onset(&format!("+{huge}")).is_err());
|
|
631
|
+
assert!(parse_duration(&huge).is_err());
|
|
632
|
+
}
|
|
633
|
+
|
|
582
634
|
#[test]
|
|
583
635
|
fn onset_validation_rejects_leading_dot() {
|
|
584
636
|
assert!(parse_onset("+.5").is_err());
|
|
@@ -322,18 +322,18 @@ pub fn anonymize(path: impl AsRef<Path>, opts: &AnonymizeOptions) -> Result<Anon
|
|
|
322
322
|
// Shift the binary startdate too; a raw (unparseable) one is left as it is.
|
|
323
323
|
let new_start = match header.start_datetime.as_datetime() {
|
|
324
324
|
Some(dt) => {
|
|
325
|
-
let shifted =
|
|
326
|
-
|
|
325
|
+
let shifted =
|
|
326
|
+
shift_datetime(*dt, shift).filter(|s| (MIN_YEAR..=MAX_YEAR).contains(&s.year()));
|
|
327
|
+
let Some(shifted) = shifted else {
|
|
327
328
|
return Err(EdfError::InvalidArgument {
|
|
328
329
|
name: "date_shift_days",
|
|
329
330
|
reason: format!(
|
|
330
|
-
"shifting the start date by {shift} days lands
|
|
331
|
+
"shifting the start date by {shift} days lands outside the \
|
|
331
332
|
{MIN_YEAR}-{MAX_YEAR} range representable in the EDF startdate field; \
|
|
332
|
-
pass an explicit date_shift_days"
|
|
333
|
-
shifted.year()
|
|
333
|
+
pass an explicit date_shift_days"
|
|
334
334
|
),
|
|
335
335
|
});
|
|
336
|
-
}
|
|
336
|
+
};
|
|
337
337
|
Some(shifted)
|
|
338
338
|
}
|
|
339
339
|
None => None,
|
|
@@ -671,7 +671,7 @@ fn format_edf_plus_date(d: &NaiveDate) -> String {
|
|
|
671
671
|
}
|
|
672
672
|
|
|
673
673
|
fn shift_date(d: NaiveDate, days: i32) -> Option<NaiveDate> {
|
|
674
|
-
NaiveDate::from_num_days_from_ce_opt(d.num_days_from_ce()
|
|
674
|
+
NaiveDate::from_num_days_from_ce_opt(d.num_days_from_ce().checked_add(days)?)
|
|
675
675
|
}
|
|
676
676
|
|
|
677
677
|
fn shift_maybe_date(date: &MaybeDate, days: i32) -> Option<MaybeDate> {
|
|
@@ -683,9 +683,8 @@ fn shift_maybe_date(date: &MaybeDate, days: i32) -> Option<MaybeDate> {
|
|
|
683
683
|
}
|
|
684
684
|
}
|
|
685
685
|
|
|
686
|
-
fn shift_datetime(dt: NaiveDateTime, days: i32) -> NaiveDateTime {
|
|
687
|
-
|
|
688
|
-
date.and_time(dt.time())
|
|
686
|
+
fn shift_datetime(dt: NaiveDateTime, days: i32) -> Option<NaiveDateTime> {
|
|
687
|
+
Some(shift_date(dt.date(), days)?.and_time(dt.time()))
|
|
689
688
|
}
|
|
690
689
|
|
|
691
690
|
/// The stable part of a subject's identity, used to key the pseudonym.
|
|
@@ -1269,6 +1268,32 @@ mod tests {
|
|
|
1269
1268
|
assert!(f.header().patient_id.starts_with("MCH-0234567"));
|
|
1270
1269
|
}
|
|
1271
1270
|
|
|
1271
|
+
#[test]
|
|
1272
|
+
fn anonymize_rejects_a_shift_past_the_date_range() {
|
|
1273
|
+
let dir = tempdir().unwrap();
|
|
1274
|
+
let path = build_file(&dir, "overflow.edf");
|
|
1275
|
+
for days in [i32::MAX, i32::MIN, 1_000_000_000] {
|
|
1276
|
+
let err = anonymize(
|
|
1277
|
+
&path,
|
|
1278
|
+
&AnonymizeOptions {
|
|
1279
|
+
date_shift_days: Some(days),
|
|
1280
|
+
..Default::default()
|
|
1281
|
+
},
|
|
1282
|
+
)
|
|
1283
|
+
.unwrap_err();
|
|
1284
|
+
assert!(
|
|
1285
|
+
matches!(
|
|
1286
|
+
err,
|
|
1287
|
+
EdfError::InvalidArgument {
|
|
1288
|
+
name: "date_shift_days",
|
|
1289
|
+
..
|
|
1290
|
+
}
|
|
1291
|
+
),
|
|
1292
|
+
"{days}: {err:?}"
|
|
1293
|
+
);
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1272
1297
|
#[test]
|
|
1273
1298
|
fn edits_refuse_a_file_that_is_open_and_leave_it_unchanged() {
|
|
1274
1299
|
let dir = tempdir().unwrap();
|
|
@@ -122,6 +122,7 @@ pub fn plan_epochs(
|
|
|
122
122
|
post: f64,
|
|
123
123
|
) -> Result<EpochPlan> {
|
|
124
124
|
validate_pre_post(pre, post)?;
|
|
125
|
+
group.check_matches(file.header())?;
|
|
125
126
|
if group.kind() != GroupKind::Rectangular {
|
|
126
127
|
return Err(epoch_argument(
|
|
127
128
|
"group",
|
|
@@ -277,6 +278,7 @@ pub fn extract_epochs(
|
|
|
277
278
|
plan: &EpochPlan,
|
|
278
279
|
pad: EpochPad,
|
|
279
280
|
) -> Result<(Vec<f64>, Vec<bool>, Vec<usize>)> {
|
|
281
|
+
group.check_matches(file.header())?;
|
|
280
282
|
let EpochPlan {
|
|
281
283
|
windows,
|
|
282
284
|
valid,
|
|
@@ -434,7 +436,7 @@ pub(crate) fn read_samples(proxy: &SignalProxy, s_start: usize, s_end: usize) ->
|
|
|
434
436
|
return Ok(Vec::new());
|
|
435
437
|
}
|
|
436
438
|
let count = s_end - s_start;
|
|
437
|
-
let mut buf =
|
|
439
|
+
let mut buf = crate::alloc::filled_vec(count, 0.0f64, "samples")?;
|
|
438
440
|
proxy.read_physical(s_start, s_end, &mut buf)?;
|
|
439
441
|
Ok(buf)
|
|
440
442
|
}
|
|
@@ -448,7 +450,7 @@ pub(crate) fn read_digital_samples(
|
|
|
448
450
|
return Ok(Vec::new());
|
|
449
451
|
}
|
|
450
452
|
let count = s_end - s_start;
|
|
451
|
-
let mut buf =
|
|
453
|
+
let mut buf = crate::alloc::filled_vec(count, 0i32, "samples")?;
|
|
452
454
|
proxy.read_digital(s_start, s_end, &mut buf)?;
|
|
453
455
|
Ok(buf)
|
|
454
456
|
}
|
|
@@ -457,6 +459,7 @@ pub(crate) fn read_digital_samples(
|
|
|
457
459
|
mod tests {
|
|
458
460
|
use super::*;
|
|
459
461
|
use crate::group::SignalGroup;
|
|
462
|
+
use crate::header::EdfVariant;
|
|
460
463
|
use std::io::Write;
|
|
461
464
|
use tempfile::NamedTempFile;
|
|
462
465
|
|
|
@@ -517,6 +520,34 @@ mod tests {
|
|
|
517
520
|
SignalGroup::from_indices(file.header(), indices).unwrap()
|
|
518
521
|
}
|
|
519
522
|
|
|
523
|
+
#[test]
|
|
524
|
+
fn forced_plus_d_without_annotation_channel_uses_uniform_timing() {
|
|
525
|
+
let f = NamedTempFile::new().unwrap();
|
|
526
|
+
write_contig(f.path().to_str().unwrap(), 10, 10.0, 2);
|
|
527
|
+
let plus_c = crate::file::EdfFile::open(f.path()).unwrap();
|
|
528
|
+
let plus_d =
|
|
529
|
+
crate::file::EdfFile::open_with_variant(f.path(), EdfVariant::EdfPlusD).unwrap();
|
|
530
|
+
let plan_c = plan_epochs(&plus_c, &group_of(&plus_c, &[0, 1]), &[3.0], 0.5, 0.5).unwrap();
|
|
531
|
+
let plan_d = plan_epochs(&plus_d, &group_of(&plus_d, &[0, 1]), &[3.0], 0.5, 0.5).unwrap();
|
|
532
|
+
assert_eq!(plan_d.valid, vec![true]);
|
|
533
|
+
assert_eq!(plan_c, plan_d);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
#[test]
|
|
537
|
+
fn group_from_another_file_is_rejected() {
|
|
538
|
+
let a = NamedTempFile::new().unwrap();
|
|
539
|
+
let b = NamedTempFile::new().unwrap();
|
|
540
|
+
write_contig(a.path().to_str().unwrap(), 10, 4.0, 2);
|
|
541
|
+
write_contig(b.path().to_str().unwrap(), 10, 8.0, 2);
|
|
542
|
+
let fa = crate::file::EdfFile::open(a.path()).unwrap();
|
|
543
|
+
let fb = crate::file::EdfFile::open(b.path()).unwrap();
|
|
544
|
+
let foreign = group_of(&fa, &[0, 1]);
|
|
545
|
+
assert!(plan_epochs(&fb, &foreign, &[3.0], 0.5, 0.5).is_err());
|
|
546
|
+
let own = group_of(&fb, &[0, 1]);
|
|
547
|
+
let plan = plan_epochs(&fb, &own, &[3.0], 0.5, 0.5).unwrap();
|
|
548
|
+
assert!(extract_epochs(&fb, &foreign, &plan, EpochPad::Drop).is_err());
|
|
549
|
+
}
|
|
550
|
+
|
|
520
551
|
#[test]
|
|
521
552
|
fn plan_rejects_absurd_window_width() {
|
|
522
553
|
let f = NamedTempFile::new().unwrap();
|
|
@@ -10,7 +10,7 @@ use regex::RegexBuilder;
|
|
|
10
10
|
use crate::annotation::Annotation;
|
|
11
11
|
use crate::error::{EdfError, Result};
|
|
12
12
|
use crate::group::{PadMode, SignalGroup};
|
|
13
|
-
use crate::header::{EdfHeader, EdfVariant, PatientInfo, RecordingInfo, read_usize};
|
|
13
|
+
use crate::header::{EdfHeader, EdfVariant, MaybeDateTime, PatientInfo, RecordingInfo, read_usize};
|
|
14
14
|
use crate::mmap::{Advice, MappedFile, ScanMode};
|
|
15
15
|
use crate::proxy::SignalProxy;
|
|
16
16
|
use crate::proxy_2d::Proxy2D;
|
|
@@ -412,6 +412,7 @@ impl EdfFile {
|
|
|
412
412
|
let target_variant = variant.unwrap_or(self.variant());
|
|
413
413
|
let header = &self.file.header;
|
|
414
414
|
|
|
415
|
+
// a placeholder for an unparseable date, which the copy restores after writing
|
|
415
416
|
let whole_seconds = match header.start_datetime.as_datetime() {
|
|
416
417
|
Some(dt) => *dt,
|
|
417
418
|
None => NaiveDateTime::new(
|
|
@@ -536,7 +537,10 @@ impl EdfFile {
|
|
|
536
537
|
record_duration_secs: record_dur,
|
|
537
538
|
signals: signals_spec,
|
|
538
539
|
annotation_bytes_per_record,
|
|
539
|
-
|
|
540
|
+
// the writer rejects an empty table, and a zero-record copy needs none
|
|
541
|
+
record_onsets: source_onsets
|
|
542
|
+
.clone()
|
|
543
|
+
.filter(|o| keep_onsets && !o.is_empty()),
|
|
540
544
|
};
|
|
541
545
|
|
|
542
546
|
// a source header may hold non-ASCII bytes, which the copy writes as '?'
|
|
@@ -564,6 +568,10 @@ impl EdfFile {
|
|
|
564
568
|
}
|
|
565
569
|
|
|
566
570
|
writer.finish()?;
|
|
571
|
+
// the writer needs a real date, so put an unparseable source date back afterwards
|
|
572
|
+
if let MaybeDateTime::Raw { date, time } = &header.start_datetime {
|
|
573
|
+
crate::writer::patch_start_fields(path, date, time)?;
|
|
574
|
+
}
|
|
567
575
|
Ok(())
|
|
568
576
|
}
|
|
569
577
|
}
|
|
@@ -657,6 +665,17 @@ impl EdfFile {
|
|
|
657
665
|
path: path.as_ref().to_path_buf(),
|
|
658
666
|
source: e,
|
|
659
667
|
})?;
|
|
668
|
+
// same advisory lock as a full open, so the read does not race an active writer
|
|
669
|
+
if let Err(std::fs::TryLockError::WouldBlock) = file.try_lock_shared() {
|
|
670
|
+
return Err(EdfError::Io {
|
|
671
|
+
path: path.as_ref().to_path_buf(),
|
|
672
|
+
op: "opening",
|
|
673
|
+
source: std::io::Error::new(
|
|
674
|
+
std::io::ErrorKind::ResourceBusy,
|
|
675
|
+
"an EdfWriter is still writing this file",
|
|
676
|
+
),
|
|
677
|
+
});
|
|
678
|
+
}
|
|
660
679
|
|
|
661
680
|
// Read 256-byte main header, then 256 bytes per signal.
|
|
662
681
|
let mut buf = vec![b' '; 256];
|
|
@@ -749,6 +768,42 @@ mod tests {
|
|
|
749
768
|
assert!(got[0].text.starts_with("a"));
|
|
750
769
|
}
|
|
751
770
|
|
|
771
|
+
#[test]
|
|
772
|
+
fn write_to_keeps_an_unparseable_start_date() {
|
|
773
|
+
let file = build_synthetic_file(2, false, 0);
|
|
774
|
+
let mut bytes = std::fs::read(file.path()).unwrap();
|
|
775
|
+
bytes[168..176].copy_from_slice(b"xx.xx.xx");
|
|
776
|
+
let mut patched = NamedTempFile::new().unwrap();
|
|
777
|
+
patched.write_all(&bytes).unwrap();
|
|
778
|
+
patched.flush().unwrap();
|
|
779
|
+
|
|
780
|
+
let f = EdfFile::open(patched.path()).unwrap();
|
|
781
|
+
assert!(f.header().start_datetime.as_datetime().is_none());
|
|
782
|
+
let dir = tempfile::TempDir::new().unwrap();
|
|
783
|
+
let dst = dir.path().join("dst.edf");
|
|
784
|
+
f.write_to(&dst, None).unwrap();
|
|
785
|
+
let out = std::fs::read(&dst).unwrap();
|
|
786
|
+
assert_eq!(&out[168..184], &bytes[168..184]);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
#[test]
|
|
790
|
+
fn write_to_copies_an_empty_plus_d_file() {
|
|
791
|
+
use crate::writer::{EdfWriter, WriterSignal, WriterSpec};
|
|
792
|
+
let dir = tempfile::TempDir::new().unwrap();
|
|
793
|
+
let src = dir.path().join("src.edf");
|
|
794
|
+
let mut spec = WriterSpec::new(EdfVariant::EdfPlusD, 1.0);
|
|
795
|
+
spec.signals = vec![WriterSignal::new(
|
|
796
|
+
"EEG", "uV", -100.0, 100.0, -32768, 32767, 4,
|
|
797
|
+
)];
|
|
798
|
+
EdfWriter::create(&src, spec).unwrap().finish().unwrap();
|
|
799
|
+
|
|
800
|
+
let f = EdfFile::open(&src).unwrap();
|
|
801
|
+
assert_eq!(f.num_records(), 0);
|
|
802
|
+
let dst = dir.path().join("dst.edf");
|
|
803
|
+
f.write_to(&dst, None).unwrap();
|
|
804
|
+
assert_eq!(EdfFile::open(&dst).unwrap().variant(), EdfVariant::EdfPlusD);
|
|
805
|
+
}
|
|
806
|
+
|
|
752
807
|
#[test]
|
|
753
808
|
fn inspect_clamps_overdeclared_record_count() {
|
|
754
809
|
let file = build_synthetic_file(2, false, 0);
|
|
@@ -80,8 +80,8 @@ impl SignalGroup {
|
|
|
80
80
|
|
|
81
81
|
for &i in &indices[1..] {
|
|
82
82
|
let s = &header.signals[i];
|
|
83
|
-
|
|
84
|
-
if
|
|
83
|
+
// signals share one record duration, so equal rates mean equal samples per record
|
|
84
|
+
if s.num_samples != first_spr {
|
|
85
85
|
all_same_rate = false;
|
|
86
86
|
}
|
|
87
87
|
let total = num_records * s.num_samples;
|
|
@@ -115,6 +115,25 @@ impl SignalGroup {
|
|
|
115
115
|
})
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
/// Return `InvalidArgument` unless the group matches a group built from `header`.
|
|
119
|
+
pub(crate) fn check_matches(&self, header: &EdfHeader) -> Result<()> {
|
|
120
|
+
let rebuilt = Self::from_indices(header, &self.indices)?;
|
|
121
|
+
if rebuilt.kind != self.kind
|
|
122
|
+
|| rebuilt.sample_rate != self.sample_rate
|
|
123
|
+
|| rebuilt.samples_per_record != self.samples_per_record
|
|
124
|
+
|| rebuilt.min_samples != self.min_samples
|
|
125
|
+
|| rebuilt.max_samples != self.max_samples
|
|
126
|
+
{
|
|
127
|
+
return Err(EdfError::InvalidArgument {
|
|
128
|
+
name: "group",
|
|
129
|
+
reason: "the signal group does not match this file; build the group from the \
|
|
130
|
+
same file as the proxy"
|
|
131
|
+
.into(),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
Ok(())
|
|
135
|
+
}
|
|
136
|
+
|
|
118
137
|
/// File-level signal indices in the group.
|
|
119
138
|
pub fn indices(&self) -> &[usize] {
|
|
120
139
|
&self.indices
|
|
@@ -269,6 +288,42 @@ mod tests {
|
|
|
269
288
|
assert!(matches!(err, EdfError::SignalOutOfRange { .. }));
|
|
270
289
|
}
|
|
271
290
|
|
|
291
|
+
#[test]
|
|
292
|
+
fn huge_rate_is_not_equal_to_finite_rate() {
|
|
293
|
+
let h = header(
|
|
294
|
+
vec![sig("EEG0", 99_999_999, false), sig("EEG1", 1, false)],
|
|
295
|
+
1,
|
|
296
|
+
1e-310,
|
|
297
|
+
);
|
|
298
|
+
let g = SignalGroup::from_indices(&h, &[0, 1]).unwrap();
|
|
299
|
+
assert_eq!(g.kind, GroupKind::Open);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
#[test]
|
|
303
|
+
fn check_matches_rejects_other_file() {
|
|
304
|
+
let two = header(
|
|
305
|
+
vec![sig("EEG0", 256, false), sig("EEG1", 256, false)],
|
|
306
|
+
4,
|
|
307
|
+
1.0,
|
|
308
|
+
);
|
|
309
|
+
let one = header(vec![sig("EEG0", 256, false)], 4, 1.0);
|
|
310
|
+
let mixed = header(
|
|
311
|
+
vec![sig("EEG0", 256, false), sig("EEG1", 128, false)],
|
|
312
|
+
4,
|
|
313
|
+
1.0,
|
|
314
|
+
);
|
|
315
|
+
let g = SignalGroup::from_indices(&two, &[0, 1]).unwrap();
|
|
316
|
+
assert!(g.check_matches(&two).is_ok());
|
|
317
|
+
assert!(matches!(
|
|
318
|
+
g.check_matches(&one),
|
|
319
|
+
Err(EdfError::SignalOutOfRange { .. })
|
|
320
|
+
));
|
|
321
|
+
assert!(matches!(
|
|
322
|
+
g.check_matches(&mixed),
|
|
323
|
+
Err(EdfError::InvalidArgument { .. })
|
|
324
|
+
));
|
|
325
|
+
}
|
|
326
|
+
|
|
272
327
|
#[test]
|
|
273
328
|
fn covers_all_ordinary_default_false() {
|
|
274
329
|
let h = header(vec![sig("EEG0", 256, false)], 4, 1.0);
|