From d392cc02a53ec1e5772ca02d10b39f240f6bccc2 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 2 Dec 2026 23:04:01 -0600 Subject: [PATCH] Informar intervalos PIM no estimables --- models/cacu/pim.py | 49 +++++++++++++++++++++++-- models/cacu/reports.py | 3 +- models/jobs.py | 3 ++ tests/test_cacu_models.py | 6 ++- tests/test_pim_variance_availability.py | 40 ++++++++++++++++++++ 5 files changed, 95 insertions(+), 6 deletions(-) create mode 100644 tests/test_pim_variance_availability.py diff --git a/models/cacu/pim.py b/models/cacu/pim.py index d1939b8..eeacab5 100644 --- a/models/cacu/pim.py +++ b/models/cacu/pim.py @@ -149,9 +149,20 @@ class Fit: up[k] += step down[k] -= step gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step) - covariance = np.nan_to_num(self.covariance, nan=0.0) - variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient) - return self.risk(X, Z, years), np.maximum(variance, 0.0) + free = np.isfinite(np.diag(self.covariance)) + variance = np.full((len(X), len(years)), np.nan) + block = self.covariance[np.ix_(free, free)] + if block.size and np.isfinite(block).all() and np.allclose(block, block.T): + try: + positive = bool(np.all(np.linalg.eigvalsh(block) > 0)) + except np.linalg.LinAlgError: + positive = False + if positive: + values = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free]) + affected = np.any(np.abs(gradient[~free]) > 1e-10, axis=0) + valid = ~affected & np.isfinite(values) & (values >= 0) + variance[valid] = values[valid] + return self.risk(X, Z, years), variance def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit: @@ -258,8 +269,38 @@ class Mixture(BaseEstimator): point, variance = self.fits_[key].risk_with_variance( unique[:, :n_x], unique[:, n_x:], self.horizons_years ) - relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0) + relative = np.where(np.isfinite(variance), + np.sqrt(variance) / np.maximum(point, 1e-300), np.nan) band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1), np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip out[index[placed]] = band[inverse.ravel()] return out + + def variance_diagnostics(self, X: pd.DataFrame) -> dict: + """Per stratum covariance properties and input rows without a complete interval.""" + h = len(self.horizons_years) + result = [] + for key, index in self._groups(X): + f = self.fits_.get(key) + predictions = self.predict(X.iloc[index]) + missing = np.isnan(predictions[:, h:]).any(axis=1) + entry = {"stratum": [str(v) for v in key], "rows": len(index), + "rows_without_interval": int(missing.sum())} + if f is None: + entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[]) + else: + diagonal = np.diag(f.covariance) + frozen = np.flatnonzero(np.abs(f.params) >= FROZEN).tolist() + negative = np.flatnonzero(np.isfinite(diagonal) & (diagonal < 0)).tolist() + free = np.isfinite(diagonal) + block = f.covariance[np.ix_(free, free)] + try: + positive = bool(block.size and np.isfinite(block).all() + and np.allclose(block, block.T) + and (np.linalg.eigvalsh(block) > 0).all()) + except np.linalg.LinAlgError: + positive = False + entry.update(status="positive_definite" if positive else "not_estimable", + frozen_parameters=frozen, negative_variances=negative) + result.append(entry) + return {"strata": result, "horizons_years": list(self.horizons_years)} diff --git a/models/cacu/reports.py b/models/cacu/reports.py index 4014b1b..dc61b11 100644 --- a/models/cacu/reports.py +++ b/models/cacu/reports.py @@ -129,7 +129,8 @@ def _label(feature: str, value) -> str: def _band(curve, variance) -> tuple[list, list]: - relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0) + relative = np.where(np.isfinite(variance), + np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan) return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip diff --git a/models/jobs.py b/models/jobs.py index c405b37..ba4bd3e 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -71,6 +71,9 @@ class Jobs: "technical_validation": self.technical_validation(spec, metrics, data), "interpretability": self.interpretability(spec, fitted, data), } + if hasattr(fitted, "variance_diagnostics"): + found["variance_diagnostics"] = fitted.variance_diagnostics( + data["coded"][spec.features]) # Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # for its idle workers to time out (5 minutes) before it can end. get_reusable_executor().shutdown(wait=True) diff --git a/tests/test_cacu_models.py b/tests/test_cacu_models.py index 33349bf..3378a9b 100644 --- a/tests/test_cacu_models.py +++ b/tests/test_cacu_models.py @@ -81,7 +81,11 @@ def test_predictions_match_the_current_models(name): 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) + # 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) if spec.method != "logistic regression": assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all() diff --git a/tests/test_pim_variance_availability.py b/tests/test_pim_variance_availability.py new file mode 100644 index 0000000..2e969e9 --- /dev/null +++ b/tests/test_pim_variance_availability.py @@ -0,0 +1,40 @@ +import numpy as np +import pandas as pd + +from models.cacu.pim import Fit, ISpline, Mixture + + +def test_unestimable_covariances_never_produce_zero_width_intervals(): + baseline = ISpline((0.0, 1.0, 2.0), 2) + params = np.zeros(1 + baseline.n_params) + 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)))): + broken = Fit(1, 0, baseline, params, covariance, 0, True) + assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all() + + +def test_frozen_parameter_only_invalidates_horizons_it_affects(): + baseline = ISpline((0.0, 1.0, 2.0), 2) + params = np.zeros(1 + baseline.n_params) + covariance = np.eye(len(params)) + covariance[1, :] = np.nan + covariance[:, 1] = np.nan + fitted = Fit(1, 0, baseline, params, covariance, 0, True) + variance = fitted.risk_with_variance(np.ones((1, 1)), np.empty((1, 0)), [0, 1])[1] + assert np.isfinite(variance[0, 0]) + assert np.isnan(variance[0, 1]) + + +def test_diagnostics_count_rows_without_intervals(): + baseline = ISpline((0.0, 1.0, 2.0), 2) + params = np.zeros(1 + baseline.n_params) + model = Mixture((0, 1), (), (), {}) + 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'