Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place

1. No prose in code
- Remove parity-added comments and docstrings from TEA jobs, analysis and
  scoring helpers, execution, definitions, and tests. Keep base prose and
  Ruff and type-checker directives.

2. No hacks, no glued code
- Delegate both association cohort queries to persistance.eeg. Keep the
  predictor mapping and DataFrame shaping in the job, sharing biomarker
  codes and EEG study IDs with Core. Preserve column names and order, row
  selection, score filtering, and earliest fitting study.
- Use the existing MODELS registry for curve scoring in place of CURVES.
  Keep GOLD because the generic score job reads it.
- Catch lookup, database, and validation failures when loading a preview
  pipeline, preserving the existing warning. Keep execution-boundary
  exception handling for submitted tasks, telemetry and shutdown.
- Name the association test for the missing-champion case. Preserve its
  assertion and the other test assertions.

3. Everything in its place
- Keep SQL in Persistance, cohort shaping in models, and tests in their
  existing testpaths. Keep the association fits together with their
  shared design and result machinery.
This commit is contained in:
2026-11-30 13:39:51 -06:00
parent a818847b99
commit d8445fcabf
13 changed files with 60 additions and 217 deletions
+4 -16
View File
@@ -22,9 +22,7 @@ WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a
class ExecutionConfig(dg.Config):
"""Where a heavy op's work runs: the fields of `persistance.cluster.Execution`."""
mode: str | None = None # Dagster's config has no Literal: `model()` checks it
mode: str | None = None
scheduler: str | None = None
def model(self) -> cluster.Execution:
@@ -32,14 +30,12 @@ class ExecutionConfig(dg.Config):
class ScopeConfig(dg.Config):
"""Which EEGs an analysis takes: the fields of `persistance.eeg.Scope`."""
mode: str = "pending" # Dagster's config has no Literal: `model()` checks it
mode: str = "pending"
n: int | None = None
ids: list[str] = []
def model(self) -> eeg.Scope:
return eeg.Scope(**self.model_dump()) # validates
return eeg.Scope(**self.model_dump())
class PipelineRun(dg.Config):
@@ -100,7 +96,7 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
for name in config.models or jobs.JOBS.routine():
try:
found[name] = jobs.train(name, as_of, **options)
except EmptyCohort as e: # the site has no such patients; the others still train
except EmptyCohort as e:
found[name] = None
context.log.warning(f"{e}: not trained")
continue
@@ -160,8 +156,6 @@ class TeaAnalysis(dg.Config):
@dg.op
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
"""The EEGs in scope, analysed in the chosen execution. Bronze is written after the last
study, so a cancel during the analysis leaves it as it was."""
with execution.running(context, config.execution.model()):
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
@@ -170,7 +164,6 @@ def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) ->
@dg.op
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
"""Each age curve's champion scores every analysed EEG."""
found = tea_jobs.score_curves()
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
@@ -179,7 +172,6 @@ def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
@dg.op
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
"""The ADOS-2 association champion scores the EEGs (a seam: nothing until Phase 2)."""
version = tea_jobs.relate()
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
return {"ados2_association": version}
@@ -187,8 +179,6 @@ def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
@dg.op
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
"""Gold's TEA tables rebuilt from bronze. A cancel here stops dbt between models, so gold
may be partly rebuilt until the next successful run (dbt replaces each model whole)."""
silver.build(tea_jobs.GOLD_SELECT)
context.log.info("gold rebuilt")
return {"built": tea_jobs.GOLD_SELECT}
@@ -228,7 +218,6 @@ def tea_preview():
@dg.job(tags={**WRITES, "domain": "tea"})
def tea_eeg():
"""Analyse the EEGs in scope, score the age curves, relate ADOS-2, rebuild gold."""
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
@@ -237,7 +226,6 @@ def pending_eegs() -> bool:
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
"""A `tea_eeg` run for an ingest that left EEGs to analyse; otherwise a skip."""
if not has_pending():
return dg.SkipReason("the ingest brought no EEG to analyse")
return dg.RunRequest(
+3 -33
View File
@@ -1,13 +1,3 @@
"""The one way a heavy op spreads work over cores or machines: `map(fn, items)` returns the
results in input order whatever the mode (in this process, on local worker processes, on a
remote Dask scheduler). While it runs, a monitor thread reports progress: a JSON run tag the
API reads at once (Dagster shows op metadata only when the op returns, so the tag is the live
channel) and one throttled log line per tenth of the work. Ops never touch Dask themselves.
`with running(context, execution):` makes a Dagster op's context the ambient one, so that
`map` calls inside the block report on that run, share one cluster, and leave a summary in the
op's output metadata."""
import contextvars
import threading
import time
@@ -60,8 +50,6 @@ _SINGLE_THREAD = {
class Eta:
"""Seconds left, from an exponentially smoothed rate of items per second."""
def __init__(self, alpha: float = 0.3, min_done: int = 3):
self.alpha, self.min_done = alpha, min_done
self.rate: float | None = None
@@ -82,8 +70,6 @@ class Eta:
class _Ambient:
"""What `running` shares with the `map` calls in its block."""
def __init__(self, context, execution: Execution | None):
self.context, self.execution = context, execution
self.client = None
@@ -103,7 +89,6 @@ _ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
def _close(client, local_cluster) -> None:
"""Close what this module opened; a remote scheduler is only disconnected from."""
for closable in (client, local_cluster):
if closable is not None:
try:
@@ -113,7 +98,6 @@ def _close(client, local_cluster) -> None:
def _counts(dask_scheduler) -> dict:
"""Run on the scheduler: how many tasks are in each state."""
counts: dict = {}
for task in dask_scheduler.tasks.values():
counts[task.state] = counts.get(task.state, 0) + 1
@@ -121,7 +105,6 @@ def _counts(dask_scheduler) -> dict:
def _connect(resolved: Resolved, workers: int | None):
"""A client on the chosen Dask cluster and the local cluster it started, if any."""
from distributed import Client, LocalCluster
if resolved.mode == "local":
@@ -153,8 +136,6 @@ def _connect(resolved: Resolved, workers: int | None):
class _Monitor:
"""Samples one `map` every `SAMPLE_S` seconds and reports it."""
def __init__(self, ambient, resolved, phase, total, log, client):
self.ambient, self.resolved, self.phase = ambient, resolved, phase
self.total, self.log, self.client = total, log, client
@@ -215,7 +196,7 @@ class _Monitor:
counts = self.client.run_on_scheduler(_counts)
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
except Exception:
pass # a failed sample keeps the previous one
pass
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
return workers
@@ -272,7 +253,7 @@ def _run_dask(fn, iterator, client, monitor, on_error):
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
limit = max(4, 2 * threads)
results: dict[int, object] = {}
pending: dict = {} # future -> (index, item)
pending: dict = {}
completed = as_completed([])
numbered = enumerate(iterator)
try:
@@ -301,7 +282,7 @@ def _run_dask(fn, iterator, client, monitor, on_error):
return [results[i] for i in range(len(results))]
def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
def map[T, R]( # noqa: A001
fn: Callable[[T], R],
items: Iterable[T],
*,
@@ -312,15 +293,6 @@ def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
workers: int | None = None,
on_error: Callable[[T, Exception], R] | None = None,
) -> list[R]:
"""Apply `fn` to every item and return the results in input order.
`fn` is a module-level function of one item returning something picklable, and must give
the same result for the same item: then every mode returns equal lists. `items` may be a
lazy generator; at most `max(4, 2 * threads)` items are loaded and unfinished at once.
`total` is needed only when `items` has no length. `phase` is the lowercase code the
WebApp shows. `workers` overrides the local worker count (a cluster shared inside
`running` keeps the count it started with). A failed item takes `on_error(item, error)`
as its result, or, without it, the error propagates after the rest is cancelled."""
ambient = _ambient.get()
if execution is None and ambient is not None:
execution = ambient.execution
@@ -373,8 +345,6 @@ def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
@contextmanager
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
"""Make `context` and `execution` the ambient ones for the `map` calls in the block; on
exit close the shared cluster and leave the run's figures in the op's output metadata."""
ambient = _Ambient(context, execution)
token = _ambient.set(ambient)
failed = True
-1
View File
@@ -117,7 +117,6 @@ def run_read(p: str, node: Read):
def run_edf(p: str, node: Edf):
"""Keep every input row and add the header facts or the file's error."""
rows = list(nodes.rows(p, node.inputs[0]))
empty = dict.fromkeys(EDF_COLUMNS)
found = {None: {**empty, "edf_error": "empty"}}
+5 -64
View File
@@ -1,5 +1,3 @@
"""ADOS-2 associations with age-standardized EEG biomarkers, adjusted for age and module."""
from __future__ import annotations
import json
@@ -16,12 +14,6 @@ from scipy.special import expit
from core.tea import ADOS2_ITEMS
from models.tea.eeg.spindles import ZONES
BIOMARKERS = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
"posterior_rhythm": "posterior_rhythm",
"gradient": "anteroposterior_gradient",
}
ASSOCIATION_COLUMNS = (
"biomarker",
"zone",
@@ -52,7 +44,6 @@ SCORE_COLUMNS = (
)
ADJUST = ("age_months", "ados_module")
# Item number: (label, algorithm domain, supported modules).
ITEMS = {
1: ("Vocalización espontánea dirigida a otros", "SA", {"toddler", "module_1"}),
2: ("Señalar", "SA", {"toddler", "module_1", "module_2"}),
@@ -86,7 +77,6 @@ ITEMS = {
),
}
# Items each zone's spike density is paired with.
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
@@ -100,22 +90,16 @@ ZONE_ITEMS = {
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
# The calibrated severity score runs from 1 to 10 and is high from 8 (Gotham 2009; Hus 2014).
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1 # An item is altered from algorithm score 1.
ALTERED = 1
def item_code(n: int) -> str:
"""The module-independent outcome code of item `n`."""
return f"ados2_item_{n:02d}"
def pairs(level: str) -> list[dict]:
"""The pairs tested. `level` "item": spike zones and the posterior rhythm against items,
spindles and gradient against the CSS; "domain": everything against the CSS. Each pair:
biomarker, zone, predictor column, outcome kind ("item" or "domain") and outcome (item number or
`CSS`)."""
out = []
for zone in ZONES:
outcomes = [("item", n) for n in ZONE_ITEMS[zone]] if level == "item" else [("domain", CSS)]
@@ -163,14 +147,11 @@ def pairs(level: str) -> list[dict]:
def algorithm_score(v) -> pd.Series:
"""Protocol code to algorithm score: 3 is 2; 7, 8 and 9 are 0; 0, 1 and 2 stay."""
v = pd.to_numeric(pd.Series(v), errors="coerce")
return v.where(~v.isin([7, 8, 9]), 0).clip(upper=2)
def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
"""Item `n`'s algorithm score (0 to 2) for each child, read from the column of the child's
module. NaN when the item is not in that module's algorithm or has no value."""
column = ADOS2_ITEMS[n - 1]
if "ados_module" not in cohort or column not in cohort:
return pd.Series(np.nan, index=cohort.index)
@@ -178,7 +159,6 @@ def item_scores(cohort: pd.DataFrame, n: int) -> pd.Series:
def has_items(cohort: pd.DataFrame, minimum: int = 10) -> bool:
"""Whether at least `minimum` children have some item score."""
scores = pd.concat([item_scores(cohort, n) for n in ITEMS], axis=1)
return int(scores.notna().any(axis=1).sum()) >= minimum
@@ -189,16 +169,10 @@ MIN_ROWS = 8
@dataclass
class Design:
"""How a table becomes the design matrix: intercept, predictor (uncentred, z = 0 is the
reference median), numeric adjustments centred on their mean, categorical ones as indicators
against the most frequent level. Adjustments that do not vary are left out."""
predictor: str
numeric: dict[str, float] = field(default_factory=dict)
categorical: dict[str, list[str]] = field(
default_factory=dict
) # the indicator levels, by adjustment
reference: dict[str, str] = field(default_factory=dict) # the reference level, by adjustment
categorical: dict[str, list[str]] = field(default_factory=dict)
reference: dict[str, str] = field(default_factory=dict)
@classmethod
def of(cls, t: pd.DataFrame, predictor: str, adjust) -> Design:
@@ -226,7 +200,6 @@ class Design:
]
def matrix(self, t: pd.DataFrame) -> np.ndarray:
"""X for `t`. A row missing a covariate, or with a level the fit never saw, is NaN."""
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
for a, mean in self.numeric.items():
cols.append(t[a].to_numpy(float) - mean if a in t else np.full(len(t), np.nan))
@@ -264,9 +237,7 @@ class Design:
)
# Firth
def _pl(b, X, y):
"""Firth's penalised log-likelihood: l(b) + log|X'WX| / 2."""
eta = X @ b
p = expit(eta)
w = p * (1 - p)
@@ -277,8 +248,6 @@ def _pl(b, X, y):
def _score(b, X, y):
"""Firth's modified score X'(y - p + h(1/2 - p)), h the hat matrix diagonal, and the
information."""
p = expit(X @ b)
w = p * (1 - p)
info = X.T @ (X * w[:, None])
@@ -321,8 +290,6 @@ def _profile_firth(value, j, X, y, b0):
def _interval(profile, centre, maximum, scale):
"""Profile likelihood interval: where 2 (max - profile) reaches the 95 % chi-square with one
degree."""
g = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
limits = []
for sign in (-1, 1):
@@ -354,9 +321,6 @@ def _summary(model, n, coef, lo, hi, p, design, state, **extra) -> dict:
def firth(t: pd.DataFrame, outcome: str, predictor: str, adjust) -> dict:
"""Firth logistic regression of `outcome` (0/1) on `predictor`, adjusted: n, events, odds ratio
per unit of z, profiled 95 % interval, penalised likelihood-ratio p, and the state
`firth_probability` scores with."""
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
@@ -391,12 +355,9 @@ def firth_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
def firth_reference(state: dict) -> float:
"""The probability at z = 0 with the covariates at their reference: mean age, most frequent
level."""
return float(expit(state["intercept"]))
# Ordinal (proportional odds)
def _nll_ordinal(par, X, yk, K):
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
eta = X @ par[K - 1 :]
@@ -407,8 +368,6 @@ def _nll_ordinal(par, X, yk, K):
def _fit_ordinal(X, yk, K, fixed=None):
"""Minimum of the negative log-likelihood; `fixed` = (j, value) holds coefficient j of X (the
profile)."""
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
if fixed is None:
r = optimize.minimize(lambda q: _nll_ordinal(q, X, yk, K), start, method="BFGS")
@@ -425,16 +384,13 @@ def _fit_ordinal(X, yk, K, fixed=None):
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float) -> dict:
"""Ordinal logistic regression of `outcome` (ordered levels): odds ratio of a higher level per
unit of z, profiled interval, likelihood-ratio p, and the state `ordinal_probability` scores
P(outcome >= high) with."""
d = t[[outcome, predictor, *[a for a in adjust if a in t]]].dropna()
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": "too few data or no variation"}
design = Design.of(d, predictor, adjust)
X = design.matrix(d)[:, 1:] # the thresholds are the intercept
X = design.matrix(d)[:, 1:]
K = len(levels)
yk = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
@@ -447,7 +403,7 @@ def ordinal(t: pd.DataFrame, outcome: str, predictor: str, adjust, high: float)
lo, hi = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high)) # first level at or above `high`
k = int(np.searchsorted(levels, high))
return _summary(
"ordinal",
len(d),
@@ -473,12 +429,10 @@ def ordinal_probability(state: dict, t: pd.DataFrame) -> np.ndarray:
def ordinal_reference(state: dict) -> float:
"""P(outcome >= high) at z = 0 with the covariates at their reference."""
return state["always"] if state["threshold"] is None else float(1 - expit(state["threshold"]))
def bh(p) -> np.ndarray:
"""Benjamini-Hochberg q values; NaN stays NaN."""
p = np.asarray(p, dtype=float)
q = np.full(len(p), np.nan)
ok = np.isfinite(p)
@@ -492,8 +446,6 @@ def bh(p) -> np.ndarray:
def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
"""The pair's principal outcome and the ordinal one: item altered and item score, or CSS high
and CSS."""
if pair["kind"] == "item":
score = item_scores(cohort, pair["outcome"])
return (score >= ALTERED).astype(float).where(score.notna()), score
@@ -502,8 +454,6 @@ def _outcome(cohort: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
def _guarded(fit, model: str, *args, **kwargs) -> dict:
"""One fit, or a row with its reason when the design is singular: one pair never stops the
others."""
try:
return fit(*args, **kwargs)
except (np.linalg.LinAlgError, ValueError) as error:
@@ -511,8 +461,6 @@ def _guarded(fit, model: str, *args, **kwargs) -> dict:
def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
"""Principal and sensitivity fits: Firth then ordinal for an item, ordinal then Firth for the
CSS."""
p = pair["predictor"]
fit_firth = lambda: _guarded(firth, "firth", d, "_yes", p, ADJUST) # noqa: E731
if pair["kind"] == "item":
@@ -521,8 +469,6 @@ def _models(d: pd.DataFrame, pair: dict) -> tuple[dict, dict]:
def _probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
"""Each row's probability of the event, and the reference probability (z = 0, covariates at
reference)."""
if fit["model"] == "firth":
return firth_probability(fit["state"], t), firth_reference(fit["state"])
return ordinal_probability(fit["state"], t), ordinal_reference(fit["state"])
@@ -566,8 +512,6 @@ class Ados2Association:
return self.fitted["rows"]
def associations(self) -> pd.DataFrame:
"""One row per pair tested: the cohort's odds ratio per unit of z, interval, p and q, and
the sensitivity model's odds ratio and whether it points the same way."""
out = []
for r in self._rows():
f, s = r["principal"], r["sensitivity"]
@@ -601,9 +545,6 @@ class Ados2Association:
return pd.DataFrame(out, columns=list(ASSOCIATION_COLUMNS))
def score(self, cohort: pd.DataFrame) -> pd.DataFrame:
"""Each child's z and probability of the event, with the pair's reference probability (z =
0, mean age, most frequent module), for every estimated pair whose outcome exists in the
child's module."""
parts = []
for r in self._rows():
f = r["principal"]
-1
View File
@@ -120,7 +120,6 @@ def _number(v) -> float | None:
def centiles(baseline_feature: dict, age_months: float) -> dict:
"""The stored centiles interpolated at an age, with nulls outside coverage."""
curve = pd.DataFrame(baseline_feature["curve"]).astype(float).dropna()
names = [name for name in QUANTILES if name in curve or name in ("p5", "median", "p95")]
if curve.empty or not age_months > 0:
+1 -1
View File
@@ -130,7 +130,6 @@ def _date(value: str, fmt: str) -> date | None:
def header(edf: bytes) -> Header:
"""Read the declared facts from the fixed header without opening any signals."""
fixed = _fixed_header(edf)
patient = fixed["patient"].split(maxsplit=3) + [""] * 3
recording = fixed["recording"].split(maxsplit=3) + [""] * 3
@@ -160,6 +159,7 @@ def _open(edf: bytes) -> edfio.Edf:
def _kept(edf: bytes) -> list[tuple[str, str]]:
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
signals = _open(edf).signals
if not signals:
raise FileNotValid("the EDF declares zero signals")
+1 -1
View File
@@ -4,7 +4,7 @@ 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
mains, with the table's age) in worker processes; `tables` gives each scenario's training table
from the valid studies.
"""
+39 -76
View File
@@ -1,10 +1,10 @@
"""TEA jobs analyse the hospital's EEGs and score them against seven age curves
(models.tea.eeg.curves). Training uses a named reference cohort or the legacy
TEA_REFERENCE_DIR and TEA_REFERENCE_AGES settings.
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
features are kept in TEA_REFERENCE_CACHE in a JSON file named by the cohort and its hash.
Changes to the study list, ages or mains frequency require measuring the cohort again."""
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
or ages table that changes is measured again."""
import hashlib
import json
@@ -15,20 +15,19 @@ from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from sqlalchemy import bindparam, inspect, text
from core.tea import ADOS2_ITEMS, ados2
from core.measures import as_day
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS, ados2
from core.tea.fhir import eeg_study_id
from models import execution
from models.jobs import EmptyCohort
from models.tea import association
from models.tea.eeg import analysis, curves
from models.tea.eeg import reference as cohort_reference
from persistance import cluster, eeg, registry, silver
from persistance.destination import engine
ASSOCIATION = "ados2_association"
MODELS = curves.SCENARIOS
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
GOLD_SELECT = [
"tea_eeg_analyses+",
@@ -46,7 +45,6 @@ class Baseline(mlflow.pyfunc.PythonModel):
self.scenario, self.baseline = scenario, baseline
def curve(self, feature: str, ages) -> list[dict]:
"""Centiles by age for a feature, using the same interpolation as scoring."""
baseline = self.baseline[feature]
if baseline["kind"] == "count_rate":
raise LookupError("no centiles by age for a count-rate feature")
@@ -66,11 +64,8 @@ def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analys
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
"""The EEGs in scope (default: those not analysed yet), analysed in the ambient
execution; then, unless told not to, gold's TEA tables are rebuilt. Bronze is written
once, after the last study, so a cancelled run leaves it as it was."""
rows = eeg.select(scope or eeg.Scope())
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows) # lazy: bytes travel
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows)
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
eeg.save_analyses(found)
if rebuild_gold:
@@ -79,7 +74,6 @@ def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int
def _reference(reference: cluster.Reference | None) -> tuple[str, list[dict], str, int]:
"""The reference cohort's hash, cached measurements, name and mains frequency."""
if reference is None:
folder = Path(os.environ["TEA_REFERENCE_DIR"])
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
@@ -151,12 +145,10 @@ def train(
def score_curves() -> dict[str, int | None]:
"""The version of each age curve's champion that scored, None without a champion."""
return {name: score(name) for name in CURVES}
return {name: score(name) for name in MODELS}
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
"""The first EEG with a predictor per child for fitting, and all eligible EEGs for scoring."""
columns = [
"key",
"person_id",
@@ -167,62 +159,35 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
"css",
*ADOS2_ITEMS,
]
records, values = [], {}
with engine().connect() as con:
tables = inspect(con)
if tables.has_table("eeg_analysis", schema="bronze"):
items = ", ".join(ADOS2_ITEMS)
selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS)
query = text(f"""
with first_ados as (
select person_id, module, evaluation_date, {items},
row_number() over (
partition by person_id order by evaluation_date nulls last, known_at
) as rn
from silver.ados2
)
select e.person_id, e.study_date, e.edf, a.age_months,
t.module, t.evaluation_date, p.birth_date, {selected_items}
from silver.eeg as e
join bronze.eeg_analysis as a on a.edf = e.edf
join first_ados as t on t.person_id = e.person_id and t.rn = 1
left join silver.person as p on p.person_id = e.person_id
where a.valid and a.age_months is not null
""")
for raw in con.execute(query).mappings():
row = dict(raw)
for field in ("birth_date", "evaluation_date"):
row[field] = date.fromisoformat(str(row[field])[:10]) if row[field] else None
records.append(
{
**row,
"key": f"{row['person_id']}|{str(row['study_date'])[:10]}",
"ados_module": row["module"],
"css": ados2.score(
row, row["birth_date"] if row["evaluation_date"] else None
)[0],
}
)
if records and tables.has_table("eeg_scores", schema="bronze"):
biomarker = {metric: name for name, metric in association.BIOMARKERS.items()}
query = text("""
select edf, metric, part, site, z from bronze.eeg_scores
where metric in :metrics and z is not null
""").bindparams(bindparam("metrics", expanding=True))
edfs = {row["edf"] for row in records}
for edf, metric, part, site, z in con.execute(query, {"metrics": list(biomarker)}):
if edf not in edfs:
continue
name = biomarker[metric]
if name in ("spikes", "spindles"):
if part != "zones":
continue
predictor = f"z_{name}_{site}"
else:
if part != "value":
continue
predictor = f"z_{name}"
values.setdefault(edf, {})[predictor] = z
biomarker = {metric: name for name, metric in ASSOCIATION_BIOMARKERS.items()}
studies, scores = eeg.association_cohort_rows()
records = []
for row in studies:
row["evaluation_date"] = as_day(row["evaluation_date"]) if row["evaluation_date"] else None
birth = as_day(row["birth_date"]) if row["evaluation_date"] and row["birth_date"] else None
records.append(
{
**row,
"key": eeg_study_id(row["person_id"], row["study_date"]),
"ados_module": row["module"],
"css": ados2.score(row, birth)[0],
}
)
values = {}
edfs = {row["edf"] for row in records}
for row in scores:
if row["edf"] not in edfs:
continue
name = biomarker[row["metric"]]
if name in ("spikes", "spindles"):
if row["part"] != "zones":
continue
predictor = f"z_{name}_{row['site']}"
else:
if row["part"] != "value":
continue
predictor = f"z_{name}"
values.setdefault(row["edf"], {})[predictor] = row["z"]
scored = pd.DataFrame(records, columns=columns)
if values:
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="edf")
@@ -240,7 +205,6 @@ def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
"""Hash the scored EEGs, fit membership, and module identifier in canonical order."""
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
@@ -248,7 +212,6 @@ def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
def _records(frame: pd.DataFrame) -> list[dict]:
"""Coerce missing estimates and open interval limits to JSON/SQL nulls."""
clean = frame.replace([float("inf"), -float("inf")], None).astype(object)
return clean.where(clean.notna(), None).to_dict("records")
+3 -4
View File
@@ -1,9 +1,9 @@
"""Analyse a single study and its optional report without persisting the results."""
import math
from dataclasses import replace
from datetime import date
from sqlalchemy.exc import SQLAlchemyError
from core import concept_map, tea
from core.pipeline import apply_patterns
from core.tea import ados2 as scoring
@@ -32,7 +32,6 @@ def _deviations(models: dict, study: analysis.Analysis) -> dict:
if part != "value"
}
if "value" in scenario.parts and "value" not in baseline:
# A missing value short-circuits curves.score, while the sites still get scored.
models[name] = baseline | {"value": {}}
changes["value"] = None
missing_values.add(metric.code)
@@ -124,7 +123,7 @@ def _report(
try:
saved = config_log.get(pipeline)
except Exception: # noqa: BLE001 -- an unavailable saved pipeline is reported in the result
except (LookupError, SQLAlchemyError, ValueError):
saved = None
if saved is None:
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
-1
View File
@@ -15,7 +15,6 @@ def test_centile_interpolation_preserves_scoring():
"p95": [7, 9],
},
}
# At the geometric midpoint, the original log-age interpolation gives the means.
assert curves.centiles(baseline, 24) == pytest.approx(
{"p5": 2, "p25": 3, "median": 4, "p75": 6, "p95": 8}
)
+3 -12
View File
@@ -1,8 +1,3 @@
"""`execution.map` returns the same list in every mode, spreads lazy input without loading it
all, fails fast when the cluster is wrong, cleans up after a cancel, and reports progress on
the Dagster run. Remote tests need a scheduler: set `DASK_TEST_SCHEDULER` and
`DASK_EXPECTED_WORKERS` (the compose `test` profile does)."""
import json
import os
import signal
@@ -27,9 +22,6 @@ cloudpickle.register_pickle_by_value(sys.modules[__name__])
def by_value(fn):
"""Mark a worker function so that Dask ships its code, not its name: the scheduler
unpickles task graphs too, and has no test module (Dask wraps `fn` in a task, which
hides the by-value registration above from it)."""
fn.__module__ = "__main__"
return fn
@@ -178,10 +170,10 @@ def test_eta_smoothing_and_threshold():
eta = execution.Eta(alpha=0.3, min_done=3)
eta.update(0.0, 0)
eta.update(1.0, 2)
assert eta.eta_s(10) is None # fewer than 3 done
assert eta.eta_s(10) is None
eta.update(2.0, 4)
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
eta.update(3.0, 8) # a faster burst: 4 items/s
eta.update(3.0, 8)
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
@@ -252,7 +244,6 @@ CANCEL_SCRIPT = textwrap.dedent(
def run_cancelled(mode, n):
"""Start a `map` of sleepers in a subprocess, send SIGTERM after its first line."""
proc = subprocess.Popen(
[sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)],
stdout=subprocess.PIPE,
@@ -260,7 +251,7 @@ def run_cancelled(mode, n):
env={**os.environ, "DASK_LOCAL_WORKERS": "2"},
)
assert proc.stdout.readline().startswith("working: 0/")
time.sleep(3) # the cluster is up and the tasks are submitted
time.sleep(3)
return proc
-3
View File
@@ -1,5 +1,3 @@
"""The association fit and its parity with the pinned tea-lib source."""
import importlib.util
import sys
from pathlib import Path
@@ -40,7 +38,6 @@ def test_ordinal_on_monotone_trend():
def test_pairs_and_item_availability():
assert len(a.pairs("item")) == 41
assert len(a.pairs("domain")) == 15
# Item order in the source, translated by meaning into the platform catalog names.
assert ADOS2_ITEMS == [
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact",
"facial_expressions", "gaze_integration", "shared_enjoyment", "response_to_name",
+1 -4
View File
@@ -1,5 +1,3 @@
"""The tea_eeg job's graph, sensor, config classes and synthetic EEG scope."""
import os
from pathlib import Path
@@ -115,7 +113,6 @@ def test_config_mirrors_match_the_shared_models():
assert list(config.model_fields) == list(shared.model_fields)
for name, field in shared.model_fields.items():
assert config.model_fields[name].default == field.default, name
# a wrong value still reaches the shared model's validation
with pytest.raises(ValidationError):
ExecutionConfig(mode="cloud").model()
with pytest.raises(ValidationError):
@@ -140,7 +137,7 @@ def test_definitions_load_with_every_job_and_the_sensor():
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
def test_relate_is_a_no_op_until_phase_2():
def test_relate_returns_none_without_a_champion():
assert tea_jobs.relate() is None