tea_preview job: one file previewed, result as run output: preview analyses one staged EDF (and an ADOS-2 PDF) against the champions, writes nothing

This commit is contained in:
2026-11-28 13:37:27 -06:00
parent 9ed686e87a
commit 3950b3c1f5
3 changed files with 479 additions and 2 deletions
+216
View File
@@ -0,0 +1,216 @@
"""Analyse a single study and its optional report without persisting the results."""
import math
from dataclasses import replace
from datetime import date
from core import concept_map, tea
from core.pipeline import apply_patterns
from core.tea import ados2 as scoring
from models import graph
from models.tea.eeg import analysis, curves, read
from models.tea.jobs import MODELS
from persistance import config_log, registry
from persistance.previews import PreviewAdos2, PreviewEeg, PreviewMetric, PreviewResult, Site
def _deviations(models: dict, study: analysis.Analysis) -> dict:
metrics = {metric.code: metric for metric in study.metrics}
missing_values = set()
for name, baseline in models.items():
scenario = curves.SCENARIOS[name]
if scenario.metric not in metrics:
continue
metric = metrics[scenario.metric]
changes = {
part: {
site: value
for site, value in getattr(metric, part).items()
if curves.PREFIX[part] + site in baseline
}
for part in scenario.parts
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)
metrics[metric.code] = replace(metric, **changes)
features = {name: study.features.get(name, {}) for name in models}
found = curves.deviations(
models, replace(study, metrics=list(metrics.values()), features=features)
)
for code in missing_values:
found.get(code, {}).pop("value", None)
return found
def _sites(values: dict, scores: dict) -> dict[str, Site]:
return {key: Site(value=value, score=scores.get(key)) for key, value in values.items()}
def _metrics(study: analysis.Analysis, warnings: list[str]) -> list[PreviewMetric]:
models, versions = {}, {}
found = {}
if study.valid:
for name in curves.SCENARIOS:
champion = registry.champion(f"tea.{name}")
if champion is not None:
versions[name], model = champion
models[name] = model.unwrap_python_model().baseline
if not models:
warnings.append("there are no champion age curves: no z is shown")
else:
codes = {metric.code for metric in study.metrics}
warnings.extend(
f"no champion for {name}: its z is not shown"
for name, scenario in curves.SCENARIOS.items()
if name not in models and scenario.metric in codes
)
found = _deviations(models, study)
labels = {
MODELS[name].metric: f"tea.{name}/{version}"
for name, version in versions.items()
if "value" in MODELS[name].parts
}
metrics = []
for metric in study.metrics:
parts = found.get(metric.code, {})
metrics.append(
PreviewMetric(
code=metric.code,
value=metric.value,
score=parts.get("value"),
model=labels.get(metric.code) if "value" in parts else None,
electrodes=_sites(metric.electrodes, parts.get("electrodes", {})),
zones=_sites(metric.zones, parts.get("zones", {})),
)
)
return metrics
def _parse(field, value, kind, warnings):
if value is None:
return None
try:
if kind == "date":
return value if isinstance(value, date) else date.fromisoformat(value)
number = float(value)
if math.isfinite(number):
return number
except (TypeError, ValueError):
pass
warnings.append(f"{field}: could not read {value!r} as a {kind}")
return None
def _report(
content: bytes,
pipeline: str,
recorded_on: date | None,
birth: date | None,
warnings: list[str],
) -> PreviewAdos2 | None:
if not content.startswith(b"%PDF"):
warnings.append("the ADOS-2 file is not a PDF")
return None
text = graph.read_file(content)
if error := text["error"]:
warnings.append(f"the ADOS-2 report could not be read: {error}")
return None
try:
saved = config_log.get(pipeline)
except Exception: # noqa: BLE001 -- an unavailable saved pipeline is reported in the result
saved = None
if saved is None:
warnings.append(f"no saved pipeline {pipeline}: the ADOS-2 report is not read")
return None
_, definition = saved
node = next((n for n in definition.nodes if n.kind == "extract" and n.entity == "ados2"), None)
if node is None:
warnings.append(f"pipeline {pipeline} has no ados2 extract node")
return None
codes = {}
if node.concept_map:
mapping = config_log.concept_map(node.concept_map)
codes = {field: concept_map.table([mapping], field) for field in node.patterns}
found = apply_patterns(node, text["text"], codes)
if not found:
warnings.append("no ADOS-2 field was found in the report")
return None
row = dict(found[0][0])
fields = sorted(row)
evaluation_date = _parse("evaluation_date", row.get("evaluation_date"), "date", warnings)
if "evaluation_date" not in row:
evaluation_date = recorded_on
items = {
item: _parse(item, row.get(item), "number", warnings)
for item in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
}
css, classification = None, None
if evaluation_date is None:
warnings.append("ADOS-2 not scored: no evaluation date")
else:
try:
css, classification = scoring.score(
row | items | {"evaluation_date": evaluation_date}, birth
)
except (ValueError, TypeError) as exc:
warnings.append(f"ADOS-2 not scored: {exc}")
else:
if css is None and classification is None:
warnings.append(
"the ADOS-2 score could not be calculated: "
"the report lacks the module or the item scores"
)
return PreviewAdos2(
module=row.get("module"),
evaluation_date=evaluation_date,
items=items,
css=css,
classification=classification,
read=fields,
)
def preview(
edf: bytes,
ados2: bytes | None = None,
birth_date: date | None = None,
pipeline: str = "tea",
) -> PreviewResult:
study = analysis.analyze(edf, birth_date)
try:
header = read.header(edf)
except read.FileNotValid:
header = None
recorded_on = header.start_date if header else None
warnings = []
if study.error:
warnings.append(f"the EEG analysis ended with an error: {study.error}")
eeg = PreviewEeg(
valid=study.valid,
level=study.level,
recorded_on=recorded_on,
age_months=study.age_months,
clean_fraction=study.clean_fraction,
bad_channels=study.bad_channels,
channels=study.channels,
duration_min=study.duration_min,
line_noise_db=study.line_noise_db,
sleep=study.sleep,
checks=study.checks,
metrics=_metrics(study, warnings),
error=study.error,
)
report = None
if ados2 is not None:
birth = birth_date or (header.birthdate if header else None)
report = _report(ados2, pipeline, recorded_on, birth, warnings)
return PreviewResult(eeg=eeg, ados2=report, warnings=warnings)