Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d3d9cc3950 | |||
| 8c0ec5106c | |||
| b6857dab2a | |||
| bea3e4cd2d | |||
| 77fc039586 | |||
| 0c4706658b | |||
| 61721a8005 | |||
| 8d874736db | |||
| 79a55a7a62 | |||
| f1370d2776 | |||
| 639bbcda19 | |||
| 3558e24a46 |
-12
@@ -1,14 +1,2 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
|
||||||
.venv/
|
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.coverage
|
|
||||||
*.egg-info/
|
|
||||||
.env
|
|
||||||
uv.lock
|
|
||||||
|
|
||||||
# MLflow's own default local stores, used only when MLFLOW_TRACKING_URI
|
|
||||||
# isn't set (dev/tests point it elsewhere, e.g. a tmp_path file store).
|
|
||||||
mlflow.db
|
|
||||||
mlruns/
|
|
||||||
mlartifacts/
|
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
# models
|
|
||||||
|
|
||||||
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
|
|
||||||
versiones en MLflow con requisitos de promoción, registro de predicciones y
|
|
||||||
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
|
|
||||||
armados del kit de indicadores (`cohorte_armado`, en la base de cada
|
|
||||||
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
|
|
||||||
WebApi.
|
|
||||||
|
|
||||||
| Módulo | Qué hace |
|
|
||||||
|---|---|
|
|
||||||
| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. |
|
|
||||||
| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. |
|
|
||||||
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
|
|
||||||
| `registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
|
|
||||||
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
|
||||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
|
||||||
| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
|
||||||
|
|
||||||
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
|
|
||||||
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
|
|
||||||
guardan sus artefactos.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv run pytest -q
|
|
||||||
```
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import importlib
|
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from typing import Any, ClassVar, Iterator
|
|
||||||
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(domain: str, entity: str) -> Repository:
|
|
||||||
"""`entity` is the repository's name in `persistance.<domain>` without
|
|
||||||
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
|
||||||
module = importlib.import_module(f"persistance.{domain}")
|
|
||||||
try:
|
|
||||||
return getattr(module, f"{entity}_repository")
|
|
||||||
except AttributeError as exc:
|
|
||||||
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
|
||||||
|
|
||||||
|
|
||||||
class ScreeningModel(ABC):
|
|
||||||
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
|
|
||||||
|
|
||||||
Data is read through the same `persistance.<domain>.<entity>_repository`
|
|
||||||
objects WebApi writes with, so anything loaded through the import flow
|
|
||||||
is visible here. `train` may also be given rows fetched by the caller.
|
|
||||||
"""
|
|
||||||
|
|
||||||
domain: ClassVar[str]
|
|
||||||
|
|
||||||
def repository(self, entity: str) -> Repository:
|
|
||||||
return resolve_repository(self.domain, entity)
|
|
||||||
|
|
||||||
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
|
|
||||||
"""Every row of `entity` as plain dicts, read in batches."""
|
|
||||||
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def train(self, data: Any = None) -> None:
|
|
||||||
"""Fit the model, optionally on `data` passed in by the caller."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def predict(self, data: Any) -> Any:
|
|
||||||
"""Score `data` and return predictions."""
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
from typing import Any
|
|
||||||
|
|
||||||
from models.base import ScreeningModel
|
|
||||||
|
|
||||||
|
|
||||||
class CaCuModel(ScreeningModel):
|
|
||||||
"""Scaffold for the CaCu (cervical cancer) screening model.
|
|
||||||
|
|
||||||
Can pull its own training data straight from `persistance.cacu`'s
|
|
||||||
repositories (`paciente_repository`, `citologia_cervical_repository`,
|
|
||||||
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
|
|
||||||
No real model yet; this is interface scaffolding only.
|
|
||||||
"""
|
|
||||||
|
|
||||||
domain = "cacu"
|
|
||||||
|
|
||||||
def train(self, data: Any = None) -> None:
|
|
||||||
raise NotImplementedError("CaCu training is not implemented yet.")
|
|
||||||
|
|
||||||
def predict(self, data: Any) -> Any:
|
|
||||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""What the CaCu models read from a patient's timeline (gold `cacu_events`): one row per
|
||||||
|
event, with the patient's cohort index date. Columns: person_id, index_date, date, type,
|
||||||
|
value_code, value_num, source_table, source_id."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from core import cacu
|
||||||
|
|
||||||
|
RESULTS = ("bethesda", "glandular", "hpv") # what a cytology sample reports
|
||||||
|
REFERRED = ("colposcopy", "biopsy") # once either happened, screening is over
|
||||||
|
MISSING = "(none)"
|
||||||
|
|
||||||
|
|
||||||
|
def prepared(events: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
return events.assign(
|
||||||
|
date=pd.to_datetime(events["date"]), index_date=pd.to_datetime(events["index_date"])
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def days(events: pd.DataFrame) -> pd.Series:
|
||||||
|
return (events["date"] - events["index_date"]).dt.days
|
||||||
|
|
||||||
|
|
||||||
|
def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
|
||||||
|
"""Per patient (the index of `codes`), her most severe result as its cytology category."""
|
||||||
|
rank = {code: i for i, values in enumerate(cytology.values()) for code in values}
|
||||||
|
names = list(cytology)
|
||||||
|
worst = codes.map(rank).groupby(level=0).max()
|
||||||
|
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
|
||||||
|
|
||||||
|
|
||||||
|
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
|
||||||
|
"""Why she was referred: the worst result in the year before her first colposcopy."""
|
||||||
|
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
|
||||||
|
before = (events["person_id"].map(first) - events["date"]).dt.days
|
||||||
|
near = events[before.between(0, history["lookback_days"])]
|
||||||
|
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
|
||||||
|
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
||||||
|
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
||||||
|
positive = persons.isin(hpv["person_id"])
|
||||||
|
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
|
||||||
|
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
|
||||||
|
& positive.to_numpy()), "low", None)) # fmt: skip
|
||||||
|
return pd.Series(grade, index=persons.index, dtype=object)
|
||||||
|
|
||||||
|
|
||||||
|
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
|
||||||
|
"""Per patient: the cytology category and HPV result of her index sample (the first
|
||||||
|
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
|
||||||
|
when `history` asks for it."""
|
||||||
|
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
|
||||||
|
wide = near.sort_values("date", kind="stable").pivot_table(
|
||||||
|
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||||
|
)
|
||||||
|
members = events.groupby("person_id", as_index=False)["index_date"].first()
|
||||||
|
wide = wide.reindex(index=members["person_id"], columns=list(RESULTS))
|
||||||
|
codes = wide[["bethesda", "glandular"]].stack()
|
||||||
|
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
|
||||||
|
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
|
||||||
|
if history:
|
||||||
|
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
|
||||||
|
return members
|
||||||
|
|
||||||
|
|
||||||
|
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
|
||||||
|
"""Days at which she was seen free of the outcome: a biopsy below `grades`, or a
|
||||||
|
negative co-test (the later day of its two results)."""
|
||||||
|
timed = events.assign(days=d.astype(float))[d >= 0]
|
||||||
|
biopsies = timed[(timed["type"] == "biopsy") & ~timed["value_code"].isin(grades)]
|
||||||
|
visits = None
|
||||||
|
for kind, values in cacu.KNOWN_NEGATIVE.items():
|
||||||
|
found = timed[(timed["type"] == kind) & timed["value_code"].isin(values)]
|
||||||
|
found = found[["person_id", "days"]]
|
||||||
|
if visits is None:
|
||||||
|
visits = found
|
||||||
|
continue
|
||||||
|
paired = pd.merge_asof(
|
||||||
|
visits.sort_values("days"), found.rename(columns={"days": kind}).sort_values(kind),
|
||||||
|
left_on="days", right_on=kind, by="person_id", direction="nearest",
|
||||||
|
tolerance=float(cacu.INDEX_SAMPLE_DAYS),
|
||||||
|
).dropna(subset=[kind]) # fmt: skip
|
||||||
|
visits = paired.assign(days=paired[["days", kind]].max(axis=1))[["person_id", "days"]]
|
||||||
|
return pd.concat([biopsies[["person_id", "days"]], visits], ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
|
||||||
|
history: dict | None = None) -> pd.DataFrame: # fmt: skip
|
||||||
|
"""Index features plus the outcome as (c, l, r): prevalent (an outcome biopsy within
|
||||||
|
the prevalent window), free at the index (a negative before any outcome), or unknown;
|
||||||
|
and the years between her last negative and her outcome biopsy."""
|
||||||
|
d = days(events)
|
||||||
|
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades) & (d >= 0)
|
||||||
|
first = d[outcome].groupby(events.loc[outcome, "person_id"]).min()
|
||||||
|
negatives = _negatives(events, d, grades)
|
||||||
|
before = ~(negatives["days"] >= negatives["person_id"].map(first))
|
||||||
|
last_negative = negatives[before].groupby("person_id")["days"].max()
|
||||||
|
|
||||||
|
coded = index_results(events, cytology, history)
|
||||||
|
window = cacu.PREVALENT_WINDOW_DAYS
|
||||||
|
event_days, free_until = coded["person_id"].map(first), coded["person_id"].map(last_negative)
|
||||||
|
prevalent = event_days <= window
|
||||||
|
free = free_until.notna() & ~prevalent
|
||||||
|
later = event_days.notna() & ~prevalent
|
||||||
|
coded["c"] = np.where(prevalent, 1, np.where(free, 0, -999))
|
||||||
|
coded["l"] = np.where(free & (free_until > window), free_until / cacu.DAYS_PER_YEAR, 0.0)
|
||||||
|
coded["r"] = np.where(prevalent, 0.0,
|
||||||
|
np.where(later, event_days / cacu.DAYS_PER_YEAR, np.inf)) # fmt: skip
|
||||||
|
return coded
|
||||||
|
|
||||||
|
|
||||||
|
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||||
|
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
|
||||||
|
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
|
||||||
|
key = ["person_id", "source_table", "source_id"]
|
||||||
|
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||||
|
[*key, "date"]] # fmt: skip
|
||||||
|
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||||
|
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||||
|
has = has.reindex(columns=list(RESULTS))
|
||||||
|
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["hpv"].notna()]
|
||||||
|
samples = samples.set_index(key)
|
||||||
|
samples = samples[samples.index.isin(complete.index)].reset_index()
|
||||||
|
latest = samples.sort_values(["person_id", "date", "source_id"]).groupby("person_id").last()
|
||||||
|
return latest["date"]
|
||||||
|
|
||||||
|
|
||||||
|
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||||
|
"""Temporal: the earliest index dates train, the latest test."""
|
||||||
|
ordered = members.sort_values(["index_date", "person_id"], kind="stable")
|
||||||
|
cut = int(len(ordered) * train_fraction)
|
||||||
|
return ordered.iloc[:cut], ordered.iloc[cut:]
|
||||||
|
|
||||||
|
|
||||||
|
def index_sample(events: pd.DataFrame, predictors: list[str]) -> pd.DataFrame:
|
||||||
|
"""Per patient: each predictor's result on her index sample, MISSING when none."""
|
||||||
|
members = events.groupby(["person_id", "index_date"], as_index=False).size()
|
||||||
|
members = members[["person_id", "index_date"]]
|
||||||
|
sample = events[(events["type"] == "cytology") & (events["date"] == events["index_date"])]
|
||||||
|
sample = sample.groupby("person_id", as_index=False)[["source_table", "source_id"]].first()
|
||||||
|
results = events.merge(sample, on=["person_id", "source_table", "source_id"])
|
||||||
|
genotype = results["type"] == "hpv_16_18"
|
||||||
|
results.loc[genotype, "value_code"] = results.loc[genotype, "value_num"].map(
|
||||||
|
{1.0: "positive", 0.0: "negative"}
|
||||||
|
)
|
||||||
|
wide = results[results["type"].isin(predictors)].pivot_table(
|
||||||
|
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||||
|
)
|
||||||
|
wide = wide.reindex(columns=list(predictors)).astype(object)
|
||||||
|
found = members.merge(wide, left_on="person_id", right_index=True, how="left")
|
||||||
|
return found.fillna(dict.fromkeys(predictors, MISSING))
|
||||||
|
|
||||||
|
|
||||||
|
def windowed_outcome(events: pd.DataFrame, grades: list[str], years: float,
|
||||||
|
follow_up_end: pd.Timestamp) -> pd.DataFrame: # fmt: skip
|
||||||
|
"""y: an outcome biopsy within `years` of the index; known: y, or followed that long."""
|
||||||
|
window = years * cacu.DAYS_PER_YEAR
|
||||||
|
outcome = (events["type"] == "biopsy") & events["value_code"].isin(grades)
|
||||||
|
outcome &= days(events).between(0, window)
|
||||||
|
members = events.groupby(["person_id", "index_date"], as_index=False).size()
|
||||||
|
members["y"] = members["person_id"].isin(events.loc[outcome, "person_id"]).astype(int)
|
||||||
|
followed = (follow_up_end - members["index_date"]).dt.days
|
||||||
|
members["known"] = (members["y"] == 1) | (followed >= window)
|
||||||
|
return members[["person_id", "y", "known"]]
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Training and scoring of the CaCu models: what the Dagster jobs run."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import mlflow.pyfunc
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from models.cacu import reports
|
||||||
|
from models.cacu.specs import MODELS
|
||||||
|
from persistance import gold, registry
|
||||||
|
|
||||||
|
EVENTS = "cacu_events"
|
||||||
|
|
||||||
|
|
||||||
|
def registered(name: str) -> str:
|
||||||
|
return f"cacu.{name}"
|
||||||
|
|
||||||
|
|
||||||
|
class Predictor(mlflow.pyfunc.PythonModel):
|
||||||
|
"""A fitted CaCu model as MLflow serves it: patient timelines in (gold `cacu_events`
|
||||||
|
rows with each patient's index date), one row per patient and horizon out."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, fitted):
|
||||||
|
self.name, self.fitted = name, fitted
|
||||||
|
|
||||||
|
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||||
|
return MODELS[self.name].predict(self.fitted, model_input)
|
||||||
|
|
||||||
|
|
||||||
|
def train(name: str, as_of: date | None = None) -> int:
|
||||||
|
"""A new registered version of the model, trained on its cohort's timelines up to
|
||||||
|
`as_of` (default: today), with its metrics and its two generated reports."""
|
||||||
|
spec, as_of = MODELS[name], as_of or date.today()
|
||||||
|
events = gold.timelines(EVENTS, spec.cohort, as_of)
|
||||||
|
args = (as_of,) if spec.method == "logistic regression" else ()
|
||||||
|
fitted, metrics, data = spec.train(events, *args)
|
||||||
|
found = {
|
||||||
|
"technical_validation": reports.technical_validation(spec, metrics, data),
|
||||||
|
"interpretability": reports.interpretability(spec, fitted, data),
|
||||||
|
}
|
||||||
|
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
||||||
|
return registry.register(registered(name), Predictor(name, fitted), params, metrics, found)
|
||||||
|
|
||||||
|
|
||||||
|
def score(name: str) -> int | None:
|
||||||
|
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
||||||
|
batch; None when the model has no champion yet."""
|
||||||
|
found = registry.champion(registered(name))
|
||||||
|
if found is None:
|
||||||
|
return None
|
||||||
|
version, model = found
|
||||||
|
risks = model.predict(gold.timelines(EVENTS, MODELS[name].cohort))
|
||||||
|
gold.save_scores(registered(name), version, risks)
|
||||||
|
return version
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
"""Prevalence-incidence mixture for interval-censored outcomes (PIMixture, Cheung et al.).
|
||||||
|
|
||||||
|
A patient either has the outcome at the index visit (prevalence, a logistic model) or may
|
||||||
|
develop it later (incidence, a proportional-hazards model with an I-spline baseline). Each
|
||||||
|
patient is coded `c` = 1 (prevalent), 0 (known free at the index), or UNKNOWN, with the
|
||||||
|
interval (l, r] in years where an incident outcome happened. No library fits this model, so
|
||||||
|
the likelihood is written here; everything else is scipy.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from scipy.interpolate import BSpline
|
||||||
|
from scipy.optimize import minimize
|
||||||
|
from scipy.special import expit
|
||||||
|
from scipy.stats import norm
|
||||||
|
from sklearn.base import BaseEstimator
|
||||||
|
|
||||||
|
UNKNOWN = -999
|
||||||
|
TINY = 1e-12 # floor inside every log
|
||||||
|
FROZEN = 15.0 # a parameter this far out sits on the boundary: fixed, not estimated
|
||||||
|
HESSIAN_STEP = 1e-4
|
||||||
|
|
||||||
|
|
||||||
|
def ispline_basis(t, degree: int, knots) -> np.ndarray:
|
||||||
|
"""Integrated B-splines: monotone from 0 at the first knot to 1 at the last."""
|
||||||
|
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
|
||||||
|
full = np.r_[np.repeat(knots[0], degree + 1), knots[1:-1], np.repeat(knots[-1], degree + 1)]
|
||||||
|
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
|
||||||
|
bsplines = BSpline.design_matrix(inside, full, degree, extrapolate=False).toarray()
|
||||||
|
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
|
||||||
|
basis[t >= knots[-1]] = 1.0
|
||||||
|
basis[t <= knots[0]] = 0.0
|
||||||
|
return basis
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ISpline:
|
||||||
|
"""Baseline cumulative hazard: I-splines with non-negative (exp) coefficients."""
|
||||||
|
|
||||||
|
knots: tuple[float, ...]
|
||||||
|
degree: int
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def at_quantiles(cls, l, r, n_knots: int, degree: int) -> "ISpline":
|
||||||
|
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
||||||
|
return cls(tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots))), degree)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def n_params(self) -> int:
|
||||||
|
return len(self.knots) + self.degree - 2
|
||||||
|
|
||||||
|
def cumulative_hazard(self, t, params) -> np.ndarray:
|
||||||
|
return ispline_basis(t, self.degree, self.knots) @ np.exp(params)
|
||||||
|
|
||||||
|
def start(self, c, l, r) -> np.ndarray:
|
||||||
|
"""Every coefficient equal, so the hazard is the crude event rate."""
|
||||||
|
at_risk, finite = c != 1, np.isfinite(r)
|
||||||
|
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
|
||||||
|
events = (at_risk & finite & (r > 0)).sum()
|
||||||
|
# exp(-log(...)), not a plain division: on a flat likelihood BFGS follows the start's
|
||||||
|
# last bit, and this is the start the current models were fitted from.
|
||||||
|
rate = np.exp(-np.log(max(exposure, 1e-6) / (events + 0.5)))
|
||||||
|
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
|
||||||
|
|
||||||
|
|
||||||
|
def survival(t, baseline: ISpline, baseline_params, beta, Z) -> np.ndarray:
|
||||||
|
t = np.asarray(t, dtype=float)
|
||||||
|
with np.errstate(over="ignore", invalid="ignore"):
|
||||||
|
found = np.exp(-baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta))
|
||||||
|
found = np.where(t <= 0, 1.0, found)
|
||||||
|
return np.where(np.isinf(t), 0.0, found)
|
||||||
|
|
||||||
|
|
||||||
|
def neg_loglik(params, c, l, r, X, Z, baseline: ISpline, w) -> float:
|
||||||
|
n_x, n_z = X.shape[1], Z.shape[1]
|
||||||
|
theta, beta, rest = params[:n_x], params[n_x : n_x + n_z], params[n_x + n_z :]
|
||||||
|
pi = expit(X @ theta)
|
||||||
|
interval = survival(l, baseline, rest, beta, Z) - survival(r, baseline, rest, beta, Z)
|
||||||
|
interval = np.maximum(interval, TINY)
|
||||||
|
row = np.zeros(len(c))
|
||||||
|
prevalent, free, unknown = c == 1, c == 0, c == UNKNOWN
|
||||||
|
row[prevalent] = np.log(pi[prevalent] + TINY)
|
||||||
|
row[free] = np.log(1 - pi[free] + TINY) + np.log(interval[free])
|
||||||
|
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
||||||
|
return -np.sum(w * row)
|
||||||
|
|
||||||
|
|
||||||
|
def hessian(f, x, step: float = HESSIAN_STEP) -> np.ndarray:
|
||||||
|
"""Central-difference Hessian of f at x."""
|
||||||
|
p = len(x)
|
||||||
|
out = np.zeros((p, p))
|
||||||
|
for i in range(p):
|
||||||
|
for j in range(i, p):
|
||||||
|
ei, ej = np.zeros(p), np.zeros(p)
|
||||||
|
ei[i], ej[j] = step, step
|
||||||
|
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (
|
||||||
|
4 * step * step
|
||||||
|
)
|
||||||
|
out[i, j] = out[j, i] = value
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _ridge_logistic(c, X, ridge: float = 1e-3) -> np.ndarray:
|
||||||
|
"""Prevalence coefficients from the patients whose index status is known."""
|
||||||
|
known = c != UNKNOWN
|
||||||
|
if not known.any():
|
||||||
|
return np.zeros(X.shape[1])
|
||||||
|
y, Xk = (c[known] == 1).astype(float), X[known]
|
||||||
|
|
||||||
|
def loss(theta):
|
||||||
|
eta = Xk @ theta
|
||||||
|
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
|
||||||
|
|
||||||
|
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Fit:
|
||||||
|
n_x: int
|
||||||
|
n_z: int
|
||||||
|
baseline: ISpline
|
||||||
|
params: np.ndarray
|
||||||
|
covariance: np.ndarray # NaN where a parameter is frozen
|
||||||
|
neg_loglik: float
|
||||||
|
converged: bool
|
||||||
|
|
||||||
|
def risk(self, X, Z, years, params=None) -> np.ndarray:
|
||||||
|
"""Cumulative risk at each horizon: prevalent, or incident by then."""
|
||||||
|
p = self.params if params is None else params
|
||||||
|
theta, beta, rest = (
|
||||||
|
p[: self.n_x],
|
||||||
|
p[self.n_x : self.n_x + self.n_z],
|
||||||
|
p[self.n_x + self.n_z :],
|
||||||
|
)
|
||||||
|
pi = expit(X @ theta)
|
||||||
|
return np.column_stack([
|
||||||
|
pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), self.baseline, rest, beta, Z))
|
||||||
|
for t in years
|
||||||
|
]) # fmt: skip
|
||||||
|
|
||||||
|
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
|
||||||
|
"""Risk and its delta-method variance (central-difference gradient)."""
|
||||||
|
gradient = np.empty((len(self.params), len(X), len(years)))
|
||||||
|
for k, value in enumerate(self.params):
|
||||||
|
step = 1e-5 * max(1.0, abs(value))
|
||||||
|
up, down = self.params.copy(), self.params.copy()
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
||||||
|
"""Maximum likelihood from two starts (BFGS); covariance from the numerical Hessian."""
|
||||||
|
n_x, n_z = X.shape[1], Z.shape[1]
|
||||||
|
start = baseline.start(c, l, r)
|
||||||
|
starts = [np.r_[_ridge_logistic(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x + n_z), start]]
|
||||||
|
args = (c, l, r, X, Z, baseline, w)
|
||||||
|
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
|
||||||
|
best = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
|
||||||
|
free = np.abs(best.x) < FROZEN
|
||||||
|
covariance = np.full((len(best.x), len(best.x)), np.nan)
|
||||||
|
h = hessian(lambda p: neg_loglik(p, *args), best.x)
|
||||||
|
try:
|
||||||
|
covariance[np.ix_(free, free)] = np.linalg.inv(h[np.ix_(free, free)])
|
||||||
|
except np.linalg.LinAlgError:
|
||||||
|
pass
|
||||||
|
converged = bool(np.max(np.abs(best.jac[free]), initial=0.0) < 1e-3)
|
||||||
|
return Fit(n_x, n_z, baseline, best.x, covariance, float(best.fun), converged)
|
||||||
|
|
||||||
|
|
||||||
|
class Mixture(BaseEstimator):
|
||||||
|
"""One mixture per stratum. Categorical features get one dummy per level after the first
|
||||||
|
level seen in the stratum (`levels` gives their order); rows at a level the stratum never
|
||||||
|
saw are left out. Every feature enters prevalence; `incidence_features` also incidence."""
|
||||||
|
|
||||||
|
def __init__(self, horizons_years, incidence_features, strata, levels, knots=3, degree=4,
|
||||||
|
interval_level=0.95): # fmt: skip
|
||||||
|
self.horizons_years = horizons_years
|
||||||
|
self.incidence_features = incidence_features
|
||||||
|
self.strata = strata
|
||||||
|
self.levels = levels
|
||||||
|
self.knots = knots
|
||||||
|
self.degree = degree
|
||||||
|
self.interval_level = interval_level
|
||||||
|
|
||||||
|
def _seen(self, X: pd.DataFrame) -> dict:
|
||||||
|
return {
|
||||||
|
f: [v for v in values if (X[f] == v).any()]
|
||||||
|
for f, values in self.levels.items()
|
||||||
|
if f in X.columns and f not in self.strata
|
||||||
|
}
|
||||||
|
|
||||||
|
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
|
||||||
|
if not seen:
|
||||||
|
return np.ones(len(X), dtype=bool)
|
||||||
|
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0)
|
||||||
|
|
||||||
|
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
|
||||||
|
columns = []
|
||||||
|
for f in features:
|
||||||
|
if f in self.strata:
|
||||||
|
continue
|
||||||
|
if f in seen:
|
||||||
|
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
|
||||||
|
else:
|
||||||
|
columns.append(X[f].to_numpy(dtype=float))
|
||||||
|
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
|
||||||
|
|
||||||
|
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
||||||
|
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
||||||
|
return prevalence, self._columns(X, self.incidence_features, seen)
|
||||||
|
|
||||||
|
def _groups(self, X: pd.DataFrame):
|
||||||
|
if not self.strata:
|
||||||
|
return [((), np.arange(len(X)))]
|
||||||
|
groups = X.groupby(list(self.strata), sort=True).indices.items()
|
||||||
|
return [(key if isinstance(key, tuple) else (key,), rows) for key, rows in groups]
|
||||||
|
|
||||||
|
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
|
||||||
|
"""X: the features; y: c, l, r. Identical rows are fitted once, weighted."""
|
||||||
|
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)],
|
||||||
|
axis=1).assign(w=1.0) # fmt: skip
|
||||||
|
self.fits_, self.seen_ = {}, {}
|
||||||
|
for key, index in self._groups(X):
|
||||||
|
group = rows.iloc[index]
|
||||||
|
seen = self._seen(group)
|
||||||
|
group = group[self._placed(group, seen)]
|
||||||
|
group = group.groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
|
||||||
|
prevalence, incidence = self._design(group[X.columns], seen)
|
||||||
|
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||||
|
baseline = ISpline.at_quantiles(l, r, self.knots, self.degree)
|
||||||
|
self.seen_[key] = seen
|
||||||
|
self.fits_[key] = fit(c, l, r, prevalence, incidence, baseline, group["w"].to_numpy())
|
||||||
|
self.neg_loglik_ = float(sum(f.neg_loglik for f in self.fits_.values()))
|
||||||
|
self.converged_ = all(f.converged for f in self.fits_.values())
|
||||||
|
return self
|
||||||
|
|
||||||
|
def predict(self, X: pd.DataFrame) -> np.ndarray:
|
||||||
|
"""Per row and horizon: (risk, low, high) as three blocks of columns; NaN where the
|
||||||
|
row's stratum or level was never seen."""
|
||||||
|
h = len(self.horizons_years)
|
||||||
|
out = np.full((len(X), 3 * h), np.nan)
|
||||||
|
z = norm.ppf(0.5 + self.interval_level / 2)
|
||||||
|
for key, index in self._groups(X):
|
||||||
|
if key not in self.fits_:
|
||||||
|
continue
|
||||||
|
members = X.iloc[index]
|
||||||
|
placed = self._placed(members, self.seen_[key])
|
||||||
|
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||||
|
design = np.column_stack([prevalence, incidence])
|
||||||
|
unique, inverse = np.unique(design, axis=0, return_inverse=True)
|
||||||
|
n_x = prevalence.shape[1]
|
||||||
|
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)
|
||||||
|
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
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""The two reports training writes for each model version (the third, the clinical
|
||||||
|
validation, is a document the clinical team adds). Both are data the governance page draws.
|
||||||
|
|
||||||
|
- technical validation: how the version was trained and tested, and its held-out metrics;
|
||||||
|
- interpretability: what drives its predictions. For the mixture, observed against
|
||||||
|
predicted risk per combination of its features: the Turnbull estimate (the
|
||||||
|
nonparametric cumulative risk under interval censoring) with a bootstrap band, the
|
||||||
|
model's curve with its delta-method band, and expected over observed at each horizon.
|
||||||
|
For the logistic regression, its coefficients and calibration by risk decile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from scipy.stats import norm
|
||||||
|
from sklearn.metrics import brier_score_loss
|
||||||
|
|
||||||
|
from models.cacu.pim import Mixture
|
||||||
|
from models.cacu.specs import Logistic, Pim
|
||||||
|
|
||||||
|
GRID_STEP = 0.1 # years between points of a curve
|
||||||
|
BOOTSTRAP = 200
|
||||||
|
SEED = 20261122
|
||||||
|
Z = norm.ppf(0.975)
|
||||||
|
|
||||||
|
|
||||||
|
def technical_validation(spec: Pim | Logistic, metrics: dict, data: dict) -> dict:
|
||||||
|
members = data.get("coded", data.get("labelled"))
|
||||||
|
return {
|
||||||
|
"model": spec.name,
|
||||||
|
"method": spec.method,
|
||||||
|
"cohort": spec.cohort,
|
||||||
|
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
|
||||||
|
"members": len(members),
|
||||||
|
"index_dates": [str(members["index_date"].min()), str(members["index_date"].max())],
|
||||||
|
"metrics": metrics,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
|
||||||
|
"""Turnbull's EM: support points and cumulative risk at each. A prevalent case's event
|
||||||
|
is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r]."""
|
||||||
|
finite = r[np.isfinite(r)]
|
||||||
|
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
|
||||||
|
low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
|
||||||
|
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
|
||||||
|
patterns, counts = np.unique(inside, axis=0, return_counts=True)
|
||||||
|
p = np.full(len(support), 1 / len(support))
|
||||||
|
for _ in range(iters):
|
||||||
|
weighted = patterns * p
|
||||||
|
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
|
||||||
|
done = np.max(np.abs(new - p)) < tol
|
||||||
|
p = new
|
||||||
|
if done:
|
||||||
|
break
|
||||||
|
return support, np.cumsum(p)
|
||||||
|
|
||||||
|
|
||||||
|
def _at(support, cumulative, t) -> np.ndarray:
|
||||||
|
i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
|
||||||
|
return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)])
|
||||||
|
|
||||||
|
|
||||||
|
def _label(feature: str, value) -> str:
|
||||||
|
if value is None or (isinstance(value, float) and np.isnan(value)):
|
||||||
|
return "NA"
|
||||||
|
if feature == "hpv_positive":
|
||||||
|
return "positive" if float(value) == 1.0 else "negative"
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _band(curve, variance) -> tuple[list, list]:
|
||||||
|
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
||||||
|
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||||
|
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
|
||||||
|
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
|
||||||
|
if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all():
|
||||||
|
return None
|
||||||
|
prevalence, incidence = mixture._design(row, mixture.seen_[key])
|
||||||
|
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
|
||||||
|
return point[0], variance[0]
|
||||||
|
|
||||||
|
|
||||||
|
def interpretability(spec: Pim | Logistic, model, data: dict) -> dict:
|
||||||
|
if isinstance(spec, Logistic):
|
||||||
|
return _logistic(model, data["test"])
|
||||||
|
coded = data["coded"]
|
||||||
|
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
|
||||||
|
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
|
||||||
|
members = coded.reset_index(drop=True)
|
||||||
|
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
|
||||||
|
horizons = np.asarray(spec.horizons, dtype=float)
|
||||||
|
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
|
||||||
|
rng = np.random.default_rng(SEED)
|
||||||
|
groups = []
|
||||||
|
for _, combination in labels.drop_duplicates().iterrows():
|
||||||
|
mask = (labels == combination).all(axis=1).to_numpy()
|
||||||
|
group = members[mask]
|
||||||
|
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
|
||||||
|
support, cumulative = turnbull(c, l, r)
|
||||||
|
boot_grid, boot_h = [], []
|
||||||
|
for _ in range(BOOTSTRAP):
|
||||||
|
pick = rng.integers(0, len(group), len(group))
|
||||||
|
s, cum = turnbull(c[pick], l[pick], r[pick])
|
||||||
|
boot_grid.append(_at(s, cum, grid))
|
||||||
|
boot_h.append(_at(s, cum, horizons))
|
||||||
|
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
|
||||||
|
entry = {
|
||||||
|
"combination": combination.to_dict(),
|
||||||
|
"n": int(mask.sum()),
|
||||||
|
"prevalent": int((c == 1).sum()),
|
||||||
|
"incident": int(((c != 1) & np.isfinite(r)).sum()),
|
||||||
|
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
|
||||||
|
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
|
||||||
|
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
|
||||||
|
"predicted": None,
|
||||||
|
"expected_over_observed": [],
|
||||||
|
} # fmt: skip
|
||||||
|
probe = group.iloc[[0]][spec.features]
|
||||||
|
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
|
||||||
|
if at_grid is not None:
|
||||||
|
low, high = _band(*at_grid)
|
||||||
|
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
|
||||||
|
"low": low, "high": high} # fmt: skip
|
||||||
|
for k, h in enumerate(horizons):
|
||||||
|
e = None if at_h is None else float(at_h[0][k])
|
||||||
|
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
|
||||||
|
"ratio": None, "low": None, "high": None} # fmt: skip
|
||||||
|
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
|
||||||
|
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
|
||||||
|
value = e / observed[k]
|
||||||
|
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
|
||||||
|
"high": value * np.exp(Z * se)} # fmt: skip
|
||||||
|
entry["expected_over_observed"].append(ratio)
|
||||||
|
groups.append(entry)
|
||||||
|
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
|
||||||
|
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
|
||||||
|
"groups": groups} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
||||||
|
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
|
||||||
|
names = encoder.get_feature_names_out()
|
||||||
|
p = test["p"]
|
||||||
|
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
|
||||||
|
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
|
||||||
|
observed=("y", "mean")) # fmt: skip
|
||||||
|
return {
|
||||||
|
"model": "logistic regression",
|
||||||
|
"kind": "coefficients",
|
||||||
|
"intercept": float(classifier.intercept_[0]),
|
||||||
|
"coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)),
|
||||||
|
"calibration": {
|
||||||
|
"brier": float(brier_score_loss(test["y"], p)),
|
||||||
|
"bins": [
|
||||||
|
{
|
||||||
|
"range": str(k),
|
||||||
|
"n": int(v.n),
|
||||||
|
"predicted": float(v.predicted),
|
||||||
|
"observed": float(v.observed),
|
||||||
|
}
|
||||||
|
for k, v in table.iterrows()
|
||||||
|
],
|
||||||
|
}, # fmt: skip
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""The CaCu models: each is a spec (what it reads and how it is set) over one of two methods,
|
||||||
|
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
|
||||||
|
patient timelines of the spec's cohort (see features)."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
|
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||||
|
from sklearn.pipeline import Pipeline
|
||||||
|
from sklearn.preprocessing import OneHotEncoder
|
||||||
|
|
||||||
|
from core import cacu
|
||||||
|
from models.cacu import features as f
|
||||||
|
from models.cacu.pim import Mixture
|
||||||
|
|
||||||
|
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
||||||
|
TRAIN_FRACTION = 0.7
|
||||||
|
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||||
|
|
||||||
|
|
||||||
|
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
||||||
|
"""One row per patient and horizon; patients the model can't score are left out."""
|
||||||
|
h = len(horizons)
|
||||||
|
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
||||||
|
members, risks = members[scored], risks[scored]
|
||||||
|
n = len(members)
|
||||||
|
frame = pd.DataFrame({
|
||||||
|
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||||
|
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
||||||
|
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
||||||
|
"probability": risks[:, :h].ravel(),
|
||||||
|
}) # fmt: skip
|
||||||
|
if risks.shape[1] == 3 * h:
|
||||||
|
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
||||||
|
else:
|
||||||
|
frame["ci_low"] = frame["ci_high"] = np.nan
|
||||||
|
return frame[OUTPUT]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Pim:
|
||||||
|
"""Cumulative risk of the outcome at the index and by each horizon (PIMixture)."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
cohort: str
|
||||||
|
grades: list[str]
|
||||||
|
cytology: dict[str, list[str]]
|
||||||
|
strata: tuple[str, ...]
|
||||||
|
incidence_features: tuple[str, ...]
|
||||||
|
history: dict | None = None # a feature from before the index (the referral grade)
|
||||||
|
predict_at: Literal["index", "last_screening_cytology"] = "index"
|
||||||
|
horizons: tuple[float, ...] = HORIZONS
|
||||||
|
method: str = field(default="prevalence-incidence mixture", init=False)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def features(self) -> list[str]:
|
||||||
|
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
|
||||||
|
|
||||||
|
def _history(self) -> dict | None:
|
||||||
|
return self.history and {**self.history, "cytology": self.cytology}
|
||||||
|
|
||||||
|
def train(self, events: pd.DataFrame) -> tuple[Mixture, dict, dict]:
|
||||||
|
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
|
||||||
|
members it learned from (for the reports)."""
|
||||||
|
events = f.prepared(events)
|
||||||
|
coded = f.interval_coded(events, self.grades, self.cytology, self._history())
|
||||||
|
train, test = f.split(coded, TRAIN_FRACTION)
|
||||||
|
levels = {"cytology": list(self.cytology)}
|
||||||
|
if self.history:
|
||||||
|
levels[self.history["feature"]] = list(self.history["levels"])
|
||||||
|
mixture = Mixture(self.horizons, self.incidence_features, self.strata, levels)
|
||||||
|
mixture.fit(train[self.features], train[["c", "l", "r"]])
|
||||||
|
return mixture, self.metrics(mixture, train, test), {"coded": coded}
|
||||||
|
|
||||||
|
def metrics(self, mixture: Mixture, train, test) -> dict:
|
||||||
|
found = {
|
||||||
|
"n_train": len(train),
|
||||||
|
"n_test": len(test),
|
||||||
|
"neg_loglik": mixture.neg_loglik_,
|
||||||
|
"converged": float(mixture.converged_),
|
||||||
|
}
|
||||||
|
risks = mixture.predict(test[self.features])
|
||||||
|
for column, horizon in enumerate(self.horizons):
|
||||||
|
case = (test["c"] == 1) | ((test["c"] != 1) & (test["r"] <= horizon))
|
||||||
|
free = (test["c"] == 0) & (test["l"] >= horizon) & ~case
|
||||||
|
status = np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
||||||
|
known = ~np.isnan(status) & ~np.isnan(risks[:, column])
|
||||||
|
y, p, tag = status[known], risks[known, column], f"{horizon:g}y"
|
||||||
|
found[f"n_known_{tag}"] = int(known.sum())
|
||||||
|
if known.any():
|
||||||
|
found[f"observed_{tag}"] = float(y.mean())
|
||||||
|
found[f"expected_{tag}"] = float(p.mean())
|
||||||
|
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
|
||||||
|
if len(np.unique(y)) == 2:
|
||||||
|
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
|
||||||
|
return found
|
||||||
|
|
||||||
|
def predict(self, mixture: Mixture, events: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
events = f.prepared(events)
|
||||||
|
if self.predict_at == "last_screening_cytology":
|
||||||
|
chosen = f.last_screening_cytology(events)
|
||||||
|
events = events[events["person_id"].isin(chosen.index)]
|
||||||
|
events = events.assign(index_date=events["person_id"].map(chosen))
|
||||||
|
members = f.index_results(events, self.cytology, self._history())
|
||||||
|
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||||
|
return _rows(members, mixture.predict(members[self.features]), self.horizons)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Logistic:
|
||||||
|
"""Probability of the outcome within one year of the index sample."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
cohort: str
|
||||||
|
grades: list[str]
|
||||||
|
predictors: tuple[str, ...] = ("bethesda", "hpv", "hpv_16_18")
|
||||||
|
years: float = 1.0
|
||||||
|
method: str = field(default="logistic regression", init=False)
|
||||||
|
|
||||||
|
def train(self, events: pd.DataFrame, follow_up_end) -> tuple[Pipeline, dict, dict]:
|
||||||
|
"""Patients whose outcome is unknown (followed less than a year, no outcome) are left
|
||||||
|
out. Follow-up ends at `follow_up_end`: the date the data are known to."""
|
||||||
|
events = f.prepared(events)
|
||||||
|
found = f.index_sample(events, list(self.predictors))
|
||||||
|
outcome = f.windowed_outcome(events, self.grades, self.years,
|
||||||
|
pd.Timestamp(follow_up_end)) # fmt: skip
|
||||||
|
labelled = found.merge(outcome, on="person_id")
|
||||||
|
labelled = labelled[labelled["known"]].reset_index(drop=True)
|
||||||
|
train, test = f.split(labelled, TRAIN_FRACTION)
|
||||||
|
X = list(self.predictors)
|
||||||
|
model = Pipeline([("encode", OneHotEncoder(handle_unknown="ignore")),
|
||||||
|
("classify", LogisticRegression(max_iter=1000))]) # fmt: skip
|
||||||
|
model.fit(train[X], train["y"])
|
||||||
|
p = model.predict_proba(test[X])[:, 1]
|
||||||
|
metrics = {
|
||||||
|
"n_train": len(train),
|
||||||
|
"n_test": len(test),
|
||||||
|
"auc": float(roc_auc_score(test["y"], p)),
|
||||||
|
"brier": float(brier_score_loss(test["y"], p)),
|
||||||
|
"positive_rate_train": float(train["y"].mean()),
|
||||||
|
"positive_rate_test": float(test["y"].mean()),
|
||||||
|
"mean_probability_test": float(p.mean()),
|
||||||
|
}
|
||||||
|
return model, metrics, {"labelled": labelled, "test": test.assign(p=p)}
|
||||||
|
|
||||||
|
def predict(self, model: Pipeline, events: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||||
|
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||||
|
p = model.predict_proba(members[list(self.predictors)])[:, 1]
|
||||||
|
return _rows(members, p[:, None], (self.years,))
|
||||||
|
|
||||||
|
|
||||||
|
_REFERRAL = {
|
||||||
|
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
||||||
|
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
||||||
|
"high": ["High Grade"],
|
||||||
|
} # fmt: skip
|
||||||
|
|
||||||
|
MODELS = {
|
||||||
|
m.name: m
|
||||||
|
for m in [
|
||||||
|
Pim("cin2_pim", "cacu_cohort_surveillance", cacu.CIN2_PLUS, cacu.KPNC,
|
||||||
|
strata=("hpv_positive",), incidence_features=("cytology",),
|
||||||
|
predict_at="last_screening_cytology"),
|
||||||
|
Pim("cancer_pim", "cacu_cohort_surveillance", cacu.CANCER, cacu.KPNC,
|
||||||
|
strata=("hpv_positive",), incidence_features=("cytology",),
|
||||||
|
predict_at="last_screening_cytology"),
|
||||||
|
Pim("cin2_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN2_PLUS,
|
||||||
|
cacu.KPNC_3, strata=("referral_grade",),
|
||||||
|
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
||||||
|
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
||||||
|
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
||||||
|
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||||
|
]
|
||||||
|
} # fmt: skip
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
from typing import Any
|
|
||||||
|
|
||||||
from models.base import ScreeningModel
|
|
||||||
|
|
||||||
|
|
||||||
class CaMaModel(ScreeningModel):
|
|
||||||
"""Scaffold for the CaMa (breast cancer) screening model.
|
|
||||||
|
|
||||||
Can pull its own training data straight from `persistance.cama`'s
|
|
||||||
repositories (`paciente_repository`, `mastografia_repository`,
|
|
||||||
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
|
|
||||||
No real model yet; this is interface scaffolding only.
|
|
||||||
"""
|
|
||||||
|
|
||||||
domain = "cama"
|
|
||||||
|
|
||||||
def train(self, data: Any = None) -> None:
|
|
||||||
raise NotImplementedError("CaMa training is not implemented yet.")
|
|
||||||
|
|
||||||
def predict(self, data: Any) -> Any:
|
|
||||||
raise NotImplementedError("CaMa prediction is not implemented yet.")
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import dagster as dg
|
||||||
|
|
||||||
|
from models import graph
|
||||||
|
from models.cacu import jobs as cacu
|
||||||
|
from models.cacu.specs import MODELS as CACU_MODELS
|
||||||
|
from persistance import config_log, silver
|
||||||
|
|
||||||
|
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||||
|
|
||||||
|
|
||||||
|
class PipelineRun(dg.Config):
|
||||||
|
pipeline: str
|
||||||
|
version: int | None = None # default: the latest saved
|
||||||
|
|
||||||
|
|
||||||
|
@dg.op
|
||||||
|
def run_pipeline(context: dg.OpExecutionContext, config: PipelineRun) -> int:
|
||||||
|
"""Every node of the pipeline graph, inputs first. Returns the config version run."""
|
||||||
|
version, pipeline = config_log.get(config.pipeline, config.version)
|
||||||
|
context.log.info(f"{config.pipeline} v{version}: {len(pipeline.nodes)} nodes")
|
||||||
|
graph.run(config.pipeline, pipeline, log=context.log.info)
|
||||||
|
return version
|
||||||
|
|
||||||
|
|
||||||
|
@dg.job(tags=WRITES)
|
||||||
|
def ingest():
|
||||||
|
run_pipeline()
|
||||||
|
|
||||||
|
|
||||||
|
class Training(dg.Config):
|
||||||
|
models: list[str] = list(CACU_MODELS)
|
||||||
|
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||||
|
|
||||||
|
|
||||||
|
@dg.op
|
||||||
|
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
|
||||||
|
"""A new registered version of each model (MLflow), with its reports."""
|
||||||
|
as_of = date.fromisoformat(config.as_of) if config.as_of else None
|
||||||
|
found = {}
|
||||||
|
for name in config.models:
|
||||||
|
found[name] = cacu.train(name, as_of)
|
||||||
|
context.log.info(f"{name}: version {found[name]}")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
@dg.job
|
||||||
|
def train_cacu():
|
||||||
|
train_models()
|
||||||
|
|
||||||
|
|
||||||
|
class Scoring(dg.Config):
|
||||||
|
models: list[str] = list(CACU_MODELS)
|
||||||
|
|
||||||
|
|
||||||
|
@dg.op
|
||||||
|
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
|
||||||
|
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
|
||||||
|
found = {name: cacu.score(name) for name in config.models}
|
||||||
|
for name, version in found.items():
|
||||||
|
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||||
|
silver.build(["cacu_risk+"])
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
@dg.job(tags=WRITES)
|
||||||
|
def score_cacu():
|
||||||
|
score_models()
|
||||||
|
|
||||||
|
|
||||||
|
defs = dg.Definitions(jobs=[ingest, train_cacu, score_cacu])
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
"""ONNX checkpoint inspection (ML-01b, MLD-03).
|
|
||||||
|
|
||||||
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
|
|
||||||
which hands it to MLflow directly — nothing here manages storage paths.
|
|
||||||
`onnx` is an optional dependency (`models[export]`); without it
|
|
||||||
`inspect_onnx_metadata` returns `{"available": False}`.
|
|
||||||
"""
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
|
||||||
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
|
|
||||||
`{"available": False}` when the optional `onnx` package isn't installed;
|
|
||||||
`ValueError` when it is and the file isn't a valid ONNX model."""
|
|
||||||
try:
|
|
||||||
import onnx
|
|
||||||
except ImportError:
|
|
||||||
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
|
|
||||||
|
|
||||||
try:
|
|
||||||
model = onnx.load(str(path))
|
|
||||||
onnx.checker.check_model(model)
|
|
||||||
except Exception as exc:
|
|
||||||
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
|
|
||||||
return {
|
|
||||||
"available": True,
|
|
||||||
"ir_version": model.ir_version,
|
|
||||||
"producer_name": model.producer_name,
|
|
||||||
"producer_version": model.producer_version,
|
|
||||||
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
|
|
||||||
"graph_inputs": [i.name for i in model.graph.input],
|
|
||||||
"graph_outputs": [o.name for o in model.graph.output],
|
|
||||||
}
|
|
||||||
+431
@@ -0,0 +1,431 @@
|
|||||||
|
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||||
|
places what the targets staged into silver."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import unicodedata
|
||||||
|
from collections.abc import Callable
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
from functools import cache
|
||||||
|
|
||||||
|
import ocrmypdf
|
||||||
|
import pandas as pd
|
||||||
|
import pdfplumber
|
||||||
|
import splink.comparison_library as cl
|
||||||
|
from markitdown import MarkItDown
|
||||||
|
from openai import OpenAI, OpenAIError
|
||||||
|
from splink import Linker, SettingsCreator, block_on
|
||||||
|
from splink.backends.duckdb import DuckDBAPI
|
||||||
|
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||||
|
|
||||||
|
from core import catalog, concept_map, fhir_in
|
||||||
|
from core.pipeline import (
|
||||||
|
HELD,
|
||||||
|
IDENTIFIERS,
|
||||||
|
QUOTES,
|
||||||
|
RECORD,
|
||||||
|
Extract,
|
||||||
|
Fhir,
|
||||||
|
Join,
|
||||||
|
Link,
|
||||||
|
Map,
|
||||||
|
Pipeline,
|
||||||
|
Read,
|
||||||
|
Route,
|
||||||
|
Target,
|
||||||
|
answer_schema,
|
||||||
|
apply_patterns,
|
||||||
|
ground,
|
||||||
|
join,
|
||||||
|
map_row,
|
||||||
|
matches,
|
||||||
|
validate,
|
||||||
|
)
|
||||||
|
from persistance import config_log, nodes, silver
|
||||||
|
|
||||||
|
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
|
||||||
|
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||||
|
"text": {"data_type": "text", "nullable": True},
|
||||||
|
"ocr": {"data_type": "bool"},
|
||||||
|
"error": {"data_type": "text", "nullable": True},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _reader() -> MarkItDown:
|
||||||
|
return MarkItDown()
|
||||||
|
|
||||||
|
|
||||||
|
def _lines(text: str) -> str:
|
||||||
|
"""Non-empty lines, with the spacing inside each collapsed."""
|
||||||
|
return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def _text(content: bytes) -> str:
|
||||||
|
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
|
||||||
|
(spacing within a line collapsed); every other format through MarkItDown."""
|
||||||
|
if content.startswith(b"%PDF"):
|
||||||
|
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||||
|
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
|
||||||
|
return _reader().convert_stream(io.BytesIO(content)).text_content
|
||||||
|
|
||||||
|
|
||||||
|
def read_file(content: bytes) -> dict:
|
||||||
|
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
|
||||||
|
try:
|
||||||
|
found = _text(content)
|
||||||
|
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
|
||||||
|
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
|
||||||
|
text = io.BytesIO()
|
||||||
|
ocrmypdf.ocr(
|
||||||
|
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
|
||||||
|
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
|
||||||
|
sidecar=text,
|
||||||
|
) # fmt: skip
|
||||||
|
found = _lines(text.getvalue().decode())
|
||||||
|
return {"text": found, "ocr": ocr, "error": None}
|
||||||
|
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
|
||||||
|
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
|
||||||
|
|
||||||
|
|
||||||
|
def run_read(p: str, node: Read):
|
||||||
|
"""The input's rows with the file column replaced by its text; each file read once."""
|
||||||
|
rows = list(nodes.rows(p, node.inputs[0]))
|
||||||
|
keys = {}
|
||||||
|
for row in rows:
|
||||||
|
content = row.pop(node.column)
|
||||||
|
row["key"] = hashlib.sha256(content).hexdigest() if content else None
|
||||||
|
keys[row["key"]] = content
|
||||||
|
found = nodes.cached("read_cache", set(keys) - {None})
|
||||||
|
new = {k: c for k, c in keys.items() if k and k not in found}
|
||||||
|
with ProcessPoolExecutor() as pool:
|
||||||
|
read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
|
||||||
|
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
|
||||||
|
found |= read
|
||||||
|
for row in rows:
|
||||||
|
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||||
|
row |= {k: result[k] for k in READ_COLUMNS}
|
||||||
|
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||||
|
|
||||||
|
|
||||||
|
def run_route(p: str, node: Route):
|
||||||
|
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
|
||||||
|
|
||||||
|
|
||||||
|
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
|
||||||
|
"""The node's ConceptMap as a translation table per field (none without one)."""
|
||||||
|
if node.concept_map is None:
|
||||||
|
return {}
|
||||||
|
found = config_log.concept_map(node.concept_map)
|
||||||
|
return {f: concept_map.table([found], f) for f in fields}
|
||||||
|
|
||||||
|
|
||||||
|
def run_map(p: str, node: Map):
|
||||||
|
codes = _codes(node, node.fields)
|
||||||
|
rows = [map_row(node, r, codes) for r in nodes.rows(p, node.inputs[0])]
|
||||||
|
return nodes.write(p, node.id, rows)
|
||||||
|
|
||||||
|
|
||||||
|
def run_fhir(p: str, node: Fhir):
|
||||||
|
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
|
||||||
|
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
|
||||||
|
found: dict[str, dict] = {}
|
||||||
|
for row in nodes.rows(p, node.inputs[0]):
|
||||||
|
bundle = json.loads(row[node.column])
|
||||||
|
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||||
|
found[r[RECORD]] = r
|
||||||
|
return nodes.write(p, node.id, list(found.values()))
|
||||||
|
|
||||||
|
|
||||||
|
def run_join(p: str, node: Join):
|
||||||
|
left, right = (list(nodes.rows(p, i)) for i in node.inputs)
|
||||||
|
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _llm() -> tuple[OpenAI, str] | None:
|
||||||
|
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
||||||
|
if not (url := os.environ.get("LLM_URL")):
|
||||||
|
return None
|
||||||
|
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
||||||
|
try:
|
||||||
|
client.models.list()
|
||||||
|
except OpenAIError:
|
||||||
|
return None
|
||||||
|
return client, os.environ["LLM_MODEL"]
|
||||||
|
|
||||||
|
|
||||||
|
PROMPT = (
|
||||||
|
"Extract every {entity} record stated in the document. For each field give its value "
|
||||||
|
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
||||||
|
"copied character by character. Leave out fields the document does not state.{hints}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_llm(node: Extract, text: str) -> dict:
|
||||||
|
client, model = _llm()
|
||||||
|
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
||||||
|
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
||||||
|
if found := nodes.cached("llm_cache", {key}):
|
||||||
|
return json.loads(found[key]["answer"])
|
||||||
|
reply = client.chat.completions.create(
|
||||||
|
model=model, temperature=0, seed=7,
|
||||||
|
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||||
|
response_format={"type": "json_schema", "json_schema": {
|
||||||
|
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
||||||
|
) # fmt: skip
|
||||||
|
answer = reply.choices[0].message.content
|
||||||
|
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||||
|
return json.loads(answer)
|
||||||
|
|
||||||
|
|
||||||
|
def run_extract(p: str, node: Extract):
|
||||||
|
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||||
|
codes = _codes(node, node.patterns)
|
||||||
|
out = []
|
||||||
|
for row in nodes.rows(p, node.inputs[0]):
|
||||||
|
text = row.get(node.column) or ""
|
||||||
|
if use_llm:
|
||||||
|
found = ground(_ask_llm(node, text), text)
|
||||||
|
elif node.patterns:
|
||||||
|
found = apply_patterns(node, text, codes)
|
||||||
|
else:
|
||||||
|
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||||
|
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||||
|
out.append({**values, RECORD: row[RECORD], "_index": index,
|
||||||
|
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
||||||
|
HELD: json.dumps(held) if held else None}) # fmt: skip
|
||||||
|
return nodes.write(p, node.id, out)
|
||||||
|
|
||||||
|
|
||||||
|
def _comparison(field: str):
|
||||||
|
if field == "birth_date":
|
||||||
|
return cl.DateOfBirthComparison(field, input_is_string=True)
|
||||||
|
if field == "full_name":
|
||||||
|
return cl.NameComparison(field)
|
||||||
|
if field in ("record_number", "curp", "nss"):
|
||||||
|
return cl.LevenshteinAtThresholds(field, [1, 2])
|
||||||
|
return cl.ExactMatch(field)
|
||||||
|
|
||||||
|
|
||||||
|
def _plain(identifier: str) -> str:
|
||||||
|
"""An identifier as compared: letters and digits only, upper case."""
|
||||||
|
return "".join(ch for ch in identifier if ch.isalnum()).upper()
|
||||||
|
|
||||||
|
|
||||||
|
def _name(name: str) -> str:
|
||||||
|
"""A name as compared: upper case, without accents, single spaces."""
|
||||||
|
plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
|
||||||
|
return " ".join(plain.upper().split())
|
||||||
|
|
||||||
|
|
||||||
|
def _near(identifier: str) -> list[str]:
|
||||||
|
"""The identifier and every version of it with one character left out: two identifiers
|
||||||
|
one typo apart (a wrong, missing, extra or swapped character) share one of these."""
|
||||||
|
return sorted(
|
||||||
|
{identifier} | {identifier[:i] + identifier[i + 1 :] for i in range(len(identifier))}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[str, str]]:
|
||||||
|
"""One row per record: its identity fields (first value found, reviewers' corrections
|
||||||
|
applied, identifiers plain); records rejected for identity are left out. And the input
|
||||||
|
each record came through (its record number's system), and its name as written."""
|
||||||
|
skip, fixed = nodes.rejected("identity"), nodes.corrections()
|
||||||
|
records: dict[str, dict] = {}
|
||||||
|
sources: dict[str, str] = {}
|
||||||
|
written: dict[str, str] = {} # each record's name as it came (compared normalised)
|
||||||
|
for i in node.inputs:
|
||||||
|
for row in nodes.rows(p, i):
|
||||||
|
if row.get(HELD) or row[RECORD] in skip:
|
||||||
|
continue
|
||||||
|
row = {**row, **fixed.get(row[RECORD], {})} # a reviewer's correction wins
|
||||||
|
mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]})
|
||||||
|
sources.setdefault(row[RECORD], i)
|
||||||
|
for f in node.fields:
|
||||||
|
if row.get(f) is not None and mine.get(f) is None:
|
||||||
|
value = str(row[f])
|
||||||
|
if f == "full_name":
|
||||||
|
written[row[RECORD]] = " ".join(value.split())
|
||||||
|
mine[f] = (
|
||||||
|
_plain(value) if f in IDENTIFIERS
|
||||||
|
else _name(value) if f == "full_name" else value
|
||||||
|
) # fmt: skip
|
||||||
|
frame = pd.DataFrame(list(records.values()))
|
||||||
|
present = [f for f in node.fields if f in frame and frame[f].notna().any()]
|
||||||
|
return frame[["unique_id", *present]], sources, written
|
||||||
|
|
||||||
|
|
||||||
|
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
|
||||||
|
clusters = cluster_pairwise_predictions_at_threshold(
|
||||||
|
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
|
||||||
|
)
|
||||||
|
return clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(records)
|
||||||
|
|
||||||
|
|
||||||
|
def run_link(p: str, node: Link):
|
||||||
|
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
|
||||||
|
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
|
||||||
|
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
|
||||||
|
don't contradict each other are queued for review, with Splink's probability."""
|
||||||
|
records, sources, written = _identities(p, node)
|
||||||
|
fields = [c for c in records.columns if c != "unique_id"]
|
||||||
|
rules = [r for r in node.rules or node.default_rules()
|
||||||
|
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
|
||||||
|
comparisons = [_comparison(f) for f in fields]
|
||||||
|
db = DuckDBAPI()
|
||||||
|
linker = Linker(
|
||||||
|
db.register(records),
|
||||||
|
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||||
|
blocking_rules_to_generate_predictions=rules),
|
||||||
|
log_level=None,
|
||||||
|
) # fmt: skip
|
||||||
|
decided = nodes.person_decisions()
|
||||||
|
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
||||||
|
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
|
||||||
|
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
|
||||||
|
known = set(records.unique_id)
|
||||||
|
edges = pd.DataFrame(
|
||||||
|
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
|
||||||
|
)
|
||||||
|
persons = _persons(records, edges, db)
|
||||||
|
|
||||||
|
facts = [f for f in ("birth_date", "sex") if f in fields]
|
||||||
|
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
|
||||||
|
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
|
||||||
|
held = json.dumps(["records of this person disagree on birth date or sex"])
|
||||||
|
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
|
||||||
|
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
|
||||||
|
linked = [
|
||||||
|
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
|
||||||
|
HELD: held if r.cluster_id in torn else None,
|
||||||
|
**{f: getattr(r, f) for f in fields},
|
||||||
|
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
|
||||||
|
for r in persons.itertuples()
|
||||||
|
] # fmt: skip
|
||||||
|
nodes.write(p, node.id, linked, columns)
|
||||||
|
nodes.stage("identity", p, node.id, linked, silver.identity_columns()) # silver.person
|
||||||
|
|
||||||
|
# One row per person, so random pairs are different people and Splink's u is honest.
|
||||||
|
ids = [f for f in IDENTIFIERS if f in fields]
|
||||||
|
whole = persons.drop(columns="unique_id").groupby("cluster_id").first()
|
||||||
|
for f in ids:
|
||||||
|
near = (
|
||||||
|
persons.dropna(subset=[f])
|
||||||
|
.groupby("cluster_id")[f]
|
||||||
|
.agg(lambda values: sorted({n for v in values for n in _near(v)}))
|
||||||
|
)
|
||||||
|
whole[f"{f}_near"] = near.reindex(whole.index).apply(
|
||||||
|
lambda v: v if isinstance(v, list) else []
|
||||||
|
)
|
||||||
|
whole = whole.reset_index().rename(columns={"cluster_id": "unique_id"})
|
||||||
|
blocks = [block_on(f"{f}_near", arrays_to_explode=[f"{f}_near"]) for f in ids]
|
||||||
|
reasons = [f"{f} one typo apart" for f in ids]
|
||||||
|
if "birth_date" in fields:
|
||||||
|
blocks.append(block_on("birth_date"))
|
||||||
|
reasons.append("same birth date")
|
||||||
|
model = Linker(
|
||||||
|
db.register(whole),
|
||||||
|
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||||
|
blocking_rules_to_generate_predictions=blocks),
|
||||||
|
log_level=None,
|
||||||
|
) # fmt: skip
|
||||||
|
model.training.estimate_u_using_random_sampling(max_pairs=1e6)
|
||||||
|
found = model.inference.predict(warning_mode="never").as_pandas_dataframe()
|
||||||
|
|
||||||
|
known = [f for f in ("birth_date", "sex") if f in fields]
|
||||||
|
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
||||||
|
lone = set() # persons whose identifier is carried by one record only
|
||||||
|
for f in ids:
|
||||||
|
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||||
|
lone |= {person for (person, _), n in carried.items() if n == 1}
|
||||||
|
|
||||||
|
def settle(r) -> tuple[str, str] | None:
|
||||||
|
"""(the person to settle, a possible owner), or None when the pair is implausible:
|
||||||
|
they contradict each other, or one typo apart is all they share (with sequential
|
||||||
|
record numbers every patient has such neighbours) unless one side has no
|
||||||
|
demographics and the other's identifier stands on a single record."""
|
||||||
|
a, b = r.unique_id_l, r.unique_id_r
|
||||||
|
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||||
|
if frozenset((a, b)) in decided or any(
|
||||||
|
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
if not reasons[int(r.match_key)].endswith("typo apart"):
|
||||||
|
return a, b
|
||||||
|
if a in orphan and b in lone:
|
||||||
|
return a, b
|
||||||
|
if b in orphan and a in lone:
|
||||||
|
return b, a
|
||||||
|
return None
|
||||||
|
|
||||||
|
side = {r.unique_id: r for r in whole.itertuples()}
|
||||||
|
queue = []
|
||||||
|
for r in found.itertuples():
|
||||||
|
if pair := settle(r):
|
||||||
|
person, owner = pair
|
||||||
|
queue.append(
|
||||||
|
{
|
||||||
|
"person": person,
|
||||||
|
"candidate": owner,
|
||||||
|
"probability": r.match_probability,
|
||||||
|
"reason": reasons[int(r.match_key)],
|
||||||
|
**{f"person_{f}": getattr(side[person], f) for f in fields},
|
||||||
|
**{f"candidate_{f}": getattr(side[owner], f) for f in fields},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return nodes.write(p, f"{node.id}__review", queue)
|
||||||
|
|
||||||
|
|
||||||
|
def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||||
|
"""Rows of one study into silver's staging, each given its person by the link node:
|
||||||
|
a clean row becomes one observation per field it has (long), keyed by its study
|
||||||
|
instance (the study's key values); a row a rule held waits for review, whole."""
|
||||||
|
link = next(i for i in node.inputs if kinds[i] == "link")
|
||||||
|
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
||||||
|
person = {k: r["person_id"] for k, r in linked.items()}
|
||||||
|
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
||||||
|
observations, held_rows = [], []
|
||||||
|
for i in (i for i in node.inputs if i != link):
|
||||||
|
for row in nodes.rows(p, i):
|
||||||
|
values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None}
|
||||||
|
held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
|
||||||
|
if row[RECORD] not in person:
|
||||||
|
held.append("no identity linked to this record")
|
||||||
|
else:
|
||||||
|
held += json.loads(linked[row[RECORD]].get(HELD) or "[]")
|
||||||
|
base = {"study": node.entity, "person_id": person.get(row[RECORD]), RECORD: row[RECORD],
|
||||||
|
"_index": row.get("_index", 0), QUOTES: row.get(QUOTES)} # fmt: skip
|
||||||
|
if held:
|
||||||
|
raw = json.dumps(values, default=str, ensure_ascii=False)
|
||||||
|
held_rows.append({**base, HELD: json.dumps(held), "_raw": raw})
|
||||||
|
continue
|
||||||
|
clean = model.model_validate(values)
|
||||||
|
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||||
|
for name, field in study.fields.items():
|
||||||
|
if (value := getattr(clean, name)) is not None:
|
||||||
|
observations.append({**base, "instance": instance, "field": name,
|
||||||
|
catalog.value_column(field): value}) # fmt: skip
|
||||||
|
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||||
|
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||||
|
|
||||||
|
|
||||||
|
RUNNERS: dict[str, Callable] = {
|
||||||
|
"source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map,
|
||||||
|
"join": run_join, "extract": run_extract, "link": run_link, "fhir": run_fhir,
|
||||||
|
} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None:
|
||||||
|
kinds = {n.id: n.kind for n in pipeline.nodes}
|
||||||
|
for node in pipeline.order():
|
||||||
|
if node.kind == "target":
|
||||||
|
run_target(pipeline_id, node, kinds)
|
||||||
|
else:
|
||||||
|
RUNNERS[node.kind](pipeline_id, node)
|
||||||
|
log(f"{node.id} ({node.kind}) done")
|
||||||
|
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||||
|
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||||
|
log(f"silver and gold, from {', '.join(entities)}")
|
||||||
-267
@@ -1,267 +0,0 @@
|
|||||||
"""Extraction of results from the PDF reports stored with each study
|
|
||||||
(VAR-01..09, VARM-01..05).
|
|
||||||
|
|
||||||
Each `OcrJob` says which table, which stored PDF and which result columns
|
|
||||||
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
|
|
||||||
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
|
|
||||||
entry in `OCR_JOBS`.
|
|
||||||
|
|
||||||
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
|
|
||||||
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
|
|
||||||
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
|
|
||||||
are then located by caption matching tolerant to OCR errors, and by
|
|
||||||
lexicon matching over the narrative with NegEx-style negation handling
|
|
||||||
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
|
|
||||||
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
|
|
||||||
value carries a 0..1 confidence: caption match quality x parse quality x
|
|
||||||
Tesseract's word confidence.
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from typing import Any, ClassVar
|
|
||||||
|
|
||||||
from sqlalchemy import func, or_
|
|
||||||
from sqlmodel import select
|
|
||||||
|
|
||||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
|
|
||||||
from core.cama.enums import GradoHistologicoMama
|
|
||||||
from core.ocr import OcrEstatus
|
|
||||||
from extraction import FieldKind, FieldSpec, read_document
|
|
||||||
from extraction.nlp import RecordExtractor, SegmentLine
|
|
||||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
|
||||||
from extraction.ocr import TesseractOcr
|
|
||||||
from models.base import resolve_repository
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
# Below this confidence a value is stored but flagged for manual review.
|
|
||||||
REVIEW_THRESHOLD = 0.8
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class OcrExtractionResult:
|
|
||||||
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
|
|
||||||
|
|
||||||
values: dict[str, Any]
|
|
||||||
confianza: float
|
|
||||||
estatus: OcrEstatus
|
|
||||||
requiere_revision: bool
|
|
||||||
metodo_principal: str
|
|
||||||
metodo_alternativo: str | None = None
|
|
||||||
quality_validation: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class OcrColumnSpec:
|
|
||||||
"""The columns of one extraction on its table: the stored PDF, the
|
|
||||||
five traceability columns, and extractor result key -> result column."""
|
|
||||||
|
|
||||||
blob_field: str
|
|
||||||
confianza_field: str
|
|
||||||
estatus_field: str
|
|
||||||
requiere_revision_field: str
|
|
||||||
metodo_principal_field: str
|
|
||||||
metodo_alternativo_field: str
|
|
||||||
result_field_map: dict[str, str] = field(default_factory=dict)
|
|
||||||
|
|
||||||
|
|
||||||
class OcrExtractor(ABC):
|
|
||||||
@abstractmethod
|
|
||||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
||||||
"""Reads `pdf_blob`. A document that can be read but where nothing
|
|
||||||
is found returns estatus FALLIDO with requiere_revision; an
|
|
||||||
unreadable one may raise, and the driver records FALLIDO."""
|
|
||||||
|
|
||||||
|
|
||||||
class ReportOcrExtractor(OcrExtractor):
|
|
||||||
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
|
|
||||||
|
|
||||||
fields: ClassVar[dict[str, FieldSpec]]
|
|
||||||
|
|
||||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
||||||
document = read_document("reporte.pdf", pdf_blob)
|
|
||||||
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
|
|
||||||
found = RecordExtractor(list(self.fields.values())).extract(lines)
|
|
||||||
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
|
|
||||||
|
|
||||||
sources = {page.source for page in document.pages}
|
|
||||||
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
|
|
||||||
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
|
|
||||||
evidence = {key: value.to_dict() for key, value in by_key.items()}
|
|
||||||
missing = [key for key in self.fields if key not in by_key]
|
|
||||||
if missing:
|
|
||||||
evidence["faltantes"] = missing
|
|
||||||
|
|
||||||
if not by_key:
|
|
||||||
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
|
|
||||||
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
|
|
||||||
return OcrExtractionResult(
|
|
||||||
values={key: value.value for key, value in by_key.items()},
|
|
||||||
confianza=confianza,
|
|
||||||
estatus=OcrEstatus.REALIZADO,
|
|
||||||
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
|
|
||||||
metodo_principal=principal,
|
|
||||||
metodo_alternativo=alternativo,
|
|
||||||
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
|
|
||||||
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
|
|
||||||
|
|
||||||
|
|
||||||
class VphOcrExtractor(ReportOcrExtractor):
|
|
||||||
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
|
|
||||||
|
|
||||||
fields = {
|
|
||||||
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
|
|
||||||
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
|
|
||||||
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class CinGradoOcrExtractor(ReportOcrExtractor):
|
|
||||||
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
|
|
||||||
|
|
||||||
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
|
|
||||||
|
|
||||||
|
|
||||||
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
|
|
||||||
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
|
|
||||||
|
|
||||||
fields = {
|
|
||||||
"grado": choice_field(
|
|
||||||
"bx_grado_histologico",
|
|
||||||
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
|
|
||||||
scan_free_text=True,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
|
|
||||||
return OcrColumnSpec(
|
|
||||||
blob_field=blob_field,
|
|
||||||
confianza_field=f"{prefix}_ocr_confianza",
|
|
||||||
estatus_field=f"{prefix}_ocr_estatus",
|
|
||||||
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
|
|
||||||
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
|
|
||||||
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
|
|
||||||
result_field_map=results,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
CIT_VPH_COLUMNS = _ocr_columns(
|
|
||||||
"cit_vph",
|
|
||||||
"cit_vph_pdf_blob",
|
|
||||||
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
|
|
||||||
)
|
|
||||||
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
|
|
||||||
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class OcrJob:
|
|
||||||
domain: str
|
|
||||||
entity: str # repository name in persistance.<domain>, without `_repository`
|
|
||||||
label: str
|
|
||||||
columns: OcrColumnSpec
|
|
||||||
extractor: type[OcrExtractor]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def repository(self) -> Repository:
|
|
||||||
"""Resolved on use, so it follows whatever database URL is active."""
|
|
||||||
return resolve_repository(self.domain, self.entity)
|
|
||||||
|
|
||||||
|
|
||||||
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
|
|
||||||
(job.domain, job.entity): job
|
|
||||||
for job in (
|
|
||||||
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
|
|
||||||
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
|
|
||||||
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class OcrRunSummary:
|
|
||||||
processed: int = 0
|
|
||||||
skipped_already_done: int = 0
|
|
||||||
failed: int = 0
|
|
||||||
needs_review: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
def run_pending_extractions(
|
|
||||||
repository: Repository,
|
|
||||||
spec: OcrColumnSpec,
|
|
||||||
extractor: OcrExtractor,
|
|
||||||
*,
|
|
||||||
domain: str,
|
|
||||||
entity: str,
|
|
||||||
governance_repository: Repository | None = None,
|
|
||||||
source_description: str | None = None,
|
|
||||||
limit: int = 500,
|
|
||||||
) -> OcrRunSummary:
|
|
||||||
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
|
|
||||||
persisted result is what prevents duplicate runs. A failing row is
|
|
||||||
stored as FALLIDO and the batch continues. With `governance_repository`,
|
|
||||||
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
|
|
||||||
from core.governance.enums import EstatusExtraccion
|
|
||||||
from core.governance.models import ExtractionRun
|
|
||||||
|
|
||||||
summary = OcrRunSummary()
|
|
||||||
model = repository.model
|
|
||||||
primary_key = list(model.__table__.primary_key.columns)
|
|
||||||
estatus = getattr(model, spec.estatus_field)
|
|
||||||
with_report = getattr(model, spec.blob_field).is_not(None)
|
|
||||||
done = estatus == OcrEstatus.REALIZADO.value
|
|
||||||
with repository.open_session() as session:
|
|
||||||
summary.skipped_already_done = session.exec(select(func.count()).select_from(model).where(with_report, done)).one()
|
|
||||||
pending = select(model).where(with_report, or_(estatus.is_(None), ~done)).order_by(*primary_key).limit(limit)
|
|
||||||
for tracked in session.exec(pending).all():
|
|
||||||
pk_value = getattr(tracked, primary_key[0].name)
|
|
||||||
started_at = datetime.now(timezone.utc)
|
|
||||||
try:
|
|
||||||
result = extractor.extract(getattr(tracked, spec.blob_field))
|
|
||||||
except NotImplementedError:
|
|
||||||
raise
|
|
||||||
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
|
|
||||||
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
|
|
||||||
|
|
||||||
for result_key, column in spec.result_field_map.items():
|
|
||||||
if result_key in result.values:
|
|
||||||
setattr(tracked, column, result.values[result_key])
|
|
||||||
setattr(tracked, spec.confianza_field, result.confianza)
|
|
||||||
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
|
|
||||||
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
|
|
||||||
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
|
|
||||||
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
|
|
||||||
session.add(tracked)
|
|
||||||
if result.estatus == OcrEstatus.FALLIDO:
|
|
||||||
summary.failed += 1
|
|
||||||
else:
|
|
||||||
summary.processed += 1
|
|
||||||
if result.requiere_revision:
|
|
||||||
summary.needs_review += 1
|
|
||||||
|
|
||||||
if governance_repository is not None:
|
|
||||||
governance_repository.create(
|
|
||||||
ExtractionRun(
|
|
||||||
domain=domain,
|
|
||||||
entity=entity,
|
|
||||||
entity_pk=str(pk_value),
|
|
||||||
column_extracted=",".join(spec.result_field_map.values()),
|
|
||||||
source_description=source_description,
|
|
||||||
source_started_at=started_at,
|
|
||||||
source_ended_at=datetime.now(timezone.utc),
|
|
||||||
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
|
|
||||||
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
|
|
||||||
quality_validation=result.quality_validation,
|
|
||||||
estatus=(
|
|
||||||
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
|
|
||||||
).value,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
session.commit()
|
|
||||||
return summary
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
|
|
||||||
produced it. Callers go through `PredictionService` rather than calling
|
|
||||||
`model.predict(...)` directly.
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
from collections.abc import Callable
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from core.governance.models import ModelPrediction
|
|
||||||
from mlflow import MlflowException
|
|
||||||
from persistance.governance import model_prediction_repository
|
|
||||||
|
|
||||||
from models.base import ScreeningModel
|
|
||||||
from models.registry import PRODUCTION_ALIAS, registered_name, registry
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Interpretability:
|
|
||||||
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
|
||||||
Each model fills the ones its method has (odds ratio for a logistic
|
|
||||||
regression, hazard ratio for a survival model)."""
|
|
||||||
|
|
||||||
odds_ratio: float | None = None
|
|
||||||
hazard_ratio: float | None = None
|
|
||||||
probabilidad_acumulada: float | None = None
|
|
||||||
|
|
||||||
def to_json(self) -> str:
|
|
||||||
return json.dumps(
|
|
||||||
{
|
|
||||||
"odds_ratio": self.odds_ratio,
|
|
||||||
"hazard_ratio": self.hazard_ratio,
|
|
||||||
"probabilidad_acumulada": self.probabilidad_acumulada,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ApplicabilityRejected(Exception):
|
|
||||||
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
|
||||||
should report it as a client error (4xx), not a server error."""
|
|
||||||
|
|
||||||
|
|
||||||
class PredictionService:
|
|
||||||
"""Runs a `ScreeningModel` and records its predictions against the
|
|
||||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
|
||||||
|
|
||||||
If `aplicable` is given, each row (a dict of fields) is checked with it
|
|
||||||
(EL-04b). Inapplicable rows are still scored but stored with
|
|
||||||
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
model: ScreeningModel,
|
|
||||||
*,
|
|
||||||
domain: str,
|
|
||||||
scenario: str,
|
|
||||||
aplicable: Callable[[dict], bool] | None = None,
|
|
||||||
reject_inapplicable: bool = False,
|
|
||||||
):
|
|
||||||
self.model = model
|
|
||||||
self.domain = domain
|
|
||||||
self.scenario = scenario
|
|
||||||
self.aplicable = aplicable
|
|
||||||
self.reject_inapplicable = reject_inapplicable
|
|
||||||
|
|
||||||
def active_model_version(self):
|
|
||||||
"""The MLflow model version currently holding the `produccion`
|
|
||||||
alias for this (domain, scenario), or `None`."""
|
|
||||||
name = registered_name(self.domain, self.scenario)
|
|
||||||
try:
|
|
||||||
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
||||||
except MlflowException:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def predict_and_record(
|
|
||||||
self,
|
|
||||||
data: Any,
|
|
||||||
*,
|
|
||||||
pac_id_hospital: str,
|
|
||||||
episodio_id: int | None = None,
|
|
||||||
interpretability: Interpretability | None = None,
|
|
||||||
) -> ModelPrediction:
|
|
||||||
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
|
||||||
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
|
||||||
propagated unchanged.
|
|
||||||
"""
|
|
||||||
applicability_passed = True
|
|
||||||
if self.aplicable is not None:
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
raise TypeError("the applicability check needs the input as a dict of fields")
|
|
||||||
applicability_passed = self.aplicable(data)
|
|
||||||
if not applicability_passed and self.reject_inapplicable:
|
|
||||||
raise ApplicabilityRejected(
|
|
||||||
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Predict first, so an unimplemented model raises NotImplementedError
|
|
||||||
# even when no version is in production.
|
|
||||||
output = self.model.predict(data)
|
|
||||||
|
|
||||||
model_version = self.active_model_version()
|
|
||||||
if model_version is None:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
|
||||||
"promueva una con models.registry.registry.promote antes de predecir"
|
|
||||||
)
|
|
||||||
|
|
||||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
|
||||||
prediction = model_prediction_repository.create(
|
|
||||||
ModelPrediction(
|
|
||||||
mlflow_run_id=model_version.run_id,
|
|
||||||
modelo_nombre=model_version.name,
|
|
||||||
modelo_version=str(model_version.version),
|
|
||||||
domain=self.domain,
|
|
||||||
pac_id_hospital=pac_id_hospital,
|
|
||||||
episodio_id=episodio_id,
|
|
||||||
input_hash=input_hash,
|
|
||||||
output=json.dumps(output, default=str),
|
|
||||||
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
|
||||||
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
|
||||||
interpretability=interpretability.to_json() if interpretability else None,
|
|
||||||
applicability_passed=applicability_passed,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return prediction
|
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
|
||||||
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
|
||||||
about on its own: the promotion checks tied to the cohort a version was
|
|
||||||
trained on and to the validation-report convention.
|
|
||||||
|
|
||||||
Training, versioning, artifact storage and stage live in MLflow itself
|
|
||||||
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
|
||||||
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
|
|
||||||
of its versions, never stored here and read from MLflow on every call.
|
|
||||||
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
|
|
||||||
database). A version points to its build with the `kit.armado_id` tag, and
|
|
||||||
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
|
||||||
"""
|
|
||||||
import re
|
|
||||||
import tempfile
|
|
||||||
from dataclasses import asdict, dataclass
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from importlib import import_module
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
|
||||||
from mlflow import MlflowClient, MlflowException
|
|
||||||
from persistance.governance import model_prediction_repository
|
|
||||||
from sqlmodel import select
|
|
||||||
|
|
||||||
from models.export import inspect_onnx_metadata
|
|
||||||
|
|
||||||
DOMAINS = ("cacu", "cama", "tea")
|
|
||||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
|
||||||
PRODUCTION_ALIAS = "produccion"
|
|
||||||
ARMADO_TAG = "kit.armado_id"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class PromotionCheck:
|
|
||||||
code: str
|
|
||||||
requirement: str
|
|
||||||
passed: bool
|
|
||||||
detail: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
class PromotionBlocked(Exception):
|
|
||||||
def __init__(self, checks: list[PromotionCheck]):
|
|
||||||
self.checks = checks
|
|
||||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
|
|
||||||
super().__init__(f"la versión no cumple: {failed}")
|
|
||||||
|
|
||||||
|
|
||||||
def registered_name(domain: str, scenario: str) -> str:
|
|
||||||
return f"{domain}-{scenario}"
|
|
||||||
|
|
||||||
|
|
||||||
class ModelRegistry:
|
|
||||||
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
|
|
||||||
|
|
||||||
def __init__(self, client: MlflowClient | None = None):
|
|
||||||
self._client = client
|
|
||||||
|
|
||||||
@property
|
|
||||||
def client(self) -> MlflowClient:
|
|
||||||
return self._client or MlflowClient()
|
|
||||||
|
|
||||||
def get(self, domain: str, scenario: str, version: str):
|
|
||||||
try:
|
|
||||||
return self.client.get_model_version(registered_name(domain, scenario), version)
|
|
||||||
except MlflowException as exc:
|
|
||||||
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
|
|
||||||
|
|
||||||
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
|
||||||
"""Every version, newest first. `scenario` needs `domain`; `domain`
|
|
||||||
alone matches every scenario of that domain (MLflow's own
|
|
||||||
`search_registered_models` LIKE filter); neither matches everything."""
|
|
||||||
if domain and domain not in DOMAINS:
|
|
||||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
|
||||||
if scenario and not re.fullmatch(r"[\w-]+", scenario):
|
|
||||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
|
||||||
if domain and scenario:
|
|
||||||
names = [registered_name(domain, scenario)]
|
|
||||||
elif domain:
|
|
||||||
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
|
|
||||||
else:
|
|
||||||
return [self._describe(mv) for mv in self.client.search_model_versions()]
|
|
||||||
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
|
|
||||||
|
|
||||||
def _status(self, mv) -> str:
|
|
||||||
try:
|
|
||||||
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
|
|
||||||
if str(production.version) == str(mv.version):
|
|
||||||
return "produccion"
|
|
||||||
except MlflowException:
|
|
||||||
pass
|
|
||||||
if mv.tags.get("retirada_en"):
|
|
||||||
return "retirada"
|
|
||||||
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
|
|
||||||
|
|
||||||
def status(self, domain: str, scenario: str, version: str) -> str:
|
|
||||||
return self._status(self.get(domain, scenario, version))
|
|
||||||
|
|
||||||
def register(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
domain: str,
|
|
||||||
scenario: str,
|
|
||||||
environment: Environment | str,
|
|
||||||
cohorte_armado_id: int | None = None,
|
|
||||||
metrics: dict[str, Any] | None = None,
|
|
||||||
hyperparameters: dict[str, Any] | None = None,
|
|
||||||
**reports: str | None,
|
|
||||||
) -> str:
|
|
||||||
"""For training code that runs elsewhere and reports over the API.
|
|
||||||
In-process training uses `models.training.TrainingRun` directly."""
|
|
||||||
from models.training import TrainingRun
|
|
||||||
|
|
||||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
|
||||||
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
|
|
||||||
|
|
||||||
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
|
||||||
"""MLD-01/01b/03 documents are usually written after training."""
|
|
||||||
unknown = set(reports) - set(REPORT_TAGS)
|
|
||||||
if unknown:
|
|
||||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
|
||||||
name = registered_name(domain, scenario)
|
|
||||||
for tag, uri in reports.items():
|
|
||||||
self.client.set_model_version_tag(name, version, tag, uri or "")
|
|
||||||
|
|
||||||
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
|
|
||||||
"""Logs an artifact file to the run behind an already-registered
|
|
||||||
version (ML-01a/b), e.g. a checkpoint exported after training.
|
|
||||||
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
|
|
||||||
rejected (400) instead of silently stored."""
|
|
||||||
mv = self.get(domain, scenario, version)
|
|
||||||
kind_value = kind.value if hasattr(kind, "value") else str(kind)
|
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
|
||||||
path = Path(tmp) / filename
|
|
||||||
path.write_bytes(data)
|
|
||||||
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
|
|
||||||
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
|
|
||||||
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
|
|
||||||
|
|
||||||
def _describe(self, mv) -> dict[str, Any]:
|
|
||||||
run = self.client.get_run(mv.run_id)
|
|
||||||
return {
|
|
||||||
"name": mv.name,
|
|
||||||
"version": str(mv.version),
|
|
||||||
"run_id": mv.run_id,
|
|
||||||
"tags": dict(mv.tags),
|
|
||||||
"metrics": dict(run.data.metrics),
|
|
||||||
"created_at": _iso(mv.creation_timestamp),
|
|
||||||
"status": self._status(mv),
|
|
||||||
}
|
|
||||||
|
|
||||||
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
|
||||||
return self._describe(self.get(domain, scenario, version))
|
|
||||||
|
|
||||||
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
|
||||||
"""Everything a version came from and produced: its cohort build (with
|
|
||||||
its attrition), logged artifacts and predictions."""
|
|
||||||
mv = self.get(domain, scenario, version)
|
|
||||||
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
|
||||||
return {
|
|
||||||
"model_version": self.describe(domain, scenario, version),
|
|
||||||
"cohorte_armado": armado,
|
|
||||||
"cohorte_exclusiones": exclusiones,
|
|
||||||
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
|
|
||||||
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
|
|
||||||
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
|
|
||||||
}
|
|
||||||
|
|
||||||
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
|
|
||||||
mv = self.get(domain, scenario, version)
|
|
||||||
run = self.client.get_run(mv.run_id)
|
|
||||||
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
|
||||||
metrics = run.data.metrics
|
|
||||||
artifacts = self.client.list_artifacts(mv.run_id)
|
|
||||||
return [
|
|
||||||
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
|
|
||||||
PromotionCheck(
|
|
||||||
"ML-03",
|
|
||||||
"enlazada al armado de cohorte con el que se entrenó",
|
|
||||||
armado is not None,
|
|
||||||
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
|
|
||||||
),
|
|
||||||
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
|
|
||||||
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
|
|
||||||
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
|
|
||||||
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
|
|
||||||
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
|
|
||||||
]
|
|
||||||
|
|
||||||
def promote(self, domain: str, scenario: str, version: str):
|
|
||||||
"""Makes this the production version of its scenario, tagging the
|
|
||||||
previous one `retirada_en`. Promotion is always a manual step
|
|
||||||
(MLD-01/01b)."""
|
|
||||||
checks = self.checks(domain, scenario, version)
|
|
||||||
if not all(check.passed for check in checks):
|
|
||||||
raise PromotionBlocked(checks)
|
|
||||||
name = registered_name(domain, scenario)
|
|
||||||
try:
|
|
||||||
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
||||||
if str(previous.version) != str(version):
|
|
||||||
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
|
|
||||||
except MlflowException:
|
|
||||||
pass
|
|
||||||
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
|
||||||
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
|
|
||||||
return self.get(domain, scenario, version)
|
|
||||||
|
|
||||||
def retire(self, domain: str, scenario: str, version: str):
|
|
||||||
"""Withdraws a version from production; its scenario has no active
|
|
||||||
model until another one is promoted, so predictions stop."""
|
|
||||||
name = registered_name(domain, scenario)
|
|
||||||
try:
|
|
||||||
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
||||||
except MlflowException:
|
|
||||||
active = None
|
|
||||||
if active is None or str(active.version) != str(version):
|
|
||||||
raise ValueError("la versión no está en producción")
|
|
||||||
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
|
|
||||||
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
|
||||||
return self.get(domain, scenario, version)
|
|
||||||
|
|
||||||
|
|
||||||
def _now_iso() -> str:
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def _iso(epoch_millis: int) -> str:
|
|
||||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
registry = ModelRegistry()
|
|
||||||
|
|
||||||
|
|
||||||
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
|
|
||||||
"""The kit cohort build a version was trained on, and its attrition steps."""
|
|
||||||
if not armado_id:
|
|
||||||
return None, []
|
|
||||||
cohortes = import_module(f"persistance.{domain}").cohorte_repository
|
|
||||||
armado = cohortes.get(int(armado_id))
|
|
||||||
if armado is None:
|
|
||||||
return None, []
|
|
||||||
exclusion = cohortes.cohortes.CohorteExclusion
|
|
||||||
pasos = cohortes.leer(lambda sesion: sesion.exec(
|
|
||||||
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
|
||||||
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
|
|
||||||
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
|
||||||
"armado_en": armado.armado_en.isoformat()},
|
|
||||||
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
from typing import Any
|
|
||||||
|
|
||||||
from models.base import ScreeningModel
|
|
||||||
|
|
||||||
|
|
||||||
class TeaModel(ScreeningModel):
|
|
||||||
"""Scaffold for the TEA (autism spectrum disorder) screening model.
|
|
||||||
|
|
||||||
Can pull its own training data straight from `persistance.tea`'s
|
|
||||||
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
|
|
||||||
...) or be handed already-fetched rows. No real model yet; this is
|
|
||||||
interface scaffolding only.
|
|
||||||
"""
|
|
||||||
|
|
||||||
domain = "tea"
|
|
||||||
|
|
||||||
def train(self, data: Any = None) -> None:
|
|
||||||
raise NotImplementedError("TEA training is not implemented yet.")
|
|
||||||
|
|
||||||
def predict(self, data: Any) -> Any:
|
|
||||||
raise NotImplementedError("TEA prediction is not implemented yet.")
|
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
"""Bookkeeping around a training run (ML-01..ML-05).
|
|
||||||
|
|
||||||
Does not train anything. It opens an MLflow run, records which cohort
|
|
||||||
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
|
||||||
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
|
||||||
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
|
|
||||||
methods instead of the fluent API's global active run, so two runs in one
|
|
||||||
process never interfere.
|
|
||||||
|
|
||||||
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
|
|
||||||
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
|
||||||
from mlflow import MlflowClient, MlflowException
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
from models.base import resolve_repository
|
|
||||||
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
|
|
||||||
|
|
||||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
|
||||||
|
|
||||||
|
|
||||||
class ReadOnlyRepository:
|
|
||||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
|
||||||
Write methods raise `PermissionError` so a training routine cannot
|
|
||||||
modify clinical data."""
|
|
||||||
|
|
||||||
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
|
||||||
|
|
||||||
def __init__(self, repository: Repository):
|
|
||||||
self._repository = repository
|
|
||||||
self.model = repository.model
|
|
||||||
|
|
||||||
def get(self, id_):
|
|
||||||
return self._repository.get(id_)
|
|
||||||
|
|
||||||
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
|
||||||
return self._repository.list(limit=limit, offset=offset, **filters)
|
|
||||||
|
|
||||||
def count(self, **filters) -> int:
|
|
||||||
return self._repository.count(**filters)
|
|
||||||
|
|
||||||
def __getattr__(self, name: str):
|
|
||||||
if name in self._WRITE_METHODS:
|
|
||||||
raise PermissionError(
|
|
||||||
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
|
||||||
)
|
|
||||||
raise AttributeError(name)
|
|
||||||
|
|
||||||
|
|
||||||
class TrainingRun:
|
|
||||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
|
||||||
runs require `cohorte_armado_id`, the indicator kit cohort build they were
|
|
||||||
trained on, so their metrics trace back to that data (ML-03); dev runs may
|
|
||||||
omit it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
domain: str,
|
|
||||||
scenario: str,
|
|
||||||
environment: Environment | str,
|
|
||||||
cohorte_armado_id: int | None = None,
|
|
||||||
):
|
|
||||||
if domain not in DOMAINS:
|
|
||||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
|
||||||
environment = Environment(environment)
|
|
||||||
if environment is Environment.PROD and cohorte_armado_id is None:
|
|
||||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
|
|
||||||
|
|
||||||
self.domain = domain
|
|
||||||
self.scenario = scenario
|
|
||||||
self.environment = environment
|
|
||||||
self.cohorte_armado_id = cohorte_armado_id
|
|
||||||
self.client = MlflowClient()
|
|
||||||
experiment_id = self._experiment_id()
|
|
||||||
run = self.client.create_run(
|
|
||||||
experiment_id,
|
|
||||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
|
|
||||||
)
|
|
||||||
self.run_id = run.info.run_id
|
|
||||||
if cohorte_armado_id is not None:
|
|
||||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
|
||||||
|
|
||||||
def _experiment_id(self) -> str:
|
|
||||||
name = registered_name(self.domain, self.scenario)
|
|
||||||
experiment = self.client.get_experiment_by_name(name)
|
|
||||||
if experiment:
|
|
||||||
return experiment.experiment_id
|
|
||||||
root = os.environ.get(ARTIFACT_ROOT_ENV)
|
|
||||||
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
|
|
||||||
|
|
||||||
def repository(self, entity: str) -> ReadOnlyRepository:
|
|
||||||
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
|
|
||||||
return ReadOnlyRepository(resolve_repository(self.domain, entity))
|
|
||||||
|
|
||||||
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
|
||||||
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
|
||||||
named for its kind."""
|
|
||||||
kind = ArtifactKind(kind)
|
|
||||||
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
|
|
||||||
if metadata:
|
|
||||||
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
|
|
||||||
|
|
||||||
def finish(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
metrics: dict[str, Any] | None = None,
|
|
||||||
hyperparameters: dict[str, Any] | None = None,
|
|
||||||
**reports: str | None,
|
|
||||||
) -> str:
|
|
||||||
"""Logs metrics/params to the run, registers it as a new version of
|
|
||||||
`<domain>-<scenario>` tagged with `models.registry`'s promotion
|
|
||||||
inputs (environment, cohort link, report URIs), and returns the new
|
|
||||||
version string. Call once, after training (and artifact logging)
|
|
||||||
completes."""
|
|
||||||
unknown = set(reports) - set(REPORT_TAGS)
|
|
||||||
if unknown:
|
|
||||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
|
||||||
for key, value in (metrics or {}).items():
|
|
||||||
self.client.log_metric(self.run_id, key, value)
|
|
||||||
for key, value in (hyperparameters or {}).items():
|
|
||||||
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
|
||||||
|
|
||||||
name = registered_name(self.domain, self.scenario)
|
|
||||||
try:
|
|
||||||
self.client.create_registered_model(name)
|
|
||||||
except MlflowException as exc:
|
|
||||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
|
||||||
raise
|
|
||||||
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
|
|
||||||
if self.cohorte_armado_id is not None:
|
|
||||||
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
|
|
||||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
|
||||||
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
|
|
||||||
self.client.set_terminated(self.run_id)
|
|
||||||
return str(model_version.version)
|
|
||||||
+22
-28
@@ -1,36 +1,30 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "models"
|
name = "models"
|
||||||
version = "0.1.0"
|
version = "0.0.0"
|
||||||
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
|
description = "Dagster assets and jobs; one module per model."
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"core",
|
||||||
"persistance",
|
"persistance",
|
||||||
"extraction",
|
"dagster",
|
||||||
"mlflow>=2.9",
|
"dagster-webserver",
|
||||||
|
"mlflow-skinny",
|
||||||
|
"openai>=3.59.0",
|
||||||
|
"splink>=5.0.0",
|
||||||
|
"markitdown[docx,xlsx]>=0.1.9",
|
||||||
|
"ocrmypdf>=17.14.2",
|
||||||
|
"pdfplumber>=0.11.11",
|
||||||
|
"scikit-learn>=1.9.1",
|
||||||
|
"scipy>=1.18.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
|
||||||
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
|
||||||
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
|
|
||||||
# requires it, see that module's docstring.
|
|
||||||
export = [
|
|
||||||
"onnx>=1.15",
|
|
||||||
]
|
|
||||||
|
|
||||||
[tool.uv.sources]
|
|
||||||
persistance = { path = "../Persistance", editable = true }
|
|
||||||
extraction = { path = "../Extraction", editable = true }
|
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["hatchling"]
|
requires = ["uv_build>=0.12,<0.13"]
|
||||||
build-backend = "hatchling.build"
|
build-backend = "uv_build"
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
[tool.uv.build-backend]
|
||||||
packages = ["models"]
|
module-name = "models"
|
||||||
|
module-root = ""
|
||||||
[dependency-groups]
|
[tool.uv.sources]
|
||||||
dev = [
|
core = { workspace = true }
|
||||||
"pytest>=8.0.0",
|
persistance = { workspace = true }
|
||||||
"onnx>=1.15",
|
|
||||||
"reportlab>=4.0",
|
|
||||||
]
|
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
|
|
||||||
import importlib
|
|
||||||
|
|
||||||
from persistance import db as persistance_db
|
|
||||||
from persistance import settings as persistance_settings
|
|
||||||
|
|
||||||
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
|
|
||||||
engine = getattr(persistance_db, f"get_{domain}_engine")
|
|
||||||
engine.cache_clear()
|
|
||||||
importlib.import_module(f"core.{domain}.models")
|
|
||||||
if domain != "governance":
|
|
||||||
importlib.import_module(f"core.{domain}.indicadores.models")
|
|
||||||
base = getattr(importlib.import_module(base_module), base_class)
|
|
||||||
base.metadata.create_all(engine())
|
|
||||||
return engine
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def governance_db(tmp_path, monkeypatch):
|
|
||||||
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
|
|
||||||
yield
|
|
||||||
engine.cache_clear()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def cacu_db(tmp_path, monkeypatch):
|
|
||||||
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
|
|
||||||
yield
|
|
||||||
engine.cache_clear()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def mlflow_tracking(tmp_path, monkeypatch):
|
|
||||||
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
|
|
||||||
import mlflow
|
|
||||||
|
|
||||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
|
||||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
|
||||||
mlflow.set_tracking_uri(uri)
|
|
||||||
monkeypatch.chdir(tmp_path)
|
|
||||||
yield
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def production_ready(governance_db, cacu_db, mlflow_tracking):
|
|
||||||
"""Factory: registers a PROD version that passes every promotion check,
|
|
||||||
returns (domain, scenario, version)."""
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
|
||||||
from models.registry import registry
|
|
||||||
|
|
||||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
|
||||||
version = registry.register(
|
|
||||||
domain=domain, scenario=scenario, environment=Environment.PROD,
|
|
||||||
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
|
|
||||||
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
|
||||||
interpretability_report_uri="docs/interpretabilidad.html",
|
|
||||||
)
|
|
||||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
|
|
||||||
return domain, scenario, version
|
|
||||||
|
|
||||||
return make
|
|
||||||
|
|
||||||
|
|
||||||
def tiny_onnx() -> bytes:
|
|
||||||
import onnx.helper
|
|
||||||
|
|
||||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
|
||||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
|
||||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
|
||||||
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
|
|
||||||
|
|
||||||
|
|
||||||
def armado(huella: str) -> int:
|
|
||||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
|
||||||
from persistance.db import get_cacu_session
|
|
||||||
|
|
||||||
with get_cacu_session() as session:
|
|
||||||
fila = CohorteArmado(
|
|
||||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
|
||||||
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
|
|
||||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
|
||||||
session.add(fila)
|
|
||||||
session.flush()
|
|
||||||
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
|
|
||||||
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
|
|
||||||
session.commit()
|
|
||||||
return fila.armado_id
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""The CaCu models compute what the current ones compute: fed the timelines the current
|
||||||
|
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
|
||||||
|
gives the current model's predictions.
|
||||||
|
|
||||||
|
Fixed on purpose, so left out of the comparison:
|
||||||
|
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
|
||||||
|
(1970-01-01 for everyone); the rewrite returns the index sample's date.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models.cacu.specs import MODELS
|
||||||
|
|
||||||
|
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
||||||
|
RTOL = 1e-6 # as captured (models.json)
|
||||||
|
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
|
||||||
|
REFERENCE_CUTOFF = "2026-11-23"
|
||||||
|
|
||||||
|
TYPES = {
|
||||||
|
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
|
||||||
|
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
|
||||||
|
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
|
||||||
|
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
|
||||||
|
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
|
||||||
|
} # fmt: skip
|
||||||
|
CODES = {
|
||||||
|
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
|
||||||
|
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
|
||||||
|
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
|
||||||
|
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
|
||||||
|
}
|
||||||
|
COHORTS = {
|
||||||
|
"cacu_cohort_surveillance": "cohorte_vigilancia",
|
||||||
|
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def timelines(cohort: str) -> pd.DataFrame:
|
||||||
|
"""A reference cohort's timelines in the platform's names and codes."""
|
||||||
|
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
|
||||||
|
found = found.rename(columns={
|
||||||
|
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
|
||||||
|
"valor_codigo": "value_code", "valor_numerico": "value_num",
|
||||||
|
"fuente_tabla": "source_table", "fuente_id": "source_id",
|
||||||
|
}) # fmt: skip
|
||||||
|
found["type"] = found["type"].map(TYPES)
|
||||||
|
for kind, codes in CODES.items():
|
||||||
|
rows = found["type"] == kind
|
||||||
|
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
|
||||||
|
"cin2_logistic"]) # fmt: skip
|
||||||
|
def test_predictions_match_the_current_models(name):
|
||||||
|
spec = MODELS[name]
|
||||||
|
events = timelines(COHORTS[spec.cohort])
|
||||||
|
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
|
||||||
|
model, metrics, _ = spec.train(events, *args)
|
||||||
|
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
||||||
|
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
|
||||||
|
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
|
||||||
|
|
||||||
|
found = spec.predict(model, events)
|
||||||
|
both = found.merge(
|
||||||
|
reference,
|
||||||
|
left_on=["person_id", "horizon_years"],
|
||||||
|
right_on=["pac_id", "horizonte_anios"],
|
||||||
|
how="outer",
|
||||||
|
indicator=True,
|
||||||
|
)
|
||||||
|
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
|
||||||
|
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)
|
||||||
|
if spec.method != "logistic regression":
|
||||||
|
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
"""`models` reads through Persistance's Repository, the same path WebApi
|
|
||||||
uses, against a temporary SQLite database."""
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_dataset_pages_through_every_row(cacu_db):
|
|
||||||
from datetime import date
|
|
||||||
|
|
||||||
from core.cacu.models import Paciente
|
|
||||||
from models.cacu import CaCuModel
|
|
||||||
|
|
||||||
model = CaCuModel()
|
|
||||||
repository = model.repository("paciente")
|
|
||||||
for i in range(7):
|
|
||||||
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
|
||||||
|
|
||||||
rows = list(model.dataset("paciente", batch_size=3))
|
|
||||||
assert [r["pac_id_hospital"] for r in rows] == [f"M-{i}" for i in range(7)]
|
|
||||||
assert list(model.dataset("paciente", pac_id_hospital="M-3"))[0]["pac_sexo"] == "Femenino"
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_entity_is_a_clear_error():
|
|
||||||
from models.tea import TeaModel
|
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="no nope_repository"):
|
|
||||||
TeaModel().repository("nope")
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
import onnx
|
|
||||||
import onnx.helper
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from models.export import inspect_onnx_metadata
|
|
||||||
|
|
||||||
|
|
||||||
def _tiny_onnx_bytes() -> bytes:
|
|
||||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
|
||||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
|
||||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
|
||||||
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
|
|
||||||
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
|
||||||
return model.SerializeToString()
|
|
||||||
|
|
||||||
|
|
||||||
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
|
|
||||||
path = tmp_path / "model.onnx"
|
|
||||||
path.write_bytes(_tiny_onnx_bytes())
|
|
||||||
|
|
||||||
metadata = inspect_onnx_metadata(path)
|
|
||||||
|
|
||||||
assert metadata["available"] is True
|
|
||||||
assert metadata["producer_name"] == "pytest-fixture"
|
|
||||||
assert metadata["graph_inputs"] == ["x"]
|
|
||||||
assert metadata["graph_outputs"] == ["y"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
|
|
||||||
"""A protobuf-valid but structurally broken graph (a node reading an
|
|
||||||
input the graph never declares) must be rejected: `onnx.load` alone
|
|
||||||
only parses the protobuf and would let this through."""
|
|
||||||
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
|
|
||||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
|
||||||
graph = onnx.helper.make_graph([node], "broken", [], [y])
|
|
||||||
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
|
|
||||||
path = tmp_path / "model.onnx"
|
|
||||||
path.write_bytes(model.SerializeToString())
|
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
|
|
||||||
inspect_onnx_metadata(path)
|
|
||||||
|
|
||||||
|
|
||||||
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
|
|
||||||
import builtins
|
|
||||||
|
|
||||||
real_import = builtins.__import__
|
|
||||||
|
|
||||||
def fake_import(name, *args, **kwargs):
|
|
||||||
if name == "onnx":
|
|
||||||
raise ImportError("onnx not installed")
|
|
||||||
return real_import(name, *args, **kwargs)
|
|
||||||
|
|
||||||
monkeypatch.setattr(builtins, "__import__", fake_import)
|
|
||||||
path = tmp_path / "model.onnx"
|
|
||||||
path.write_bytes(b"irrelevant")
|
|
||||||
assert inspect_onnx_metadata(path) == {
|
|
||||||
"available": False,
|
|
||||||
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Phase 1 gate, stages 1-2: everything a site has reaches bronze, once, and every document
|
||||||
|
the rules point at is read into text (scanned ones through OCR)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from synthetic.site import build
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital"
|
||||||
|
|
||||||
|
|
||||||
|
def graph(tmp: Path, hospital_tables: dict[str, list[str]]) -> dict:
|
||||||
|
"""What an operator would draw for this site: one Source per table or set of files, and
|
||||||
|
a Read on each column that holds documents."""
|
||||||
|
|
||||||
|
def table(node_id, db, name):
|
||||||
|
args = {"credentials": f"sqlite:///{db}", "table": name}
|
||||||
|
return {"id": node_id, "kind": "source", "source": SQL_TABLE, "args": args}
|
||||||
|
|
||||||
|
def files(node_id, glob, **extra):
|
||||||
|
args = {"bucket_url": str(tmp / "site" / "files"), "file_glob": glob}
|
||||||
|
return {"id": node_id, "kind": "source", "source": FILES, "args": args, **extra}
|
||||||
|
|
||||||
|
nodes = [
|
||||||
|
table(f"{name}_{t}", tmp / f"hospital_{name}.db", t)
|
||||||
|
for name, tables in hospital_tables.items()
|
||||||
|
for t in tables
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"nodes": nodes
|
||||||
|
+ [
|
||||||
|
table("his_patients", tmp / "site" / "site.db", "pacientes_his"),
|
||||||
|
table("archivos", tmp / "site" / "site.db", "ArchivosUni"),
|
||||||
|
files("notes", "*.csv", source=READERS, resource="read_csv"),
|
||||||
|
files("altas", "*.xlsx", then="persistance.readers:read_excel"),
|
||||||
|
files("pdfs", "*.pdf", then="persistance.readers:read_bytes"),
|
||||||
|
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
|
||||||
|
{"id": "pdfs_text", "kind": "read", "inputs": ["pdfs"], "column": "content"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
SQL_TABLE = "dlt.sources.sql_database:sql_table"
|
||||||
|
FILES = "dlt.sources.filesystem:filesystem"
|
||||||
|
READERS = "dlt.sources.filesystem:readers"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path):
|
||||||
|
count, query = platform.count, platform.query
|
||||||
|
tables = {}
|
||||||
|
for name in ("cacu", "cama"):
|
||||||
|
shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db")
|
||||||
|
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||||
|
found = con.execute("select name from sqlite_master where type = 'table'")
|
||||||
|
tables[name] = [t for (t,) in found]
|
||||||
|
truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"]
|
||||||
|
(tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables)))
|
||||||
|
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||||
|
|
||||||
|
by_place = {}
|
||||||
|
for r in truth:
|
||||||
|
by_place.setdefault(r["where"].split(":")[0].split("/")[0], []).append(r)
|
||||||
|
expected = {
|
||||||
|
"his_patients": len(by_place["pacientes_his"]),
|
||||||
|
"altas": len(by_place["altas.xlsx"]),
|
||||||
|
"notes": len(by_place["consultas.csv"]),
|
||||||
|
"archivos": len(by_place["ArchivosUni"]),
|
||||||
|
"pdfs": len(by_place["files"]),
|
||||||
|
"archivos_text": len(by_place["ArchivosUni"]),
|
||||||
|
"pdfs_text": len(by_place["files"]),
|
||||||
|
}
|
||||||
|
for name, names in tables.items():
|
||||||
|
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
|
||||||
|
for t in names:
|
||||||
|
expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0]
|
||||||
|
|
||||||
|
def counts():
|
||||||
|
return {node: count(f"bronze.n__site__{node}") for node in expected}
|
||||||
|
|
||||||
|
for _ in range(2): # loading the same site again changes nothing
|
||||||
|
platform.ingest()
|
||||||
|
assert counts() == expected
|
||||||
|
read_once = query("select key, _dlt_load_id from bronze.read_cache order by key")
|
||||||
|
assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once
|
||||||
|
|
||||||
|
with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates
|
||||||
|
con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1")
|
||||||
|
platform.ingest()
|
||||||
|
assert counts() == expected
|
||||||
|
corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1"
|
||||||
|
assert query(corrected) == [("64000",)]
|
||||||
|
|
||||||
|
read = query("select id, text, ocr, error from bronze.n__site__archivos_text")
|
||||||
|
assert all(error is None for *_, error in read)
|
||||||
|
space = re.compile(r"\s+")
|
||||||
|
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
|
||||||
|
for r in by_place["ArchivosUni"]:
|
||||||
|
txt, ocr = by_id[int(r["where"].split(":")[1])]
|
||||||
|
assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans
|
||||||
|
if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly
|
||||||
|
assert r["identity"]["record_number"] in txt, (r["where"], txt)
|
||||||
|
assert query("select key, _dlt_load_id from bronze.read_cache order by key") == (
|
||||||
|
read_once
|
||||||
|
) # reruns never read a file again
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
from models.cacu import CaCuModel
|
|
||||||
from models.cama import CaMaModel
|
|
||||||
from models.tea import TeaModel
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
|
||||||
def test_train_not_implemented(cls):
|
|
||||||
model = cls()
|
|
||||||
with pytest.raises(NotImplementedError):
|
|
||||||
model.train()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("cls", [CaCuModel, CaMaModel, TeaModel])
|
|
||||||
def test_predict_not_implemented(cls):
|
|
||||||
model = cls()
|
|
||||||
with pytest.raises(NotImplementedError):
|
|
||||||
model.predict(data=None)
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
from core.ocr import OcrEstatus
|
|
||||||
from models.ocr import (
|
|
||||||
CIT_VPH_COLUMNS,
|
|
||||||
OcrExtractionResult,
|
|
||||||
OcrExtractor,
|
|
||||||
run_pending_extractions,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class StubVphExtractor(OcrExtractor):
|
|
||||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
||||||
return OcrExtractionResult(
|
|
||||||
values={"resultado": "POSITIVO", "genotipo_16": 1, "genotipo_18": 0},
|
|
||||||
confianza=0.92,
|
|
||||||
estatus=OcrEstatus.REALIZADO,
|
|
||||||
requiere_revision=False,
|
|
||||||
metodo_principal="stub-v1",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AlwaysFailsExtractor(OcrExtractor):
|
|
||||||
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
|
|
||||||
raise RuntimeError("boom")
|
|
||||||
|
|
||||||
|
|
||||||
def _make_cacu_citologia_repo():
|
|
||||||
from core.cacu.models import CitologiaCervical
|
|
||||||
from persistance.cacu import citologia_cervical_repository
|
|
||||||
|
|
||||||
return citologia_cervical_repository, CitologiaCervical
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_pending_extractions_populates_result_and_metadata(cacu_db):
|
|
||||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
|
||||||
repo.create(
|
|
||||||
CitologiaCervical(
|
|
||||||
pac_id_hospital="H-1",
|
|
||||||
cit_vph_pdf_blob=b"%PDF-fake",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
|
|
||||||
|
|
||||||
assert summary.processed == 1
|
|
||||||
assert summary.skipped_already_done == 0
|
|
||||||
row = repo.list()[0]
|
|
||||||
assert row.cit_vph_resultado == "POSITIVO"
|
|
||||||
assert row.cit_vph_genotipo_16 == 1
|
|
||||||
assert row.cit_vph_ocr_estatus == OcrEstatus.REALIZADO
|
|
||||||
assert row.cit_vph_ocr_requiere_revision is False
|
|
||||||
assert row.cit_vph_ocr_metodo_principal == "stub-v1"
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_pending_extractions_is_idempotent(cacu_db):
|
|
||||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
|
|
||||||
|
|
||||||
first = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
|
|
||||||
second = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
|
|
||||||
|
|
||||||
assert first.processed == 1
|
|
||||||
assert second.processed == 0
|
|
||||||
assert second.skipped_already_done == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_pending_extractions_persists_failure_instead_of_crashing(cacu_db):
|
|
||||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
|
|
||||||
|
|
||||||
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, AlwaysFailsExtractor(), domain="cacu", entity="citologiacervical")
|
|
||||||
|
|
||||||
assert summary.failed == 1
|
|
||||||
row = repo.list()[0]
|
|
||||||
assert row.cit_vph_ocr_estatus == OcrEstatus.FALLIDO
|
|
||||||
assert row.cit_vph_ocr_requiere_revision is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db):
|
|
||||||
from persistance.governance import extraction_run_repository
|
|
||||||
|
|
||||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
|
|
||||||
|
|
||||||
run_pending_extractions(
|
|
||||||
repo,
|
|
||||||
CIT_VPH_COLUMNS,
|
|
||||||
StubVphExtractor(),
|
|
||||||
domain="cacu",
|
|
||||||
entity="citologiacervical",
|
|
||||||
governance_repository=extraction_run_repository,
|
|
||||||
source_description="HIS export 2026-09-01",
|
|
||||||
)
|
|
||||||
|
|
||||||
runs = extraction_run_repository.list()
|
|
||||||
assert len(runs) == 1
|
|
||||||
assert runs[0].domain == "cacu"
|
|
||||||
assert runs[0].source_description == "HIS export 2026-09-01"
|
|
||||||
|
|
||||||
|
|
||||||
def test_done_rows_do_not_use_up_the_batch(cacu_db):
|
|
||||||
repo, CitologiaCervical = _make_cacu_citologia_repo()
|
|
||||||
for n in range(3):
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital=f"H-{n}", cit_vph_pdf_blob=b"%PDF-fake",
|
|
||||||
cit_vph_ocr_estatus=OcrEstatus.REALIZADO.value))
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital="H-nuevo", cit_vph_pdf_blob=b"%PDF-fake"))
|
|
||||||
repo.create(CitologiaCervical(pac_id_hospital="H-sin-pdf"))
|
|
||||||
|
|
||||||
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu",
|
|
||||||
entity="citologiacervical", limit=1)
|
|
||||||
|
|
||||||
assert (summary.processed, summary.skipped_already_done) == (1, 3)
|
|
||||||
assert repo.list(pac_id_hospital="H-nuevo")[0].cit_vph_resultado == "POSITIVO"
|
|
||||||
assert repo.list(pac_id_hospital="H-sin-pdf")[0].cit_vph_ocr_estatus is None
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
from core.ocr import OcrEstatus
|
|
||||||
from extraction.testing import scanned_pdf, text_pdf
|
|
||||||
from models.ocr import CinGradoOcrExtractor, GradoHistologicoOcrExtractor, VphOcrExtractor
|
|
||||||
|
|
||||||
|
|
||||||
def test_cin_grade_from_narrative_diagnosis():
|
|
||||||
report = text_pdf(
|
|
||||||
[
|
|
||||||
[
|
|
||||||
"REPORTE DE ESTUDIO HISTOPATOLOGICO",
|
|
||||||
"Descripción microscópica: epitelio escamoso con atipia en el tercio inferior.",
|
|
||||||
"No se observa carcinoma invasor.",
|
|
||||||
"DIAGNÓSTICO:",
|
|
||||||
"Lesión intraepitelial escamosa de bajo grado (NIC I) asociada a VPH.",
|
|
||||||
]
|
|
||||||
]
|
|
||||||
)
|
|
||||||
result = CinGradoOcrExtractor().extract(report)
|
|
||||||
assert result.values == {"grado": "LIEBG"}
|
|
||||||
assert result.estatus is OcrEstatus.REALIZADO
|
|
||||||
|
|
||||||
|
|
||||||
def test_breast_histological_grade_prefers_in_situ_over_its_prefix():
|
|
||||||
report = text_pdf([["Diagnóstico: CARCINOMA DUCTAL IN SITU de alto grado nuclear."]])
|
|
||||||
assert GradoHistologicoOcrExtractor().extract(report).values == {"grado": "CARCINOMA_IN_SITU"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_scanned_vph_report_uses_tesseract_and_reports_confidence():
|
|
||||||
report = scanned_pdf([["Resultado VPH: NEGATIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: NO DETECTADO"]])
|
|
||||||
result = VphOcrExtractor().extract(report)
|
|
||||||
assert result.values == {"resultado": "NEGATIVO", "genotipo_16": 0, "genotipo_18": 0}
|
|
||||||
assert result.metodo_principal.startswith("tesseract")
|
|
||||||
assert 0 < result.confianza <= 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_fields_require_review_and_empty_reports_fail():
|
|
||||||
partial = VphOcrExtractor().extract(text_pdf([["VPH alto riesgo: POSITIVO"]]))
|
|
||||||
assert partial.estatus is OcrEstatus.REALIZADO and partial.requiere_revision
|
|
||||||
empty = VphOcrExtractor().extract(text_pdf([["Hoja sin resultados de laboratorio"]]))
|
|
||||||
assert empty.estatus is OcrEstatus.FALLIDO and empty.requiere_revision
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import json
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from models.base import ScreeningModel
|
|
||||||
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
|
||||||
from models.registry import registry
|
|
||||||
|
|
||||||
|
|
||||||
class StubModel(ScreeningModel):
|
|
||||||
domain = "cacu"
|
|
||||||
|
|
||||||
def train(self, data=None):
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
def predict(self, data):
|
|
||||||
return {"label": "positivo", "confianza": 0.73}
|
|
||||||
|
|
||||||
|
|
||||||
def never_applicable(row: dict) -> bool:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _promote_a_version(production_ready):
|
|
||||||
domain, scenario, version = production_ready("v1-prod")
|
|
||||||
return registry.promote(domain, scenario, version)
|
|
||||||
|
|
||||||
|
|
||||||
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
|
|
||||||
version = _promote_a_version(production_ready)
|
|
||||||
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
|
|
||||||
|
|
||||||
prediction = service.predict_and_record(
|
|
||||||
{"edad": 40},
|
|
||||||
pac_id_hospital="H-1",
|
|
||||||
interpretability=Interpretability(odds_ratio=1.8),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert prediction.mlflow_run_id == version.run_id
|
|
||||||
assert prediction.modelo_version == str(version.version)
|
|
||||||
assert prediction.applicability_passed is True
|
|
||||||
assert json.loads(prediction.output)["label"] == "positivo"
|
|
||||||
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
|
|
||||||
|
|
||||||
|
|
||||||
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
|
|
||||||
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
|
|
||||||
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
|
|
||||||
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
||||||
|
|
||||||
|
|
||||||
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
|
|
||||||
_promote_a_version(production_ready)
|
|
||||||
service = PredictionService(
|
|
||||||
StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable
|
|
||||||
)
|
|
||||||
|
|
||||||
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
||||||
assert prediction.applicability_passed is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_applicability_gate_can_reject_outright(production_ready):
|
|
||||||
_promote_a_version(production_ready)
|
|
||||||
service = PredictionService(
|
|
||||||
StubModel(),
|
|
||||||
domain="cacu",
|
|
||||||
scenario="tamizaje",
|
|
||||||
aplicable=never_applicable,
|
|
||||||
reject_inapplicable=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
with pytest.raises(ApplicabilityRejected):
|
|
||||||
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
||||||
|
|
||||||
|
|
||||||
def test_applicability_gate_needs_a_dict(production_ready):
|
|
||||||
_promote_a_version(production_ready)
|
|
||||||
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable)
|
|
||||||
with pytest.raises(TypeError):
|
|
||||||
service.predict_and_record([40], pac_id_hospital="H-1")
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import pytest
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
|
||||||
from models.registry import PromotionBlocked, registry
|
|
||||||
|
|
||||||
|
|
||||||
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
|
|
||||||
version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
assert registry.status("cacu", "tamizaje", version) == "desarrollo"
|
|
||||||
with pytest.raises(PromotionBlocked) as blocked:
|
|
||||||
registry.promote("cacu", "tamizaje", version)
|
|
||||||
failed = {check.code for check in blocked.value.checks if not check.passed}
|
|
||||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
|
|
||||||
domain, scenario, first = production_ready("v1")
|
|
||||||
_, _, second = production_ready("v2", metrics={"auc": 0.84})
|
|
||||||
assert registry.status(domain, scenario, first) == "candidata"
|
|
||||||
registry.promote(domain, scenario, first)
|
|
||||||
registry.promote(domain, scenario, second)
|
|
||||||
assert registry.status(domain, scenario, first) == "retirada"
|
|
||||||
assert registry.status(domain, scenario, second) == "produccion"
|
|
||||||
other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico")
|
|
||||||
registry.promote(other_domain, other_scenario, other_version)
|
|
||||||
assert registry.status(domain, scenario, second) == "produccion"
|
|
||||||
|
|
||||||
|
|
||||||
def test_reports_can_be_attached_after_training(production_ready):
|
|
||||||
domain, scenario, version = production_ready("v1")
|
|
||||||
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None)
|
|
||||||
assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed
|
|
||||||
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf")
|
|
||||||
assert all(c.passed for c in registry.checks(domain, scenario, version))
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
registry.attach_reports(domain, scenario, version, metrics="{}")
|
|
||||||
|
|
||||||
|
|
||||||
def test_artifacts_are_logged_to_the_run(production_ready):
|
|
||||||
domain, scenario, version = production_ready("v1")
|
|
||||||
lineage = registry.lineage(domain, scenario, version)
|
|
||||||
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_retire_and_lineage(production_ready):
|
|
||||||
domain, scenario, first = production_ready("v1", metrics={"auc": 0.8, "brier": 0.2})
|
|
||||||
_, _, second = production_ready("v2", metrics={"auc": 0.85})
|
|
||||||
registry.promote(domain, scenario, second)
|
|
||||||
lineage = registry.lineage(domain, scenario, second)
|
|
||||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
|
||||||
assert [p["paso"] for p in lineage["cohorte_exclusiones"]] == ["candidatas", "sin evento previo"]
|
|
||||||
assert lineage["model_version"]["status"] == "produccion"
|
|
||||||
registry.retire(domain, scenario, second)
|
|
||||||
assert registry.status(domain, scenario, second) == "retirada"
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
registry.retire(domain, scenario, second)
|
|
||||||
|
|
||||||
|
|
||||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
|
||||||
from models.export import inspect_onnx_metadata
|
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="ONNX"):
|
|
||||||
import tempfile
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
|
||||||
path = Path(tmp) / "x.onnx"
|
|
||||||
path.write_bytes(b"weights")
|
|
||||||
inspect_onnx_metadata(path)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
|
|
||||||
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
registry.versions(domain, scenario)
|
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust,
|
||||||
|
and everything the platform can't decide alone is put in front of a reviewer.
|
||||||
|
|
||||||
|
The site hides its answers the way real ones do: demographics split between a database
|
||||||
|
and an Excel file with mistyped record numbers (one of them another patient's real number),
|
||||||
|
reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultations, and
|
||||||
|
contradicting copies of some reports.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
FIELDS = {
|
||||||
|
"cervical_cytology": ("sample_date", "adequacy", "result", "hpv"),
|
||||||
|
"cervical_biopsy": ("request_date", "histology"),
|
||||||
|
}
|
||||||
|
BOOLS = {"hpv"}
|
||||||
|
|
||||||
|
|
||||||
|
def _value(field, v):
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
if field in BOOLS:
|
||||||
|
return bool(v)
|
||||||
|
return v.isoformat() if isinstance(v, date) else str(v)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_messy_site_becomes_silver_and_review_gets_the_rest(platform, messy_site, tmp_path):
|
||||||
|
truth = messy_site.truth
|
||||||
|
(tmp_path / "pipeline.json").write_text(messy_site.drawn)
|
||||||
|
platform.save("concept_maps", "messy_site", messy_site.concept_map)
|
||||||
|
platform.save("pipelines", "site", tmp_path / "pipeline.json")
|
||||||
|
platform.ingest()
|
||||||
|
q = platform.query
|
||||||
|
of = messy_site.patients(q)
|
||||||
|
|
||||||
|
# Persons: nobody is merged with somebody else, except where a record number belongs to
|
||||||
|
# two patients, and that person is held (torn) until a reviewer corrects the record.
|
||||||
|
members: dict[str, set] = {}
|
||||||
|
held, person_of = set(), {}
|
||||||
|
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
|
||||||
|
members.setdefault(person, set()).add(of[record])
|
||||||
|
person_of[record] = person
|
||||||
|
if why:
|
||||||
|
held.add(person)
|
||||||
|
torn = {p for p, who in members.items() if len(who) > 1}
|
||||||
|
assert torn and torn == held, (torn, held)
|
||||||
|
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
|
||||||
|
|
||||||
|
# A name reaches silver as the registry wrote it (accents, ñ); linking compared it
|
||||||
|
# without them, so the reports' plain upper-case names still joined.
|
||||||
|
torn_patients = {x for p in torn for x in members[p]}
|
||||||
|
written = {r["values"]["full_name"] for r in truth
|
||||||
|
if r["entity"] == "identity" and r["person"] not in torn_patients} # fmt: skip
|
||||||
|
names = {text for (text,) in q("select text from silver.person_name")}
|
||||||
|
assert any("ñ" in n for n in written) and written <= names
|
||||||
|
|
||||||
|
# Every patient split into several persons is in the review queue, joined by candidates.
|
||||||
|
parts: dict[str, set] = {}
|
||||||
|
for p, x in patient.items():
|
||||||
|
parts.setdefault(x, set()).add(p)
|
||||||
|
# A queued person or candidate is one of its records (decisions are kept by record).
|
||||||
|
queued = {
|
||||||
|
frozenset(person_of[r] for r in pair)
|
||||||
|
for pair in q("select person, candidate from bronze.n__site__persons__review")
|
||||||
|
}
|
||||||
|
for x, persons in parts.items():
|
||||||
|
if len(persons) > 1:
|
||||||
|
reached, frontier = set(), {next(iter(persons))}
|
||||||
|
while frontier:
|
||||||
|
reached |= frontier
|
||||||
|
frontier = {
|
||||||
|
b for a in frontier for pair in queued if a in pair for b in pair
|
||||||
|
} - reached
|
||||||
|
assert persons <= reached, (x, persons)
|
||||||
|
|
||||||
|
# Every value accepted from a document is what the document says.
|
||||||
|
at = {r["where"]: r for r in truth}
|
||||||
|
place = {
|
||||||
|
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
|
||||||
|
}
|
||||||
|
place |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")}
|
||||||
|
for entity, fields in FIELDS.items():
|
||||||
|
accepted: dict[str, dict] = {} # each accepted record, from its observations (long)
|
||||||
|
for record, field, *values in q(
|
||||||
|
"select _record, field, value_text, value_num, value_bool, value_date "
|
||||||
|
f"from bronze.staged__observation where study = '{entity}'"
|
||||||
|
):
|
||||||
|
value = next((v for v in values if v is not None), None)
|
||||||
|
accepted.setdefault(record, dict.fromkeys(fields))[field] = value
|
||||||
|
for record, values in accepted.items():
|
||||||
|
t = at[place[record]]
|
||||||
|
if not t.get("flipped"):
|
||||||
|
got = {f: _value(f, values[f]) for f in fields}
|
||||||
|
assert got == {f: t["values"][f] for f in fields}, (t["where"], got)
|
||||||
|
|
||||||
|
# A value a rule held (a scan misread: "LJEBG") is held because it is wrong: it is
|
||||||
|
# never loaded, and a reviewer sees it.
|
||||||
|
misread = set()
|
||||||
|
for record, raw in q("select _record, _raw from bronze.staged__held"):
|
||||||
|
if record in place and person_of.get(record) not in torn:
|
||||||
|
t, got = at[place[record]], json.loads(raw)
|
||||||
|
fields = FIELDS[t["entity"]]
|
||||||
|
assert {f: _value(f, got.get(f)) for f in fields} != {
|
||||||
|
f: t["values"][f] for f in fields}, t["where"] # fmt: skip
|
||||||
|
misread.add(place[record])
|
||||||
|
|
||||||
|
# Silver: everything except contradicting reports, rows of the torn person and misreads.
|
||||||
|
out = {place[r] for r, p in person_of.items() if p in torn and r in place} | misread
|
||||||
|
torn_notes = {
|
||||||
|
(e, date.fromisoformat("-".join(reversed(f.split("/")))).isoformat())
|
||||||
|
for e, f, r in q("select expediente, fecha, _record from bronze.n__site__notes")
|
||||||
|
if person_of.get(r) in torn
|
||||||
|
}
|
||||||
|
|
||||||
|
def silver(entity):
|
||||||
|
fields = FIELDS[entity]
|
||||||
|
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
|
||||||
|
return {
|
||||||
|
(patient[p], *(_value(f, v) for f, v in zip(fields, values, strict=True)))
|
||||||
|
for p, *values in rows
|
||||||
|
}
|
||||||
|
|
||||||
|
def expected(entity, keep):
|
||||||
|
return {
|
||||||
|
(r["person"], *(r["values"][f] for f in FIELDS[entity]))
|
||||||
|
for r in truth
|
||||||
|
if r["entity"] == entity and r["where"] not in out and keep(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert silver("cervical_cytology") == expected(
|
||||||
|
"cervical_cytology", lambda r: not r.get("conflict")
|
||||||
|
)
|
||||||
|
assert silver("cervical_biopsy") == expected("cervical_biopsy", lambda r: True)
|
||||||
|
notes = q("select person_id, note_date, specialty, icd10 from silver.clinical_note")
|
||||||
|
assert sorted((patient[p], *map(str, n)) for p, *n in notes) == sorted(
|
||||||
|
(r["person"], r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"])
|
||||||
|
for r in truth
|
||||||
|
if r["entity"] == "clinical_note"
|
||||||
|
and (r["person"], r["values"]["note_date"]) not in torn_notes
|
||||||
|
)
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
|
||||||
from models.registry import registry
|
|
||||||
from mlflow import MlflowException
|
|
||||||
|
|
||||||
from models.training import ReadOnlyRepository, TrainingRun
|
|
||||||
|
|
||||||
|
|
||||||
def test_prod_run_requires_a_cohort_build():
|
|
||||||
with pytest.raises(ValueError, match="cohorte_armado_id"):
|
|
||||||
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD)
|
|
||||||
|
|
||||||
|
|
||||||
def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
assert run.cohorte_armado_id is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
|
|
||||||
checkpoint = tmp_path / "model.onnx"
|
|
||||||
checkpoint.write_bytes(b"fake-onnx-bytes")
|
|
||||||
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
|
||||||
version = run.finish(metrics={"auc": 0.81})
|
|
||||||
|
|
||||||
mv = registry.get("cacu", "tamizaje", version)
|
|
||||||
assert mv.tags["environment"] == Environment.DEV.value
|
|
||||||
metrics = registry.client.get_run(mv.run_id).data.metrics
|
|
||||||
assert metrics["auc"] == 0.81
|
|
||||||
|
|
||||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
|
|
||||||
assert any(path.endswith("model.onnx") for path in artifacts)
|
|
||||||
|
|
||||||
|
|
||||||
def test_read_only_repository_blocks_writes(cacu_db):
|
|
||||||
from persistance.cacu import paciente_repository
|
|
||||||
|
|
||||||
read_only = ReadOnlyRepository(paciente_repository)
|
|
||||||
assert read_only.list() == []
|
|
||||||
with pytest.raises(PermissionError, match="ML-04"):
|
|
||||||
read_only.create(object())
|
|
||||||
with pytest.raises(PermissionError, match="ML-04"):
|
|
||||||
read_only.open_session()
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
repo = run.repository("paciente")
|
|
||||||
assert isinstance(repo, ReadOnlyRepository)
|
|
||||||
with pytest.raises(PermissionError):
|
|
||||||
repo.create(object())
|
|
||||||
|
|
||||||
|
|
||||||
def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, tmp_path, monkeypatch):
|
|
||||||
root = tmp_path / "artefactos"
|
|
||||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
|
|
||||||
run = TrainingRun(domain="cama", scenario="riesgo", environment=Environment.DEV)
|
|
||||||
experiment = run.client.get_experiment_by_name("cama-riesgo")
|
|
||||||
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
|
||||||
|
|
||||||
|
|
||||||
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
assert run.finish() == "1"
|
|
||||||
|
|
||||||
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
assert second.finish() == "2"
|
|
||||||
|
|
||||||
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
|
|
||||||
def unreachable(name):
|
|
||||||
raise MlflowException("servidor no disponible")
|
|
||||||
|
|
||||||
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
|
|
||||||
with pytest.raises(MlflowException, match="no disponible"):
|
|
||||||
third.finish()
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_domain_is_rejected():
|
|
||||||
with pytest.raises(ValueError, match="dominio desconocido"):
|
|
||||||
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
|
||||||
Reference in New Issue
Block a user