Files
models/models/tea/eeg/reference.py
T
alberto cc95054a96 The tea_eeg job: analyse, score the age curves, relate ADOS-2, rebuild gold; a sensor starts it after an ingest
Analysis and the reference cohort's measuring run on execution.map; relate is the
Phase 2 seam. A LocalCluster starts inside a multiprocess Dagster step (checked on a
real run), so the ops keep the default executor.
2026-11-27 18:02:28 -06:00

61 lines
2.4 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 the cluster's workers; `tables` gives each scenario's training table
from the valid studies.
"""
from pathlib import Path
import pandas as pd
from models import execution
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(study: tuple[str, Path, float, float]) -> dict:
key, path, age, mains_hz = study
a = analyze(Path(path).read_bytes(), 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, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]:
"""Each study's verdict and features, in listing order."""
items = [(k, p, a, mains_hz) for k, p, a in studies]
return execution.map(_one, items, phase="measuring_reference", workers=workers)
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
}