diff --git a/models/definitions.py b/models/definitions.py index 224afca..abdfba3 100644 --- a/models/definitions.py +++ b/models/definitions.py @@ -6,6 +6,7 @@ from datetime import date import dagster as dg from models import graph +from models.jobs import EmptyCohort from persistance import config_log, silver WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite) @@ -51,7 +52,12 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict: as_of = date.fromisoformat(config.as_of) if config.as_of else None found = {} for name in config.models or jobs.JOBS.routine(): - found[name] = jobs.train(name, as_of) + try: + found[name] = jobs.train(name, as_of) + except EmptyCohort as e: # the site has no such patients; the others still train + found[name] = None + context.log.warning(f"{e}: not trained") + continue context.log.info(f"{config.domain}.{name}: version {found[name]}") return found diff --git a/models/jobs.py b/models/jobs.py index b3a1272..2995acd 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -14,6 +14,10 @@ from joblib.externals.loky import get_reusable_executor from persistance import gold, registry +class EmptyCohort(ValueError): + """The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from.""" + + class Predictor(mlflow.pyfunc.PythonModel): """A fitted model as MLflow serves it: patient timelines in (gold `_events` rows with each patient's index date), one row per patient and horizon out.""" @@ -51,6 +55,8 @@ class Jobs: fitted, metrics, found = spec.train(None, as_of) else: events = gold.timelines(self.events, spec.cohort, as_of) + if events.empty: + raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") fitted, metrics, data = spec.train(events, as_of) found = { "technical_validation": self.technical_validation(spec, metrics, data), diff --git a/tests/test_cacu_models.py b/tests/test_cacu_models.py index 482dd1e..1785c87 100644 --- a/tests/test_cacu_models.py +++ b/tests/test_cacu_models.py @@ -112,3 +112,14 @@ def test_survival_matches_the_current_model_with_its_index_fixed(): 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")