Files
ISSSTELEON/tools/capture_reference.py
T
alberto 125b413ec6 TEA reference recaptured from sitio-b: 62 children with real EDFs, M30/M31, follow-up queries, patient summaries, code systems, association tables, baselines bundle
The hospital manifest records the sitio-b TEA hospital (sha256 2b2abae4...), which replaces the
200-child synthetic one. follow_up and patients are stored gzipped (58 MB and 6 MB as JSON); the
capture tool writes them that way with mtime 0, so a recapture is byte-identical.
2026-11-27 23:53:48 -06:00

541 lines
22 KiB
Python

"""Capture the current platform's outputs once, on the synthetic hospital, as reference fixtures.
For one domain: start the image of its reference instance locally (never the live instance), load
the hospital with the loader that filled that instance, compute indicators and models with the
image's own worker and CLI, and save what its API and CLI return. Talks to the image only through
the Docker CLI and HTTP; no code from it is imported.
uv run python tools/capture_reference.py cacu --hospital tests/fixtures/hospital
"""
import argparse
import gzip
import hashlib
import io
import json
import subprocess
import time
import urllib.parse
import urllib.request
import zipfile
from datetime import UTC, datetime
from pathlib import Path
# CaCu and CaMa use the images behind :5210 and :18122. TEA uses the sitio-b deployment
# documented in the TEA Functional Atlas. Each uses the dev-data loader matching its schemas.
DOMAINS = {
"cacu": ("isssteleon-cacu197/webapi:local", "isssteleon-cacu197-load:latest"),
"cama": ("isssteleon/webapi:cama-dev-3743ea6", "isssteleon-cacu197-load:latest"),
"tea": ("sitio-b/webapi:local", "sitio-b-load:latest"),
}
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
GZIPPED = {"follow_up", "patients"} # TEA files tens of MB as JSON, stored as .json.gz
PAGES = { # other GET pages whose content is computed from the loaded data
"cacu": ["/cacu/seguimiento?page_size=200"],
"cama": [
"/cama/seguimiento",
"/cama/modelo/curvas",
"/cama/modelo/escenarios",
"/cama/modelo/desarrollo",
"/cama/modelo/recurrencia",
],
"tea": ["/governance/tea/eeg/summary", "/governance/tea/eeg"],
}
RTOL = 1e-6 # tolerance the rewritten models must meet against these predictions
# Defects fixed inside the throwaway capture container only, so a scenario that failed there can
# give a reference: (file under /app, sed expression, why). Each one is written to the manifest.
PATCHES = {
"cacu": [
(
"models/models/steps/indexing.py",
"s/^VECTORIZED = {.*}$/VECTORIZED = {}/",
"the vectorised primera_biopsia_invasora ignored event_grades (CIS, CARCINOMA) and its"
" rules, so CaCu survival indexed nobody; the per-patient rule honours both",
)
],
}
ENTRYPOINT = "/app/WebApi/docker-entrypoint.sh"
# Show alterations as on sitio-b. DEV_REVISION serves the patient-level FHIR routes.
TEA_ENV = ["-e", "TEA_ALTERACIONES_VALIDADAS=1", "-e", "DEV_REVISION=capture"]
# TEA's age curves train on the Helsinki reference cohort; the image reads it from S3, which
# this machine doesn't reach, so the same EDFs are mounted from their local copy.
REFERENCE = Path("/mnt/drive/eeg-helsinki")
REFERENCE_AGES = "anon_codex_age_sex.csv" # Anon. Filename, Quantized Age (years), Quantized Sex
TEA_TABLES = [ # the EEG analysis as the instance stores it, beyond what its pages show
"eeg", "eeg_criterio", "eeg_metrica", "eeg_metrica_electrodo", "eeg_metrica_zona", "ados2",
"relacion_ados2", "relacion_ados2_paciente",
] # fmt: skip
# End of the last captured period. Pass it explicitly because the old API defaults to today.
CUTOFF = "2026-12-31"
# First day of each window ending at CUTOFF, as computed by core.follow_up.window_start.
WINDOWS = {1: "2026-12-01", 3: "2026-10-01", 6: "2026-07-01", 12: "2026-01-01"}
def docker(*args: str, check: bool = True) -> str:
result = subprocess.run(["docker", *args], capture_output=True, text=True)
if check and result.returncode:
raise RuntimeError(f"docker {args[0]} failed:\n{_tail(result)}")
return result.stdout
def image_id(tag: str) -> str:
return docker("image", "inspect", "-f", "{{.Id}}", tag).strip()
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def get(api: str, path: str, **params: str):
return get_query(api, path, list(params.items()))
def get_query(api: str, path: str, pairs: list[tuple[str, str]]):
url = f"{api}{path}" + (f"?{urllib.parse.urlencode(pairs)}" if pairs else "")
try:
with urllib.request.urlopen(url, timeout=600) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"null")
def wait(predicate, what: str, timeout: float = 3600) -> None:
deadline = time.monotonic() + timeout
while not predicate():
if time.monotonic() > deadline:
raise TimeoutError(what)
time.sleep(3)
def run_cli(container: str, *args: str) -> subprocess.CompletedProcess:
cmd = "cd /app/WebApi && uv run --no-sync python -m models " + " ".join(args)
return subprocess.run(
["docker", "exec", container, "sh", "-c", cmd], capture_output=True, text=True
)
def _follow_up_queries(code_systems, value_sets) -> list[list[tuple[str, str]]]:
B = [("date", f"le{CUTOFF}")]
queries = [B]
queries.extend([("date", f"ge{WINDOWS[months]}"), *B] for months in sorted(WINDOWS))
queries.extend(B + [("status", s)] for s in ("active", "finished"))
for name, parameter in (("paso", "etapa"), ("grupo-edad", "grupo-edad")):
system = code_systems["systems"].get(name, {})
queries.extend(B + [(parameter, c["code"])] for c in system.get("concept", []))
queries.extend(
B + [("mchat", f"ge{lo}"), ("mchat", f"le{hi}")] for lo, hi in ((0, 2), (3, 7), (8, 20))
)
queries.extend(
B + [("css", f"ge{lo}"), ("css", f"le{hi}")] for lo, hi in ((1, 2), (3, 4), (5, 7), (8, 10))
)
queries.extend(B + [("resultado-eeg", r)] for r in ("normal", "anormal", "sin-eeg-valido"))
alterations = value_sets.get("tea-alteracion", {})
codes = {
concept["code"]
for include in alterations.get("compose", {}).get("include", [])
for concept in include.get("concept", [])
}
codes.update(
concept["code"] for concept in alterations.get("expansion", {}).get("contains", [])
)
queries.extend(B + [("alteracion", c)] for c in sorted(codes))
queries.extend(B + [("sexo", s)] for s in ("FEMENINO", "MASCULINO"))
queries.extend(B + [("modelo", m)] for m in ("si", "no"))
return queries
def _tea_fhir(api: str) -> dict[str, object]:
_, index = get(api, "/tea/fhir/CodeSystem")
systems = {}
for entry in index.get("entry", []):
system_id = entry["resource"]["id"]
status, body = get(api, f"/tea/fhir/CodeSystem/{system_id}")
systems[system_id] = body if status == 200 else {"status": status, "body": body}
code_systems = {"index": index, "systems": systems}
status, body = get(api, "/tea/fhir/ValueSet/tea-alteracion")
value_sets = {"tea-alteracion": body if status == 200 else {"status": status, "body": body}}
_, measures = get(api, "/tea/fhir/Measure")
follow_up = {}
queries = _follow_up_queries(code_systems, value_sets)
for q in queries:
episode_status, episodes = get_query(
api, "/tea/fhir/EpisodeOfCare", q + [("_include", "*"), ("_count", "200")]
)
summary_status, summary = get_query(api, "/tea/fhir/EpisodeOfCare/$resumen-eeg", q)
follow_up[urllib.parse.urlencode(q)] = {
"episodes": {"status": episode_status, "body": episodes},
"summary": {"status": summary_status, "body": summary},
}
patients = {}
base_episodes = follow_up[urllib.parse.urlencode(queries[0])]["episodes"]["body"]
for entry in base_episodes.get("entry", []):
resource = entry["resource"]
if (
entry.get("search", {}).get("mode") == "match"
and resource["resourceType"] == "EpisodeOfCare"
):
patient_id = resource["id"]
status, body = get(api, f"/tea/fhir/Patient/{patient_id}/$resumen-tea")
patients[patient_id] = {"status": status, "body": body}
return {
"code_systems": code_systems,
"value_sets": value_sets,
"measures": measures,
"follow_up": follow_up,
"patients": patients,
}
def _tea_bundle(api: str) -> dict:
try:
with urllib.request.urlopen(
f"{api}/governance/tea/baselines/export?production=1", timeout=600
) as response:
body = response.read()
with zipfile.ZipFile(io.BytesIO(body)) as bundle:
files = sorted(bundle.namelist())
return {
"status": response.status,
"sha256_header": response.headers.get("X-Baselines-Sha256"),
"versions_header": response.headers.get("X-Baselines-Versions"),
"sha256_body": hashlib.sha256(body).hexdigest(),
"files": files,
"manifest": json.loads(bundle.read("manifest.json"))
if "manifest.json" in files
else None,
}
except urllib.error.HTTPError as error:
return {"status": error.code, "error": error.read().decode(errors="replace")}
def _source_manifest(path: Path) -> dict:
repos = {}
for name in (".", "WebApi", "WebApp", "models"):
folder = path / name
if not folder.is_dir():
continue
def git(*args: str, folder: Path = folder) -> bytes:
return subprocess.run(
["git", "-C", str(folder), *args], capture_output=True, check=True
).stdout
if Path(git("rev-parse", "--show-toplevel").decode().strip()) != folder.resolve():
continue
repos[name] = {
"head": git("rev-parse", "HEAD").decode().strip(),
"branch": git("branch", "--show-current").decode().strip(),
"diff_sha256": hashlib.sha256(git("diff", "HEAD", "--binary")).hexdigest(),
"untracked": sorted(
git("ls-files", "--others", "--exclude-standard").decode().splitlines()
),
}
return {"path": str(path), "repos": repos}
def capture(
domain: str,
hospital: Path,
out: Path,
only: list[str] | None = None,
*,
source: Path | None = None,
) -> None:
"""Capture everything, or with `only` just those model scenarios, merged into what is saved."""
(image, loader), name = DOMAINS[domain], f"capture-{domain}"
volume = f"{name}-data"
docker("rm", "-f", name, f"{name}-worker", check=False)
docker("volume", "rm", "-f", volume, check=False)
env = ["-e", "WEBAPI_SQL_ALLOWED_DIALECTS=sqlite"]
mounts = ["-v", f"{volume}:/data", "-v", f"{hospital.resolve()}:/hospital:ro"]
if domain == "tea":
env += TEA_ENV
mounts += ["-v", f"{REFERENCE}:/reference:ro"]
patches = PATCHES.get(domain, [])
start = _patched(patches)
docker("run", "-d", "--name", name, "--network", "bridge", *env, *mounts, *start(image))
try:
ip = docker("inspect", "-f", "{{.NetworkSettings.Networks.bridge.IPAddress}}", name).strip()
api = f"http://{ip}:5000"
wait(lambda: _ok(api, "/health"), "API up", 600)
load = docker(
"run",
"--rm",
"--network",
"bridge",
loader,
"cargar",
domain,
"--api",
api,
"--hospital",
f"sqlite:////hospital/hospital_{domain}.db",
)
if domain == "tea": # curves first: the analysis scores each EEG against them
curves, reference = _train_curves(name, api)
docker(
"run",
"-d",
"--name",
f"{name}-worker",
"--network",
"bridge",
*env,
*mounts,
*start(image, "indicadores"),
)
wait(
lambda: get(api, "/reportes/indicadores")[1][domain].get("estado") in ("ok", "error"),
"indicators computed",
)
docker("rm", "-f", f"{name}-worker")
out.mkdir(parents=True, exist_ok=True)
def save(file: str, data) -> None:
(out / file).parent.mkdir(parents=True, exist_ok=True)
text = json.dumps(data, indent=1, ensure_ascii=False, sort_keys=True, default=str)
if file.endswith(".gz"): # the large ones; mtime 0 keeps a recapture byte-identical
(out / file).write_bytes(gzip.compress((text + "\n").encode(), mtime=0))
else:
(out / file).write_text(text + "\n")
if only:
return _capture_models(domain, name, api, out, save, only, load, patches)
if domain == "tea":
for table in TEA_TABLES:
save(f"tables/{table}.json", _table(name, "/data/tea.db", table))
save("indicator_run.json", get(api, "/reportes/indicadores")[1][domain])
measures = {}
for m in get(api, f"/{domain}/indicadores")[1]:
status, body = get(
api,
f"/{domain}/indicadores/{m['id']}",
periodos=",".join(PERIODS), # knowledge date left to its default, the last load
)
measures[m["id"]] = {"status": status, "body": body}
save("indicators.json", measures)
pages = {p: dict(zip(("status", "body"), get(api, p), strict=True)) for p in PAGES[domain]}
if domain == "tea": # each analysed EEG's metrics
for eeg in pages["/governance/tea/eeg"]["body"]:
path = f"/governance/tea/eeg/{eeg['id']}/metrics"
pages[path] = dict(zip(("status", "body"), get(api, path), strict=True))
save("pages.json", pages)
if domain == "tea":
for file, content in _tea_fhir(api).items():
save(f"{file}.json.gz" if file in GZIPPED else f"{file}.json", content)
save("baselines_bundle.json", _tea_bundle(api))
models = curves if domain == "tea" else _models(domain, name, api, None)
save("models.json", models)
for path in ("/data/ref", "/data/cohorts"): # predictions and the cohorts they came from
docker("cp", f"{name}:{path}", str(out), check=False)
save(
"manifest.json",
{
"domain": domain,
"image": {"tag": image, "id": image_id(image)},
"loader": {"tag": loader, "id": image_id(loader)},
"hospital_sha256": sha256(hospital / f"hospital_{domain}.db"),
"load": load.strip().splitlines(),
"knowledge_cutoff": "last load",
"periods": PERIODS,
"captured_at": datetime.now(UTC).isoformat(timespec="seconds"),
"models": {k: v["status"] for k, v in models.items()},
"patches": [{"file": f, "sed": e, "why": w} for f, e, w in patches],
**(
{"reference_cohort": reference, "env": TEA_ENV[1::2], "cutoff": CUTOFF}
if domain == "tea"
else {}
),
**({"source": _source_manifest(source)} if source is not None else {}),
},
)
finally:
docker("rm", "-f", name, f"{name}-worker", check=False)
docker("volume", "rm", "-f", volume, check=False)
def _models(domain: str, name: str, api: str, only: list[str] | None) -> dict:
"""Train (and estimate) each scenario of the domain with the image's own CLI."""
models = {}
scenarios = [
s for s in get(api, "/governance/scenarios")[1]["scenarios"] if s["domain"] == domain
]
for s in scenarios:
scenario = s["scenario"]
# A cohort model trains on its dbt cohort; an external one on its own reference set.
source = ["--export", "--source", "dbt", "--manifest", "$DBT_MANIFEST"]
trained = run_cli(
name,
"run",
domain,
scenario,
*([] if s["external"] else source),
"--train",
"--environment",
"dev",
)
versions = [
v
for v in get(api, "/governance/model-versions")[1]["model_versions"]
if v["tags"].get("scenario") == scenario and v["tags"].get("domain") == domain
]
if trained.returncode or not versions:
models[scenario] = {"status": "train failed", "error": _tail(trained)}
continue
version = max(versions, key=lambda v: int(v["version"]))
if s["external"]: # scored by the platform's own analysis, captured in the pages
models[scenario] = {"status": "ok", "error": None, "version": version, "rtol": RTOL}
continue
estimated = run_cli(
name,
"run",
domain,
scenario,
"--estimate",
"--version",
str(version["version"]),
"--environment",
"dev",
"--output",
f"/data/ref/{scenario}.parquet",
)
models[scenario] = {
"status": "estimate failed" if estimated.returncode else "ok",
"error": _tail(estimated) if estimated.returncode else None,
"version": version,
"rtol": RTOL,
}
return models
def _patched(patches: list[tuple[str, str, str]]):
"""`docker run` arguments that start the image with the patches applied first."""
def start(image: str, *args: str) -> list[str]:
if not patches:
return [image, *args]
seds = " && ".join(f"sed -i '{e}' /app/{f}" for f, e, _ in patches)
return ["--entrypoint", "sh", image, "-c", f'{seds} && exec {ENTRYPOINT} "$@"', "-", *args]
return start
def _python(container: str, code: str) -> str:
"""Run Python in the image's own environment and return what it prints."""
command = "cd /app/WebApi && uv run --no-sync python -"
result = subprocess.run(
["docker", "exec", "-i", container, "sh", "-c", command],
input=code,
capture_output=True,
text=True,
)
if result.returncode:
raise RuntimeError(_tail(result))
return result.stdout
def _table(container: str, db: str, table: str) -> list[dict]:
"""A table of the instance's SQLite database, every row, in key order."""
code = f"""
import json, sqlite3
con = sqlite3.connect("file:{db}?mode=ro", uri=True)
con.row_factory = sqlite3.Row
rows = [dict(r) for r in con.execute('select * from "{table}" order by 1')]
for r in rows:
for k, v in r.items():
if isinstance(v, bytes):
r[k] = f"<{{len(v)}} bytes>"
print(json.dumps(rows, default=str))
"""
return json.loads(_python(container, code))
def _train_curves(name: str, api: str) -> tuple[dict, dict]:
"""TEA's age curves trained on the local copy of the reference cohort, with the image's own
settings for it, and put in production by alias: the image's promotion asks for the clinical
reports a capture can't have, and only a version in production scores an EEG."""
ages = (REFERENCE / REFERENCE_AGES).read_text().splitlines()
table = ["archivo,edad_anos", *(",".join(line.split(",")[:2]) for line in ages[1:])]
_python(name, f"open('/tmp/ages.csv', 'w').write({chr(10).join(table)!r} + '\\n')")
trained = run_cli(name, "run", "tea", "eeg", "--train", "--environment", "dev",
"--reference-dir", "/reference", "--reference-ages", "/tmp/ages.csv",
"--reference-name", "hk1k", "--line-hz", "50") # fmt: skip
if trained.returncode:
raise RuntimeError(f"tea curves failed:\n{_tail(trained)}")
found = json.loads(
_python(
name,
"""
import json
from mlflow import MlflowClient
c, found = MlflowClient(), {}
for m in c.search_registered_models():
if m.name.startswith("tea-"):
v = max(c.search_model_versions(f"name='{m.name}'"), key=lambda v: int(v.version))
c.set_registered_model_alias(m.name, "produccion", v.version)
run = c.get_run(v.run_id).data
found[m.name] = {"version": v.version, "tags": v.tags, "metrics": run.metrics,
"params": run.params}
print(json.dumps(found))
""",
)
)
models = {k: {"status": "ok", "error": None, "version": v} for k, v in found.items()}
reference = {
"folder": str(REFERENCE),
"ages_table": REFERENCE_AGES,
"ages_table_sha256": sha256(REFERENCE / REFERENCE_AGES),
"as_image_settings": {"name": "hk1k", "line_hz": 50, "ages_months": [16, 36]},
"promoted_by_alias": "produccion set directly on the newest version of each tea-* model",
"train_output": trained.stdout.strip().splitlines(),
}
return models, reference
def _capture_models(domain, name, api, out, save, only, load, patches) -> None:
"""Capture only some scenarios, merged into the saved models.json and manifest."""
models = {**json.loads((out / "models.json").read_text()), **_models(domain, name, api, only)}
save("models.json", models)
(out / "ref").mkdir(exist_ok=True)
for scenario in only:
docker("cp", f"{name}:/data/ref/{scenario}.parquet", str(out / "ref"), check=False)
manifest = json.loads((out / "manifest.json").read_text())
manifest["models"] = {k: v["status"] for k, v in models.items()}
manifest.setdefault("partial_captures", []).append(
{
"scenarios": only,
"captured_at": datetime.now(UTC).isoformat(timespec="seconds"),
"load": load.strip().splitlines(),
"patches": [{"file": f, "sed": e, "why": w} for f, e, w in patches],
}
)
save("manifest.json", manifest)
def _ok(api: str, path: str) -> bool:
try:
return get(api, path)[0] == 200
except OSError:
return False
def _tail(result: subprocess.CompletedProcess) -> str:
return "\n".join((result.stderr or result.stdout).strip().splitlines()[-15:])
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("domain", choices=DOMAINS)
parser.add_argument("--hospital", type=Path, default=Path("tests/fixtures/hospital"))
parser.add_argument("--out", type=Path, default=Path("tests/fixtures/reference"))
parser.add_argument("--only", nargs="+", help="capture just these model scenarios")
parser.add_argument("--source-checkout", type=Path, default=None)
args = parser.parse_args()
capture(
args.domain, args.hospital, args.out / args.domain, args.only, source=args.source_checkout
)