Files
models/tests/test_cacu_development_selection.py
T
2026-12-04 09:12:15 -06:00

95 lines
4.0 KiB
Python

import numpy as np
import pandas as pd
import pytest
from models.cacu.development_firth import FirthFamily
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
@pytest.mark.parametrize("method", METHODS)
def test_methods_fit_simulated_data(method):
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
def test_candidates_and_imputation_use_only_training_rows():
train = pd.DataFrame(
{"a": [0.0, 1.0, np.nan, 1.0], "copy": [0.0, 1.0, np.nan, 1.0], "absent": [np.nan] * 4}
)
assert _candidates(train, 0.7, 5) == ["a"]
a, b = _matrix(train, pd.DataFrame({"a": [np.nan]}), ["a"])
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
def test_nested_cv_and_loocv_record_every_attempt():
X = pd.DataFrame({"a": [0, 0, 1, 1, 0, 1, 0, 1], "b": [0, 1, 0, 1, 1, 0, 0, 1]})
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
assert report["development_only"] and report["max_subsets"] == 4
assert set(report["validation"]) == {"cv", "loocv"}
assert {a["method"] for a in report["attempts"]} == set(METHODS)
assert all("variables" in a and "error" in a for a in report["attempts"])
assert all(len(report["validation"]["loocv"][m]["selected"]) == len(X) for m in METHODS)
def test_budget_rejects_large_loocv_before_fitting():
X = pd.DataFrame({"a": [0, 1] * 10})
with pytest.raises(ValueError, match="exceeds configured limit"):
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
def test_development_job_is_not_a_production_score():
from core.models import DEVELOPMENT
from models.definitions import defs
assert "cacu.cin2_firth_development" in DEVELOPMENT
job = defs.get_job_def("cacu_development_evaluation")
assert job.name == "cacu_development_evaluation"
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
import dagster as dg
import mlflow
from mlflow.tracking._tracking_service import utils as tracking_utils
from models.cacu import development_selection, encoders, features
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
from persistance import gold
monkeypatch.setenv("MLFLOW_TRACKING_URI", (tmp_path / "mlruns").as_uri())
monkeypatch.setenv("MLFLOW_ALLOW_FILE_STORE", "true")
monkeypatch.setattr(tracking_utils, "_tracking_uri", tracking_utils._tracking_uri)
mlflow.set_tracking_uri((tmp_path / "mlruns").as_uri())
patients = [str(i) for i in range(8)]
events = pd.DataFrame(
{"person_id": patients, "date": ["2025-01-01"] * 8, "index_date": ["2025-01-01"] * 8}
)
encoded = pd.DataFrame(
{
"person_id": patients,
"index_date": ["2025-01-01"] * 8,
"factor": [0, 0, 1, 1, 0, 1, 0, 1],
}
)
outcomes = pd.DataFrame(
{"person_id": patients, "known": [True] * 8, "y": [0, 1, 0, 1, 0, 1, 1, 0]}
)
monkeypatch.setattr(gold, "evidence_timelines", lambda *a: events)
monkeypatch.setattr(gold, "cervical_forms", lambda *a: pd.DataFrame())
monkeypatch.setattr(encoders, "encode", lambda *a: encoded)
monkeypatch.setattr(features, "windowed_outcome", lambda *a: outcomes)
real = development_selection.evaluate
monkeypatch.setattr(
development_selection,
"evaluate",
lambda X, y, **kw: real(
X, y, candidate_limit=1, subset_limit=1, outer_folds=2, inner_folds=2, **kw
),
)
with dg.build_op_context() as context:
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of="2026-01-01"))
artifacts = mlflow.MlflowClient().list_artifacts(run_id, "reports")
assert [a.path for a in artifacts] == ["reports/development_evaluation.json"]