Merge dev into the CaMa consolidation branch
This commit is contained in:
@@ -6,7 +6,10 @@ Each step is a function of `cycle.py`. It takes the `Context` and, as parameters
|
||||
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
|
||||
Persistance's repositories (`ctx.repos`), so each one can run on its own.
|
||||
|
||||
migrate -> catalogs, registry, definitions
|
||||
migrate -> catalogs, registry, definitions, score_ados2
|
||||
score_ados2 -> analyze_eeg (TEA: the ADOS-2 CSS and classification, quick)
|
||||
analyze_eeg -> relate_ados2, load (TEA: the EEG analysis)
|
||||
relate_ados2 -> load (TEA: the ADOS-2 association)
|
||||
catalogs -> load, check_silver
|
||||
load -> views, event_models, observe, check_silver
|
||||
registry -> observe
|
||||
|
||||
@@ -13,7 +13,7 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.eeg import live_eeg_analysis
|
||||
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
||||
from webapi.orchestration.estimators import live_estimators
|
||||
from webapi.orchestration.runner import run
|
||||
|
||||
@@ -45,7 +45,9 @@ def main(argv: list[str] | None = None) -> None:
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
|
||||
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project))
|
||||
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project),
|
||||
ados2_relation=live_ados2_relation(args.project),
|
||||
ados2_scoring=live_ados2_scoring(args.project))
|
||||
for paso in run(ctx, only=args.only):
|
||||
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
||||
|
||||
|
||||
@@ -42,5 +42,11 @@ class Context:
|
||||
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
|
||||
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
|
||||
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||
# The domain's ADOS-2 scoring (`webapi.orchestration.eeg.live_ados2_scoring`): run by the `score_ados2` step, it
|
||||
# writes each evaluation's CSS and classification from its items. Without it, that step does nothing.
|
||||
ados2_scoring: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||
# The domain's ADOS-2 association (`webapi.orchestration.eeg.live_ados2_relation`): run by the `relate_ados2` step
|
||||
# after the EEG analysis, it fits the model on the analysed EEGs. Without it, that step does nothing.
|
||||
ados2_relation: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
|
||||
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
|
||||
repos: Any = field(default=None, compare=False, repr=False)
|
||||
|
||||
@@ -82,17 +82,38 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
return counts
|
||||
|
||||
|
||||
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
def analyze_eeg(migrate: str, score_ados2: dict, ctx: Context) -> dict[str, int]:
|
||||
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
|
||||
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo`.
|
||||
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
|
||||
and `eeg_metrica_zona`.
|
||||
Waits for `score_ados2` only so the quick scoring doesn't queue behind a long analysis.
|
||||
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
|
||||
if ctx.eeg_analysis is None:
|
||||
return {}
|
||||
return asdict(ctx.eeg_analysis())
|
||||
|
||||
|
||||
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], ctx: Context) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis.
|
||||
def score_ados2(migrate: str, ctx: Context) -> dict:
|
||||
"""The CSS and classification of each ADOS-2 from its items, module, algorithm and the child's age
|
||||
(`ctx.ados2_scoring`), written to bronze before the association and `load` read them. Returns how many
|
||||
evaluations were scored; nothing without a scoring (every domain but TEA)."""
|
||||
if ctx.ados2_scoring is None:
|
||||
return {}
|
||||
return asdict(ctx.ados2_scoring())
|
||||
|
||||
|
||||
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
|
||||
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
|
||||
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
|
||||
the version and its counts; nothing without an association (every domain but TEA)."""
|
||||
if ctx.ados2_relation is None:
|
||||
return {}
|
||||
return asdict(ctx.ados2_relation())
|
||||
|
||||
|
||||
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], relate_ados2: dict, ctx: Context) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis and
|
||||
the ADOS-2 association.
|
||||
|
||||
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
|
||||
"""
|
||||
@@ -203,20 +224,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte
|
||||
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
|
||||
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
|
||||
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden
|
||||
`confirm-risks`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
lotes = {}
|
||||
for url in cohort_urls(ctx.project, _manifest(ctx)):
|
||||
estimador = ctx.estimators.get(url)
|
||||
if estimador is None:
|
||||
estimadores = ctx.estimators.get(url) or []
|
||||
if not estimadores:
|
||||
continue
|
||||
|
||||
def frame(sesion, url=url):
|
||||
@@ -226,8 +247,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
|
||||
armado_id, ancho = ctx.repos.gold.cohorts.read(frame)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[url] = ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
lotes[url] = []
|
||||
for estimador in estimadores:
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
|
||||
return lotes
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
|
||||
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load, and the
|
||||
ADOS-2 association fitted on what it left.
|
||||
|
||||
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
|
||||
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
|
||||
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
|
||||
`ADOS2_SCORING=off` leaves the ADOS-2 CSS and classification out of the cycle (`python -m models tea score-ados2`
|
||||
still computes them).
|
||||
`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it).
|
||||
"""
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
@@ -11,6 +15,8 @@ from typing import Any
|
||||
|
||||
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
|
||||
CLUSTERS = ("auto", "local", "remote", "sync")
|
||||
RELATION_ENV = "ADOS2_RELATION"
|
||||
SCORING_ENV = "ADOS2_SCORING"
|
||||
|
||||
|
||||
def cluster() -> str:
|
||||
@@ -27,3 +33,27 @@ def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
|
||||
from models.eeg_analysis import analyze_pending
|
||||
|
||||
return partial(analyze_pending, cluster=cluster())
|
||||
|
||||
|
||||
def live_ados2_relation(domain: str) -> Callable[[], Any] | None:
|
||||
"""The domain's ADOS-2 association for the cycle, or none: only TEA has one, and `off` leaves it out."""
|
||||
value = os.environ.get(RELATION_ENV, "on")
|
||||
if value not in ("on", "off"):
|
||||
raise ValueError(f"{RELATION_ENV} must be on or off, not {value!r}")
|
||||
if domain != "tea" or value == "off":
|
||||
return None
|
||||
from models.ados2_relation import relate
|
||||
|
||||
return relate
|
||||
|
||||
|
||||
def live_ados2_scoring(domain: str) -> Callable[[], Any] | None:
|
||||
"""The domain's ADOS-2 scoring for the cycle, or none: only TEA has one, and `off` leaves it out."""
|
||||
value = os.environ.get(SCORING_ENV, "on")
|
||||
if value not in ("on", "off"):
|
||||
raise ValueError(f"{SCORING_ENV} must be on or off, not {value!r}")
|
||||
if domain != "tea" or value == "off":
|
||||
return None
|
||||
from models.ados2_scoring import score_pending
|
||||
|
||||
return score_pending
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
|
||||
its domain has in production.
|
||||
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version
|
||||
of its domain in production, one batch per model.
|
||||
|
||||
`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
|
||||
@@ -11,7 +11,6 @@ unused by design.
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -38,12 +37,7 @@ class ScenarioEstimator:
|
||||
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.estimation import scored_frame
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.storage import KitBuild
|
||||
@@ -54,13 +48,11 @@ class ScenarioEstimator:
|
||||
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))]
|
||||
return [tuple(row) for row in risk_rows(scored_frame(resolved, frame))]
|
||||
|
||||
def procedencia(self) -> Provenance:
|
||||
if self._provenance is None:
|
||||
@@ -68,45 +60,19 @@ class ScenarioEstimator:
|
||||
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]:
|
||||
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
|
||||
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
|
||||
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
|
||||
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
|
||||
configured: `estimate` then does nothing."""
|
||||
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)
|
||||
found: dict[str, list[ScenarioEstimator]] = {}
|
||||
for name in registry.in_production(domain):
|
||||
try:
|
||||
registry.resolve(domain, name)
|
||||
scenario = Scenario.load(domain, name)
|
||||
except LookupError:
|
||||
continue
|
||||
found[scenario.cohort] = ScenarioEstimator(domain, name)
|
||||
found.setdefault(scenario.cohort, []).append(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)}
|
||||
|
||||
@@ -203,13 +203,20 @@ estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo"
|
||||
|
||||
[cacu.seguimiento.precedencia]
|
||||
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de
|
||||
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir).
|
||||
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de "CASO",
|
||||
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cinco, sin repetir).
|
||||
# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo).
|
||||
valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
|
||||
valor = ["CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.caso.grados]
|
||||
# Qué grados de biopsia hacen de la paciente un caso (ya tiene cáncer, invasor o in situ): su estatus es CASO, gane lo
|
||||
# que gane lo demás, y lo que se le sigue es la supervivencia. Opciones: grados de `GradoCIN`.
|
||||
valor = ["CIS", "CARCINOMA"]
|
||||
estado = "provisional"
|
||||
fuente = "Responsable del proyecto, 2026-11-22: un escenario para las pacientes que ya tienen cáncer, sobre el que se evalúa la supervivencia; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.colposcopia.evidencias]
|
||||
# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto):
|
||||
# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`
|
||||
|
||||
Reference in New Issue
Block a user