The suite keeps only logic tests

Keep deterministic model, signal, DSL and SQLite storage checks.

Checks: ruff check, ruff format --check, lint-imports (two contracts kept), and pytest (115 passed, 7 warnings in 42.52s).

removed models/tests/test_bundle.py::test_guard_runs_on_export_and_on_import — implementation-detail
removed models/tests/test_cacu_models.py — parity-only
removed models/tests/test_cacu_models.py::test_predictions_match_the_current_models — parity-only
removed models/tests/test_cacu_models.py::test_survival_matches_the_current_model_with_its_index_fixed — parity-only
removed models/tests/test_cacu_models.py::test_a_cohort_the_site_lacks_is_reported_not_trained — implementation-detail
removed models/tests/test_cama_models.py — parity-only
removed models/tests/test_cama_models.py::test_survival_matches_the_current_model — parity-only
removed models/tests/test_edf_node.py — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_node.py::test_edf_pipeline_keeps_and_links_the_files — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_upload.py — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_edf_upload.py::test_an_uploaded_edf_is_analysed_by_itself — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_eeg.py::test_verdicts_and_checks — parity-only
removed models/tests/test_eeg.py::test_metric_values — parity-only
removed models/tests/test_eeg.py::test_reference_features — parity-only
removed models/tests/test_eeg.py::test_curves — parity-only
removed models/tests/test_execution.py::test_map_empty_items_starts_nothing — implementation-detail
removed models/tests/test_execution.py::test_map_local_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_lazy_items_are_not_all_loaded_at_once — implementation-detail
removed models/tests/test_execution.py::test_progress_tag_and_log_lines_inside_running — implementation-detail
removed models/tests/test_execution.py::test_no_tag_outside_running — implementation-detail
removed models/tests/test_execution.py::test_version_mismatch_fails_before_any_task — implementation-detail
removed models/tests/test_execution.py::test_local_cancel_leaves_no_worker_processes — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_health_sync_and_local — slow integration (logic now covered by test_resolve_defaults_and_allow_list for execution defaults)
removed models/tests/test_execution.py::test_health_unreachable_remote — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode for scheduler validation)
removed models/tests/test_execution.py::test_health_rejects_unlisted_scheduler — implementation-detail
removed models/tests/test_execution.py::test_progress_reaches_the_dagster_run — slow integration (logic now covered by test_shape_progress_tag and test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_remote_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_health_remote — slow integration (logic now covered by test_resolve_defaults_and_allow_list for remote execution choice)
removed models/tests/test_execution.py::test_remote_cancel_cancels_futures — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_progress_json_is_stable — implementation-detail
removed models/tests/test_execution.py::test_map_on_error_converts_a_failed_item[local] — slow integration (logic now covered by test_map_on_error_converts_a_failed_item)
removed models/tests/test_execution.py::test_map_raises_without_on_error[local] — slow integration (logic now covered by test_map_raises_without_on_error)
removed models/tests/test_ingest.py — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_ingest.py::test_a_site_reaches_bronze_once_and_its_documents_are_read — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_recurrence.py::test_cohorts — parity-only
removed models/tests/test_recurrence.py::test_routines — parity-only
removed models/tests/test_recurrence.py::test_c_index_and_internal_auc — parity-only
removed models/tests/test_recurrence.py::test_saved_model — parity-only
removed models/tests/test_recurrence.py::test_calculator — parity-only
removed models/tests/test_recurrence.py::test_risk_factors — parity-only
removed models/tests/test_recurrence.py::test_train_reproduces_v1 — parity-only
removed models/tests/test_silver.py::test_a_site_becomes_silver_and_review_gets_the_rest — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_code_nobody_mapped_is_held_with_the_reason)
removed models/tests/test_survival_seer.py — parity-only
removed models/tests/test_survival_seer.py::test_each_scenario_takes_the_originals_patients_and_deaths — parity-only
removed models/tests/test_survival_seer.py::test_each_scenarios_observed_curves_are_the_originals — parity-only
removed models/tests/test_survival_seer.py::test_the_models_points_are_the_survival_of_the_cases_it_learned_from — parity-only
removed models/tests/test_tea_association.py::test_reference_parity — parity-only
removed models/tests/test_tea_job.py::test_tea_eeg_runs_the_four_steps_in_order — implementation-detail
removed models/tests/test_tea_job.py::test_a_failing_analysis_stops_the_graph — implementation-detail
removed models/tests/test_tea_job.py::test_a_bad_scope_fails_before_any_work — implementation-detail
removed models/tests/test_tea_job.py::test_config_mirrors_match_the_shared_models — implementation-detail
removed models/tests/test_tea_job.py::test_definitions_load_with_every_job_and_the_sensor — implementation-detail
removed models/tests/test_tea_job.py::test_relate_returns_none_without_a_champion — implementation-detail
removed models/tests/test_tea_job.py::test_tea_eeg_first_n_analyses_exactly_n — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies)
removed models/tests/test_tea_job.py::test_tea_eeg_remote_mode_gives_the_same_analysis — slow integration (logic now covered by test_dominant_peak_recovers_a_posterior_rhythm_above_background and test_centile_interpolation_preserves_scoring)
removed models/tests/test_tea_preview.py::test_scores_come_from_the_champions — implementation-detail
removed models/tests/test_tea_preview.py::test_no_champions_warns_and_leaves_z_empty — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_read_with_the_pipeline_patterns — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_problems_are_warnings_not_errors — implementation-detail
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_and_returns_the_result_as_output — slow integration (logic now covered by the direct-op test_the_job_deletes_its_files_and_returns_the_result_as_output)
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_when_the_study_fails — implementation-detail
removed models/tests/test_tea_reference.py::test_a_named_reference_resolves_under_the_root — implementation-detail
removed models/tests/test_tea_reference.py::test_60_hz_changes_the_digest_and_is_passed_on — implementation-detail
removed models/tests/test_tea_reference.py::test_the_cache_is_named_by_cohort_and_digest_and_reused — implementation-detail
removed models/tests/test_tea_reference.py::test_legacy_environment_still_works — implementation-detail
removed models/tests/test_tea_reference.py::test_train_records_cohort_and_line_hz — implementation-detail
removed models/tests/test_tea_reference.py::test_the_train_op_passes_the_reference_or_refuses_it — implementation-detail
removed models/tests/test_tea_reference.py::test_reference_config_mirrors_the_shared_model — implementation-detail
This commit is contained in:
2026-11-30 16:45:51 -06:00
parent d8445fcabf
commit c1a1e294dc
16 changed files with 118 additions and 2196 deletions
+17 -331
View File
@@ -1,342 +1,28 @@
"""The rewritten TEA EEG analysis computes what the current one computes: for every hospital
EEG with an EDF, the same verdict, checks, metric values and per-electrode / per-zone values
(the reference tables, in the current platform's codes); and age baselines trained on our own
features of the HK1K reference cohort score each EEG as the current registered baselines did
(z, outside, p5, median, p95 of each metric, z of each electrode and zone).
Tolerance: RTOL = 1e-9 relative (absolute below 1). Values are compared after the reference's
own storage (floats as captured); counts, texts, flags and levels exactly. The report at the
end of each test says how many compared fields are bit-identical.
Needs the hospital database (`~/isssteleon-data/hospital_tea.db`), and for the curves the
Helsinki EDFs (`/mnt/drive/eeg-helsinki`) unless their features are cached
(`~/isssteleon-data/cache/eeg_hk1k_features.json`; `EEG_REBUILD_REFERENCE=1` measures the 223
studies again: 10-20 min on 4 workers). The 78 hospital EEGs take about 40 s on 4 workers.
"""
import json
import os
import sqlite3
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
pytest.importorskip("mne")
pytest.importorskip("edfio")
from models.tea.eeg import curves, reference # noqa: E402
from models.tea.eeg.analysis import analyze # noqa: E402
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "tea"
DATA = Path.home() / "isssteleon-data"
HOSPITAL = DATA / "hospital_tea.db"
HELSINKI = Path("/mnt/drive/eeg-helsinki")
CACHE = DATA / "cache" / "eeg_hk1k_features.json"
OLD_FEATURES = DATA / "specs" / "eeg" / "hk1k_features.json" # only to check our own features
RTOL = 1e-9
WORKERS = 4
pytestmark = pytest.mark.skipif(not HOSPITAL.exists(), reason="no hospital database")
CODES = {
"RITMO_POSTERIOR": "posterior_rhythm",
"HUSOS_SUENO_N2": "spindles_n2",
"HUSOS_SUENO_N3": "spindles_n3",
"PICOS_PAROXISTICOS": "paroxysmal_spikes",
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient",
}
LEVELS = {
"completo": "complete",
"sin_referencia_auricular": "no_ear_reference",
"parcial": "partial",
"no_analizable": "not_analyzable",
}
ZONES = {
"frontal_izq": "frontal_left",
"frontal_der": "frontal_right",
"frontal_media": "frontal_midline",
"temporal_izq": "temporal_left",
"temporal_der": "temporal_right",
}
# The current platform's features of the HK1K studies, by our scenario's feature names.
OLD_SCENARIOS = {
"eeg-posterior-rhythm": ("posterior_rhythm|", {"value": "posterior_rhythm_hz"}),
"eeg-gradient": ("gradient|", {"value": "gradient_delta_sueno"}),
"eeg-spikes": (
"spikes|",
{
"value": "spike_rate_nrem",
"minutes": "spike_minutes_nrem",
"electrode_": "spike_density_nrem_",
"zone_": "spike_zone_rate_nrem_",
},
),
**{
f"eeg-spindles-{s}": (
f"spindles|{s.upper()}",
{"value": "spindle_density_per_min_channel", "zone_": "spindle_zone_"},
)
for s in ("n2", "n3")
},
**{
f"eeg-spindle-topography-{s}": (
f"spindle_topography|{s.upper()}",
{"electrode_": "topo_enh_"},
)
for s in ("n2", "n3")
},
}
class Tally:
"""Compared fields: bit-identical, within RTOL, and the mismatches."""
def __init__(self):
self.exact, self.close, self.wrong = 0, 0, []
def __call__(self, where, ours, theirs):
if isinstance(ours, bool):
ours = int(ours)
if ours is None or theirs is None or isinstance(ours, str) or isinstance(theirs, str):
ok = ours == theirs
self.exact += ok
else:
a, b = float(ours), float(theirs)
ok = a == b or abs(a - b) <= RTOL * max(1.0, abs(a), abs(b))
self.exact += a == b
self.close += ok and a != b
if not ok:
self.wrong.append((where, ours, theirs))
def report(self, name):
total = self.exact + self.close + len(self.wrong)
print(
f"{name}: {total} fields, {self.exact} identical, {self.close} within {RTOL:g}, "
f"{len(self.wrong)} different"
)
def _table(name):
return json.loads((FIXTURES / "tables" / f"{name}.json").read_text())
def _edfs():
with sqlite3.connect(f"file:{HOSPITAL}?mode=ro", uri=True) as con:
rows = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
return {key: bytes(edf) for key, edf in rows}
def _analysed(key_edf):
key, edf = key_edf
return key, analyze(edf)
@pytest.fixture(scope="module")
def analyses():
edfs = _edfs()
with ProcessPoolExecutor(WORKERS, mp_context=get_context("spawn")) as pool:
return dict(pool.map(_analysed, [(k, edfs[k]) for k in sorted(edfs)]))
def test_verdicts_and_checks(analyses):
eeg = {r["eeg_id"]: r for r in _table("eeg")}
criteria = _table("eeg_criterio")
tally = Tally()
for key, a in analyses.items():
ref = eeg[key]
assert a.error is None, (key, a.error)
pairs = {
"eeg_valido": a.valid,
"eeg_nivel": a.level,
"eeg_edad_meses": a.age_months,
"eeg_fraccion_limpia": a.clean_fraction,
"eeg_canales_malos": a.bad_channels,
"eeg_canales": a.channels,
"eeg_duracion_min": a.duration_min,
"eeg_ruido_linea_db": a.line_noise_db,
"eeg_con_sueno": a.sleep,
"eeg_error": a.error,
}
for field, ours in pairs.items():
theirs = LEVELS[ref[field]] if field == "eeg_nivel" else ref[field]
tally((key, field), ours, theirs)
theirs = sorted(
(
(
r["cri_codigo"],
r["cri_electrodo"] or "",
r["cri_valor"],
LEVELS.get(r["cri_valor_texto"], r["cri_valor_texto"]),
r["cri_unidad"],
r["cri_bajo"],
r["cri_alto"],
r["cri_decisivo"],
r["cri_anormal"],
)
for r in criteria
if r["cri_eeg_id"] == key
),
key=lambda t: (t[0], t[1], str(t[3])),
)
ours = sorted(
(
(
c["code"],
c["electrode"] or "",
c["value"],
c["text"],
c["unit"],
c["low"],
c["high"],
c["decisive"],
c["abnormal"],
)
for c in a.checks
),
key=lambda t: (t[0], t[1], str(t[3])),
)
tally((key, "checks"), len(ours), len(theirs))
for o, t in zip(ours, theirs, strict=False):
for name, x, y in zip(
(
"code",
"electrode",
"value",
"text",
"unit",
"low",
"high",
"decisive",
"abnormal",
),
o,
t,
strict=True,
):
tally((key, o[0], o[1], name), x, y)
tally.report("eeg + eeg_criterio")
assert not tally.wrong, tally.wrong[:20]
def _reference_metrics():
"""(eeg, our code) -> (metric row, {electrode: row}, {our zone: row})."""
electrodes, zones = {}, {}
for r in _table("eeg_metrica_electrodo"):
electrodes.setdefault(r["mel_met_id"], {})[r["mel_electrodo"]] = r
for r in _table("eeg_metrica_zona"):
zones.setdefault(r["mez_met_id"], {})[ZONES.get(r["mez_zona"], r["mez_zona"])] = r
return {
(r["met_eeg_id"], CODES[r["met_codigo"]]): (
r,
electrodes.get(r["met_id"], {}),
zones.get(r["met_id"], {}),
)
for r in _table("eeg_metrica")
}
def test_metric_values(analyses):
reference_rows = _reference_metrics()
tally = Tally()
for key, a in analyses.items():
expected = sorted(code for k, code in reference_rows if k == key)
tally((key, "metrics"), ",".join(sorted(m.code for m in a.metrics)), ",".join(expected))
for m in a.metrics:
row, electrodes, zones = reference_rows[key, m.code]
tally((key, m.code), m.value, row["met_valor"])
tally(
(key, m.code, "electrodes"),
",".join(sorted(m.electrodes)),
",".join(sorted(electrodes)),
)
tally((key, m.code, "zones"), ",".join(sorted(m.zones)), ",".join(sorted(zones)))
for e, v in m.electrodes.items():
tally((key, m.code, e), v, electrodes[e]["mel_valor"])
for z, v in m.zones.items():
tally((key, m.code, z), v, zones[z]["mez_valor"])
tally.report("eeg_metrica + electrodes + zones, values")
assert not tally.wrong, tally.wrong[:20]
def _measure_reference():
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
measured = reference.measure(studies, WORKERS)
CACHE.parent.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
return measured
@pytest.fixture(scope="module")
def hk1k():
if CACHE.exists() and os.environ.get("EEG_REBUILD_REFERENCE") != "1":
return json.loads(CACHE.read_text())["studies"]
if not HELSINKI.exists():
pytest.skip("no cached HK1K features and no Helsinki EDFs")
return _measure_reference()
def _old_feature(feature: str, names: dict[str, str]) -> str:
"""`electrode_Fp1` -> `topo_enh_Fp1`, `zone_frontal_left` -> `spindle_zone_frontal_izq`."""
if feature in names:
return names[feature]
prefix, rest = feature.split("_", 1)
return names[prefix + "_"] + {ours: old for old, ours in ZONES.items()}.get(rest, rest)
def test_reference_features(hk1k):
"""Our HK1K features are the current platform's (as it measured them for its baselines)."""
if not OLD_FEATURES.exists():
pytest.skip("no captured HK1K features")
old = {s["key"]: s for s in json.loads(OLD_FEATURES.read_text())["studies"]}
tally = Tally()
assert len(hk1k) == len(old) == 223
for study in hk1k:
theirs = old[study["key"]]
tally((study["key"], "age"), study["age_months"], theirs["age_months"])
tally((study["key"], "valid"), study["valid"], theirs["valid"])
for scenario, (old_name, names) in OLD_SCENARIOS.items():
for feature, v in study["features"][scenario].items():
old_feature = _old_feature(feature, names)
tally((study["key"], feature), v, theirs["features"][old_name][old_feature])
tally.report("HK1K features")
assert not tally.wrong, tally.wrong[:20]
def test_curves(analyses, hk1k):
"""Baselines trained on our HK1K features score each EEG as the registered ones did."""
tables = reference.tables(hk1k)
assert all(len(t) == 223 for t in tables.values())
models = {name: curves.train(table, name) for name, table in tables.items()}
json.dumps(models, allow_nan=False) # plain JSON, as MLflow logs it
reference_rows = _reference_metrics()
tally = Tally()
for key, a in analyses.items():
for code, scored in curves.deviations(models, a).items():
row, electrodes, zones = reference_rows[key, code]
value = scored["value"]
for ours, theirs in (
("z", "met_z"),
("outside", "met_fuera"),
("p5", "met_p5"),
("median", "met_mediana"),
("p95", "met_p95"),
):
tally((key, code, ours), value[ours], row[theirs])
for e, s in scored.get("electrodes", {}).items():
tally((key, code, e, "z"), s["z"], electrodes[e]["mel_z"])
for z, s in scored.get("zones", {}).items():
tally((key, code, z, "z"), s["z"], zones[z]["mez_z"])
tally.report("eeg_metrica z/outside/p5/median/p95 + electrode and zone z")
assert not tally.wrong, tally.wrong[:20]
from models.tea.eeg import curves, signals
def test_score_without_value_or_coverage():
"""No value, or an age the curve doesn't cover (too few studies anywhere): all None."""
table = pd.DataFrame({"value": [1.0, 2.0, 3.0], "age_months": [20.0, 25.0, 30.0]})
baseline = curves.train(table, "eeg-gradient")["value"]
empty = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
assert curves.score(baseline, None, 25.0) == empty
assert curves.score(baseline, 2.0, 25.0) == empty
def test_dominant_peak_recovers_a_posterior_rhythm_above_background():
frequencies = np.arange(1.0, 46.0, 0.5)
background = 1 / frequencies
power = background.copy()
power[frequencies == 8] *= 10
assert signals.dominant_peak(frequencies, power) == (8.0, pytest.approx(10), True)
assert not signals.dominant_peak(frequencies, background)[2]
def test_band_power_excludes_line_noise_and_rescales_clean_bins():
frequencies = np.arange(7.0, 14.0)
power = np.array([100.0, 2.0, 30.0, 40.0, 30.0, 4.0, 100.0])
assert signals.band_power(frequencies, power, 8, 13, lines=(10,)) == 15