From c1a1e294dc1d3a40f3768d2d2a8dd8e140d85489 Mon Sep 17 00:00:00 2001 From: alberto Date: Mon, 30 Nov 2026 16:45:51 -0600 Subject: [PATCH] The suite keeps only logic tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- tests/edf_files.py | 46 ----- tests/test_bundle.py | 39 ++-- tests/test_cacu_models.py | 125 ------------ tests/test_cama_models.py | 49 ----- tests/test_edf_node.py | 54 ------ tests/test_edf_upload.py | 60 ------ tests/test_eeg.py | 348 ++-------------------------------- tests/test_execution.py | 303 +---------------------------- tests/test_ingest.py | 89 --------- tests/test_recurrence.py | 270 ++------------------------ tests/test_silver.py | 183 ++---------------- tests/test_survival_seer.py | 182 ------------------ tests/test_tea_association.py | 72 ------- tests/test_tea_job.py | 200 +++---------------- tests/test_tea_preview.py | 192 ++----------------- tests/test_tea_reference.py | 102 ---------- 16 files changed, 118 insertions(+), 2196 deletions(-) delete mode 100644 tests/test_cacu_models.py delete mode 100644 tests/test_cama_models.py delete mode 100644 tests/test_edf_node.py delete mode 100644 tests/test_edf_upload.py delete mode 100644 tests/test_ingest.py delete mode 100644 tests/test_survival_seer.py diff --git a/tests/edf_files.py b/tests/edf_files.py index d93787a..3c2fad8 100644 --- a/tests/edf_files.py +++ b/tests/edf_files.py @@ -1,25 +1,9 @@ -import sqlite3 from datetime import date from pathlib import Path import edfio import numpy as np -SEX_MAP = { - "resourceType": "ConceptMap", - "status": "active", - "group": [ - { - "source": "urn:edf", - "target": "http://hl7.org/fhir/administrative-gender", - "element": [ - {"code": "F", "target": [{"code": "female", "equivalence": "equivalent"}]}, - {"code": "M", "target": [{"code": "male", "equivalence": "equivalent"}]}, - ], - } - ], -} - def small_edf( path: Path, @@ -46,33 +30,3 @@ def small_edf( ) edf.write(path) return path.read_bytes() - - -def hospital(path: Path) -> str: - with sqlite3.connect(path) as con: - con.execute("create table pacientes (record_number text primary key, birth_date text)") - con.executemany("insert into pacientes values (?, ?)", - [("N1001", "2025-01-05"), ("N1002", "2025-02-05")]) # fmt: skip - return f"sqlite:///{path}" - - -def pipeline(hospital_url: str, bucket_url: str) -> dict: - return {"nodes": [ - {"id": "patients", "kind": "source", "source": "dlt.sources.sql_database:sql_table", - "args": {"credentials": hospital_url, "table": "pacientes"}}, - {"id": "patients_identity", "kind": "map", "inputs": ["patients"], - "fields": {"record_number": "record_number", "birth_date": "birth_date"}, - "formats": {"birth_date": "%Y-%m-%d"}}, - {"id": "uploads", "kind": "source", "source": "dlt.sources.filesystem:filesystem", - "args": {"bucket_url": bucket_url, "file_glob": "*.edf"}, - "then": "persistance.readers:read_bytes"}, - {"id": "header", "kind": "edf", "inputs": ["uploads"], "column": "content"}, - {"id": "uploads_identity", "kind": "map", "inputs": ["header"], "concept_map": "edf_sex", - "fields": {"record_number": "edf_patient_code", "birth_date": "edf_birth_date", - "sex": "edf_sex"}, "formats": {"birth_date": "%Y-%m-%d"}}, - {"id": "eegs", "kind": "map", "inputs": ["header"], - "fields": {"study_date": "edf_study_date", "lab_record_id": "edf_record_code", - "edf": "content"}, "formats": {"study_date": "%Y-%m-%d"}}, - {"id": "people", "kind": "link", "inputs": ["patients_identity", "uploads_identity"]}, - {"id": "target", "kind": "target", "inputs": ["eegs", "people"], "entity": "eeg"}, - ]} # fmt: skip diff --git a/tests/test_bundle.py b/tests/test_bundle.py index 00dbe27..5a7595b 100644 --- a/tests/test_bundle.py +++ b/tests/test_bundle.py @@ -7,7 +7,7 @@ import mlflow import pandas as pd import pytest -from core.domains import Domain, part +from core.domains import Domain from persistance import bundle, config, registry DOMAIN = Domain.TEA @@ -53,7 +53,7 @@ def _register(value=1, clinical=True): def _trust(data): sha = hashlib.sha256(data).hexdigest() with bundle.trusted_file().open("a") as file: - file.write(f"\n# approved\n {sha.upper()} \n") + file.write(f"\n {sha.upper()} \n") return sha @@ -193,23 +193,28 @@ def test_tampered_bundles_are_refused(stores): bundle.import_(DOMAIN, data) -def test_guard_runs_on_export_and_on_import(stores, monkeypatch): - _register() - hook = part(DOMAIN, "bundle") - monkeypatch.setattr(hook, "guard", lambda version: []) - exported = bundle.export(DOMAIN, versions="latest") - _trust(exported.data) - monkeypatch.setattr(hook, "guard", lambda version: ["problem"]) - for operation in ( - lambda: bundle.export(DOMAIN, versions="latest"), - lambda: bundle.import_(DOMAIN, exported.data), - ): - with pytest.raises(bundle.BundleError, match=r"tea\.curve_x v1: problem"): - operation() - - def test_import_refuses_an_untrusted_digest(stores): _register() exported = bundle.export(DOMAIN, versions="latest") with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"): bundle.import_(DOMAIN, exported.data) + + +def test_version_lifecycle(stores): + first = _register(clinical=False) + second = _register(clinical=True) + assert registry.status(NAME, first) == "candidate" + with pytest.raises(registry.MissingReports, match="clinical_validation"): + registry.promote(NAME, first) + registry.add_report(NAME, first, "clinical_validation", "review.txt", b"approved") + registry.promote(NAME, first) + assert registry.status(NAME, first) == "champion" + with pytest.raises(ValueError, match="the champion cannot be retired"): + registry.retire(NAME, first) + registry.promote(NAME, second) + assert registry.status(NAME, first) == "candidate" + registry.retire(NAME, first) + assert registry.status(NAME, first) == "retired" + with pytest.raises(ValueError, match="is retired"): + registry.promote(NAME, first) + assert registry.champion_version(NAME) == second diff --git a/tests/test_cacu_models.py b/tests/test_cacu_models.py deleted file mode 100644 index 1785c87..0000000 --- a/tests/test_cacu_models.py +++ /dev/null @@ -1,125 +0,0 @@ -"""The CaCu models compute what the current ones compute: fed the timelines the current -platform built for its cohorts (the reference fixtures, in its codes), each rewritten model -gives the current model's predictions. - -Fixed on purpose, so left out of the comparison: -- cin2_logistic's index date: the current estimator reads P(no outcome) as a date - (1970-01-01 for everyone); the rewrite returns the index sample's date. -""" - -import json -from pathlib import Path - -import numpy as np -import pandas as pd -import pytest - -from models.cacu.specs import MODELS - -REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu" -RTOL = 1e-6 # as captured (models.json) -# The current platform's cohort cutoff, where the logistic model's follow-up ends. -REFERENCE_CUTOFF = "2026-11-23" - -TYPES = { - "citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv", - "vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy", - "orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history", - "diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth", - "defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order", -} # fmt: skip -CODES = { - "bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"}, - "biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"}, - "hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"}, - "cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"}, -} -COHORTS = { - "cacu_cohort_surveillance": "cohorte_vigilancia", - "cacu_cohort_post_treatment": "cohorte_post_tratamiento", -} - - -def timelines(cohort: str) -> pd.DataFrame: - """A reference cohort's timelines in the platform's names and codes.""" - found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet") - found = found.rename(columns={ - "pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type", - "valor_codigo": "value_code", "valor_numerico": "value_num", - "fuente_tabla": "source_table", "fuente_id": "source_id", - }) # fmt: skip - found["type"] = found["type"].map(TYPES) - for kind, codes in CODES.items(): - rows = found["type"] == kind - found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes) - return found - - -@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment", - "cin2_logistic"]) # fmt: skip -def test_predictions_match_the_current_models(name): - spec = MODELS[name] - events = timelines(COHORTS[spec.cohort]) - args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else () - model, metrics, _ = spec.train(events, *args) - reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet") - current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"] - assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"] - - found = spec.predict(model, events) - both = found.merge( - reference, - left_on=["person_id", "horizon_years"], - right_on=["pac_id", "horizonte_anios"], - how="outer", - indicator=True, - ) - assert (both["_merge"] == "both").all(), "the same patients and horizons are scored" - for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"), - ("ci_high", "ic_alto")]: # fmt: skip - if theirs in both: - np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0) - if spec.method != "logistic regression": - assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() - - -def test_survival_matches_the_current_model_with_its_index_fixed(): - """Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current - index read only invasive carcinoma, so it indexed nobody; the reference was captured with - that fixed); out: no birth date, a death by the biopsy.""" - spec = MODELS["survival"] - events = timelines("cohorte_total").drop(columns="index_date") - events["date"] = pd.to_datetime(events["date"]) - events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4) - cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])] - index = cases.groupby("person_id")["date"].min().rename("index_date") - index = index[(index >= "2018-01-01") & (index < "2027-01-01")] - born = set(events.loc[events["type"] == "birth", "person_id"]) - died = events[events["type"] == "death"].groupby("person_id")["date"].min() - index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)] - events = events.merge(index, left_on="person_id", right_index=True) - - model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date()) - current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"] - for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m", - "stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip - assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name - found = spec.predict(model, events) - reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet") - both = found.merge(reference, left_on=["person_id", "horizon_years"], - right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip - assert len(both) == len(reference) == len(found) - for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"), - ("ci_high", "ic_alto")]: # fmt: skip - np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True) - - -def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch): - """A site with no colposcopies has nobody in the post-colposcopy cohort: training that - model says so (and the train job goes on with the others) instead of failing inside it.""" - from models import jobs - from models.cacu.jobs import JOBS - - monkeypatch.setattr(jobs.gold, "timelines", lambda *a: pd.DataFrame()) - with pytest.raises(jobs.EmptyCohort, match="cacu_cohort_post_colposcopy"): - JOBS.train("cin2_pim_post_colposcopy") diff --git a/tests/test_cama_models.py b/tests/test_cama_models.py deleted file mode 100644 index f8588ae..0000000 --- a/tests/test_cama_models.py +++ /dev/null @@ -1,49 +0,0 @@ -"""CaMa's models give the current platform's predictions on its own cohort (the reference -fixtures), read in the platform's timeline shape.""" - -import json -from pathlib import Path - -import numpy as np -import pandas as pd - -from models.cama.specs import MODELS - -REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" -TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there -TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"} -CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"} - - -def _timelines() -> pd.DataFrame: - """The reference cohort's members (first invasive biopsy report in the window) with their - events, as gold.cama_events gives them.""" - old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet") - old = old[old["tipo"].isin(TYPES)] - events = pd.DataFrame({ - "person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]), - "type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES), - "value_num": old["valor_numerico"], "source_table": old["fuente_tabla"], - "source_id": old["fuente_id"], - "record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4), - }) # fmt: skip - invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")] - index = invasive.groupby("person_id")["date"].min().rename("index_date") - index = index[(index >= "2018-01-01") & (index < "2027-01-01")] - return events.merge(index, left_on="person_id", right_index=True) - - -def test_survival_matches_the_current_model(): - spec = MODELS["survival"] - events = _timelines() - model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date()) - current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"] - for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"): - assert metrics[name] == current["metrics"][name], name - ours = spec.predict(model, events) - ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet") - ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"]) - both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1") - assert len(both) == len(ref) == len(ours) - assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() - np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6) diff --git a/tests/test_edf_node.py b/tests/test_edf_node.py deleted file mode 100644 index 1b30651..0000000 --- a/tests/test_edf_node.py +++ /dev/null @@ -1,54 +0,0 @@ -import json -from datetime import date -from hashlib import sha256 - -from edf_files import SEX_MAP, hospital, pipeline, small_edf - - -def test_edf_pipeline_keeps_and_links_the_files(platform, tmp_path): - hospital_url = hospital(tmp_path / "hospital.db") - uploads = tmp_path / "uploads" - uploads.mkdir() - a = small_edf(uploads / "a.edf") - b = small_edf(uploads / "b.edf", patient_code="N1002", birthdate=date(2025, 2, 5)) - bad = b"junk" - (uploads / "bad.edf").write_bytes(bad) - clean = {sha256(a).hexdigest(): a, sha256(b).hexdigest(): b} - bad_hash = sha256(bad).hexdigest() - - drawing = tmp_path / "edf.json" - drawing.write_text(json.dumps(pipeline(hospital_url, str(uploads)))) - concepts = tmp_path / "sex.json" - concepts.write_text(json.dumps(SEX_MAP)) - platform.save("concept_maps", "edf_sex", concepts) - platform.save("pipelines", "edf", drawing) - - for _ in range(2): - platform.ingest("edf") - people = dict( - platform.query( - "select i.value, p.person_id from silver.person p " - "join silver.person_identifier i on i.person_id = p.person_id" - ) - ) - assert set(people) == {"N1001", "N1002"} - studies = platform.query("select person_id, study_date, lab_record_id, edf from silver.eeg") - assert {(p, str(d), lab, key) for p, d, lab, key in studies} == { - (people["N1001"], "2026-03-02", "LAB-1", sha256(a).hexdigest()), - (people["N1002"], "2026-03-02", "LAB-1", sha256(b).hexdigest()), - } - assert len(studies) == 2 - assert { - key: bytes(value) - for key, value in platform.query("select key, content from bronze.files") - } == {**clean, bad_hash: bad} - assert platform.count("bronze.n__edf__header") == 3 - ((error, *fields),) = platform.query( - "select edf_error, edf_patient_code, edf_sex, edf_birth_date, edf_study_date, " - "edf_record_code, edf_duration_s, edf_channels from bronze.n__edf__header " - f"where content = '{bad_hash}'" - ) - assert error and fields == [None] * 7 - ((study, reasons),) = platform.query("select study, _held from bronze.staged__held") - assert study == "eeg" - assert any(reason.startswith("study_date:") for reason in json.loads(reasons)) diff --git a/tests/test_edf_upload.py b/tests/test_edf_upload.py deleted file mode 100644 index 1bae187..0000000 --- a/tests/test_edf_upload.py +++ /dev/null @@ -1,60 +0,0 @@ -import time - -import pytest -from edf_files import SEX_MAP, hospital, pipeline, small_edf - - -def _ok(response): - assert response.status_code == 200, response.text - return response.json() - - -def wait_for(api, run_id: str, seconds: int = 900) -> None: - deadline = time.monotonic() + seconds - while (state := _ok(api.get(f"/runs/{run_id}"))["state"]) in ("queued", "running"): - assert time.monotonic() < deadline, f"run {run_id} still {state}" - time.sleep(2) - assert state == "succeeded" - - -@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) -def test_an_uploaded_edf_is_analysed_by_itself(api, tmp_path): - hospital_url = hospital(tmp_path / "hospital.db") - data = small_edf(tmp_path / "a.edf") - - def upload(): - result = _ok(api.post("/ingest/uploads", files={"file": ("a.edf", data)})) - assert set(result) == {"bucket_url", "file_name"} - assert result["file_name"] == "a.edf" - return result["bucket_url"] - - def run(): - wait_for(api, _ok(api.post("/ingest/pipelines/edf/runs", json={}))["run_id"]) - - def runs(): - return _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"})) - - bucket_url = upload() - _ok(api.put("/ingest/concept-maps/edf_sex", json=SEX_MAP)) - _ok(api.put("/ingest/pipelines/edf", json=pipeline(hospital_url, bucket_url))) - run() - - deadline = time.monotonic() + 600 - found = runs() - while not any(item["state"] == "succeeded" for item in found): - assert time.monotonic() < deadline, found - time.sleep(2) - found = runs() - (first,) = found - (study,) = _ok(api.get("/tea/eegs")) - assert study["study_date"] == "2026-03-02" - assert study["lab_record_id"] == "LAB-1" - assert study["analysed"] is True - - assert upload() == bucket_url - run() - deadline = time.monotonic() + 60 - while time.monotonic() < deadline: - assert [item["id"] for item in runs()] == [first["id"]] - time.sleep(2) - assert [item["id"] for item in runs()] == [first["id"]] diff --git a/tests/test_eeg.py b/tests/test_eeg.py index c94fc0a..8c038b8 100644 --- a/tests/test_eeg.py +++ b/tests/test_eeg.py @@ -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 diff --git a/tests/test_execution.py b/tests/test_execution.py index 951e1f1..f645302 100644 --- a/tests/test_execution.py +++ b/tests/test_execution.py @@ -1,54 +1,14 @@ -import json -import os -import signal -import subprocess -import sys -import textwrap -import threading -import time -from types import SimpleNamespace - -import cloudpickle -import dagster as dg -import numpy as np -import psutil import pytest from models import execution -from models.execution import Execution, ExecutionError, Progress +from models.execution import Execution, ExecutionError from persistance import cluster -cloudpickle.register_pickle_by_value(sys.modules[__name__]) - -def by_value(fn): - fn.__module__ = "__main__" - return fn - - -@by_value def square(x): return int(x) ** 2 -@by_value -def numeric(x): - rng = np.random.default_rng(x) - return float(np.linalg.norm(rng.normal(size=(20, 20)) @ rng.normal(size=(20, 20)))) - - -@by_value -def slow(x): - time.sleep(0.2) - return x - - -@by_value -def sleep_forever(x): - time.sleep(60) - - -@by_value def fail_on_three(x): if x == 3: raise RuntimeError("three") @@ -59,15 +19,6 @@ def fail_on_three(x): def env(monkeypatch): for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"): monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("DASK_LOCAL_WORKERS", "2") - - -def fake_context(): - context = SimpleNamespace(run_id="r1", logs=[], tags=[], metadata=[]) - context.log = SimpleNamespace(info=context.logs.append) - context.instance = SimpleNamespace(add_run_tags=lambda run, tags: context.tags.append(tags)) - context.add_output_metadata = context.metadata.append - return context def test_resolve_defaults_and_allow_list(monkeypatch): @@ -101,67 +52,14 @@ def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch): assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5" -def test_map_empty_items_starts_nothing(monkeypatch): - import distributed - - def boom(*a, **k): - raise AssertionError("a cluster was started") - - monkeypatch.setattr(distributed, "LocalCluster", boom) - assert execution.map(square, []) == [] - assert execution.map(square, iter([]), total=0) == [] - - -def test_map_local_equals_sync(monkeypatch): - items = list(range(12)) +def test_map_on_error_converts_a_failed_item(monkeypatch): monkeypatch.setenv("EXECUTION_MODE", "sync") - expected = execution.map(numeric, items, log=lambda s: None) - monkeypatch.setenv("EXECUTION_MODE", "local") - assert execution.map(numeric, items, log=lambda s: None) == expected - - -def test_map_lazy_items_are_not_all_loaded_at_once(): - state = {"loaded": 0, "finished": 0, "peak": 0} - lock = threading.Lock() - - def generate(): - for i in range(30): - with lock: - state["loaded"] += 1 - state["peak"] = max(state["peak"], state["loaded"] - state["finished"]) - yield i - - class Counting: - def __init__(self): - self.n = 0 - - out = [] - real = execution._Monitor.item_done - - def item_done(self): - with lock: - state["finished"] += 1 - real(self) - - execution._Monitor.item_done = item_done - try: - out = execution.map(slow, generate(), total=30, log=lambda s: None) - finally: - execution._Monitor.item_done = real - assert out == list(range(30)) - assert state["peak"] <= max(4, 2 * 2) - - -@pytest.mark.parametrize("mode", ["sync", "local"]) -def test_map_on_error_converts_a_failed_item(monkeypatch, mode): - monkeypatch.setenv("EXECUTION_MODE", mode) out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None) assert out == [0, 1, 2, -3, 4, 5] -@pytest.mark.parametrize("mode", ["sync", "local"]) -def test_map_raises_without_on_error(monkeypatch, mode): - monkeypatch.setenv("EXECUTION_MODE", mode) +def test_map_raises_without_on_error(monkeypatch): + monkeypatch.setenv("EXECUTION_MODE", "sync") with pytest.raises(RuntimeError, match="three"): execution.map(fail_on_three, range(6), log=lambda s: None) @@ -176,196 +74,3 @@ def test_eta_smoothing_and_threshold(): eta.update(3.0, 8) assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0) assert eta.eta_s(10) == pytest.approx(2 / eta.rate) - - -def test_progress_tag_and_log_lines_inside_running(monkeypatch): - monkeypatch.setenv("EXECUTION_MODE", "sync") - context = fake_context() - with execution.running(context): - execution.map(square, range(6), phase="analyzing") - first, last = (Progress.model_validate_json(t[execution.PROGRESS_TAG]) for t in - (context.tags[0], context.tags[-1])) # fmt: skip - assert first.done == 0 and last.done == last.total == 6 and last.phase == "analyzing" - assert context.logs[0] == "analyzing: 0/6" and context.logs[-1] == "analyzing: 6/6" - summary = context.metadata[-1] - assert set(summary) == {"mode", "scheduler", "phases", "peak_cpu_pct", "peak_memory_bytes"} - - -def test_no_tag_outside_running(monkeypatch): - monkeypatch.setenv("EXECUTION_MODE", "sync") - context = fake_context() - execution.map(square, range(3), log=context.logs.append) - assert context.tags == [] and context.logs - - -def test_version_mismatch_fails_before_any_task(monkeypatch): - import distributed - - monkeypatch.setenv("DASK_SCHEDULERS", "x:8786") - submitted = [] - - class SpyClient: - def __init__(self, *a, **k): - self.closed = False - - def submit(self, *a, **k): - submitted.append(a) - - def close(self): - self.closed = True - - monkeypatch.setattr(distributed, "Client", SpyClient) - monkeypatch.setattr(cluster, "versions_error", lambda client: "numpy 1.0 vs 2.0") - with pytest.raises(execution.ClusterVersionError, match="numpy 1.0 vs 2.0"): - execution.map(square, range(3), execution=Execution(mode="remote")) - assert submitted == [] - - -CANCEL_SCRIPT = textwrap.dedent( - """ - import signal, sys - from models import execution - from models.execution import Execution - - def stop(*a): - raise KeyboardInterrupt - - def sleep_forever(x): - import time - time.sleep(60) - - signal.signal(signal.SIGTERM, stop) - import cloudpickle - cloudpickle.register_pickle_by_value(sys.modules["__main__"]) - execution.map(sleep_forever, range({n}), log=lambda s: print(s, flush=True), - execution=Execution(mode="{mode}")) - """ -) - - -def run_cancelled(mode, n): - proc = subprocess.Popen( - [sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)], - stdout=subprocess.PIPE, - text=True, - env={**os.environ, "DASK_LOCAL_WORKERS": "2"}, - ) - assert proc.stdout.readline().startswith("working: 0/") - time.sleep(3) - return proc - - -def test_local_cancel_leaves_no_worker_processes(): - proc = run_cancelled("local", 4) - children = psutil.Process(proc.pid).children(recursive=True) - assert children - proc.send_signal(signal.SIGTERM) - proc.wait(timeout=30) - deadline = time.time() + 20 - while time.time() < deadline and any(c.is_running() and c.status() != "zombie" - for c in children): # fmt: skip - time.sleep(0.5) - assert not [c for c in children if c.is_running() and c.status() != "zombie"] - - -def test_health_sync_and_local(monkeypatch): - sync = execution.health(Execution(mode="sync")) - assert sync.reachable and sync.workers == 1 and sync.threads == 1 - local = execution.health(Execution(mode="local")) - assert local.reachable and local.workers == 2 and local.versions_ok is None - - -def test_health_unreachable_remote(monkeypatch): - monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1") - started = time.time() - h = execution.health(Execution(mode="remote")) - assert not h.reachable and h.error and time.time() - started < 15 - - -def test_health_rejects_unlisted_scheduler(monkeypatch): - monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1") - with pytest.raises(ExecutionError): - execution.health(Execution(mode="remote", scheduler="tcp://127.0.0.1:2")) - with pytest.raises(ExecutionError): - execution.health(Execution(mode="sync"), reference="../x") - - -def test_progress_reaches_the_dagster_run(): - @dg.op - def analyze(context) -> dg.Nothing: - with execution.running(context, Execution(mode="sync")): - execution.map(square, range(6), phase="analyzing") - - @dg.op(ins={"start": dg.In(dg.Nothing)}) - def after(context): - pass - - @dg.job - def two(): - after(analyze()) - - instance = dg.DagsterInstance.ephemeral() - result = two.execute_in_process(instance=instance) - assert result.success - tags = instance.get_run_by_id(result.run_id).tags - progress = Progress.model_validate_json(tags[execution.PROGRESS_TAG]) - assert (progress.done, progress.total, progress.phase) == (6, 6, "analyzing") - event = next(e for e in result.events_for_node("analyze") if e.is_successful_output) - assert "mode" in event.event_specific_data.metadata - - -@pytest.fixture(scope="module") -def scheduler(): - address = os.environ.get("DASK_TEST_SCHEDULER") - if not address: - pytest.skip("DASK_TEST_SCHEDULER is not set") - expected = int(os.environ["DASK_EXPECTED_WORKERS"]) - os.environ["DASK_SCHEDULERS"] = address - deadline = time.time() + 60 - while time.time() < deadline: - if execution.health(Execution(mode="remote", scheduler=address)).workers == expected: - return cluster.normalize(address) - time.sleep(1) - pytest.fail(f"the scheduler never showed {expected} workers") - - -def test_map_remote_equals_sync(scheduler, monkeypatch): - monkeypatch.setenv("DASK_SCHEDULERS", scheduler) - items = list(range(12)) - expected = execution.map(numeric, items, execution=Execution(mode="sync"), log=print) - remote = execution.map(numeric, items, execution=Execution(mode="remote"), log=print) - assert remote == expected - - -def test_health_remote(scheduler, monkeypatch): - monkeypatch.setenv("DASK_SCHEDULERS", scheduler) - h = execution.health(Execution(mode="remote")) - assert h.reachable and h.workers == h.expected_workers == 2 - assert h.versions_ok and h.latency_ms > 0 and h.dashboard_ok - - -def test_remote_cancel_cancels_futures(scheduler, monkeypatch): - from distributed import Client - - monkeypatch.setenv("DASK_SCHEDULERS", scheduler) - proc = run_cancelled("remote", 8) - proc.send_signal(signal.SIGTERM) - proc.wait(timeout=30) - with Client(scheduler, timeout=10) as client: - deadline = time.time() + 20 - processing = None - while time.time() < deadline: - processing = client.run_on_scheduler(execution._counts).get("processing", 0) - if processing == 0: - break - time.sleep(0.5) - assert processing == 0 - assert client.scheduler_info()["workers"] - - -def test_progress_json_is_stable(monkeypatch): - monkeypatch.setenv("EXECUTION_MODE", "sync") - context = fake_context() - with execution.running(context): - execution.map(square, range(2)) - assert json.loads(context.tags[-1][execution.PROGRESS_TAG])["mode"] == "sync" diff --git a/tests/test_ingest.py b/tests/test_ingest.py deleted file mode 100644 index 19e8bd2..0000000 --- a/tests/test_ingest.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document -the rules point at is read into text (scanned ones through OCR). The site: the synthetic -hospitals' tables (SQLite) and ISSSTELEON's test source (SQL Server tables of PDFs).""" - -import json -import re -import shutil -import sqlite3 -from pathlib import Path - -FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" - - -def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> dict: - """What an operator would draw for this site: one Source per table, and a Read on each - column that holds documents.""" - - def table(node_id, credentials, name, **args): - args = {"credentials": credentials, "table": name, **args} - return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args} - - nodes = [ - table(f"{name}_{t}", f"sqlite:///{tmp / f'hospital_{name}.db'}", t) - for name, tables in hospital_tables.items() - for t in tables - ] - return { - "nodes": nodes - + [ - table("resultados", site_url, "ResultadoSubrogado", schema="dbo"), - {"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"}, - ] - } - - -SQL_TABLE = "dlt.sources.sql_database:sql_table" - - -def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, tmp_path): - count, query = platform.count, platform.query - tables = {} - for name in ("cacu", "cama"): - shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db") - with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: - found = con.execute("select name from sqlite_master where type = 'table'") - tables[name] = [t for (t,) in found] - truth = site.truth - (tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables, site.url))) - platform.save("pipelines", "site", tmp_path / "pipeline.json") - - by_place = {} - for r in truth: - by_place.setdefault(r["where"].split(":")[0], []).append(r) - documents = len(truth) - expected = {"resultados": documents, "text": documents} - for name, names in tables.items(): - with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con: - for t in names: - expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0] - - def counts(): - return {node: count(f"bronze.n__site__{node}") for node in expected} - - for _ in range(2): # loading the same site again changes nothing - platform.ingest() - assert counts() == expected - read_once = query("select key, _dlt_load_id from bronze.read_cache order by key") - assert len(read_once) == documents # each file read once - - with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates - con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1") - platform.ingest() - assert counts() == expected - corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1" - assert query(corrected) == [("64000",)] - - space = re.compile(r"\s+") - for table in ("ResultadoSubrogado",): - read = query("select id, text, ocr, error from bronze.n__site__text") - assert [error for *_, error in read if error is not None] == [] - by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} - for r in by_place[table]: - txt, ocr = by_id[int(r["where"].split(":")[1])] - assert bool(ocr) == r.get("scanned", False) # OCR runs on scans, and only on scans - if "record_number" in r["identity"]: # even scanned, the number reads back exactly - assert r["identity"]["record_number"] in txt, (r["where"], txt) - assert query("select key, _dlt_load_id from bronze.read_cache order by key") == ( - read_once - ) # reruns never read a file again diff --git a/tests/test_recurrence.py b/tests/test_recurrence.py index 0543134..8d3e9b5 100644 --- a/tests/test_recurrence.py +++ b/tests/test_recurrence.py @@ -1,235 +1,13 @@ -"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two -published datasets, loaded by the platform's `cama_reference` pipeline (the files are in -`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia). - -Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's -constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes -and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal -cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull -curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value -on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence; -v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within -FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within -SOLVER_TOLERANCE of the exact series. - -The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to -convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1 -(about an hour); the default set takes about two minutes. -""" - -import json -import os -import re -from pathlib import Path - import numpy as np import pandas as pd -import pytest -from joblib.externals.loky import get_reusable_executor from scipy.special import gammaln -from conftest import _platform -from models import curves -from models.cama import recurrence -from models.cama.recurrence import calculator, cohorts, factors, modeling, reports +from models import curves, survival -RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia")) -V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1" -# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock, -# short of the optimum this fit converges to (largest gap measured: 0.053). -FRACTIONAL_TOLERANCE = 0.06 -SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured) -FACTOR_TOLERANCE = 1.01e-4 - -FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt") -PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json" -pytestmark = pytest.mark.skipif( - not all((RAW / f).exists() for f in FILES), reason="no reference raw files" -) -slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset") - - -def _json(path: str): - return json.loads((V1 / path).read_text()) - - -VERSION = _json("version.json") if V1.exists() else {} -DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exists() else {} -FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else [] - - -@pytest.fixture(scope="module") -def raws(tmp_path_factory) -> dict[str, pd.DataFrame]: - """Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh - platform, read back from its tables.""" - folder = tmp_path_factory.mktemp("platform") - platform = _platform("sqlite", folder) - drawn = folder / "pipeline.json" - drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW))) - platform.save("pipelines", "cama_reference", drawn) - platform.ingest("cama_reference") - # What the training job reads (models.cama.specs), from that platform. - out = folder / "datasets.pkl" - platform.run("python", "-c", "import pandas as pd; from models.cama.specs import MODELS; " - f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip - return pd.read_pickle(out) - - -@pytest.fixture(scope="module") -def prepared(raws): - return {s: cohorts.prepare(s, raw) for s, raw in raws.items()} - - -@pytest.fixture(scope="module") -def fits(prepared): - found = modeling.fit(prepared, {}) - get_reusable_executor().shutdown(wait=True) - return found - - -# ---------------------------------------------------------------- comparisons - - -# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the -# platform keeps the dataset's text (0, 1...). Same categories, in the same order. -STAGES = {f"{n}.0": str(n) for n in range(5)} - - -def _stages(table: dict) -> dict: - """v1's summary with the stages as the dataset writes them.""" - text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table)) - return json.loads(text) - - -def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0): - ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}} - if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip - assert len(mine) == len(ref) - for i, (a, b) in enumerate(zip(mine, ref, strict=True)): - assert a.keys() == b.keys(), i - for c, z in b.items(): - x = a[c] - if isinstance(z, float) and not isinstance(z, bool) and x is not None: - assert abs(x - z) <= tolerance, (i, c, x, z) - else: - assert x == z, (i, c, x, z) - - -def _auc_rows(rows: list[dict], with_bootstrap: bool) -> list[dict]: - keep = slice(None) if with_bootstrap else slice(0, 6) - return [dict(list(r.items())[keep]) for r in rows] - - -def _reference_selection(source: str) -> dict: - """v1's bootstrap selection shares, as its risk-factor table published them.""" - found = {} - for r in DEVELOPMENT["factores_riesgo"]["filas"]: - if r["cohorte"] == source and r["tipo"] == "factor de riesgo": - found.setdefault(r["horizonte_meses"], {})[r["variable"]] = r[ - "freq_seleccion_bootstrap" - ] - return found - - -def _check_figures(records: list[dict], fractional_tolerance: float): - assert [(r["cohorte"], r["escenario"]) for r in records] == [ - (r["cohorte"], r["escenario"]) for r in FIGURES - ] - for mine, ref in zip(records, FIGURES, strict=True): - fixed = ("condiciones", "n", "recaidas", "observado_hasta", "months_max", "cohorte_nombre") - assert {k: mine[k] for k in fixed} == {k: ref[k] for k in fixed} - assert mine["bootstrap_replicas"] == ref["bootstrap_replicas"] - assert mine["km"]["months"] == ref["km"]["months"] - for part in ("S", "low", "high"): - np.testing.assert_allclose(mine["km"][part], ref["km"][part], rtol=0, atol=1e-12) - got, want = mine["points"]["COMB"][part], ref["points"]["COMB"][part] - np.testing.assert_allclose(got, want, rtol=0, atol=1e-12) - np.testing.assert_allclose(mine["weibull"]["t"], ref["weibull"]["t"], rtol=0, atol=0) - np.testing.assert_allclose(mine["weibull"]["S"], ref["weibull"]["S"], rtol=0, atol=1e-12) - gap = np.nanmax(np.abs(np.subtract(mine["weibull_fractional"]["S"], - ref["weibull_fractional"]["S"]))) # fmt: skip - assert gap <= fractional_tolerance, (mine["escenario"], gap) - - -# ---------------------------------------------------------------- fast - - -def test_cohorts(prepared, raws): - sampling = _json("rutinas/MUESTREO.json")["cohortes"] - missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"] - for source, c in prepared.items(): - assert len(c.frame) == sampling[source]["pacientes"] - assert int(c.frame["evento"].sum()) == sampling[source]["recaidas"] - assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"] - assert c.covariates == list(missing[source]) - assert cohorts.unknown_shares(c) == missing[source] - pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame) - assert prepared["metabric"].covariates == VERSION["model"]["covariates"] - - -def test_routines(prepared): - found = reports.routines(prepared, modeling.N_BOOTSTRAP) - for name, record in found.items(): - assert record == _json(f"rutinas/{name}.json"), name - - -def test_c_index_and_internal_auc(fits): - rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])] - assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False) - metrics = reports.metrics(rows) - assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k} - - -def test_saved_model(fits): - """METABRIC's terms (in order of entry), parents, and their whole-cohort refits.""" - tables = modeling.tables(fits["metabric"]) - for h, mine in tables.items(): - ref = VERSION["model"]["tables"][str(h)] - cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()} - assert {**mine, "hbn_cpt": cpt} == ref, h - frame, covariates = fits["metabric"].cohort.frame, fits["metabric"].cohort.covariates - model = recurrence.Recurrence("metabric", recurrence.HORIZONS, covariates, tables) - found = model.predict(frame.iloc[:5]) - assert list(found.columns) == ["recurrence_12m", "recurrence_36m", "recurrence_60m"] - t = tables[36] - row = frame.iloc[0] - x = np.array([float(f"{v}_{row[v]}" == term) for term in t["lr_terms"] - for v in [modeling.variable_of(term, model.covariates)]]) # fmt: skip - p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + x @ np.array(t["lr_coefficients"])))) - p_hbn = t["hbn_cpt"][tuple(row[p] for p in t["hbn_parents"])] - assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15) - - -@pytest.mark.slow -@slow -def test_calculator(fits): - """All 60 table rows, and the 20 figures but their fractional Weibull's tolerance.""" - records, rows = [], [] - for source in recurrence.SOURCES: - found = calculator.calculator(fits[source]) - records += found[0] - rows += found[1] - get_reusable_executor().shutdown(wait=True) - table = reports.table(pd.DataFrame(rows).round(4)) - assert table["columnas"] == DEVELOPMENT["calculadora"]["columnas"] - _same_rows(table["filas"], DEVELOPMENT["calculadora"]["filas"]) - _check_figures(records, FRACTIONAL_TOLERANCE) - - -def test_risk_factors(fits): - """All 273 rows, with v1's bootstrap selection shares (the slow test computes them).""" - table = pd.concat( - [factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES], - ignore_index=True, - ) - _same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"], - FACTOR_TOLERANCE) # fmt: skip - summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)] - assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"]) +SOLVER_TOLERANCE = 1e-6 def test_fractional_weibull_reproduces_the_classic_one(): - """With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's.""" t = np.linspace(0, 300, 61) for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)): found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam) @@ -237,7 +15,6 @@ def test_fractional_weibull_reproduces_the_classic_one(): def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741 - """E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small.""" j = np.arange(terms - 1) log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1) - gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip @@ -245,7 +22,6 @@ def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> def test_fractional_weibull_solver_matches_the_series(): - """Where the series is exact in floats (|z| < 2), the solver gives it within its error.""" t = np.linspace(0, 72, 289) for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)): s = k + a - 2 @@ -255,28 +31,20 @@ def test_fractional_weibull_solver_matches_the_series(): np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE) -# ---------------------------------------------------------------- slow: the whole v1 run - - -@pytest.mark.slow -@slow -def test_train_reproduces_v1(raws): - model, metrics, found = recurrence.train(raws, bootstrap=True) - assert metrics == VERSION["metrics"] - for h in recurrence.HORIZONS: - mine = model.tables[h] - cpt = {"|".join(k): v for k, v in mine["hbn_cpt"].items()} - assert {**mine, "hbn_cpt": cpt} == VERSION["model"]["tables"][str(h)] - technical = found["technical_validation"] - for name, record in technical["rutinas"].items(): - assert record == _json(f"rutinas/{name}.json"), name - tables = technical["recurrencia_desarrollo"]["tablas"] - _same_rows(tables["auc"]["filas"], DEVELOPMENT["auc"]["filas"]) - _same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"]) - _same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"], - FACTOR_TOLERANCE) # fmt: skip - assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"]) - figures = found["interpretability"]["recurrencia"] - assert figures["horizons_months"] == [12, 36, 60] - _check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE) - json.dumps(found, allow_nan=False) # JSON-able as it is +def test_survival_censors_deaths_after_follow_up_or_horizon(): + index = pd.Series(["2020-01-01"] * 4) + death = pd.Series(["2020-03-05", "2020-05-15", "2020-08-01", None]) + result = survival.outcomes(index, death, "2020-06-01", cap_months=3) + assert list(result.itertuples(index=False, name=None)) == [ + (2, True), + (3, False), + (3, False), + (3, False), + ] + uncapped = survival.outcomes(index, death, "2020-06-01", cap_months=0) + assert list(uncapped.itertuples(index=False, name=None)) == [ + (2, True), + (4, True), + (4, False), + (4, False), + ] diff --git a/tests/test_silver.py b/tests/test_silver.py index 33d1cb1..3992012 100644 --- a/tests/test_silver.py +++ b/tests/test_silver.py @@ -1,172 +1,19 @@ -"""Phase 1 gate: ISSSTELEON's test source, drawn once as a pipeline, becomes silver an analyst -can trust, and everything the platform can't decide alone is put in front of a reviewer. - -The source hides its answers the way the real one does (synthetic.site): one PDF per study in -one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result -is a document of its own on its cytology's order; pathology comes scanned, the name surname -first and no birth date; some forms say "MA." for María or misspell the name and leave the -employee number out; some HPV reports were re-issued the other way; two women share a name. -Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms. -""" - -import json -from collections import Counter -from datetime import date - -from core import catalog - -FIELDS = { - "cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", - "hpv_18"), - "cervical_biopsy": ("request_date", "report_date", "histology"), - "mammography": ("exam_date", "report_date", "adequacy", "birads"), - "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", - "er", "pr", "her2", "ki67_pct", "size_mm", "stage"), - "breast_treatment": ("start_date", "kind"), - "clinical_note": ("note_date", "specialty", "icd10"), - "death": ("death_date",), -} # fmt: skip -BOOLS = {"hpv", "hpv_16", "hpv_18"} -NUMBERS = {"ki67_pct", "size_mm"} +from persistance.nodes import stable_persons -def value(field, v): - if v is None: - return None - if field in BOOLS: - return bool(v) if not isinstance(v, str) else v == "true" - if field in NUMBERS: - return float(v) - return v.isoformat() if isinstance(v, date) else str(v) +def test_person_ids_survive_a_review_merge_and_split(fresh_platform): + older = stable_persons({"one": ["a"]})["one"] + newer = stable_persons({"two": ["b", "c"]})["two"] + assert older != newer + assert stable_persons({"merged": ["a", "b", "c"]}) == {"merged": older} + with fresh_platform.connect() as connection: + assert connection.exec_driver_sql( + "select person_id, replaced_by from bronze.person_link" + ).all() == [(newer, older)] -def said(record: dict, entity: str) -> dict | None: - """What a document says of one study (an oncology note: its treatment and the note).""" - if entity == "clinical_note": - return record.get("clinical_note") - return record["values"] if record["entity"] == entity else None - - -def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path): - truth = site.truth - (tmp_path / "pipeline.json").write_text(site.drawn) - platform.save("concept_maps", "erick_site", site.concept_map) - platform.save("pipelines", "site", tmp_path / "pipeline.json") - platform.ingest() - q = platform.query - of = site.patients(q) - - # Persons: nobody is merged with somebody else, except the two women of one name, joined - # by a pathology report (it shows no birth date) and held (torn) until a reviewer says - # whose report it is. - # A person nothing names (a scan whose name line wasn't read) is held as well: there is - # nobody to join her to. - members: dict[str, set] = {} - held, nameless, named, person_of = set(), set(), set(), {} - for record, person, why, *identifiers in q( - "select _record, person_id, _held, full_name, birth_date, record_number " - "from bronze.n__site__persons" - ): - members.setdefault(person, set()).add(of[record]) - person_of[record] = person - if any(identifiers): - named.add(person) - if why and "no name" in why: - nameless.add(person) - elif why: - held.add(person) - assert nameless == set(members) - named, nameless - torn = {p for p, who in members.items() if len(who) > 1} - assert len(torn) == 1 and torn == held, (torn, held) - assert members[next(iter(torn))] == set(site.meta["namesakes"]) - patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless} - - # Every woman split into several persons (a misspelled form, say) is in the review - # queue, joined by candidates. - parts: dict[str, set] = {} - for p, x in patient.items(): - parts.setdefault(x, set()).add(p) - queued = { - frozenset(person_of[r] for r in pair) - for pair in q("select person, candidate from bronze.n__site__persons__review") - } - split = {x: persons for x, persons in parts.items() if len(persons) > 1} - assert split # the misspelled forms, at least - for x, persons in split.items(): - reached, frontier = set(), {next(iter(persons))} - while frontier: - reached |= frontier - frontier = {b for a in frontier for pair in queued if a in pair for b in pair} - frontier -= reached - assert persons <= reached, (x, persons) - - # Every value accepted from a typed document is what the document says; and most of what - # the documents say is read (a scan's columns can come back out of order, and a value its - # pattern doesn't find is left out, never guessed). A scan can misread one valid code as - # another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's - # values, each listed. - at = {r["where"]: r for r in truth} - place = {r: f"ResultadoSubrogado:{i}" - for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip - record_of = {w: r for r, w in place.items()} - accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows) - for entity in FIELDS: - mine = accepted[entity] = {} - for record, field, *values in q( - "select _record, field, value_text, value_num, value_bool, value_date " - f"from bronze.staged__observation where study = '{entity}'" - ): - got = next((v for v in values if v is not None), None) - mine.setdefault(record, {})[field] = value(field, got) - assert mine, entity - stated = read = scanned = 0 - missed: Counter = Counter() - wrong = [] - for record, got in mine.items(): - t = at[place[record]] - if not t.get("flipped"): - truly = {f: v for f, v in said(t, entity).items() if v is not None} - differ = {f: (v, value(f, truly.get(f))) for f, v in got.items() - if v != value(f, truly.get(f))} # fmt: skip - assert t.get("scanned") or not differ, (t["where"], differ) - wrong += [(t["where"], differ)] if differ else [] - scanned += len(got) if t.get("scanned") else 0 - stated, read = stated + len(truly), read + len(got) - missed.update(set(truly) - set(got)) - assert read >= 0.95 * stated, (entity, read, stated, missed) - assert len(wrong) <= 0.01 * scanned, (entity, wrong) - - # A row a rule held because of a value (a scan misread) is held because it is wrong: - # never loaded, and a reviewer sees it. - misread = set() - for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"): - if record in place and person_of.get(record) not in torn | nameless: - t, got = at[place[record]], json.loads(raw) - truly = said(t, entity) - assert {f: value(f, got.get(f)) for f in truly} != { - f: value(f, v) for f, v in truly.items()}, t["where"] # fmt: skip - misread.add(record) - - # Silver: each person's studies, the records of one study key merged (a cytology form and - # its HPV report are one cytology), but for the torn person's, the misreads, and a study - # whose reports contradict each other (until review says which is right). - for entity, fields in FIELDS.items(): - key = catalog.studies()[entity].key - merged: dict[tuple, dict] = {} - disputed = set() - for r in truth: - record = record_of[r["where"]] - got = accepted[entity].get(record) - if got is None or person_of[record] in torn | nameless or record in misread: - continue - at_key = (person_of[record], *(got.get(k) for k in key)) - merged.setdefault(at_key, {}).update(got) - if r.get("conflict"): - disputed.add(at_key) - expected = {(k[0], *(row.get(f) for f in fields)) - for k, row in merged.items() if k not in disputed} # fmt: skip - rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}") - got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True))) - for p, *values in rows if p not in torn | nameless} # fmt: skip - assert got == expected, (entity, sorted(got - expected, key=str)[:4], - sorted(expected - got, key=str)[:4]) # fmt: skip + split = {"small": ["a"], "large": ["b", "c"]} + assigned = stable_persons(split) + assert assigned["large"] == older + assert assigned["small"] not in {older, newer} + assert stable_persons(split) == assigned diff --git a/tests/test_survival_seer.py b/tests/test_survival_seer.py deleted file mode 100644 index 724dc6e..0000000 --- a/tests/test_survival_seer.py +++ /dev/null @@ -1,182 +0,0 @@ -"""CaMa survival measured against the SEER-trained original (Luis's pipeline, -`05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each -clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier, -Weibull, fractional Weibull), and model points close to the original's. - -SEER is real registry data under NCI's use agreement: it is read from outside git -(SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran -(LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped. - -Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's -results, its first course of treatment a month later, and its death or last contact placed so -the platform's whole months of follow-up are SEER's survival months. - -The model points are not the original's: it trains on every case, the platform on the -earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few -recorded deaths yet. They are checked against the survival of the cases the model learned -from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1.""" - -import os -import re -from pathlib import Path - -import numpy as np -import pandas as pd -import pytest - -from models import curves, survival -from models.cama.specs import MODELS -from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks - -SEER = Path( - os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv") -) -RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run")) -AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it - -pytestmark = [ - pytest.mark.skipif( - not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()), - reason="SEER and the original's outputs are outside git", - ), - pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"), -] -CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative) -CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier - -STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"} -GRADE = {"G1": "1", "G2": "2", "G3": "3"} -RECEPTOR = {"Positivo": "positive", "Negativo": "negative"} -SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"} - - -def _her2(subtype: str) -> str | None: - return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None - - -def _age(recode: str) -> float: - """The age band's lower bound, as the original reads it ("65-69 years": 65).""" - found = re.search(r"\d+", str(recode)) - return float(found.group()) if found else np.nan - - -def seer_events(frame: pd.DataFrame) -> pd.DataFrame: - """SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis).""" - months = pd.to_numeric(frame["Survival_months"], errors="coerce") - frame, months = frame[months.notna()], months[months.notna()] - dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead") - person = frame["Patient_ID"].to_numpy() - # Whole months from the index are SEER's. A survivor's index is months + 1/2 before the - # cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so - # late that the death would pass the cutoff), and she dies months + 1/4 after it. So the - # index dates keep SEER's calendar, which the model's split by index date reads. - latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D") - year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01") - spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D") - index = latest.where(~dead, (year + spread).where(year + spread < latest, latest)) - death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D") - birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5) - * DAYS_PER_YEAR, "D") # fmt: skip - base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(), - "record_number": person}) # fmt: skip - rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)] - rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death", - value_code=None)) # fmt: skip - hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-") - hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+") - er = frame["Receptor_estrogeno_cat"].map(RECEPTOR) - pr = frame["Receptor_progesterona_cat"].map(RECEPTOR) - both_negative = er.eq("negative") & pr.eq("negative") - results = { - "biopsy": pd.Series("invasive", index=frame.index), - "stage": frame["Estadio_cat"].map(STAGE), - "grade": frame["Grado_histologico_cat"].map(GRADE), - # Hormone receptors as SEER's subtype states them, which the original's scenarios read: - # SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely - # borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown. - "er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None), - "pr": pr.mask(hr_negative, "negative"), - "her2": frame["Subtipo_molecular_cat"].map(_her2), - "histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3", - } - for kind, values in results.items(): - rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy())) - size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce") - rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None, - value_num=size.where(size < 990).to_numpy())) # fmt: skip - course = { - "surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY), - "chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}), - "radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}), - } - month_later = index + pd.Timedelta(days=30) - for values in course.values(): - rows.append(base.assign(date=month_later.to_numpy(), type="treatment", - value_code=values.to_numpy())) # fmt: skip - events = pd.concat(rows, ignore_index=True) - events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna() - | events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip - events["value_num"] = events.get("value_num") - events["source_table"], events["source_id"] = "seer", events["person_id"] - return events.reset_index(drop=True) - - -@pytest.fixture(scope="module") -def trained(): - events = seer_events(pd.read_csv(SEER, dtype=str)) - spec = MODELS["survival"] - model, metrics, data = spec.train(events, AS_OF) - return spec, model, metrics, data - - -def _original(name: str) -> pd.DataFrame: - return pd.read_csv(RUN / name) - - -def test_each_scenario_takes_the_originals_patients_and_deaths(trained): - spec, _, _, data = trained - members = pd.concat([data["train"], data["test"]]).reset_index(drop=True) - masks = scenario_masks(members, spec.scenarios) - theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo") - for name, row in theirs.iterrows(): - mask = masks[name] - assert (int(mask.sum()), int(members["event"][mask].sum())) == ( - row["n"], - row["fallecidos"], - ), name - - -@pytest.fixture(scope="module") -def report(trained): - spec, model, _, data = trained - return survival.interpretability(spec, model, data) - - -def test_each_scenarios_observed_curves_are_the_originals(report): - theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo") - assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index) - for e in report["escenarios"]: - row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"]) - months = np.arange(len(km)) - weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"]) - fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"]) - assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"] - assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE) - assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"] - - -def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report): - spec, _, _, data = trained - train = data["train"].reset_index(drop=True) - masks = scenario_masks(train, spec.scenarios) - theirs = _original("subgrupos_puntos_LR_HBN.csv") - horizons = list(spec.borders[1:]) - for e in report["escenarios"]: - mask = masks[e["escenario"]] - months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool) - km, _, _ = curves.kaplan_meier(months, event, horizons[-1]) - ours = np.array(e["points"]["COMB"]["S"]) - assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"] - original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")] - gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max() - print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}") diff --git a/tests/test_tea_association.py b/tests/test_tea_association.py index 38ac4ed..77130da 100644 --- a/tests/test_tea_association.py +++ b/tests/test_tea_association.py @@ -1,23 +1,9 @@ -import importlib.util -import sys -from pathlib import Path -from types import ModuleType - import numpy as np import pandas as pd from core.tea import ADOS2_ITEMS from models.tea import association as a -REFERENCE = Path("/home/milk/tea-parity/specs/P2-ref") -MODULES = {"toddler": "TODDLER", "module_1": "MODULO_1", "module_2": "MODULO_2"} -ZONES = dict(zip( - a.ZONE_ITEMS, - ("frontal_izq", "frontal_der", "frontal_media", "central", "parietal", - "temporal_izq", "temporal_der", "occipital"), - strict=True, -)) # fmt: skip - def test_firth_on_separation(): frame = pd.DataFrame({"z": np.arange(12), "event": [0] * 6 + [1] * 6}) @@ -53,61 +39,3 @@ def test_pairs_and_item_availability(): } ) np.testing.assert_allclose(a.item_scores(frame, 1), [2, 0, np.nan, np.nan]) - - -def _reference(monkeypatch): - package = ModuleType("p2_reference") - package.__path__ = [str(REFERENCE)] - contracts = ModuleType("tea.contracts") - contracts.ZONES = tuple(ZONES.values()) - contracts.ASSOCIATION_COLUMNS = a.ASSOCIATION_COLUMNS - contracts.SCORE_COLUMNS = a.SCORE_COLUMNS - contracts.CONTRACT_VERSION = None - monkeypatch.setitem(sys.modules, "p2_reference", package) - monkeypatch.setitem(sys.modules, "tea.contracts", contracts) - for name in ("_items", "_models", "api"): - qualified = f"p2_reference.{name}" - spec = importlib.util.spec_from_file_location(qualified, REFERENCE / f"{name}.py") - module = importlib.util.module_from_spec(spec) - monkeypatch.setitem(sys.modules, qualified, module) - spec.loader.exec_module(module) - return sys.modules["p2_reference.api"] - - -def test_reference_parity(monkeypatch): - ref = _reference(monkeypatch) - rng = np.random.default_rng(0) - cohort = pd.DataFrame( - { - "key": range(50), - "age_months": rng.uniform(16, 48, 50), - "ados_module": rng.choice(list(MODULES), 50), - "css": rng.integers(1, 11, 50), - **{item: rng.choice([0, 1, 2, 3, 7, 8], 50) for item in ADOS2_ITEMS}, - **{ - predictor: rng.normal(size=50) - for predictor in dict.fromkeys(pair["predictor"] for pair in a.pairs("item")) - }, - } - ) - other = cohort.drop(columns=ADOS2_ITEMS).copy() - other["ados_module"] = other["ados_module"].map(MODULES) - for number, (_, _, modules) in ref.it.ITEMS.items(): - for module, code in modules.items(): - chosen = other["ados_module"] == module - other.loc[chosen, code] = cohort.loc[chosen, ADOS2_ITEMS[number - 1]] - other = other.rename( - columns={ - f"z_{b}_{zone}": f"z_{b}_{old}" - for zone, old in ZONES.items() - for b in ("spikes", "spindles") - } - ) - ours = a.Ados2Association().fit(cohort) - theirs = ref.Ados2Association().fit(other) - for actual, expected in ( - (ours.associations(), theirs.associations()), - (a.Model(ours.fitted).predict(None, cohort), theirs.score(other)), - ): - actual["zone"] = actual["zone"].replace(ZONES) - pd.testing.assert_frame_equal(actual, expected, check_exact=True) diff --git a/tests/test_tea_job.py b/tests/test_tea_job.py index 0bb3f39..6ecbca1 100644 --- a/tests/test_tea_job.py +++ b/tests/test_tea_job.py @@ -1,83 +1,11 @@ -import os -from pathlib import Path +from datetime import date import dagster as dg import pytest from pydantic import ValidationError -from sqlalchemy import inspect -from models import definitions, execution -from models.definitions import ( - ExecutionConfig, - ScopeConfig, - after_ingest, - defs, - tea_eeg, - tea_eeg_after_ingest, -) -from models.tea import jobs as tea_jobs -from persistance import cluster, destination, eeg -from synthetic import tea - - -def _config(scope: dict) -> dict: - return {"ops": {"tea_analyze_studies": {"config": { - "scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip - - -@pytest.fixture -def calls(monkeypatch): - log = [] - - def analyze(scope=None, *, rebuild_gold=True): - log.append(("analyze", scope, rebuild_gold)) - return 2 - - monkeypatch.setattr(tea_jobs, "analyze", analyze) - monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3}) - monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",))) - monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel))) - return log - - -def test_tea_eeg_runs_the_four_steps_in_order(calls): - result = tea_eeg.execute_in_process( - instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2}) - ) - assert result.success - assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"] - assert calls[0][1].n == 2 and calls[0][2] is False - assert calls[3][1] == tea_jobs.GOLD_SELECT - assert result.output_for_node("tea_analyze_studies") == {"analysed": 2} - assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}} - assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None} - assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT} - - -def test_a_failing_analysis_stops_the_graph(calls, monkeypatch): - def boom(scope=None, *, rebuild_gold=True): - raise RuntimeError("no signal") - - monkeypatch.setattr(tea_jobs, "analyze", boom) - result = tea_eeg.execute_in_process( - instance=dg.DagsterInstance.ephemeral(), - run_config=_config({"mode": "pending"}), - raise_on_error=False, - ) - assert not result.success - assert calls == [] - - -def test_a_bad_scope_fails_before_any_work(calls): - result = tea_eeg.execute_in_process( - instance=dg.DagsterInstance.ephemeral(), - run_config=_config({"mode": "first_n"}), - raise_on_error=False, - ) - assert not result.success - assert calls == [] - failure = next(e for e in result.all_events if e.is_step_failure) - assert "first_n needs n" in str(failure.event_specific_data.error) +from models.definitions import ScopeConfig, after_ingest +from persistance import eeg def test_scope_validation(): @@ -108,17 +36,6 @@ def test_scope_validation(): ScopeConfig(mode="first_n").model() -def test_config_mirrors_match_the_shared_models(): - for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)): - assert list(config.model_fields) == list(shared.model_fields) - for name, field in shared.model_fields.items(): - assert config.model_fields[name].default == field.default, name - with pytest.raises(ValidationError): - ExecutionConfig(mode="cloud").model() - with pytest.raises(ValidationError): - ScopeConfig(mode="all").model() - - def test_after_ingest_requests_a_run_only_with_pending_eegs(): skip = after_ingest("r1", lambda: False) assert isinstance(skip, dg.SkipReason) @@ -130,92 +47,31 @@ def test_after_ingest_requests_a_run_only_with_pending_eegs(): assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1" -def test_definitions_load_with_every_job_and_the_sensor(): - dg.Definitions.validate_loadable(defs) - names = {j.name for j in defs.jobs} - assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"} - assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING - - -def test_relate_returns_none_without_a_champion(): - assert tea_jobs.relate() is None - - -@pytest.fixture -def synthetic_tea(platform, tmp_path, monkeypatch): - tea.build(tmp_path / "hospital_tea.db") - fixtures = Path(__file__).parents[2] / "tests" / "fixtures" - drawing = tmp_path / "pipeline.json" - drawing.write_text( - (fixtures / "pipelines" / "hospital_tea.json") - .read_text() - .replace("{hospital}", str(tmp_path)) - ) - platform.save("concept_maps", "hospital_tea", fixtures / "concept_maps" / "hospital_tea.json") - platform.save("pipelines", "tea", drawing) - platform.ingest("tea") - - for name in ("PLATFORM_DATABASE_URL", "DLT_DATA_DIR", "EXECUTION_MODE"): - monkeypatch.setenv(name, platform.env[name]) - monkeypatch.setattr(destination, "DATA_DIR", tmp_path) - destination.engine.cache_clear() - try: - yield platform - finally: - destination.engine.cache_clear() - - -@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) -def test_tea_eeg_first_n_analyses_exactly_n(synthetic_tea): - table = "bronze.eeg_analysis" - with destination.engine().connect() as con: - has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze") - before = synthetic_tea.count(table) if has_analysis else 0 - pending = len(eeg.pending()) - tea_jobs.analyze(eeg.Scope(mode="first_n", n=3), rebuild_gold=False) - assert synthetic_tea.count(table) == before + 3 - assert len(eeg.pending()) == pending - 3 - - -@pytest.mark.skipif( - not os.environ.get("DASK_TEST_SCHEDULER"), reason="DASK_TEST_SCHEDULER is not set" -) -@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) -def test_tea_eeg_remote_mode_gives_the_same_analysis(synthetic_tea): - def snapshot(): - analyses = synthetic_tea.query( - "select edf, valid, level, age_months, clean_fraction, bad_channels " - "from bronze.eeg_analysis order by edf" +def test_tea_eeg_first_n_selects_exactly_n_pending_studies(fresh_platform): + with fresh_platform.begin() as con: + con.exec_driver_sql("create table silver.person (person_id text, birth_date text)") + con.exec_driver_sql("insert into silver.person values ('p1', '2023-01-01')") + con.exec_driver_sql("create table silver.eeg (person_id text, study_date text, edf text)") + con.exec_driver_sql( + "insert into silver.eeg values (?, ?, ?)", + [ + ("p1", "2025-01-01", "c"), + ("p1", "2025-02-01", "b"), + ("p1", "2025-03-01", "a"), + ("p1", "2025-04-01", "d"), + ("p1", "2025-05-01", None), + ], ) - metrics = synthetic_tea.query( - "select edf, code, value from bronze.eeg_metrics order by edf, code" - ) - return analyses, metrics + con.exec_driver_sql("create table bronze.eeg_analysis (edf text)") + con.exec_driver_sql("insert into bronze.eeg_analysis values ('b')") - assert tea_jobs.analyze(eeg.Scope(mode="first_n", n=2), rebuild_gold=False) == 2 - before, metrics_before = snapshot() - ids = [study["id"] for study in eeg.studies() if study["analysed"]] - assert len(ids) == 2 - - @dg.op - def remote_analysis(context): - remote = cluster.Execution(mode="remote", scheduler=os.environ["DASK_TEST_SCHEDULER"]) - with execution.running(context, remote): - return tea_jobs.analyze(eeg.Scope(mode="ids", ids=ids), rebuild_gold=False) - - @dg.job - def reanalyze(): - remote_analysis() - - result = reanalyze.execute_in_process() - assert result.success - assert result.output_for_node("remote_analysis") == 2 - after, metrics_after = snapshot() - - def close(value): - return pytest.approx(value, rel=1e-12) if isinstance(value, float) else value - - assert [tuple(row) for row in after] == [tuple(map(close, row)) for row in before] - assert [tuple(row) for row in metrics_after] == [ - tuple(map(close, row)) for row in metrics_before + birth = date(2023, 1, 1) + assert eeg.select(eeg.Scope(mode="first_n", n=2)) == [ + {"edf": "a", "birth_date": birth}, + {"edf": "c", "birth_date": birth}, ] + assert eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-02-01"])) == [ + {"edf": "b", "birth_date": birth} + ] + with pytest.raises(LookupError, match="has no signal"): + eeg.select(eeg.Scope(mode="ids", ids=["p1|2025-05-01"])) diff --git a/tests/test_tea_preview.py b/tests/test_tea_preview.py index 1f6b662..8f9f8c1 100644 --- a/tests/test_tea_preview.py +++ b/tests/test_tea_preview.py @@ -1,17 +1,11 @@ import hashlib import os -from datetime import date -from types import SimpleNamespace -import dagster as dg import pytest +from dagster import build_op_context -from core import tea -from core.pipeline import Extract, Pipeline, Source -from core.tea import ados2 -from models.definitions import tea_preview +from models.definitions import Preview, preview_study from models.tea import preview as study -from models.tea.eeg import analysis, curves from persistance import config, previews @@ -51,177 +45,17 @@ def test_an_unreadable_file_is_a_result_not_a_crash(): assert result.eeg.recorded_on is None -@pytest.fixture -def valid_study(monkeypatch): - metric = analysis.Metric("paroxysmal_spikes", 3, {"F3": 3, "F4": 0}, {"frontal": 3}) - analysed = analysis.Analysis( - valid=True, - level="valid", - age_months=42, - clean_fraction=1, - bad_channels=0, - channels=19, - duration_min=20, - line_noise_db=None, - sleep=True, - checks=[], - metrics=[metric], - features={"eeg-spikes": {curves.EXPOSURE: 20}}, - error=None, - ) - monkeypatch.setattr(analysis, "analyze", lambda *_: analysed) - - -def test_scores_come_from_the_champions(monkeypatch, valid_study): - baseline = dict.fromkeys(("value", "electrode_F3", "zone_frontal")) - model = SimpleNamespace(unwrap_python_model=lambda: SimpleNamespace(baseline=baseline)) - monkeypatch.setattr(study.registry, "champion", lambda _: (3, model)) - score = {"z": 1, "outside": 0, "p5": 0, "median": 2, "p95": 4} - - def deviations(models, analysed): - assert set(models) == set(curves.SCENARIOS) - assert analysed.metrics[0].electrodes == {"F3": 3} - return { - "paroxysmal_spikes": { - "value": score, - "electrodes": {"F3": score}, - "zones": {"frontal": score}, - } - } - - monkeypatch.setattr(curves, "deviations", deviations) - result = study.preview(b"edf") - metric = result.eeg.metrics[0] - assert metric.score == previews.Score(**score) - assert metric.electrodes == { - "F3": previews.Site(value=3, score=previews.Score(**score)), - "F4": previews.Site(value=0, score=None), - } - assert metric.zones == {"frontal": previews.Site(value=3, score=previews.Score(**score))} - assert metric.model == "tea.eeg-spikes/3" - assert not result.warnings - - -def test_no_champions_warns_and_leaves_z_empty(monkeypatch, valid_study): - monkeypatch.setattr(study.registry, "champion", lambda _: None) - result = study.preview(b"edf") - assert result.warnings == ["there are no champion age curves: no z is shown"] - metric = result.eeg.metrics[0] - assert metric.score is metric.model is None - assert all(site.score is None for site in (metric.electrodes | metric.zones).values()) - - -def _pipeline(patterns): - return Pipeline( - nodes=[ - Source(id="source", source="dlt.sources.sql_database:sql_table"), - Extract( - id="x", - inputs=["source"], - column="text", - entity="ados2", - method="patterns", - patterns=patterns, - ), # fmt: skip - ] - ) - - -def test_ados2_read_with_the_pipeline_patterns(monkeypatch): - text = "module module_1; date 2025-01-01; pointing 2; gestures 1; intonation 3" - patterns = { - "module": r"module (\w+)", - "evaluation_date": r"date ([\d-]+)", - "pointing": r"pointing (\d+)", - "gestures": r"gestures (\d+)", - "intonation": r"intonation (\d+)", - } - monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None}) - monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns))) - birth = date(2022, 1, 1) - result = study.preview(b"edf", b"%PDF", birth) - row = dict(module="module_1", evaluation_date=date(2025, 1, 1), - pointing=2, gestures=1, intonation=3) # fmt: skip - assert result.ados2 is not None - assert result.ados2.items == { - name: row.get(name) for name in tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS - } - assert result.ados2.module == row["module"] - assert result.ados2.evaluation_date == row["evaluation_date"] - assert result.ados2.read == sorted(row) - assert (result.ados2.css, result.ados2.classification) == ados2.score(row, birth) - assert not result.warnings - - -def test_ados2_problems_are_warnings_not_errors(monkeypatch): - def check(report, *warnings): - result = study.preview(b"edf", report) - assert result.eeg == study.preview(b"edf").eeg - assert result.warnings == list(warnings) - return result.ados2 - - assert check(b"text", "the ADOS-2 file is not a PDF") is None - monkeypatch.setattr(study.graph, "read_file", lambda _: {"error": "broken"}) - assert check(b"%PDF", "the ADOS-2 report could not be read: broken") is None - - def missing(_): - raise LookupError("tea") - - text = "pointing bad; date 2025-01-01" - monkeypatch.setattr(study.graph, "read_file", lambda _: {"text": text, "error": None}) - monkeypatch.setattr(study.config_log, "get", missing) - assert check(b"%PDF", "no saved pipeline tea: the ADOS-2 report is not read") is None - monkeypatch.setattr(study.config_log, "get", lambda _: (1, Pipeline(nodes=[]))) - assert check(b"%PDF", "pipeline tea has no ados2 extract node") is None - monkeypatch.setattr( - study.config_log, "get", lambda _: (1, _pipeline({"module": r"missing (.)"})) - ) - assert check(b"%PDF", "no ADOS-2 field was found in the report") is None - - patterns = {"pointing": r"pointing (\w+)"} - monkeypatch.setattr(study.config_log, "get", lambda _: (1, _pipeline(patterns))) - report = check( - b"%PDF", - "pointing: could not read 'bad' as a number", - "ADOS-2 not scored: no evaluation date", - ) - assert report is not None - assert report.read == ["pointing"] - assert report.items["pointing"] is report.css is report.classification is None - - patterns = {"evaluation_date": r"date ([\d-]+)"} - report = check( - b"%PDF", - "the ADOS-2 score could not be calculated: the report lacks the module or the item scores", - ) - assert report is not None - assert report.css is report.classification is None - - -def _execute(key, ados_key, *, raise_on_error=True): - with dg.DagsterInstance.ephemeral() as instance: - return tea_preview.execute_in_process( - run_config={"ops": {"preview_study": {"config": {"edf": key, "ados2": ados_key}}}}, - instance=instance, - raise_on_error=raise_on_error, - ) - - def test_the_job_deletes_its_files_and_returns_the_result_as_output(preview_area): - run = _execute(previews.put(b"edf"), previews.put(b"not a report")) - assert run.success - assert not list(preview_area.iterdir()) - assert run.output_for_node("preview_study") == {"valid": False, "warnings": 1} - (event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT) - result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value) - assert result.eeg.valid is False + edf = previews.put(b"not an EDF") + report = previews.put(b"not a PDF") + with build_op_context() as context: + result = preview_study(context, Preview(edf=edf, ados2=report)) + assert result == {"valid": False, "warnings": 1} + assert list(preview_area.iterdir()) == [] -def test_the_job_deletes_its_files_when_the_study_fails(monkeypatch, preview_area): - def failed(*_): - raise RuntimeError("study failed") - - monkeypatch.setattr(study, "preview", failed) - run = _execute(previews.put(b"edf"), previews.put(b"%PDF"), raise_on_error=False) - assert not run.success - assert not list(preview_area.iterdir()) +def test_the_job_deletes_its_files_when_the_study_fails(preview_area): + report = previews.put(b"%PDF") + with build_op_context() as context, pytest.raises(LookupError, match="no preview file"): + preview_study(context, Preview(edf="0" * 64, ados2=report)) + assert list(preview_area.iterdir()) == [] diff --git a/tests/test_tea_reference.py b/tests/test_tea_reference.py index b818a8e..1047612 100644 --- a/tests/test_tea_reference.py +++ b/tests/test_tea_reference.py @@ -1,13 +1,8 @@ -import hashlib -from types import SimpleNamespace - import pytest from edf_files import small_edf from pydantic import ValidationError -from models import definitions from models.tea import jobs -from models.tea.eeg import curves, reference from persistance.cluster import Reference @@ -24,48 +19,6 @@ def cohort(tmp_path, monkeypatch): return folder, ages -@pytest.fixture -def measurements(monkeypatch): - calls = [] - - def measure(studies, *, mains_hz): - calls.append((studies, mains_hz)) - return [ - {"key": key, "age_months": age, "valid": True, "error": None, "features": {}} - for key, _, age in studies - ] - - monkeypatch.setattr(reference, "measure", measure) - return calls - - -def test_a_named_reference_resolves_under_the_root(cohort, measurements): - _, measured, name, hz = jobs._reference(Reference(name="hel")) - [(studies, mains_hz)] = measurements - assert len(studies) == len(measured) == 3 - assert all(path.parent == cohort[0] for _, path, _ in studies) - assert mains_hz == 50.0 - assert (name, hz) == ("hel", 50) - - -def test_60_hz_changes_the_digest_and_is_passed_on(cohort, measurements): - digest_50, *_ = jobs._reference(Reference(name="hel")) - digest_60, _, _, hz = jobs._reference(Reference(name="hel", line_hz=60)) - assert digest_50 == hashlib.sha256(b"0.edf|18.0\n1.edf|24.0\n2.edf|30.0").hexdigest() - assert digest_60 != digest_50 - assert hz == 60 - assert measurements[-1][1] == 60.0 - - -def test_the_cache_is_named_by_cohort_and_digest_and_reused(cohort, measurements, monkeypatch): - cache = cohort[0].parent / "c" - monkeypatch.setenv("TEA_REFERENCE_CACHE", str(cache)) - result = jobs._reference(Reference(name="hel")) - assert [p.name for p in cache.iterdir()] == [f"hel-{result[0][:16]}.json"] - assert jobs._reference(Reference(name="hel")) == result - assert len(measurements) == 1 - - def test_bad_references_fail_with_a_reason(cohort): folder, ages = cohort for name in ("..", ".", "nope"): @@ -87,58 +40,3 @@ def test_bad_references_fail_with_a_reason(cohort): Reference(name="../x") with pytest.raises(ValidationError, match="line_hz"): Reference(name="hel", line_hz=55) - - -def test_legacy_environment_still_works(cohort, measurements, monkeypatch): - folder, ages = cohort - monkeypatch.setenv("TEA_REFERENCE_DIR", str(folder)) - monkeypatch.setenv("TEA_REFERENCE_AGES", str(ages)) - _, measured, name, hz = jobs._reference(None) - assert len(measured) == 3 - assert (name, hz) == ("hk1k", 50) - assert measurements[0][1] == 50.0 - - -def test_train_records_cohort_and_line_hz(cohort, measurements, monkeypatch): - monkeypatch.setattr(reference, "tables", lambda measured: {"curve": measured}) - monkeypatch.setattr(curves, "train", lambda table, name: {"value": {}}) - registrations = [] - - def register(*args): - registrations.append(args) - return 1 - - monkeypatch.setattr(jobs.registry, "register", register) - config = Reference(name="hel", line_hz=60) - assert jobs.train("curve", reference=config) == 1 - [(_, _, params, _, reports)] = registrations - digest, *_ = jobs._reference(config) - assert params == {"cohort": "hel", "cohort_sha256": digest, "line_hz": "60"} - technical = reports["technical_validation"] - assert technical["cohort"] == "hel" - assert technical["line_hz"] == 60 - - -def test_the_train_op_passes_the_reference_or_refuses_it(monkeypatch): - calls = [] - - def train(name, as_of, reference=None): - calls.append((name, as_of, reference)) - return 1 - - fake = SimpleNamespace(train=train) - monkeypatch.setattr(definitions, "_jobs", lambda domain: fake) - config = {"ops": {"train_models": {"config": { - "domain": "tea", "models": ["curve"], "execution": {"mode": "sync"}, - "reference": {"name": "a", "line_hz": 60}, - }}}} # fmt: skip - assert definitions.train.execute_in_process(run_config=config).success - assert calls == [("curve", None, Reference(name="a", line_hz=60))] - - fake.train = lambda name, as_of: 1 - with pytest.raises(ValueError, match="tea models take no reference cohort"): - definitions.train.execute_in_process(run_config=config) - - -def test_reference_config_mirrors_the_shared_model(): - assert definitions.ReferenceConfig.model_fields.keys() == Reference.model_fields.keys()