"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version its domain has in production. `estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`, `desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger set, so an estimator here ignores the wide frame and rebuilds the model's own input (`models.io.storage.KitBuild`): the cycle's latest build for membership, the domain's timeline for the events, then the production version in MLflow to score it at the horizons its run recorded (`horizons_years`). `estimar`'s arguments go unused by design. """ from dataclasses import dataclass from importlib import import_module from typing import Any @dataclass(frozen=True) class Provenance: modelo_nombre: str modelo_version: str mlflow_run_id: str modelo_sha: str | None def como_dict(self) -> dict[str, str]: return {key: value for key, value in self.__dict__.items() if value} class ScenarioEstimator: """Scores a domain's cohort with the version of one scenario that is in production (or `version`, to test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has something to report when `estimate` calls it.""" def __init__(self, domain: str, scenario: str, version: str | None = None): self.domain = domain self.scenario = scenario self.version = version self.desenlace = "" self._provenance: Provenance | None = None def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: import json import mlflow.pyfunc import numpy as np from models.dags.estimation import estimate_frame from models.dags.training import Scenario from models.io.registry import registered_name, registry from models.io.storage import KitBuild from models.steps.risks import risk_rows repos = import_module(f"persistance.{self.domain}") scenario = Scenario.load(self.domain, self.scenario) build_id = repos.cohort_repository.latest_build(scenario.cohort) resolved = registry.resolve(self.domain, scenario.scenario, self.version) frame = KitBuild(self.domain, build_id).frame() horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"]) probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(frame)) self.desenlace = scenario.outcome self._provenance = Provenance( modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version, mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha) return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))] def procedencia(self) -> Provenance: if self._provenance is None: raise RuntimeError("estimar() runs before procedencia()") return self._provenance class Cin2LogisticEstimator(ScenarioEstimator): """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`).""" def __init__(self, domain: str = "cacu", version: str | None = None): super().__init__(domain, "cin2_logistic", version) self.desenlace = "cin2_mas" # The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production # scores the cohort it names. LIVE_SCENARIOS = {"cama": ("survival",)} def _scenario_estimators(domain: str) -> dict[str, Any]: from models.dags.training import Scenario from models.io.registry import registry found = {} for name in LIVE_SCENARIOS.get(domain, ()): scenario = Scenario.load(domain, name) try: registry.resolve(domain, name) except LookupError: continue found[scenario.cohort] = ScenarioEstimator(domain, name) return found def live_estimators(domain: str) -> dict[str, Any]: """The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" if domain != "cacu": return _scenario_estimators(domain) from models.dags.training import Scenario from models.io.registry import registry scenario = Scenario.load(domain, "cin2_logistic") try: registry.resolve(domain, scenario.scenario) except LookupError: return {} return {scenario.cohort: Cin2LogisticEstimator(domain)}