Value checks with pandera on cohort files, read and written, and on estimates, written and stored
This commit is contained in:
@@ -6,7 +6,7 @@ import mlflow.pyfunc
|
|||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from models.cacu.cin2_logistic.model import SETTINGS
|
from models.cacu.cin2_logistic.model import SETTINGS
|
||||||
from models.io.contracts import ESTIMATE_COLUMNS
|
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||||
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
|
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
|
||||||
from models.io.registry import ResolvedVersion, registered_name, registry
|
from models.io.registry import ResolvedVersion, registered_name, registry
|
||||||
from models.io.storage import read_cohort, read_metadata, write_once
|
from models.io.storage import read_cohort, read_metadata, write_once
|
||||||
@@ -29,8 +29,7 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No
|
|||||||
if already_estimated(output_path, resolved.version, cohort):
|
if already_estimated(output_path, resolved.version, cohort):
|
||||||
return resolved, False
|
return resolved, False
|
||||||
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
|
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
|
||||||
if tuple(risks.columns) != ESTIMATE_COLUMNS:
|
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
|
||||||
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
|
|
||||||
window = SETTINGS["outcome_window_months"]
|
window = SETTINGS["outcome_window_months"]
|
||||||
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
|
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
|
||||||
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
|
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
|
||||||
|
|||||||
+37
-1
@@ -4,6 +4,7 @@
|
|||||||
every row.
|
every row.
|
||||||
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
|
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
|
||||||
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
|
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
|
||||||
|
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
|
||||||
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
||||||
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
|
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
|
||||||
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
||||||
@@ -15,6 +16,7 @@ from datetime import date
|
|||||||
from typing import NamedTuple, Protocol, runtime_checkable
|
from typing import NamedTuple, Protocol, runtime_checkable
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
import pandera.pandas as pandera
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
COHORT_SCHEMA = pa.schema([
|
COHORT_SCHEMA = pa.schema([
|
||||||
@@ -26,11 +28,45 @@ COHORT_SCHEMA = pa.schema([
|
|||||||
|
|
||||||
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
|
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
|
||||||
|
|
||||||
|
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
|
||||||
|
# schema says which columns and types; these say what a valid row and a valid file are.
|
||||||
|
COHORT_FRAME = pandera.DataFrameSchema(
|
||||||
|
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
|
||||||
|
"fecha_indice": pandera.Column(nullable=False),
|
||||||
|
"fecha": pandera.Column(nullable=False),
|
||||||
|
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||||
|
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||||
|
"fuente_tabla": pandera.Column(str, nullable=False),
|
||||||
|
"fuente_id": pandera.Column(str, nullable=False)},
|
||||||
|
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
|
||||||
|
error="a member has more than one index date"),
|
||||||
|
name="cohort build")
|
||||||
|
|
||||||
|
ESTIMATE_FRAME = pandera.DataFrameSchema(
|
||||||
|
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
|
||||||
|
"fecha_indice": pandera.Column(nullable=False),
|
||||||
|
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
||||||
|
strict=True, ordered=True, name="estimate")
|
||||||
|
|
||||||
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
|
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
|
||||||
|
|
||||||
|
|
||||||
class CohortFileError(ValueError):
|
class CohortFileError(ValueError):
|
||||||
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s."""
|
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
|
||||||
|
`COHORT_FRAME`."""
|
||||||
|
|
||||||
|
|
||||||
|
class EstimateError(ValueError):
|
||||||
|
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
|
||||||
|
|
||||||
|
|
||||||
|
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
|
||||||
|
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
|
||||||
|
try:
|
||||||
|
return schema.validate(frame, lazy=True)
|
||||||
|
except pandera.errors.SchemaErrors as failed:
|
||||||
|
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
|
||||||
|
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
|
||||||
|
|
||||||
|
|
||||||
class CohortDefinitionError(ValueError):
|
class CohortDefinitionError(ValueError):
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ import pyarrow as pa
|
|||||||
import pyarrow.parquet as pq
|
import pyarrow.parquet as pq
|
||||||
from sqlalchemy.engine import make_url
|
from sqlalchemy.engine import make_url
|
||||||
|
|
||||||
from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
|
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
|
||||||
CohortQueries, ExclusionRule)
|
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
||||||
|
|
||||||
|
|
||||||
def cohorts_root(database_url: str) -> Path:
|
def cohorts_root(database_url: str) -> Path:
|
||||||
@@ -108,7 +108,7 @@ def read_cohort(path: str | Path) -> pd.DataFrame:
|
|||||||
schema = pq.read_schema(path)
|
schema = pq.read_schema(path)
|
||||||
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
||||||
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
||||||
return pd.read_parquet(path)
|
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
|
||||||
|
|
||||||
|
|
||||||
def write_once(table: pa.Table, path: Path) -> None:
|
def write_once(table: pa.Table, path: Path) -> None:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from datetime import date, datetime, timezone
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pyarrow as pa
|
import pyarrow as pa
|
||||||
|
|
||||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
|
||||||
from models.io.lineage import table_sha256
|
from models.io.lineage import table_sha256
|
||||||
|
|
||||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||||
@@ -36,5 +36,7 @@ def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str
|
|||||||
|
|
||||||
|
|
||||||
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
|
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
|
||||||
|
"""The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written."""
|
||||||
|
check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}")
|
||||||
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
|
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
|
||||||
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
||||||
|
|||||||
@@ -2,16 +2,12 @@
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from models.io.contracts import ESTIMATE_COLUMNS
|
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||||
|
|
||||||
|
|
||||||
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
|
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
|
||||||
"""One risk per member at the model's horizon, without an interval; a member scored twice stops the batch."""
|
"""One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a
|
||||||
if tuple(estimate.columns) != ESTIMATE_COLUMNS:
|
member scored twice or a probability outside 0..1 stops the batch."""
|
||||||
raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}")
|
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
|
||||||
if estimate["pac_id"].duplicated().any():
|
|
||||||
raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}")
|
|
||||||
if not estimate["probabilidad"].between(0, 1).all():
|
|
||||||
raise ValueError("a probability outside 0..1")
|
|
||||||
return [(int(pac_id), float(horizon_years), float(probability), None, None)
|
return [(int(pac_id), float(horizon_years), float(probability), None, None)
|
||||||
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
|
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
|
||||||
|
|||||||
+3
-1
@@ -13,11 +13,13 @@ dependencies = [
|
|||||||
"pandas>=2.0",
|
"pandas>=2.0",
|
||||||
"pyarrow>=15",
|
"pyarrow>=15",
|
||||||
"scikit-learn>=1.4",
|
"scikit-learn>=1.4",
|
||||||
|
# The values of the cohort and estimate files (`models.io.contracts`).
|
||||||
|
"pandera>=0.20",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
||||||
# models.io.export.inspect_onnx_metadata — writing/logging a checkpoint never
|
# models.io.tracking.inspect_onnx_metadata — writing/logging a checkpoint never
|
||||||
# requires it, see that module's docstring.
|
# requires it, see that module's docstring.
|
||||||
export = [
|
export = [
|
||||||
"onnx>=1.15",
|
"onnx>=1.15",
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""What this module covers: the value checks of the cohort and estimate files (`COHORT_FRAME`, `ESTIMATE_FRAME`,
|
||||||
|
`check_frame` in `models.io.contracts`), and that reading a cohort file and building one apply them.
|
||||||
|
|
||||||
|
Fixtures: none; `_events` makes a valid two-member frame and each test breaks one rule.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date, datetime, timezone
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pyarrow as pa
|
||||||
|
import pyarrow.parquet as pq
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, ESTIMATE_FRAME, CohortFileError, EstimateError,
|
||||||
|
check_frame)
|
||||||
|
from models.io.storage import read_cohort
|
||||||
|
from models.steps.cohort_file import cohort_table
|
||||||
|
|
||||||
|
|
||||||
|
def _events(**changes):
|
||||||
|
frame = pd.DataFrame({"pac_id": [1, 1, 2], "fecha_indice": [date(2025, 1, 1)] * 2 + [date(2025, 2, 1)],
|
||||||
|
"fecha": [date(2025, 1, 1), date(2025, 3, 1), date(2025, 2, 1)],
|
||||||
|
"conocida_en": [datetime(2025, 4, 1, tzinfo=timezone.utc)] * 3,
|
||||||
|
"clase": ["procedimiento", "medicion", "procedimiento"],
|
||||||
|
"tipo": ["citologia", "bethesda", "citologia"], "codigo": ["c", "b", "c"],
|
||||||
|
"valor_codigo": [None, "NORMAL", None], "valor_numerico": [None, None, None],
|
||||||
|
"fuente_tabla": ["citologiacervical"] * 3, "fuente_id": ["a", "a", "b"]})
|
||||||
|
for column, (row, value) in changes.items():
|
||||||
|
frame.loc[row, column] = value
|
||||||
|
return frame
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_valid_build_passes():
|
||||||
|
"""Pins down: a well-formed frame comes back unchanged. Fails if a check rejects valid data, which would stop every
|
||||||
|
export and training."""
|
||||||
|
assert check_frame(COHORT_FRAME, _events(), CohortFileError, "test").equals(_events())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("changes, check", [
|
||||||
|
({"fecha_indice": (1, date(2025, 1, 5))}, "more than one index date"),
|
||||||
|
({"pac_id": (2, 0)}, "greater_than"),
|
||||||
|
({"fecha": (0, None)}, "not_nullable"),
|
||||||
|
({"tipo": (1, "")}, "str_length"),
|
||||||
|
])
|
||||||
|
def test_a_broken_build_names_what_failed(changes, check):
|
||||||
|
"""Pins down: two index dates for a member, a non-positive id, a missing date or an empty type are refused, and
|
||||||
|
the error names the check. Fails if a broken file reaches a model, where it would train on wrong rows."""
|
||||||
|
with pytest.raises(CohortFileError, match=check):
|
||||||
|
check_frame(COHORT_FRAME, _events(**changes), CohortFileError, "test")
|
||||||
|
|
||||||
|
|
||||||
|
def test_reading_and_building_a_file_apply_the_checks(tmp_path):
|
||||||
|
"""Pins down: `read_cohort` refuses a file whose rows break `COHORT_FRAME`, and `cohort_table` refuses to build
|
||||||
|
one. Fails if either path skips the check."""
|
||||||
|
broken = _events(fecha_indice=(1, date(2025, 1, 5)))
|
||||||
|
path = tmp_path / "1.parquet"
|
||||||
|
pq.write_table(pa.Table.from_pandas(broken, schema=COHORT_SCHEMA, preserve_index=False), path)
|
||||||
|
|
||||||
|
with pytest.raises(CohortFileError):
|
||||||
|
read_cohort(path)
|
||||||
|
with pytest.raises(CohortFileError):
|
||||||
|
cohort_table(broken, {"build": 1})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("estimate", [
|
||||||
|
pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "probabilidad": [0.1, 0.2]}),
|
||||||
|
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [1.2]}),
|
||||||
|
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "probabilidad": [0.1], "extra": [1]}),
|
||||||
|
pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "probabilidad": [0.1]}),
|
||||||
|
])
|
||||||
|
def test_an_estimate_is_one_probability_per_member_in_its_columns(estimate):
|
||||||
|
"""Pins down: a member twice, a probability outside 0..1, an extra column or another column order are refused.
|
||||||
|
Fails if a malformed output can be written or stored as risks."""
|
||||||
|
with pytest.raises(EstimateError):
|
||||||
|
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
|
||||||
Reference in New Issue
Block a user