61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
|
children of 16 to 36 months, recorded on 50 Hz mains.
|
|
|
|
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
|
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
|
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
|
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
|
|
from the valid studies.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
|
|
import pandas as pd
|
|
|
|
from models import cluster
|
|
from models.tea.eeg.analysis import analyze
|
|
from models.tea.eeg.curves import SCENARIOS
|
|
|
|
NAME = "hk1k"
|
|
MAINS_HZ = 50.0
|
|
AGES = (16.0, 36.0)
|
|
|
|
|
|
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
|
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
|
table = pd.read_csv(ages_table)
|
|
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
|
found = []
|
|
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
|
|
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
|
if age is not None and age == age and ages[0] <= age <= ages[1]:
|
|
found.append((path, age))
|
|
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
|
|
|
|
|
def _one(key: str, edf: bytes, age: float) -> dict:
|
|
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
|
|
return {
|
|
"key": key,
|
|
"age_months": age,
|
|
"valid": a.valid,
|
|
"error": a.error,
|
|
"features": a.features,
|
|
}
|
|
|
|
|
|
def measure(studies) -> list[dict]:
|
|
"""Each study's verdict and features, in listing order, each a task on the cluster
|
|
(models.cluster)."""
|
|
# each task carries its recording: workers see no local folder
|
|
return cluster.run(_one, ((key, Path(path).read_bytes(), age) for key, path, age in studies))
|
|
|
|
|
|
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
|
"""Scenario -> its training table: the valid studies' features and `age_months`."""
|
|
usable = [s for s in measured if s["valid"] and s["error"] is None]
|
|
return {
|
|
name: pd.DataFrame([{**s["features"][name], "age_months": s["age_months"]} for s in usable])
|
|
for name in SCENARIOS
|
|
}
|