Age at the recording from the EDF header (start minus birth date) when no age is passed; preprocessing 0.2.0
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "tea"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
description = "Modular EEG biomarker library for TEA: validation, preprocessing, processes and biomarkers, each a replaceable module"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ Every biomarker and every process is its own module. Modules talk only
|
||||
through `tea.contracts`; see the architecture plan.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.2.0"
|
||||
|
||||
@@ -3,10 +3,12 @@ The shared API of `tea`: the only code every module may import.
|
||||
|
||||
from tea.contracts import Recording, Preprocessed, Study, Labels
|
||||
from tea.contracts import check_module, CONTRACT_VERSION
|
||||
from tea.contracts import header_age_months
|
||||
"""
|
||||
|
||||
from tea.contracts.data import (
|
||||
CONTRACT_VERSION,
|
||||
DAYS_PER_MONTH,
|
||||
DEVIATION_COLUMNS,
|
||||
SPAN_COLUMNS,
|
||||
WINDOW_COLUMNS,
|
||||
@@ -16,6 +18,8 @@ from tea.contracts.data import (
|
||||
Study,
|
||||
ValidationSummary,
|
||||
empty_spans,
|
||||
header_age_months,
|
||||
read_edf,
|
||||
sha256_of,
|
||||
)
|
||||
from tea.contracts.protocols import (
|
||||
@@ -32,6 +36,7 @@ from tea.contracts.protocols import (
|
||||
__all__ = [
|
||||
"CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "empty_spans",
|
||||
"Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of",
|
||||
"DAYS_PER_MONTH", "header_age_months", "read_edf",
|
||||
"Module", "Validator", "Preprocessor", "Process", "Biomarker",
|
||||
"KINDS", "ContractError", "check_module",
|
||||
]
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -22,6 +23,12 @@ import pandas as pd
|
||||
|
||||
CONTRACT_VERSION = "1.0"
|
||||
|
||||
# Months of the age at a recording: days divided by this.
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
MAX_HEADER_AGE_MONTHS = 216
|
||||
# What EDF writers put in the header's start date when they don't know it.
|
||||
UNKNOWN_START = date(1985, 1, 1)
|
||||
|
||||
# Columns of the table that Biomarker.predict returns.
|
||||
DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline")
|
||||
|
||||
@@ -65,20 +72,54 @@ class Recording:
|
||||
|
||||
@classmethod
|
||||
def from_edf(cls, path: str | Path, *, age_months: float | None = None) -> Recording:
|
||||
"""Read an EDF with MNE. The only EDF reader shared through contracts."""
|
||||
import mne
|
||||
"""Read an EDF with MNE. The only EDF reader shared through contracts.
|
||||
|
||||
Without `age_months`, the age is the header's (`header_age_months`).
|
||||
"""
|
||||
path = Path(path)
|
||||
try:
|
||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="error")
|
||||
except Exception as e: # annotation texts in a Windows code page
|
||||
if "latin1" not in str(e):
|
||||
raise
|
||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="error", encoding="latin1")
|
||||
raw = read_edf(path, preload=True)
|
||||
if age_months is None:
|
||||
age_months = header_age_months(raw)
|
||||
return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path),
|
||||
source_name=path.stem)
|
||||
|
||||
|
||||
def read_edf(path: str | Path, *, preload: bool) -> Any:
|
||||
"""`mne.io.read_raw_edf`, retrying in latin1 when annotation texts are in a Windows code page."""
|
||||
import mne
|
||||
|
||||
try:
|
||||
return mne.io.read_raw_edf(path, preload=preload, verbose="error")
|
||||
except Exception as e:
|
||||
if "latin1" not in str(e):
|
||||
raise
|
||||
return mne.io.read_raw_edf(path, preload=preload, verbose="error", encoding="latin1")
|
||||
|
||||
|
||||
def header_age_months(source: Any, *, days_per_month: float = DAYS_PER_MONTH) -> float | None:
|
||||
"""
|
||||
Age at the recording from the EDF header: start date minus birth date, in
|
||||
months of `days_per_month` days, to one decimal.
|
||||
|
||||
`source` is an EDF path (only the header is read) or an `mne.io.BaseRaw`.
|
||||
None when the header lacks either date (anonymised EDF+ writes `X`), the
|
||||
start is the 01.01.85 placeholder, the birth date is after the start or the
|
||||
age exceeds `MAX_HEADER_AGE_MONTHS`.
|
||||
"""
|
||||
raw = source if hasattr(source, "info") else read_edf(source, preload=False)
|
||||
start = raw.info.get("meas_date")
|
||||
born = (raw.info.get("subject_info") or {}).get("birthday")
|
||||
if start is None or born is None:
|
||||
return None
|
||||
studied = start.date() if isinstance(start, datetime) else start
|
||||
if isinstance(born, tuple): # MNE before 1.8
|
||||
born = date(*born)
|
||||
if studied == UNKNOWN_START or born > studied:
|
||||
return None
|
||||
months = round((studied - born).days / days_per_month, 1)
|
||||
return months if months <= MAX_HEADER_AGE_MONTHS else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValidationSummary:
|
||||
"""
|
||||
|
||||
@@ -30,7 +30,7 @@ from typing import Any
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of
|
||||
from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, header_age_months, sha256_of
|
||||
|
||||
DIRECTOR_COMMIT = "7dfc641"
|
||||
_SUFFIX = {"average": "prom", "linked_ears": "orejas"}
|
||||
@@ -42,7 +42,7 @@ class PlanNotSupported(ValueError):
|
||||
|
||||
class LegacyPreprocessing:
|
||||
name = "preprocessing"
|
||||
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
|
||||
version = f"0.2.0+director.{DIRECTOR_COMMIT}"
|
||||
contract_version = CONTRACT_VERSION
|
||||
impl = "legacy"
|
||||
|
||||
@@ -88,12 +88,15 @@ class LegacyPreprocessing:
|
||||
|
||||
# ---------------------------------------------------------------- run
|
||||
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
|
||||
"""Without `age_months`, the age is the EDF header's (`header_age_months`)."""
|
||||
import mne
|
||||
|
||||
from ._director import edf_convert, lote, preproceso
|
||||
|
||||
args = self.director_args(plan)
|
||||
edf_path = Path(edf_path)
|
||||
if age_months is None:
|
||||
age_months = header_age_months(edf_path)
|
||||
nombre = edf_path.stem
|
||||
with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \
|
||||
contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings():
|
||||
|
||||
@@ -25,7 +25,14 @@ from typing import Any
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from tea.contracts import CONTRACT_VERSION, Preprocessed, ValidationSummary, sha256_of
|
||||
from tea.contracts import (
|
||||
CONTRACT_VERSION,
|
||||
Preprocessed,
|
||||
ValidationSummary,
|
||||
header_age_months,
|
||||
read_edf,
|
||||
sha256_of,
|
||||
)
|
||||
|
||||
from . import _channels, _qc, _signal
|
||||
from .plan import PreprocessPlan
|
||||
@@ -36,7 +43,7 @@ _TYPE = {"eeg": "eeg", "orejas": "eeg", "eog": "eog", "cardiaco": "ecg"}
|
||||
|
||||
class Preprocessing:
|
||||
name = "preprocessing"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
contract_version = CONTRACT_VERSION
|
||||
impl = "modern"
|
||||
|
||||
@@ -52,15 +59,11 @@ class Preprocessing:
|
||||
|
||||
# ------------------------------------------------------------------ run
|
||||
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
|
||||
import mne
|
||||
|
||||
"""Without `age_months`, the age is the EDF header's (`header_age_months`)."""
|
||||
p = PreprocessPlan.from_dict(plan)
|
||||
try:
|
||||
raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error")
|
||||
except Exception as e: # annotation texts in a Windows code page
|
||||
if "latin1" not in str(e):
|
||||
raise
|
||||
raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error", encoding="latin1")
|
||||
raw = read_edf(edf_path, preload=True)
|
||||
if age_months is None:
|
||||
age_months = header_age_months(raw)
|
||||
ren, seen, drop = {}, set(), []
|
||||
for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept
|
||||
n = _channels.normalize(c)
|
||||
|
||||
Reference in New Issue
Block a user