ADOS-2 association model: Firth/ordinal port, MLflow model, bronze and gold, gate

Port the association estimator and add its source-parity tests in models.
Wire cohort selection, fingerprint deduplication, MLflow registration, and
champion scoring into the TEA jobs. Add both bronze tables, gold models
and key tests, and extend the existing WebApi hospital gate.

Follow the spec's resolved silver/bronze cohort and full CSV fingerprint.
No adaptations beyond the resolved spec. Preserve the source numerical
code with Ruff formatting and reflowed docstrings.

Internal choices:
- Select the first ADOS-2 with a SQL window and assemble predictor columns
  by EDF in pandas. Normalize dates to days across SQLite and PostgreSQL
  and use the undated CSS path if evaluation date is absent.
- Treat unstaged analysis or score tables as empty inputs. Retain the
  existing as_of argument without a cutoff in the specified cohort.
- Keep missing and non-finite report and bronze values as null, including
  open confidence limits. Store counts as bigint and direction as boolean.
  Reuse the EEG bronze merge writer after deleting the prior projection.
- Use a NumPy default_rng seeded with 0, uniform ages, normal predictors,
  and independent draws of module, item codes, and CSS for source parity.
  Load the reference modules in a test-only namespace with stub contracts.
- Record model and WebApi changes in their existing submodule branches
  and update the corresponding gitlinks in the parent commit.

Checks: Ruff lint and format check passed. lint-imports kept both
contracts. The association unit suite passed all five tests. Eight
lightweight TEA job tests passed, with two integration tests deselected.
SQLite smoke checks passed for cohort, registration and deduplication, promotion,
prediction, bronze writes, and both dbt models and their four key tests.
Fixture replay matched the 15 published pairs and 470 published scores.
The full hospital API gate runs on the test machines.
This commit is contained in:
2026-11-29 13:32:39 -06:00
parent f830003abd
commit 9e5aa20092
+85
View File
@@ -249,7 +249,92 @@ def scored_hospital(api, platform):
return platform
def _association_gate(api, platform):
name = "ados2_association"
wait_for(api, ok(api.post("/models/tea/train", json={"models": [name]}))["run_id"], 3600)
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
pending = {"scope": {"mode": "pending"}}
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], 1800)
tables = REFERENCE / "tables"
biomarkers = {
"PICOS_PAROXISTICOS": "spikes",
"HUSOS_SUENO_N2": "spindles",
"RITMO_POSTERIOR": "posterior_rhythm",
"GRADIENTE_ANTEROPOSTERIOR": "gradient",
}
zones = {
"frontal_izq": "frontal_left",
"frontal_der": "frontal_right",
"frontal_media": "frontal_midline",
"temporal_izq": "temporal_left",
"temporal_der": "temporal_right",
}
reference = json.loads((tables / "relacion_ados2.json").read_text())
pair_keys = {}
expected_pairs = {}
for row in reference:
zone = row["rel_zona"]
pair = "|".join(
(biomarkers[row["rel_biomarcador"]], zones.get(zone, zone), row["rel_resultado"])
)
pair_keys[row["rel_id"]] = pair
expected_pairs[pair] = row
q = platform.query
pairs = {key: values for key, *values in q(
"select key, n, n_cohort, method, same_direction, odds_ratio, ci_low, ci_high, p, q "
"from gold.tea_associations"
)} # fmt: skip
assert pairs.keys() == expected_pairs.keys()
for key, row in expected_pairs.items():
n, n_cohort, method, same_direction, *stats = pairs[key]
assert (n, n_cohort, method, same_direction) == (
row["rel_n"],
row["rel_n_cohorte"],
row["rel_modelo"],
row["rel_mismo_sentido"],
), key
for value, field in zip(stats, ("or", "ic_inf", "ic_sup", "p", "q"), strict=True):
expected = row[f"rel_{field}"]
assert value == (None if expected is None else pytest.approx(expected, rel=1e-3)), (
key,
field,
)
# Match reference EEG IDs to silver EEGs by the same signal hash used for analysis.
with sqlite3.connect(HOSPITAL / "hospital_tea.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}
eeg_ids = {
(edf, str(day)[:10]): f"{person}|{str(day)[:10]}"
for edf, person, day in q("select edf, person_id, study_date from silver.eeg")
}
reference_eegs = {
row["eeg_id"]: eeg_ids.get((hashes.get(row["eeg_id"]), row["eeg_fecha_estudio"]))
for row in json.loads((tables / "eeg.json").read_text())
}
reference = json.loads((tables / "relacion_ados2_paciente.json").read_text())
expected_scores = {
(reference_eegs[row["rap_eeg_id"]], pair_keys[row["rap_rel_id"]]): row for row in reference
}
score_rows = q(
"select eeg_id, pair, z, probability, reference_probability "
"from gold.tea_association_scores"
)
scores = {(eeg_id, pair): (z, prob, ref) for eeg_id, pair, z, prob, ref in score_rows}
assert scores.keys() == expected_scores.keys()
for key, row in expected_scores.items():
z, prob, ref = scores[key]
assert z == pytest.approx(row["rap_valor_z"], rel=1e-9), key
assert prob == pytest.approx(row["rap_probabilidad"], abs=1e-4), key
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
_association_gate(api, scored_hospital)
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
# promoted curves found (as the current platform's were captured: curves trained).
indicators(api)