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]
|
[project]
|
||||||
name = "tea"
|
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"
|
description = "Modular EEG biomarker library for TEA: validation, preprocessing, processes and biomarkers, each a replaceable module"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
authors = [
|
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.
|
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 Recording, Preprocessed, Study, Labels
|
||||||
from tea.contracts import check_module, CONTRACT_VERSION
|
from tea.contracts import check_module, CONTRACT_VERSION
|
||||||
|
from tea.contracts import header_age_months
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from tea.contracts.data import (
|
from tea.contracts.data import (
|
||||||
CONTRACT_VERSION,
|
CONTRACT_VERSION,
|
||||||
|
DAYS_PER_MONTH,
|
||||||
DEVIATION_COLUMNS,
|
DEVIATION_COLUMNS,
|
||||||
SPAN_COLUMNS,
|
SPAN_COLUMNS,
|
||||||
WINDOW_COLUMNS,
|
WINDOW_COLUMNS,
|
||||||
@@ -16,6 +18,8 @@ from tea.contracts.data import (
|
|||||||
Study,
|
Study,
|
||||||
ValidationSummary,
|
ValidationSummary,
|
||||||
empty_spans,
|
empty_spans,
|
||||||
|
header_age_months,
|
||||||
|
read_edf,
|
||||||
sha256_of,
|
sha256_of,
|
||||||
)
|
)
|
||||||
from tea.contracts.protocols import (
|
from tea.contracts.protocols import (
|
||||||
@@ -32,6 +36,7 @@ from tea.contracts.protocols import (
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
"CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "empty_spans",
|
"CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS", "SPAN_COLUMNS", "empty_spans",
|
||||||
"Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of",
|
"Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of",
|
||||||
|
"DAYS_PER_MONTH", "header_age_months", "read_edf",
|
||||||
"Module", "Validator", "Preprocessor", "Process", "Biomarker",
|
"Module", "Validator", "Preprocessor", "Process", "Biomarker",
|
||||||
"KINDS", "ContractError", "check_module",
|
"KINDS", "ContractError", "check_module",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|||||||
import hashlib
|
import hashlib
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date, datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -22,6 +23,12 @@ import pandas as pd
|
|||||||
|
|
||||||
CONTRACT_VERSION = "1.0"
|
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.
|
# Columns of the table that Biomarker.predict returns.
|
||||||
DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline")
|
DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline")
|
||||||
|
|
||||||
@@ -65,20 +72,54 @@ class Recording:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_edf(cls, path: str | Path, *, age_months: float | None = None) -> Recording:
|
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."""
|
"""Read an EDF with MNE. The only EDF reader shared through contracts.
|
||||||
import mne
|
|
||||||
|
|
||||||
|
Without `age_months`, the age is the header's (`header_age_months`).
|
||||||
|
"""
|
||||||
path = Path(path)
|
path = Path(path)
|
||||||
try:
|
raw = read_edf(path, preload=True)
|
||||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="error")
|
if age_months is None:
|
||||||
except Exception as e: # annotation texts in a Windows code page
|
age_months = header_age_months(raw)
|
||||||
if "latin1" not in str(e):
|
|
||||||
raise
|
|
||||||
raw = mne.io.read_raw_edf(path, preload=True, verbose="error", encoding="latin1")
|
|
||||||
return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path),
|
return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path),
|
||||||
source_name=path.stem)
|
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)
|
@dataclass(frozen=True)
|
||||||
class ValidationSummary:
|
class ValidationSummary:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ from typing import Any
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
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"
|
DIRECTOR_COMMIT = "7dfc641"
|
||||||
_SUFFIX = {"average": "prom", "linked_ears": "orejas"}
|
_SUFFIX = {"average": "prom", "linked_ears": "orejas"}
|
||||||
@@ -42,7 +42,7 @@ class PlanNotSupported(ValueError):
|
|||||||
|
|
||||||
class LegacyPreprocessing:
|
class LegacyPreprocessing:
|
||||||
name = "preprocessing"
|
name = "preprocessing"
|
||||||
version = f"0.1.0+director.{DIRECTOR_COMMIT}"
|
version = f"0.2.0+director.{DIRECTOR_COMMIT}"
|
||||||
contract_version = CONTRACT_VERSION
|
contract_version = CONTRACT_VERSION
|
||||||
impl = "legacy"
|
impl = "legacy"
|
||||||
|
|
||||||
@@ -88,12 +88,15 @@ class LegacyPreprocessing:
|
|||||||
|
|
||||||
# ---------------------------------------------------------------- run
|
# ---------------------------------------------------------------- run
|
||||||
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
|
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
|
import mne
|
||||||
|
|
||||||
from ._director import edf_convert, lote, preproceso
|
from ._director import edf_convert, lote, preproceso
|
||||||
|
|
||||||
args = self.director_args(plan)
|
args = self.director_args(plan)
|
||||||
edf_path = Path(edf_path)
|
edf_path = Path(edf_path)
|
||||||
|
if age_months is None:
|
||||||
|
age_months = header_age_months(edf_path)
|
||||||
nombre = edf_path.stem
|
nombre = edf_path.stem
|
||||||
with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \
|
with tempfile.TemporaryDirectory(prefix="tea_legacy_pre_") as tmp, \
|
||||||
contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings():
|
contextlib.redirect_stdout(io.StringIO()), warnings.catch_warnings():
|
||||||
|
|||||||
@@ -25,7 +25,14 @@ from typing import Any
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
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 . import _channels, _qc, _signal
|
||||||
from .plan import PreprocessPlan
|
from .plan import PreprocessPlan
|
||||||
@@ -36,7 +43,7 @@ _TYPE = {"eeg": "eeg", "orejas": "eeg", "eog": "eog", "cardiaco": "ecg"}
|
|||||||
|
|
||||||
class Preprocessing:
|
class Preprocessing:
|
||||||
name = "preprocessing"
|
name = "preprocessing"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
contract_version = CONTRACT_VERSION
|
contract_version = CONTRACT_VERSION
|
||||||
impl = "modern"
|
impl = "modern"
|
||||||
|
|
||||||
@@ -52,15 +59,11 @@ class Preprocessing:
|
|||||||
|
|
||||||
# ------------------------------------------------------------------ run
|
# ------------------------------------------------------------------ run
|
||||||
def run(self, edf_path, plan: Mapping[str, Any], *, age_months: float | None = None) -> Preprocessed:
|
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)
|
p = PreprocessPlan.from_dict(plan)
|
||||||
try:
|
raw = read_edf(edf_path, preload=True)
|
||||||
raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error")
|
if age_months is None:
|
||||||
except Exception as e: # annotation texts in a Windows code page
|
age_months = header_age_months(raw)
|
||||||
if "latin1" not in str(e):
|
|
||||||
raise
|
|
||||||
raw = mne.io.read_raw_edf(edf_path, preload=True, verbose="error", encoding="latin1")
|
|
||||||
ren, seen, drop = {}, set(), []
|
ren, seen, drop = {}, set(), []
|
||||||
for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept
|
for c in raw.ch_names: # edf_convert: unknown dropped, first duplicate kept
|
||||||
n = _channels.normalize(c)
|
n = _channels.normalize(c)
|
||||||
|
|||||||
Reference in New Issue
Block a user