Indicators cycle recomputes the CaMa survival scenario points over each new build; the figure draws them

This commit is contained in:
Roberto Treviño Cervantes
2026-11-22 23:22:31 -06:00
parent 93649a0e27
commit 32483249c7
3 changed files with 101 additions and 5 deletions
+33
View File
@@ -109,6 +109,7 @@ def live_client(client, monkeypatch):
return {"n": 100, "escenario": name or "Toda la cohorte"}
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3"))
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: None)
monkeypatch.setattr(live, "scenario_masks", lambda frame: masks)
monkeypatch.setattr(live, "curves", curves)
model_analysis._ANSWERS.clear()
@@ -259,3 +260,35 @@ def test_the_figure_takes_the_points_the_version_published_for_the_scenario(live
assert published["COMB"] == {"S": [0.9] * 3, "low": [0.85] * 3, "high": [0.95] * 3}
assert live_client.holder.points is None
def test_the_cycle_computes_the_scenario_points_once_per_build_and_the_figure_takes_them(live_client, tmp_path, monkeypatch):
"""Pins down: `refresh_subgroups` runs the pipeline's survival stage over the latest build's members once and saves its
scenario points beside them; the figure then draws those points instead of the ones the version published when it trained,
and a new build replaces the file. Fails if the figure keeps the training's points after the data changed, or every cycle
reruns the stage for the same build."""
from models.cama.survival import development
from webapi import model_analysis
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
build = {"id": 8}
monkeypatch.setattr(model_analysis, "_current_build", lambda d, s: ("3", build["id"]))
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: (SimpleNamespace(config={"desarrollo": {}}), "model", None, "3"))
runs = []
def stage(labelled, desarrollo):
runs.append(build["id"])
return [{"modelo": m, "meses": h, "S": 0.7, "IC_inf": 0.6, "IC_sup": 0.8, "subgrupo": "< 45 años"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
monkeypatch.setattr(development, "subgroup_points", stage)
first = model_analysis.refresh_subgroups("cama")
again = model_analysis.refresh_subgroups("cama")
rows = model_analysis._subgroup_rows("cama", "survival", "3")
build["id"] = 9
model_analysis.refresh_subgroups("cama")
assert first == ["survival"] and again == [] and runs == [8, 9]
assert [r["S"] for r in rows if r["modelo"] == "COMB"] == [0.7] * 3
assert [p.name for p in (tmp_path / "modelos").glob("*-subgrupos.json")] == ["cama-survival-v3-armado9-subgrupos.json"]
+64 -2
View File
@@ -83,6 +83,68 @@ def _live_context(domain: str, scenario: str):
return _LIVE["value"]
def _subgroups_path(domain: str, scenario: str, version: str, build_id: int) -> Path:
return _members_path(domain, scenario, version, build_id).with_name(f"{domain}-{scenario}-v{version}-armado{build_id}-subgrupos.json")
def _current_build(domain: str, scenario: str) -> tuple[str, int] | None:
import importlib
from models.dags.training import Scenario
from models.io.registry import registry
try:
version = registry.resolve(domain, scenario).version
except LookupError:
return None
build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(Scenario.load(domain, scenario).cohort)
return (str(version), build_id) if build_id is not None else None
def refresh_subgroups(domain: str) -> list[str]:
"""Runs the pipeline's survival stage over the members of the latest build (`development.subgroup_points`) for each live
scenario whose build has none yet, and saves its scenario points beside the members; the scenarios it computed. Minutes:
the indicators cycle calls it, not a request."""
from models.cama.survival import development
done = []
for scenario in LIVE_SCENARIOS.get(domain, ()):
try:
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError:
continue
current = _current_build(domain, scenario)
if current is None:
continue
path = _subgroups_path(domain, scenario, *current)
if path.exists():
continue
rows = development.subgroup_points(labelled, spec.config.get("desarrollo", {}))
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
tmp.write_text(json.dumps(rows, default=str), encoding="utf-8")
tmp.replace(path)
for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*-subgrupos.json"):
if old != path:
old.unlink(missing_ok=True)
done.append(scenario)
return done
def _subgroup_rows(domain: str, scenario: str, version: str) -> list[dict]:
"""The scenario points of the latest build computed by the cycle (`refresh_subgroups`), or the ones the version published
when it trained while the cycle hasn't computed them."""
current = _current_build(domain, scenario)
if current is not None and current[0] == str(version):
path = _subgroups_path(domain, scenario, *current)
if path.exists():
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
log.warning("no se pudo leer %s", path)
return _summary(domain, scenario, version, table="subgrupos_puntos")
def warm(domain: str) -> list[str]:
"""Loads the live context of each of the domain's live scenarios (`LIVE_SCENARIOS`), leaving their members' file for every
reader; the scenarios it loaded. One without a version in production or a build is skipped."""
@@ -184,11 +246,11 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
spec, model, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
key = json.dumps({"v": version, "e": name}, default=str)
published = live.published_points(_subgroup_rows(domain, scenario, version), name)
key = json.dumps({"v": version, "e": name, "p": published}, default=str)
with _LOCK:
record = _ANSWERS.get(key)
if record is None:
published = live.published_points(_summary(domain, scenario, version, table="subgrupos_puntos"), name)
try:
record = live.curves(spec, model, labelled, name, published)
except live.QueryError as error:
+4 -3
View File
@@ -49,12 +49,13 @@ def _short(value: Any) -> str:
def _warm_models(dominio: str) -> dict[str, Any]:
"""Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build."""
from webapi.model_analysis import warm
"""Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build,
and their scenario points computed by the pipeline over those members."""
from webapi.model_analysis import refresh_subgroups, warm
started = time.monotonic()
try:
resumen = warm(dominio)
resumen = {"cargados": warm(dominio), "escenarios_recalculados": refresh_subgroups(dominio)}
except Exception as exc: # the indicators are already saved
log.exception("no se pudieron preparar los modelos de %s", dominio)
resumen = f"error: {type(exc).__name__}"