The suite keeps only logic tests

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

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

removed models/tests/test_bundle.py::test_guard_runs_on_export_and_on_import — implementation-detail
removed models/tests/test_cacu_models.py — parity-only
removed models/tests/test_cacu_models.py::test_predictions_match_the_current_models — parity-only
removed models/tests/test_cacu_models.py::test_survival_matches_the_current_model_with_its_index_fixed — parity-only
removed models/tests/test_cacu_models.py::test_a_cohort_the_site_lacks_is_reported_not_trained — implementation-detail
removed models/tests/test_cama_models.py — parity-only
removed models/tests/test_cama_models.py::test_survival_matches_the_current_model — parity-only
removed models/tests/test_edf_node.py — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_node.py::test_edf_pipeline_keeps_and_links_the_files — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_upload.py — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_edf_upload.py::test_an_uploaded_edf_is_analysed_by_itself — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_eeg.py::test_verdicts_and_checks — parity-only
removed models/tests/test_eeg.py::test_metric_values — parity-only
removed models/tests/test_eeg.py::test_reference_features — parity-only
removed models/tests/test_eeg.py::test_curves — parity-only
removed models/tests/test_execution.py::test_map_empty_items_starts_nothing — implementation-detail
removed models/tests/test_execution.py::test_map_local_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_lazy_items_are_not_all_loaded_at_once — implementation-detail
removed models/tests/test_execution.py::test_progress_tag_and_log_lines_inside_running — implementation-detail
removed models/tests/test_execution.py::test_no_tag_outside_running — implementation-detail
removed models/tests/test_execution.py::test_version_mismatch_fails_before_any_task — implementation-detail
removed models/tests/test_execution.py::test_local_cancel_leaves_no_worker_processes — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_health_sync_and_local — slow integration (logic now covered by test_resolve_defaults_and_allow_list for execution defaults)
removed models/tests/test_execution.py::test_health_unreachable_remote — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode for scheduler validation)
removed models/tests/test_execution.py::test_health_rejects_unlisted_scheduler — implementation-detail
removed models/tests/test_execution.py::test_progress_reaches_the_dagster_run — slow integration (logic now covered by test_shape_progress_tag and test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_remote_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_health_remote — slow integration (logic now covered by test_resolve_defaults_and_allow_list for remote execution choice)
removed models/tests/test_execution.py::test_remote_cancel_cancels_futures — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_progress_json_is_stable — implementation-detail
removed models/tests/test_execution.py::test_map_on_error_converts_a_failed_item[local] — slow integration (logic now covered by test_map_on_error_converts_a_failed_item)
removed models/tests/test_execution.py::test_map_raises_without_on_error[local] — slow integration (logic now covered by test_map_raises_without_on_error)
removed models/tests/test_ingest.py — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_ingest.py::test_a_site_reaches_bronze_once_and_its_documents_are_read — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_recurrence.py::test_cohorts — parity-only
removed models/tests/test_recurrence.py::test_routines — parity-only
removed models/tests/test_recurrence.py::test_c_index_and_internal_auc — parity-only
removed models/tests/test_recurrence.py::test_saved_model — parity-only
removed models/tests/test_recurrence.py::test_calculator — parity-only
removed models/tests/test_recurrence.py::test_risk_factors — parity-only
removed models/tests/test_recurrence.py::test_train_reproduces_v1 — parity-only
removed models/tests/test_silver.py::test_a_site_becomes_silver_and_review_gets_the_rest — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_code_nobody_mapped_is_held_with_the_reason)
removed models/tests/test_survival_seer.py — parity-only
removed models/tests/test_survival_seer.py::test_each_scenario_takes_the_originals_patients_and_deaths — parity-only
removed models/tests/test_survival_seer.py::test_each_scenarios_observed_curves_are_the_originals — parity-only
removed models/tests/test_survival_seer.py::test_the_models_points_are_the_survival_of_the_cases_it_learned_from — parity-only
removed models/tests/test_tea_association.py::test_reference_parity — parity-only
removed models/tests/test_tea_job.py::test_tea_eeg_runs_the_four_steps_in_order — implementation-detail
removed models/tests/test_tea_job.py::test_a_failing_analysis_stops_the_graph — implementation-detail
removed models/tests/test_tea_job.py::test_a_bad_scope_fails_before_any_work — implementation-detail
removed models/tests/test_tea_job.py::test_config_mirrors_match_the_shared_models — implementation-detail
removed models/tests/test_tea_job.py::test_definitions_load_with_every_job_and_the_sensor — implementation-detail
removed models/tests/test_tea_job.py::test_relate_returns_none_without_a_champion — implementation-detail
removed models/tests/test_tea_job.py::test_tea_eeg_first_n_analyses_exactly_n — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies)
removed models/tests/test_tea_job.py::test_tea_eeg_remote_mode_gives_the_same_analysis — slow integration (logic now covered by test_dominant_peak_recovers_a_posterior_rhythm_above_background and test_centile_interpolation_preserves_scoring)
removed models/tests/test_tea_preview.py::test_scores_come_from_the_champions — implementation-detail
removed models/tests/test_tea_preview.py::test_no_champions_warns_and_leaves_z_empty — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_read_with_the_pipeline_patterns — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_problems_are_warnings_not_errors — implementation-detail
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_and_returns_the_result_as_output — slow integration (logic now covered by the direct-op test_the_job_deletes_its_files_and_returns_the_result_as_output)
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_when_the_study_fails — implementation-detail
removed models/tests/test_tea_reference.py::test_a_named_reference_resolves_under_the_root — implementation-detail
removed models/tests/test_tea_reference.py::test_60_hz_changes_the_digest_and_is_passed_on — implementation-detail
removed models/tests/test_tea_reference.py::test_the_cache_is_named_by_cohort_and_digest_and_reused — implementation-detail
removed models/tests/test_tea_reference.py::test_legacy_environment_still_works — implementation-detail
removed models/tests/test_tea_reference.py::test_train_records_cohort_and_line_hz — implementation-detail
removed models/tests/test_tea_reference.py::test_the_train_op_passes_the_reference_or_refuses_it — implementation-detail
removed models/tests/test_tea_reference.py::test_reference_config_mirrors_the_shared_model — implementation-detail
This commit is contained in:
2026-11-30 16:45:51 -06:00
parent d8445fcabf
commit c1a1e294dc
16 changed files with 118 additions and 2196 deletions
+19 -251
View File
@@ -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),
]