TEA gate, EEG pages, analyze and named training runs
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
"""Phase 4 gate, TEA: the synthetic hospital (EEG signals and ADOS-2 reports as BLOBs), loaded
|
||||
through one drawn pipeline, gives what the current platform gives on the same hospital (the
|
||||
reference fixtures, captured at the last load): the ADOS-2 results read from the reports and
|
||||
their scores, the EEG analysis, its indicators and its pages. Real API, Dagster and MLflow.
|
||||
|
||||
The hospital (205 MB) is kept outside git; its path is TEA_HOSPITAL (default
|
||||
~/isssteleon-data), and its hash is the manifest's.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
from core.tea import ados2
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
|
||||
# The age curves' reference cohort (public, outside git) and where its measures are kept.
|
||||
os.environ.setdefault("TEA_REFERENCE_DIR", "/mnt/drive/eeg-helsinki")
|
||||
os.environ.setdefault("TEA_REFERENCE_CACHE", str(HOSPITAL / "cache"))
|
||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "tea"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_tea.json"
|
||||
MANIFEST = ROOT / "tests" / "fixtures" / "hospital" / "manifest.json"
|
||||
# The current platform's item columns, by module, for each item's meaning.
|
||||
ITEMS = {
|
||||
"vocalization_directed": {"module_1": "sa_a2"},
|
||||
"pointing": {"module_1": "sa_a7", "module_2": "sa_a6"},
|
||||
"gestures": {"module_1": "sa_a8", "module_2": "sa_a7"},
|
||||
"unusual_eye_contact": {"module_1": "sa_b1", "module_2": "sa_b1"},
|
||||
"facial_expressions": {"module_1": "sa_b3", "module_2": "sa_b2"},
|
||||
"gaze_integration": {"module_1": "sa_b4"},
|
||||
"shared_enjoyment": {"module_1": "sa_b5", "module_2": "sa_b3"},
|
||||
"showing": {"module_1": "sa_b9", "module_2": "sa_b5"},
|
||||
"joint_attention_initiation": {"module_1": "sa_b10", "module_2": "sa_b6"},
|
||||
"joint_attention_response": {"module_1": "sa_b11"},
|
||||
"social_overtures_quality": {"module_1": "sa_b12", "module_2": "sa_b8"},
|
||||
"reciprocal_communication": {"module_2": "sa_b11"},
|
||||
"rapport_quality": {"module_2": "sa_b12"},
|
||||
"intonation": {"module_1": "rrb_a3"},
|
||||
"stereotyped_language": {"module_1": "rrb_a5", "module_2": "rrb_a4"},
|
||||
"unusual_sensory_interest": {"module_1": "rrb_d1", "module_2": "rrb_d1"},
|
||||
"hand_finger_mannerisms": {"module_1": "rrb_d2", "module_2": "rrb_d2"},
|
||||
"repetitive_interests": {"module_1": "rrb_d4", "module_2": "rrb_d4"},
|
||||
} # fmt: skip
|
||||
MODULES = {"MODULO_1": "module_1", "MODULO_2": "module_2"}
|
||||
CLASSIFICATION = {"NO_ESPECTRO": "non_spectrum", "ESPECTRO_AUTISTA": "autism_spectrum",
|
||||
"AUTISMO": "autism"} # fmt: skip
|
||||
METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2",
|
||||
"HUSOS_SUENO_N3": "spindles_n3", "PICOS_PAROXISTICOS": "paroxysmal_spikes",
|
||||
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient"} # fmt: skip
|
||||
LEVELS = {"completo": "complete", "no_analizable": "not_analyzable", "parcial": "partial",
|
||||
"sin_referencia_auricular": "no_ear_reference"} # fmt: skip
|
||||
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
CODES = { # the current platform's code -> the platform's
|
||||
"CONFIRMADO": "confirmed", "EN_PROCESO": "in_process", "SIN_TEA": "not_confirmed",
|
||||
"SOLO_MCHAT": "mchat_only", "PSICOLOGIA": "psychology", "NEUROPEDIATRIA": "neuropediatrics",
|
||||
"EEG": "eeg", "BUENO": "good", "MALO": "bad", "SIN_ANALIZAR": "not_analyzed",
|
||||
"16_23": "16-23", "24_29": "24-29", "30_36": "30-36", "sin_dato": "no_data",
|
||||
} # fmt: skip
|
||||
STRATA = {"estado": "category", "paso": "category", "calidad": "category",
|
||||
"grupo_edad": "age_group"} # fmt: skip
|
||||
|
||||
|
||||
def _report(entry: dict, ours: bool) -> tuple:
|
||||
"""Counts, score and its extensions, and strata of one report, in the platform's codes.
|
||||
The current platform's proportions report no initial population."""
|
||||
group = entry["resource"]["group"][0]
|
||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
if ours and "denominator" in populations:
|
||||
populations.pop("initial-population")
|
||||
score = group.get("measureScore", {})
|
||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
||||
strata = {}
|
||||
for s in group.get("stratifier", []):
|
||||
code = s["code"][0]
|
||||
name = code["coding"][0]["code"] if "coding" in code else STRATA[code["text"]]
|
||||
cells: dict = defaultdict(dict)
|
||||
for x in s.get("stratum", []):
|
||||
for p in x["population"]:
|
||||
kind = p["code"]["coding"][0]["code"]
|
||||
if not (ours and kind == "initial-population" and "denominator" in populations):
|
||||
cells[CODES.get(x["value"]["text"], x["value"]["text"])][kind] = p["count"]
|
||||
strata[name] = dict(cells)
|
||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
||||
|
||||
|
||||
def indicators(api) -> None:
|
||||
"""Every measure, every semester, as the current platform answers them."""
|
||||
reference = {k.upper(): v for k, v in
|
||||
json.loads((REFERENCE / "indicators.json").read_text()).items()} # fmt: skip
|
||||
(measures,) = pages(api, "/tea/fhir/Measure")
|
||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
||||
for measure in [e["resource"] for e in measures["entry"]]:
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
found = [e for b in pages(api, "/tea/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
||||
name = measure["name"]
|
||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||
a, b = _report(ours, True), _report(theirs, False)
|
||||
where = (name, ours["resource"]["period"]["start"])
|
||||
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
|
||||
if cohort:
|
||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||
continue
|
||||
assert (a[1] is None) == (b[1] is None), where
|
||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
||||
assert a[2] == pytest.approx(b[2]), where
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not (HOSPITAL / "hospital_tea.db").exists(), reason="the TEA hospital is outside git"
|
||||
)
|
||||
|
||||
|
||||
def _day(value) -> date:
|
||||
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
db = HOSPITAL / "hospital_tea.db"
|
||||
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
|
||||
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
|
||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||
put_concept_map(api, "hospital_tea")
|
||||
ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
||||
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800)
|
||||
q = platform.query
|
||||
|
||||
# Silver holds every study of the hospital; each EEG signal is kept once, by its hash.
|
||||
counts = {s: q(f"select count(*) from silver.{s}")[0][0] for s in ("mchat", "ados2", "eeg")}
|
||||
assert counts == {"mchat": 216, "ados2": 113, "eeg": 84}
|
||||
assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'"
|
||||
)[0][0] == 83 # fmt: skip
|
||||
assert q("select count(*) from silver.eeg where edf is not null")[0][0] == 78
|
||||
assert q("select count(*) from bronze.files")[0][0] == 78
|
||||
|
||||
# ADOS-2: the results read from the 50 reports are the current platform's.
|
||||
reference = {(r["ado_fecha"], r["ado_pac_id"]): r for r in
|
||||
json.loads((REFERENCE / "tables" / "ados2.json").read_text())
|
||||
if r["ado_modulo"]} # fmt: skip
|
||||
numbers = dict(q("select distinct person_id, record_number from bronze.staged__identity"))
|
||||
names = ["person_id", "evaluation_date", "module", *ITEMS]
|
||||
sql = f"select {', '.join(names)} from silver.ados2 where module is not null"
|
||||
found = [dict(zip(names, r, strict=True)) for r in q(sql)]
|
||||
assert len(found) == len(reference) == 50
|
||||
for row in found:
|
||||
theirs = reference[(str(row["evaluation_date"])[:10],
|
||||
int(numbers[row["person_id"]].removeprefix("N")))] # fmt: skip
|
||||
module = MODULES[theirs["ado_modulo"]]
|
||||
assert row["module"] == module
|
||||
for item, by_module in ITEMS.items():
|
||||
value = theirs["ado_" + by_module[module]] if module in by_module else None
|
||||
assert row[item] == (None if value is None else pytest.approx(value)), item
|
||||
# and their scores: the calibrated severity and the classification.
|
||||
birth = q(f"select birth_date from silver.person where person_id = '{row['person_id']}'")
|
||||
css, label = ados2.score({**row, "evaluation_date": _day(row["evaluation_date"])},
|
||||
_day(birth[0][0])) # fmt: skip
|
||||
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]])
|
||||
|
||||
# The EEG analysis: every signal's verdict, level and metrics are the current platform's.
|
||||
wait_for(api, ok(api.post("/models/tea/analyze"))["run_id"], 1800)
|
||||
with sqlite3.connect(db) as con:
|
||||
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
||||
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
|
||||
tables = REFERENCE / "tables"
|
||||
reference = {hashes[r["eeg_id"]]: r for r in json.loads((tables / "eeg.json").read_text())
|
||||
if r["eeg_id"] in hashes} # fmt: skip
|
||||
found = {e: (v, lvl) for e, v, lvl in q("select edf, valid, level from bronze.eeg_analysis")}
|
||||
assert set(found) == set(reference)
|
||||
for edf, theirs in reference.items():
|
||||
assert found[edf] == (bool(theirs["eeg_valido"]), LEVELS[theirs["eeg_nivel"]]), edf
|
||||
by_id = {r["eeg_id"]: hashes.get(r["eeg_id"]) for r in reference.values()}
|
||||
metrics = {(by_id.get(r["met_eeg_id"]), METRICS[r["met_codigo"]]): r
|
||||
for r in json.loads((tables / "eeg_metrica.json").read_text())} # fmt: skip
|
||||
ours = {(e, c): v for e, c, v in q("select edf, code, value from bronze.eeg_metrics")}
|
||||
for key, theirs in metrics.items():
|
||||
value = theirs["met_valor"]
|
||||
assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key
|
||||
|
||||
# Indicators, from the platform's own EEG verdicts.
|
||||
indicators(api)
|
||||
|
||||
# The age curves: one training run gives a version of each, from the reference cohort;
|
||||
# promoted after their clinical validation, they score every analysed EEG as the
|
||||
# current platform's curves do.
|
||||
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], 3600)
|
||||
names = ok(api.get("/models/tea"))
|
||||
assert len(names) == 7
|
||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
||||
for name in names:
|
||||
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
|
||||
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
|
||||
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800)
|
||||
scored = {(e, c): r for e, c, *r in q(
|
||||
"select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
|
||||
for key, theirs in metrics.items():
|
||||
if key not in scored: # an EEG of a child outside the cohort: not in gold
|
||||
continue
|
||||
expected = [theirs[f"met_{k}"] for k in ("z", "fuera", "p5", "mediana", "p95")]
|
||||
assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9)
|
||||
for v in expected], key # fmt: skip
|
||||
|
||||
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
|
||||
listed = ok(api.get("/tea/eegs"))
|
||||
summary = json.loads((REFERENCE / "pages.json").read_text())["/governance/tea/eeg/summary"]
|
||||
expected = summary["body"]
|
||||
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
|
||||
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
|
||||
one = next(e for e in listed if e["valid"])
|
||||
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
||||
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
||||
for m in shown["metrics"]) # fmt: skip
|
||||
@@ -0,0 +1,47 @@
|
||||
"""TEA's EEGs for model governance: every study with its analysis verdict, and one study's
|
||||
metrics with their age curves' scores."""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from persistance import eeg
|
||||
|
||||
router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
||||
|
||||
|
||||
class Study(BaseModel):
|
||||
id: str # person and study date
|
||||
person_id: str
|
||||
study_date: str
|
||||
lab_record_id: str | None
|
||||
analysed: bool
|
||||
valid: bool | None
|
||||
level: str | None
|
||||
|
||||
|
||||
class Metric(BaseModel):
|
||||
code: str
|
||||
value: float
|
||||
z: float | None
|
||||
outside: float | None
|
||||
model: str | None
|
||||
|
||||
|
||||
class Analysis(BaseModel):
|
||||
id: str
|
||||
valid: bool | None
|
||||
level: str | None
|
||||
age_months: float | None
|
||||
metrics: list[Metric]
|
||||
|
||||
|
||||
@router.get("")
|
||||
def studies() -> list[Study]:
|
||||
return [Study(**s) for s in eeg.studies()]
|
||||
|
||||
|
||||
@router.get("/{eeg_id}")
|
||||
def study(eeg_id: str) -> Analysis:
|
||||
if (found := eeg.study(eeg_id)) is None:
|
||||
raise HTTPException(404, detail=f"no analysed EEG {eeg_id}")
|
||||
return Analysis(**found)
|
||||
+2
-1
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi import fhir, ingest, models, review, runs
|
||||
from webapi import eeg, fhir, ingest, models, review, runs
|
||||
from webapi.auth import caller
|
||||
|
||||
app = FastAPI(
|
||||
@@ -16,6 +16,7 @@ app.include_router(ingest.router)
|
||||
app.include_router(review.router)
|
||||
app.include_router(runs.router)
|
||||
app.include_router(models.router)
|
||||
app.include_router(eeg.router)
|
||||
app.include_router(fhir.router)
|
||||
|
||||
|
||||
|
||||
+11
-1
@@ -75,6 +75,7 @@ def promote(domain: Domain, name: str, version: int) -> dict:
|
||||
|
||||
class Training(BaseModel):
|
||||
as_of: date | None = None # the date the data are taken up to (default: today)
|
||||
models: list[str] = [] # which (default: all but the slow ones, like CaMa's recurrence)
|
||||
|
||||
|
||||
def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
|
||||
@@ -89,12 +90,21 @@ def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> di
|
||||
def train(domain: Domain, request: Training,
|
||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
||||
config = {"domain": domain.value}
|
||||
config: dict = {"domain": domain.value}
|
||||
if request.as_of:
|
||||
config["as_of"] = request.as_of.isoformat()
|
||||
if request.models:
|
||||
config["models"] = request.models
|
||||
return _submit(client, "train", "train_models", config)
|
||||
|
||||
|
||||
@router.post("/{domain}/analyze")
|
||||
def analyze(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
"""Starts analysing the studies the domain's models read whole (TEA: its EEGs); follow
|
||||
it at /runs."""
|
||||
return _submit(client, "analyze", "analyze_studies", {"domain": domain.value})
|
||||
|
||||
|
||||
@router.post("/{domain}/score")
|
||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
"""Starts a risk batch from each model's champion; follow it at /runs."""
|
||||
|
||||
Reference in New Issue
Block a user