edfarray 1.2.1__tar.gz → 1.2.2__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.1 → edfarray-1.2.2}/Cargo.lock +2 -2
- {edfarray-1.2.1 → edfarray-1.2.2}/PKG-INFO +1 -1
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/Cargo.toml +1 -1
- edfarray-1.2.2/crates/edfarray-core/src/alloc.rs +33 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/edit.rs +66 -17
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/epoch.rs +68 -2
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/error.rs +9 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/file.rs +253 -61
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/lib.rs +1 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/mmap.rs +7 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/proxy.rs +57 -6
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/proxy_2d.rs +17 -1
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/proxy_3d.rs +5 -4
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/signal.rs +35 -3
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/writer.rs +426 -14
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/Cargo.toml +1 -1
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/aio.rs +2 -1
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/epoch.rs +12 -5
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/errors.rs +4 -0
- edfarray-1.2.2/crates/edfarray-python/src/numpy_util.rs +41 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/proxy_2d.rs +3 -9
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/proxy_3d.rs +2 -1
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/writer.rs +2 -1
- edfarray-1.2.1/crates/edfarray-python/src/numpy_util.rs +0 -6
- {edfarray-1.2.1 → edfarray-1.2.2}/Cargo.toml +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/LICENSE +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/README.md +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/README.md +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/annotation.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/grid.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/group.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/header.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-core/src/record.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/README.md +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/annotations.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/bin/gen_stubs.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/edit.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/file.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/group.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/indexing.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/lib.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/crates/edfarray-python/src/signal.rs +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/edfarray/__init__.py +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/edfarray/_core/__init__.pyi +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/edfarray/aio/__init__.py +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/edfarray/aio/__init__.pyi +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/edfarray/py.typed +0 -0
- {edfarray-1.2.1 → edfarray-1.2.2}/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.2"
|
|
200
200
|
dependencies = [
|
|
201
201
|
"chrono",
|
|
202
202
|
"edfarray-core",
|
|
@@ -209,7 +209,7 @@ dependencies = [
|
|
|
209
209
|
|
|
210
210
|
[[package]]
|
|
211
211
|
name = "edfarray-core"
|
|
212
|
-
version = "1.2.
|
|
212
|
+
version = "1.2.2"
|
|
213
213
|
dependencies = [
|
|
214
214
|
"chrono",
|
|
215
215
|
"hmac",
|
|
@@ -0,0 +1,33 @@
|
|
|
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(crate) 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
|
+
#[cfg(test)]
|
|
20
|
+
mod tests {
|
|
21
|
+
use super::*;
|
|
22
|
+
|
|
23
|
+
#[test]
|
|
24
|
+
fn small_allocation_succeeds() {
|
|
25
|
+
let buf = filled_vec(4, 1.0f64, "test").unwrap();
|
|
26
|
+
assert_eq!(buf, vec![1.0; 4]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
#[test]
|
|
30
|
+
fn empty_allocation_succeeds() {
|
|
31
|
+
assert!(filled_vec(0, 1.0f64, "test").unwrap().is_empty());
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -413,25 +413,29 @@ impl AuditReport {
|
|
|
413
413
|
|
|
414
414
|
/// Derive identity terms (lowercased) from the patient name, patient code, technician, and
|
|
415
415
|
/// admin code subfields.
|
|
416
|
+
/// Fall back to the tokens of the raw patient field when no subfield gives a term.
|
|
416
417
|
fn identity_terms(header: &EdfHeader) -> Vec<String> {
|
|
417
418
|
let mut terms: Vec<String> = Vec::new();
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
};
|
|
428
|
-
add_tokens(header.patient.name.as_deref(), 3);
|
|
429
|
-
add_tokens(header.patient.code.as_deref(), 4);
|
|
430
|
-
add_tokens(header.recording.technician.as_deref(), 3);
|
|
431
|
-
add_tokens(header.recording.admin_code.as_deref(), 4);
|
|
419
|
+
add_identity_tokens(&mut terms, header.patient.name.as_deref(), 3);
|
|
420
|
+
add_identity_tokens(&mut terms, header.patient.code.as_deref(), 4);
|
|
421
|
+
add_identity_tokens(&mut terms, header.recording.technician.as_deref(), 3);
|
|
422
|
+
add_identity_tokens(&mut terms, header.recording.admin_code.as_deref(), 4);
|
|
423
|
+
if terms.is_empty() {
|
|
424
|
+
add_identity_tokens(&mut terms, Some(&header.patient_id), 3);
|
|
425
|
+
}
|
|
432
426
|
terms
|
|
433
427
|
}
|
|
434
428
|
|
|
429
|
+
fn add_identity_tokens(terms: &mut Vec<String>, value: Option<&str>, min_len: usize) {
|
|
430
|
+
let Some(value) = value else { return };
|
|
431
|
+
for token in value.split([' ', '_']) {
|
|
432
|
+
let t = token.trim().to_lowercase();
|
|
433
|
+
if t.len() >= min_len && t != "x" && !terms.contains(&t) {
|
|
434
|
+
terms.push(t);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
435
439
|
/// Scan signal labels, transducers, prefilters, and annotation text for strings that repeat
|
|
436
440
|
/// the patient identity currently stored in the header fields. This function does not write
|
|
437
441
|
/// to the file.
|
|
@@ -731,8 +735,8 @@ fn generate_pseudonym(seed: &str, subject: &str) -> String {
|
|
|
731
735
|
}
|
|
732
736
|
|
|
733
737
|
/// Date shift in days, taken from `seed`. The hash is not stretched, on purpose. The shift has
|
|
734
|
-
/// only `span` possible values, so an attacker can try all of them, whatever the seed
|
|
735
|
-
/// A stretch will give no protection here and will double the cost of every call.
|
|
738
|
+
/// only `2 * span - 2` possible values, so an attacker can try all of them, whatever the seed
|
|
739
|
+
/// hash is. A stretch will give no protection here and will double the cost of every call.
|
|
736
740
|
fn derive_shift_days(seed: &str) -> i32 {
|
|
737
741
|
let digest = hmac_sha256(seed.as_bytes(), b"dates", b"");
|
|
738
742
|
// +/-10 years, skipping 0 (a zero shift leaves dates untouched).
|
|
@@ -786,7 +790,7 @@ mod tests {
|
|
|
786
790
|
),
|
|
787
791
|
record_duration_secs: 1.0,
|
|
788
792
|
signals: vec![WriterSignal::new(
|
|
789
|
-
"EEG Haagansen
|
|
793
|
+
"EEG Haagansen",
|
|
790
794
|
"uV",
|
|
791
795
|
-3200.0,
|
|
792
796
|
3200.0,
|
|
@@ -1079,6 +1083,51 @@ mod tests {
|
|
|
1079
1083
|
assert_eq!(residual.hits.len(), 2);
|
|
1080
1084
|
}
|
|
1081
1085
|
|
|
1086
|
+
#[test]
|
|
1087
|
+
fn audit_falls_back_to_raw_patient_field_tokens() {
|
|
1088
|
+
let dir = tempdir().unwrap();
|
|
1089
|
+
let path = dir.path().join("free.edf");
|
|
1090
|
+
let spec = WriterSpec {
|
|
1091
|
+
variant: EdfVariant::EdfPlusC,
|
|
1092
|
+
patient_id: "John Smith".into(),
|
|
1093
|
+
recording_id: "Startdate 01-JAN-2026 X X X".into(),
|
|
1094
|
+
start_datetime: NaiveDateTime::new(
|
|
1095
|
+
NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
|
|
1096
|
+
NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
|
|
1097
|
+
),
|
|
1098
|
+
record_duration_secs: 1.0,
|
|
1099
|
+
signals: vec![WriterSignal::new(
|
|
1100
|
+
"EEG Fpz", "uV", -3200.0, 3200.0, -32768, 32767, 32,
|
|
1101
|
+
)],
|
|
1102
|
+
annotation_bytes_per_record: None,
|
|
1103
|
+
record_onsets: None,
|
|
1104
|
+
};
|
|
1105
|
+
let anns = vec![Annotation {
|
|
1106
|
+
onset: 0.5,
|
|
1107
|
+
duration: None,
|
|
1108
|
+
text: "John Smith sat up".into(),
|
|
1109
|
+
}];
|
|
1110
|
+
write_edf(&path, spec, &[&vec![0.0f64; 64]], &anns).unwrap();
|
|
1111
|
+
|
|
1112
|
+
let report = audit(&path).unwrap();
|
|
1113
|
+
assert!(report.terms.contains(&"john".to_string()));
|
|
1114
|
+
assert!(report.terms.contains(&"smith".to_string()));
|
|
1115
|
+
assert!(!report.is_clean(), "unexpected clean: {:?}", report.hits);
|
|
1116
|
+
|
|
1117
|
+
let ann_hits: Vec<_> = report
|
|
1118
|
+
.hits
|
|
1119
|
+
.iter()
|
|
1120
|
+
.filter(|h| h.signal_index.is_none())
|
|
1121
|
+
.collect();
|
|
1122
|
+
assert_eq!(ann_hits.len(), 2);
|
|
1123
|
+
assert_eq!(ann_hits[0].term, "john");
|
|
1124
|
+
assert_eq!(ann_hits[1].term, "smith");
|
|
1125
|
+
|
|
1126
|
+
let result = anonymize(&path, &AnonymizeOptions::default()).unwrap();
|
|
1127
|
+
assert!(result.scrubbed_terms.contains(&"john".to_string()));
|
|
1128
|
+
assert!(result.scrubbed_terms.contains(&"smith".to_string()));
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1082
1131
|
#[test]
|
|
1083
1132
|
fn audit_clean_on_scrubbed_file() {
|
|
1084
1133
|
let dir = tempdir().unwrap();
|
|
@@ -166,6 +166,22 @@ pub fn plan_epochs(
|
|
|
166
166
|
// a row is always grid index `first + j`, where `first` is the first sample at or after
|
|
167
167
|
// the window start.
|
|
168
168
|
let n_samples = first_sample_at_or_after((pre + post) * sample_rate).max(1) as usize;
|
|
169
|
+
// a row that cannot fit in the address space is a units typo, not a request for more RAM
|
|
170
|
+
let row_bytes = group
|
|
171
|
+
.indices()
|
|
172
|
+
.len()
|
|
173
|
+
.checked_mul(n_samples)
|
|
174
|
+
.and_then(|row| row.checked_mul(std::mem::size_of::<f64>()));
|
|
175
|
+
if row_bytes.is_none_or(|bytes| bytes > isize::MAX as usize) {
|
|
176
|
+
return Err(epoch_argument(
|
|
177
|
+
"pre/post",
|
|
178
|
+
format!(
|
|
179
|
+
"window width {n_samples} samples x {} channels does not fit in one output \
|
|
180
|
+
row; pre + post is too large",
|
|
181
|
+
group.indices().len()
|
|
182
|
+
),
|
|
183
|
+
));
|
|
184
|
+
}
|
|
169
185
|
let n = n_samples as i64;
|
|
170
186
|
let spr_i = spr as i64;
|
|
171
187
|
|
|
@@ -311,8 +327,22 @@ pub fn extract_epochs(
|
|
|
311
327
|
_ => valid.clone(),
|
|
312
328
|
};
|
|
313
329
|
|
|
314
|
-
let row_size = nc
|
|
315
|
-
|
|
330
|
+
let row_size = nc.checked_mul(n).ok_or_else(|| {
|
|
331
|
+
epoch_argument(
|
|
332
|
+
"n_samples",
|
|
333
|
+
format!("{n} samples x {nc} channels overflows the row size"),
|
|
334
|
+
)
|
|
335
|
+
})?;
|
|
336
|
+
let total = kept.len().checked_mul(row_size).ok_or_else(|| {
|
|
337
|
+
epoch_argument(
|
|
338
|
+
"epochs",
|
|
339
|
+
format!(
|
|
340
|
+
"{} epochs x {row_size} samples per row overflows the output size",
|
|
341
|
+
kept.len()
|
|
342
|
+
),
|
|
343
|
+
)
|
|
344
|
+
})?;
|
|
345
|
+
let mut data = crate::alloc::filled_vec(total, fill, "epochs")?;
|
|
316
346
|
|
|
317
347
|
// Each task owns one row block (disjoint mutable slice), so the parallel closure never
|
|
318
348
|
// shares `data`. Nothing to fill when no rows survived or the row width collapsed to zero.
|
|
@@ -487,6 +517,42 @@ mod tests {
|
|
|
487
517
|
SignalGroup::from_indices(file.header(), indices).unwrap()
|
|
488
518
|
}
|
|
489
519
|
|
|
520
|
+
#[test]
|
|
521
|
+
fn plan_rejects_absurd_window_width() {
|
|
522
|
+
let f = NamedTempFile::new().unwrap();
|
|
523
|
+
write_contig(f.path().to_str().unwrap(), 10, 10.0, 2);
|
|
524
|
+
let file = crate::file::EdfFile::open(f.path()).unwrap();
|
|
525
|
+
let group = group_of(&file, &[0, 1]);
|
|
526
|
+
let err = plan_epochs(&file, &group, &[1.0], 1e300, 1e300).unwrap_err();
|
|
527
|
+
assert!(
|
|
528
|
+
matches!(
|
|
529
|
+
err,
|
|
530
|
+
EdfError::InvalidArgument {
|
|
531
|
+
name: "pre/post",
|
|
532
|
+
..
|
|
533
|
+
}
|
|
534
|
+
),
|
|
535
|
+
"{err:?}"
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
#[test]
|
|
540
|
+
fn extract_epochs_absurd_width_raises_instead_of_aborting() {
|
|
541
|
+
let f = NamedTempFile::new().unwrap();
|
|
542
|
+
// 1000 events x 2 channels x 2e8 samples is about 3.2 TB
|
|
543
|
+
write_contig(f.path().to_str().unwrap(), 10, 10.0, 2);
|
|
544
|
+
let file = crate::file::EdfFile::open(f.path()).unwrap();
|
|
545
|
+
let group = group_of(&file, &[0, 1]);
|
|
546
|
+
let plan = plan_epochs(&file, &group, &vec![0.0; 1000], 1e7, 1e7).unwrap();
|
|
547
|
+
assert_eq!(plan.n_samples, 200_000_000);
|
|
548
|
+
let err = extract_epochs(&file, &group, &plan, EpochPad::Fill(PadMode::Nan)).unwrap_err();
|
|
549
|
+
assert!(matches!(err, EdfError::MemoryRequest { .. }), "{err:?}");
|
|
550
|
+
|
|
551
|
+
let (data, _, dropped) = extract_epochs(&file, &group, &plan, EpochPad::Drop).unwrap();
|
|
552
|
+
assert!(data.is_empty());
|
|
553
|
+
assert_eq!(dropped.len(), 1000);
|
|
554
|
+
}
|
|
555
|
+
|
|
490
556
|
#[test]
|
|
491
557
|
fn contiguous_window_math() {
|
|
492
558
|
let f = NamedTempFile::new().unwrap();
|
|
@@ -74,6 +74,15 @@ pub enum EdfError {
|
|
|
74
74
|
|
|
75
75
|
#[error("{name}: {reason}")]
|
|
76
76
|
InvalidArgument { name: &'static str, reason: String },
|
|
77
|
+
|
|
78
|
+
/// The allocator refused a read or epoch buffer. Python raises it as `MemoryError`.
|
|
79
|
+
#[error("cannot allocate {bytes} bytes for {name} ({elements} elements)")]
|
|
80
|
+
MemoryRequest {
|
|
81
|
+
name: &'static str,
|
|
82
|
+
elements: usize,
|
|
83
|
+
// u128 because elements * size_of can exceed usize
|
|
84
|
+
bytes: u128,
|
|
85
|
+
},
|
|
77
86
|
}
|
|
78
87
|
|
|
79
88
|
pub type Result<T> = std::result::Result<T, EdfError>;
|
|
@@ -407,7 +407,7 @@ impl EdfFile {
|
|
|
407
407
|
signals: Option<&[usize]>,
|
|
408
408
|
) -> Result<()> {
|
|
409
409
|
use crate::writer::{EdfWriter, WriterSignal, WriterSpec};
|
|
410
|
-
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
|
|
410
|
+
use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike};
|
|
411
411
|
|
|
412
412
|
let target_variant = variant.unwrap_or(self.variant());
|
|
413
413
|
let header = &self.file.header;
|
|
@@ -467,21 +467,6 @@ impl EdfFile {
|
|
|
467
467
|
});
|
|
468
468
|
}
|
|
469
469
|
|
|
470
|
-
// Inherit the source annotation channel's byte budget so copying a file whose
|
|
471
|
-
// annotation channel is larger than the writer's 120-byte default does not
|
|
472
|
-
// overflow. The budget is in bytes; `EdfWriter::create` rounds it up to a
|
|
473
|
-
// multiple of the target sample size.
|
|
474
|
-
let annotation_bytes_per_record = if target_variant.is_plus() {
|
|
475
|
-
let source_sample_size = header.variant.sample_size_bytes();
|
|
476
|
-
header
|
|
477
|
-
.signals
|
|
478
|
-
.iter()
|
|
479
|
-
.find(|s| s.is_annotation)
|
|
480
|
-
.map(|s| s.num_samples * source_sample_size)
|
|
481
|
-
} else {
|
|
482
|
-
None
|
|
483
|
-
};
|
|
484
|
-
|
|
485
470
|
// An EDF+D to EDF+D copy preserves the source record onsets, so the discontinuity
|
|
486
471
|
// survives the rewrite. Any other target flattens to uniform timing. Reading the
|
|
487
472
|
// table blocks until the source annotation scan finishes.
|
|
@@ -493,19 +478,6 @@ impl EdfFile {
|
|
|
493
478
|
let keep_onsets = source_onsets.is_some() && target_variant.is_plus_d();
|
|
494
479
|
let pack_gaps = source_onsets.is_some() && !target_variant.is_plus_d();
|
|
495
480
|
|
|
496
|
-
let spec = WriterSpec {
|
|
497
|
-
variant: target_variant,
|
|
498
|
-
patient_id: header.patient_id.clone(),
|
|
499
|
-
recording_id: header.recording_id.clone(),
|
|
500
|
-
start_datetime,
|
|
501
|
-
record_duration_secs: header.record_duration_secs,
|
|
502
|
-
signals: signals_spec,
|
|
503
|
-
annotation_bytes_per_record,
|
|
504
|
-
record_onsets: source_onsets.clone().filter(|_| keep_onsets),
|
|
505
|
-
};
|
|
506
|
-
|
|
507
|
-
let mut writer = EdfWriter::create(path, spec)?;
|
|
508
|
-
|
|
509
481
|
let record_dur = header.record_duration_secs;
|
|
510
482
|
let num_records = self.num_records();
|
|
511
483
|
let source_onset = |r: usize| {
|
|
@@ -514,12 +486,61 @@ impl EdfFile {
|
|
|
514
486
|
.and_then(|o| o.get(r).copied())
|
|
515
487
|
.unwrap_or(r as f64 * record_dur)
|
|
516
488
|
};
|
|
489
|
+
let dest_onset = |r: usize| {
|
|
490
|
+
if keep_onsets {
|
|
491
|
+
source_onset(r)
|
|
492
|
+
} else {
|
|
493
|
+
r as f64 * record_dur
|
|
494
|
+
}
|
|
495
|
+
};
|
|
517
496
|
let annotations = if target_variant.is_plus() {
|
|
518
497
|
self.annotations()
|
|
519
498
|
} else {
|
|
520
499
|
Vec::new()
|
|
521
500
|
};
|
|
522
|
-
|
|
501
|
+
|
|
502
|
+
// assign annotations to records first, so the budget fits the largest re-encoded record
|
|
503
|
+
let per_record = assign_annotations(
|
|
504
|
+
&annotations,
|
|
505
|
+
num_records,
|
|
506
|
+
record_dur,
|
|
507
|
+
source_onset,
|
|
508
|
+
pack_gaps,
|
|
509
|
+
);
|
|
510
|
+
|
|
511
|
+
// the writer takes the subsecond start from `start_datetime`, so the budget must too
|
|
512
|
+
let writer_subsecond = start_datetime.nanosecond() as f64 / 1_000_000_000.0;
|
|
513
|
+
let annotation_bytes_per_record = if target_variant.is_plus() {
|
|
514
|
+
let mut budget = per_record
|
|
515
|
+
.iter()
|
|
516
|
+
.enumerate()
|
|
517
|
+
.map(|(r, anns)| {
|
|
518
|
+
crate::writer::annotation_record_bytes(dest_onset(r), writer_subsecond, anns)
|
|
519
|
+
})
|
|
520
|
+
.max()
|
|
521
|
+
.unwrap_or(0);
|
|
522
|
+
// a file with no records still needs room for the timekeeping TAL
|
|
523
|
+
let first_tal =
|
|
524
|
+
crate::writer::annotation_record_bytes(dest_onset(0), writer_subsecond, &[]);
|
|
525
|
+
budget = budget.max(first_tal);
|
|
526
|
+
Some(budget)
|
|
527
|
+
} else {
|
|
528
|
+
None
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
let spec = WriterSpec {
|
|
532
|
+
variant: target_variant,
|
|
533
|
+
patient_id: header.patient_id.clone(),
|
|
534
|
+
recording_id: header.recording_id.clone(),
|
|
535
|
+
start_datetime,
|
|
536
|
+
record_duration_secs: record_dur,
|
|
537
|
+
signals: signals_spec,
|
|
538
|
+
annotation_bytes_per_record,
|
|
539
|
+
record_onsets: source_onsets.clone().filter(|_| keep_onsets),
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
// a source header may hold non-ASCII bytes, which the copy writes as '?'
|
|
543
|
+
let mut writer = EdfWriter::create_for_copy(path, spec)?;
|
|
523
544
|
|
|
524
545
|
// Stream records to avoid loading entire file into RAM.
|
|
525
546
|
let mut proxies: Vec<SignalProxy> = Vec::with_capacity(ordinary.len());
|
|
@@ -532,36 +553,14 @@ impl EdfFile {
|
|
|
532
553
|
.map(|p| vec![0.0f64; p.header().num_samples])
|
|
533
554
|
.collect();
|
|
534
555
|
|
|
535
|
-
|
|
536
|
-
for r in 0..num_records {
|
|
556
|
+
for (r, record_annotations) in per_record.iter().enumerate() {
|
|
537
557
|
for (buf, p) in bufs.iter_mut().zip(proxies.iter()) {
|
|
538
558
|
let spr = p.header().num_samples;
|
|
539
559
|
let start = r * spr;
|
|
540
560
|
p.read_physical(start, start + spr, buf)?;
|
|
541
561
|
}
|
|
542
562
|
let row: Vec<&[f64]> = bufs.iter().map(|b| b.as_slice()).collect();
|
|
543
|
-
|
|
544
|
-
// annotations are sorted by onset, so each record takes those that start before
|
|
545
|
-
// the next record, and the last record takes the rest
|
|
546
|
-
let record_start = source_onset(r);
|
|
547
|
-
let is_last = r + 1 == num_records;
|
|
548
|
-
let next_start = source_onset(r + 1);
|
|
549
|
-
record_annotations.clear();
|
|
550
|
-
while next_ann < annotations.len()
|
|
551
|
-
&& (is_last || annotations[next_ann].onset < next_start)
|
|
552
|
-
{
|
|
553
|
-
let mut ann = annotations[next_ann].clone();
|
|
554
|
-
if pack_gaps {
|
|
555
|
-
// keep the annotation at the same offset into its record. Only gap
|
|
556
|
-
// annotations exceed the record, so the clamp moves them to the gap's end.
|
|
557
|
-
let lo = if r == 0 { f64::NEG_INFINITY } else { 0.0 };
|
|
558
|
-
let hi = if is_last { f64::INFINITY } else { record_dur };
|
|
559
|
-
ann.onset = r as f64 * record_dur + (ann.onset - record_start).clamp(lo, hi);
|
|
560
|
-
}
|
|
561
|
-
record_annotations.push(ann);
|
|
562
|
-
next_ann += 1;
|
|
563
|
-
}
|
|
564
|
-
writer.write_record_with_annotations(&row, &record_annotations)?;
|
|
563
|
+
writer.write_record_with_annotations(&row, record_annotations)?;
|
|
565
564
|
}
|
|
566
565
|
|
|
567
566
|
writer.finish()?;
|
|
@@ -569,6 +568,37 @@ impl EdfFile {
|
|
|
569
568
|
}
|
|
570
569
|
}
|
|
571
570
|
|
|
571
|
+
/// Split onset-sorted `annotations` into the records their source onsets fall in. With
|
|
572
|
+
/// `pack_gaps`, move each one to the same offset into its record on a uniform timeline.
|
|
573
|
+
fn assign_annotations(
|
|
574
|
+
annotations: &[Annotation],
|
|
575
|
+
num_records: usize,
|
|
576
|
+
record_dur: f64,
|
|
577
|
+
source_onset: impl Fn(usize) -> f64,
|
|
578
|
+
pack_gaps: bool,
|
|
579
|
+
) -> Vec<Vec<Annotation>> {
|
|
580
|
+
let mut per_record: Vec<Vec<Annotation>> = (0..num_records).map(|_| Vec::new()).collect();
|
|
581
|
+
let mut next_ann = 0;
|
|
582
|
+
for (r, record) in per_record.iter_mut().enumerate() {
|
|
583
|
+
let record_start = source_onset(r);
|
|
584
|
+
let is_last = r + 1 == num_records;
|
|
585
|
+
let next_start = source_onset(r + 1);
|
|
586
|
+
while next_ann < annotations.len() && (is_last || annotations[next_ann].onset < next_start)
|
|
587
|
+
{
|
|
588
|
+
let mut ann = annotations[next_ann].clone();
|
|
589
|
+
if pack_gaps {
|
|
590
|
+
// only gap annotations exceed the record, so the clamp moves them to the gap's end
|
|
591
|
+
let lo = if r == 0 { f64::NEG_INFINITY } else { 0.0 };
|
|
592
|
+
let hi = if is_last { f64::INFINITY } else { record_dur };
|
|
593
|
+
ann.onset = r as f64 * record_dur + (ann.onset - record_start).clamp(lo, hi);
|
|
594
|
+
}
|
|
595
|
+
record.push(ann);
|
|
596
|
+
next_ann += 1;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
per_record
|
|
600
|
+
}
|
|
601
|
+
|
|
572
602
|
/// Make sure that a `write_to` signal selection is not empty, is in range, has no annotation
|
|
573
603
|
/// channel, and has no duplicates.
|
|
574
604
|
fn validate_signal_selection(header: &EdfHeader, selected: &[usize]) -> Result<()> {
|
|
@@ -649,13 +679,11 @@ impl EdfFile {
|
|
|
649
679
|
})?;
|
|
650
680
|
|
|
651
681
|
let mut header = EdfHeader::parse(&buf)?;
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
header.reconcile_num_records_with_file_size(file_size);
|
|
658
|
-
}
|
|
682
|
+
let file_size = file
|
|
683
|
+
.metadata()
|
|
684
|
+
.map(|m| m.len() as usize)
|
|
685
|
+
.unwrap_or(expected_header_bytes);
|
|
686
|
+
header.reconcile_num_records_with_file_size(file_size);
|
|
659
687
|
|
|
660
688
|
let signal_labels: Vec<String> = header.signals.iter().map(|s| s.label.clone()).collect();
|
|
661
689
|
let sample_rates: Vec<f64> = header
|
|
@@ -686,6 +714,60 @@ mod tests {
|
|
|
686
714
|
use std::io::Write;
|
|
687
715
|
use tempfile::NamedTempFile;
|
|
688
716
|
|
|
717
|
+
#[test]
|
|
718
|
+
fn write_to_sizes_budget_from_reencoded_content() {
|
|
719
|
+
let file = build_packed_annotation_file();
|
|
720
|
+
let f = EdfFile::open(file.path()).unwrap();
|
|
721
|
+
assert_eq!(f.annotations().len(), 12);
|
|
722
|
+
|
|
723
|
+
let dir = tempfile::TempDir::new().unwrap();
|
|
724
|
+
let dst = dir.path().join("dst.edf");
|
|
725
|
+
f.write_to(&dst, None).unwrap();
|
|
726
|
+
|
|
727
|
+
let g = EdfFile::open(&dst).unwrap();
|
|
728
|
+
assert!(g.warnings().is_empty(), "{:?}", g.warnings());
|
|
729
|
+
let got = g.annotations();
|
|
730
|
+
assert_eq!(got.len(), 12);
|
|
731
|
+
assert!(got.iter().any(|a| a.text == "t00"));
|
|
732
|
+
assert!(got.iter().any(|a| a.text == "t11"));
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
#[test]
|
|
736
|
+
fn write_to_copies_multiple_annotation_channels() {
|
|
737
|
+
let file = build_two_annotation_channel_file();
|
|
738
|
+
let f = EdfFile::open(file.path()).unwrap();
|
|
739
|
+
assert_eq!(f.annotations().len(), 1);
|
|
740
|
+
|
|
741
|
+
let dir = tempfile::TempDir::new().unwrap();
|
|
742
|
+
let dst = dir.path().join("dst.edf");
|
|
743
|
+
f.write_to(&dst, None).unwrap();
|
|
744
|
+
|
|
745
|
+
let g = EdfFile::open(&dst).unwrap();
|
|
746
|
+
assert!(g.warnings().is_empty(), "{:?}", g.warnings());
|
|
747
|
+
let got = g.annotations();
|
|
748
|
+
assert_eq!(got.len(), 1);
|
|
749
|
+
assert!(got[0].text.starts_with("a"));
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
#[test]
|
|
753
|
+
fn inspect_clamps_overdeclared_record_count() {
|
|
754
|
+
let file = build_synthetic_file(2, false, 0);
|
|
755
|
+
let mut bytes = std::fs::read(file.path()).unwrap();
|
|
756
|
+
// declare 10 records in a file that holds 2
|
|
757
|
+
bytes[236..244].copy_from_slice(b"10 ");
|
|
758
|
+
let mut patched = NamedTempFile::new().unwrap();
|
|
759
|
+
patched.write_all(&bytes).unwrap();
|
|
760
|
+
patched.flush().unwrap();
|
|
761
|
+
|
|
762
|
+
let meta = EdfFile::inspect(patched.path()).unwrap();
|
|
763
|
+
assert_eq!(meta.num_records, 2);
|
|
764
|
+
assert!((meta.duration - 2.0).abs() < 1e-9);
|
|
765
|
+
|
|
766
|
+
let edf = EdfFile::open(patched.path()).unwrap();
|
|
767
|
+
assert_eq!(edf.num_records(), 2);
|
|
768
|
+
assert!((edf.duration() - meta.duration).abs() < 1e-9);
|
|
769
|
+
}
|
|
770
|
+
|
|
689
771
|
#[test]
|
|
690
772
|
fn edf_file_api() {
|
|
691
773
|
let file = build_test_file();
|
|
@@ -907,6 +989,116 @@ mod tests {
|
|
|
907
989
|
data[start..start + bytes.len().min(fs)].copy_from_slice(&bytes[..bytes.len().min(fs)]);
|
|
908
990
|
}
|
|
909
991
|
|
|
992
|
+
/// Build a 1-record EDF+C file whose 80-byte annotation channel packs 12 texts under one
|
|
993
|
+
/// onset, which needs 137 bytes when re-encoded as one TAL per text.
|
|
994
|
+
fn build_packed_annotation_file() -> NamedTempFile {
|
|
995
|
+
let ns = 2;
|
|
996
|
+
let ann_bytes = 80usize;
|
|
997
|
+
let header_bytes = 256 + 256 * ns;
|
|
998
|
+
let mut buf = vec![b' '; header_bytes];
|
|
999
|
+
|
|
1000
|
+
write_hdr(&mut buf, 0, 8, "0");
|
|
1001
|
+
write_hdr(&mut buf, 8, 80, "X X X X");
|
|
1002
|
+
write_hdr(&mut buf, 88, 80, "Startdate X X X X");
|
|
1003
|
+
write_hdr(&mut buf, 168, 8, "01.01.00");
|
|
1004
|
+
write_hdr(&mut buf, 176, 8, "00.00.00");
|
|
1005
|
+
write_hdr(&mut buf, 184, 8, &header_bytes.to_string());
|
|
1006
|
+
write_hdr(&mut buf, 192, 44, "EDF+C");
|
|
1007
|
+
write_hdr(&mut buf, 236, 8, "1");
|
|
1008
|
+
write_hdr(&mut buf, 244, 8, "1");
|
|
1009
|
+
write_hdr(&mut buf, 252, 4, &ns.to_string());
|
|
1010
|
+
|
|
1011
|
+
let sig = &mut buf[256..];
|
|
1012
|
+
write_sig(sig, 0, ns, 0, 16, "EEG");
|
|
1013
|
+
write_sig(sig, 0, ns, 96, 8, "uV");
|
|
1014
|
+
write_sig(sig, 0, ns, 104, 8, "-32768");
|
|
1015
|
+
write_sig(sig, 0, ns, 112, 8, "32767");
|
|
1016
|
+
write_sig(sig, 0, ns, 120, 8, "-32768");
|
|
1017
|
+
write_sig(sig, 0, ns, 128, 8, "32767");
|
|
1018
|
+
write_sig(sig, 0, ns, 216, 8, "2");
|
|
1019
|
+
write_sig(sig, 1, ns, 0, 16, "EDF Annotations");
|
|
1020
|
+
write_sig(sig, 1, ns, 104, 8, "-1");
|
|
1021
|
+
write_sig(sig, 1, ns, 112, 8, "1");
|
|
1022
|
+
write_sig(sig, 1, ns, 120, 8, "-32768");
|
|
1023
|
+
write_sig(sig, 1, ns, 128, 8, "32767");
|
|
1024
|
+
write_sig(sig, 1, ns, 216, 8, &(ann_bytes / 2).to_string());
|
|
1025
|
+
|
|
1026
|
+
let mut body = vec![0u8; 2 * 2 + ann_bytes];
|
|
1027
|
+
let mut tal = b"+0\x14\x14\x00".to_vec();
|
|
1028
|
+
tal.extend_from_slice(b"+0.5\x14");
|
|
1029
|
+
for i in 0..12 {
|
|
1030
|
+
tal.extend_from_slice(format!("t{i:02}").as_bytes());
|
|
1031
|
+
tal.push(crate::annotation::TAL_SEPARATOR);
|
|
1032
|
+
}
|
|
1033
|
+
tal.push(crate::annotation::TAL_TERMINATOR);
|
|
1034
|
+
assert!(tal.len() <= ann_bytes, "{} bytes", tal.len());
|
|
1035
|
+
body[4..4 + tal.len()].copy_from_slice(&tal);
|
|
1036
|
+
|
|
1037
|
+
let mut file = NamedTempFile::new().unwrap();
|
|
1038
|
+
file.write_all(&buf).unwrap();
|
|
1039
|
+
file.write_all(&body).unwrap();
|
|
1040
|
+
file.flush().unwrap();
|
|
1041
|
+
file
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/// Build a 1-record EDF+C file with a 30-byte timekeeping channel and a 60-byte second
|
|
1045
|
+
/// annotation channel that holds one 40-character annotation.
|
|
1046
|
+
fn build_two_annotation_channel_file() -> NamedTempFile {
|
|
1047
|
+
let ns = 3;
|
|
1048
|
+
let ann_bytes = 30usize;
|
|
1049
|
+
let big_ann_bytes = 60usize;
|
|
1050
|
+
let header_bytes = 256 + 256 * ns;
|
|
1051
|
+
let mut buf = vec![b' '; header_bytes];
|
|
1052
|
+
|
|
1053
|
+
write_hdr(&mut buf, 0, 8, "0");
|
|
1054
|
+
write_hdr(&mut buf, 8, 80, "X X X X");
|
|
1055
|
+
write_hdr(&mut buf, 88, 80, "Startdate X X X X");
|
|
1056
|
+
write_hdr(&mut buf, 168, 8, "01.01.00");
|
|
1057
|
+
write_hdr(&mut buf, 176, 8, "00.00.00");
|
|
1058
|
+
write_hdr(&mut buf, 184, 8, &header_bytes.to_string());
|
|
1059
|
+
write_hdr(&mut buf, 192, 44, "EDF+C");
|
|
1060
|
+
write_hdr(&mut buf, 236, 8, "1");
|
|
1061
|
+
write_hdr(&mut buf, 244, 8, "1");
|
|
1062
|
+
write_hdr(&mut buf, 252, 4, &ns.to_string());
|
|
1063
|
+
|
|
1064
|
+
let sig = &mut buf[256..];
|
|
1065
|
+
write_sig(sig, 0, ns, 0, 16, "EEG");
|
|
1066
|
+
write_sig(sig, 0, ns, 96, 8, "uV");
|
|
1067
|
+
write_sig(sig, 0, ns, 104, 8, "-32768");
|
|
1068
|
+
write_sig(sig, 0, ns, 112, 8, "32767");
|
|
1069
|
+
write_sig(sig, 0, ns, 120, 8, "-32768");
|
|
1070
|
+
write_sig(sig, 0, ns, 128, 8, "32767");
|
|
1071
|
+
write_sig(sig, 0, ns, 216, 8, "2");
|
|
1072
|
+
write_sig(sig, 1, ns, 0, 16, "EDF Annotations");
|
|
1073
|
+
write_sig(sig, 1, ns, 104, 8, "-1");
|
|
1074
|
+
write_sig(sig, 1, ns, 112, 8, "1");
|
|
1075
|
+
write_sig(sig, 1, ns, 120, 8, "-32768");
|
|
1076
|
+
write_sig(sig, 1, ns, 128, 8, "32767");
|
|
1077
|
+
write_sig(sig, 1, ns, 216, 8, &(ann_bytes / 2).to_string());
|
|
1078
|
+
write_sig(sig, 2, ns, 0, 16, "EDF Annotations");
|
|
1079
|
+
write_sig(sig, 2, ns, 104, 8, "-1");
|
|
1080
|
+
write_sig(sig, 2, ns, 112, 8, "1");
|
|
1081
|
+
write_sig(sig, 2, ns, 120, 8, "-32768");
|
|
1082
|
+
write_sig(sig, 2, ns, 128, 8, "32767");
|
|
1083
|
+
write_sig(sig, 2, ns, 216, 8, &(big_ann_bytes / 2).to_string());
|
|
1084
|
+
|
|
1085
|
+
let mut body = vec![0u8; 2 * 2 + ann_bytes + big_ann_bytes];
|
|
1086
|
+
let tal = b"+0\x14\x14\x00";
|
|
1087
|
+
body[4..4 + tal.len()].copy_from_slice(tal);
|
|
1088
|
+
let mut big = b"+0.5\x14".to_vec();
|
|
1089
|
+
big.extend_from_slice(&[b'a'; 40]);
|
|
1090
|
+
big.push(crate::annotation::TAL_SEPARATOR);
|
|
1091
|
+
big.push(crate::annotation::TAL_TERMINATOR);
|
|
1092
|
+
assert!(big.len() <= big_ann_bytes);
|
|
1093
|
+
body[4 + ann_bytes..4 + ann_bytes + big.len()].copy_from_slice(&big);
|
|
1094
|
+
|
|
1095
|
+
let mut file = NamedTempFile::new().unwrap();
|
|
1096
|
+
file.write_all(&buf).unwrap();
|
|
1097
|
+
file.write_all(&body).unwrap();
|
|
1098
|
+
file.flush().unwrap();
|
|
1099
|
+
file
|
|
1100
|
+
}
|
|
1101
|
+
|
|
910
1102
|
/// Build a 1-signal BDF file. `plus_c` writes "BDF+C" in the reserved field.
|
|
911
1103
|
fn build_synthetic_bdf_file(actual_records: usize, plus_c: bool) -> NamedTempFile {
|
|
912
1104
|
let num_signals = 1;
|