Limpiar los avisos de estilo
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
import pytest
|
||||
import numpy as np
|
||||
import pytest
|
||||
from scipy.stats import norm
|
||||
|
||||
from models.cacu.bayes_development import prevalence_gibbs as PG
|
||||
|
||||
|
||||
def test_normal_posterior_is_least_squares_under_a_flat_prior():
|
||||
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no information."""
|
||||
"""Fails if the conjugate mean does not reduce to least squares when the prior carries no\
|
||||
information."""
|
||||
rng = np.random.default_rng(1)
|
||||
X = np.column_stack([np.ones(200), rng.normal(size=200)])
|
||||
z = X @ [0.5, -1.0] + rng.normal(size=200)
|
||||
@@ -24,7 +25,8 @@ def test_latent_sign_follows_g():
|
||||
|
||||
|
||||
def test_prob_g_by_observation():
|
||||
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep her prior, or a tested
|
||||
"""Fails if a tested positive is not certainly diseased, an untested woman does not keep\
|
||||
her prior, or a tested
|
||||
negative is not discounted by 1 - kappa."""
|
||||
p, k = np.full(3, 0.2), 0.7
|
||||
out = PG.prob_g(p, np.array([1, 0, 1]), np.array([1.0, np.nan, 0.0]), k)
|
||||
@@ -33,7 +35,8 @@ def test_prob_g_by_observation():
|
||||
|
||||
|
||||
def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
||||
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit coefficients of a simulated
|
||||
"""Fails if, with kappa pinned by a strong prior, the chain misses the true probit\
|
||||
coefficients of a simulated
|
||||
cross-sectional sample (60 % tested, one test each)."""
|
||||
rng = np.random.default_rng(3)
|
||||
n, beta, kappa = 6000, np.array([-1.2, 0.8]), 0.7
|
||||
@@ -41,13 +44,24 @@ def test_gibbs_recovers_the_prevalence_with_known_sensitivity():
|
||||
g = rng.random(n) < norm.cdf(X @ beta)
|
||||
r = (rng.random(n) < 0.6).astype(int)
|
||||
y = np.where(r == 1, g & (rng.random(n) < kappa), np.nan)
|
||||
out = PG.gibbs(X, r, y, np.zeros(2), np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=4)
|
||||
out = PG.gibbs(
|
||||
X,
|
||||
r,
|
||||
y,
|
||||
np.zeros(2),
|
||||
np.eye(2) * 4,
|
||||
kappa_ab=(7000, 3000),
|
||||
iterations=1500,
|
||||
warmup=500,
|
||||
seed=4,
|
||||
)
|
||||
assert np.allclose(out["beta"].mean(0), beta, atol=0.12)
|
||||
assert abs(out["kappa"].mean() - 0.7) < 0.02
|
||||
|
||||
|
||||
def test_referral_odds():
|
||||
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) / Phi(eta) for a tested woman
|
||||
"""Fails if the arc ratio is not 1 where the arc is off, or not Phi(eta + gamma_g) /\
|
||||
Phi(eta) for a tested woman
|
||||
and the same with the survival function for an untested one."""
|
||||
eta, gg = np.array([-1.0, -1.0, 0.5]), 0.8
|
||||
out = PG.referral_odds(eta, gg, np.array([0.0, 1.0, 1.0]), np.array([1, 1, 0]))
|
||||
@@ -57,8 +71,10 @@ def test_referral_odds():
|
||||
|
||||
|
||||
def _referral_sample(n=8000, seed=5):
|
||||
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred mostly when diseased
|
||||
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell: Phi(-1.6) = 5.5 %."""
|
||||
"""Two cells: the protocol refers the abnormal one (84 %); the normal one is referred\
|
||||
mostly when diseased
|
||||
(3.6 % healthy, 38 % diseased: gamma_g = 1.5). True prevalence of the normal cell:\
|
||||
Phi(-1.6) = 5.5 %."""
|
||||
rng = np.random.default_rng(seed)
|
||||
abnormal = (rng.random(n) < 0.2).astype(float)
|
||||
X = np.column_stack([np.ones(n), abnormal])
|
||||
@@ -71,10 +87,13 @@ def _referral_sample(n=8000, seed=5):
|
||||
|
||||
|
||||
def test_the_arc_removes_the_selection_bias():
|
||||
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred cell, or if the arc
|
||||
"""Fails if ignoring who gets referred does not overstate the prevalence of the unreferred\
|
||||
cell, or if the arc
|
||||
with an informative prior on gamma_g does not bring it back to the truth (5.5 %)."""
|
||||
X, r, y, U, arc = _referral_sample()
|
||||
common = dict(b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6)
|
||||
common = dict(
|
||||
b0=np.zeros(2), B0=np.eye(2) * 4, kappa_ab=(7000, 3000), iterations=1500, warmup=500, seed=6
|
||||
)
|
||||
without = PG.gibbs(X, r, y, **common)
|
||||
with_arc = PG.gibbs(X, r, y, U=U, arc=arc, d0=[0, 0, 1.5], D0=np.diag([4, 4, 0.09]), **common)
|
||||
assert norm.cdf(without["beta"][:, 0]).mean() > 0.2
|
||||
@@ -83,7 +102,8 @@ def test_the_arc_removes_the_selection_bias():
|
||||
|
||||
|
||||
def test_split_rhat():
|
||||
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different levels do not exceed 1.1."""
|
||||
"""Fails if well-mixed chains do not give R-hat near 1, or chains stuck at different\
|
||||
levels do not exceed 1.1."""
|
||||
rng = np.random.default_rng(7)
|
||||
assert abs(PG.split_rhat(rng.normal(size=(4, 2000))) - 1) < 0.01
|
||||
assert PG.split_rhat(rng.normal(size=(4, 2000)) + np.arange(4)[:, None]) > 1.1
|
||||
@@ -94,12 +114,15 @@ def test_patterns_keep_every_woman():
|
||||
X, r, y, U, arc = _referral_sample(n=500)
|
||||
d = PG.patterns(X, r, y, U, arc)
|
||||
assert d["n"].sum() == 500
|
||||
assert len(d["n"]) == len(np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0))
|
||||
assert len(d["n"]) == len(
|
||||
np.unique(np.column_stack([X, r, np.nan_to_num(y, nan=-1), U, arc]), axis=0)
|
||||
)
|
||||
|
||||
|
||||
def test_summed_likelihood_matches_a_direct_sum():
|
||||
pytest.importorskip("pymc") # optional dependency, not in the production environment
|
||||
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g) woman by woman."""
|
||||
"""Fails if the PyMC likelihood with g summed out differs from summing P(data | g) P(g)\
|
||||
woman by woman."""
|
||||
X, r, y, U, arc = _referral_sample(n=400)
|
||||
beta, kappa, delta = np.array([-1.0, 0.9]), 0.65, np.array([-1.5, 2.5, 1.2])
|
||||
model = PG.pymc_model(X, r, y, np.zeros(2), np.eye(2), (2, 2), U, arc, np.zeros(3), np.eye(3))
|
||||
@@ -107,8 +130,13 @@ def test_summed_likelihood_matches_a_direct_sum():
|
||||
point.update({"beta": beta, "kappa_logodds__": np.log(kappa / (1 - kappa)), "delta": delta})
|
||||
got = model.compile_logp(vars=model.potentials)(point)
|
||||
p = norm.cdf(X @ beta)
|
||||
pr = lambda shift: np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
||||
|
||||
def pr(shift):
|
||||
return np.where(r == 1, norm.cdf(shift), norm.sf(shift))
|
||||
|
||||
py1 = np.where(r == 1, np.where(y == 1, kappa, 1 - kappa), 1.0)
|
||||
py0 = np.where((r == 1) & (y == 1), 0.0, 1.0)
|
||||
direct = np.log(p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0).sum()
|
||||
direct = np.log(
|
||||
p * pr(U @ delta[:2] + delta[2] * arc) * py1 + (1 - p) * pr(U @ delta[:2]) * py0
|
||||
).sum()
|
||||
assert np.isclose(got, direct)
|
||||
|
||||
@@ -6,7 +6,7 @@ from models.cacu.development_firth import FirthFamily
|
||||
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('method', METHODS)
|
||||
@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])
|
||||
@@ -15,28 +15,28 @@ def test_methods_fit_simulated_data(method):
|
||||
|
||||
|
||||
def test_candidates_and_imputation_use_only_training_rows():
|
||||
train = pd.DataFrame({'a': [0., 1., np.nan, 1.], 'copy': [0., 1., np.nan, 1.],
|
||||
'absent': [np.nan] * 4})
|
||||
assert _candidates(train, 0.7, 5) == ['a']
|
||||
a, b = _matrix(train, pd.DataFrame({'a': [np.nan]}), ['a'])
|
||||
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]})
|
||||
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)
|
||||
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'):
|
||||
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)
|
||||
|
||||
|
||||
@@ -44,9 +44,9 @@ 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'
|
||||
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):
|
||||
@@ -58,26 +58,37 @@ def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypa
|
||||
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())
|
||||
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)
|
||||
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))
|
||||
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']
|
||||
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"]
|
||||
|
||||
@@ -10,4 +10,7 @@ def test_without_an_hpv_result_she_is_not_evaluated():
|
||||
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
|
||||
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
|
||||
found = f.index_results(events, cacu.KPNC)
|
||||
assert dict(zip(found["person_id"], found["hpv_positive"])) == {"negative": 0.0, "positive": 1.0}
|
||||
assert dict(zip(found["person_id"], found["hpv_positive"], strict=False)) == {
|
||||
"negative": 0.0,
|
||||
"positive": 1.0,
|
||||
}
|
||||
|
||||
@@ -68,7 +68,9 @@ def hpv_missing_as_the_current_platform_read_it(events: pd.DataFrame) -> pd.Data
|
||||
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
||||
has = events[(events["type"] == "hpv") & near]
|
||||
missing = index[~index["person_id"].isin(has["person_id"])]
|
||||
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed") # not positive, and not a negative visit
|
||||
assumed = missing.assign(
|
||||
date=missing["index_date"], type="hpv", value_code="assumed"
|
||||
) # not positive, and not a negative visit
|
||||
return pd.concat([events, assumed[events.columns]], ignore_index=True)
|
||||
|
||||
|
||||
@@ -100,8 +102,9 @@ def test_predictions_match_the_current_models(name):
|
||||
# Older reference intervals include non-estimable covariance estimates. Preserve
|
||||
# parity for point estimates and for intervals that remain estimable.
|
||||
comparable = both[ours].notna() if ours != "probability" else np.ones(len(both), bool)
|
||||
np.testing.assert_allclose(both.loc[comparable, ours], both.loc[comparable, theirs],
|
||||
rtol=RTOL, atol=0)
|
||||
np.testing.assert_allclose(
|
||||
both.loc[comparable, ours], both.loc[comparable, theirs], rtol=RTOL, atol=0
|
||||
)
|
||||
if spec.method != "logistic regression":
|
||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||
|
||||
@@ -128,7 +131,7 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
|
||||
"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)
|
||||
assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values'])
|
||||
assert all(set(json.loads(value)) == set(spec.features) for value in found["input_values"])
|
||||
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
|
||||
|
||||
@@ -7,12 +7,16 @@ from models.cacu.specs import _rows
|
||||
|
||||
|
||||
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
||||
members = pd.DataFrame([
|
||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||
])
|
||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5),
|
||||
("cytology", "hpv"))
|
||||
members = pd.DataFrame(
|
||||
[
|
||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||
]
|
||||
)
|
||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5), ("cytology", "hpv"))
|
||||
assert [json.loads(v) for v in result.input_values] == [
|
||||
{"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}]
|
||||
{"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "HSIL", "hpv": 1},
|
||||
{"cytology": "HSIL", "hpv": 1},
|
||||
]
|
||||
|
||||
@@ -10,8 +10,11 @@ def test_unestimable_covariances_never_produce_zero_width_intervals():
|
||||
X, Z = np.ones((1, 1)), np.empty((1, 0))
|
||||
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
|
||||
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
for covariance in (np.full((len(params), len(params)), np.nan),
|
||||
-np.eye(len(params)), np.zeros((len(params), len(params)))):
|
||||
for covariance in (
|
||||
np.full((len(params), len(params)), np.nan),
|
||||
-np.eye(len(params)),
|
||||
np.zeros((len(params), len(params))),
|
||||
):
|
||||
broken = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
|
||||
@@ -35,6 +38,6 @@ def test_diagnostics_count_rows_without_intervals():
|
||||
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
|
||||
model.seen_ = {(): {}}
|
||||
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
|
||||
assert report['strata'][0]['rows_without_interval'] == 2
|
||||
assert report['strata'][0]['negative_variances']
|
||||
assert report['strata'][0]['status'] == 'not_estimable'
|
||||
assert report["strata"][0]["rows_without_interval"] == 2
|
||||
assert report["strata"][0]["negative_variances"]
|
||||
assert report["strata"][0]["status"] == "not_estimable"
|
||||
|
||||
Reference in New Issue
Block a user