From e8c264e57150e0e3cf31a30a09a211be8fcbba26 Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 21 Nov 2026 22:41:04 -0600 Subject: [PATCH] Subgroup reports for CaCu's survival and PIM scenarios, as version files and as notebooks in the code Every CaCu PIM scenario (cin2_pim, post-colposcopy, post-treatment) and the survival scenario now keep, per combination of their covariates, the model against its empirical estimate, with the methods each used: - PIM (models/cacu/cin2_pim/report.py): Turnbull's interval-censored estimate (prevalent = mass at 0, free in (l, r], unknown baseline in [0, r]; ported from bayes-pim chapter 24) with a bootstrap band, against the mixture refitted on every coded member with a delta-method band over the likelihood (inverse numerical Hessian, numerical gradient of CR(t), log scale); E/O at each horizon with log(E/O) taken as normal. - Survival (models/cacu/survival/report.py): Kaplan-Meier with Greenwood's band against the SEER pipeline's own subgroup points and bootstrap interval (survival_curves.sv_sub_weights and sv_sub_points, called as they are). A version keeps the record as analisis/subgrupos.json and a self-contained Plotly page as reportes/subgrupos.html (TrainingRun.log_report; the saver publishes a dataflow's `reports`). The same drawing is a notebook in the code, models/cacu/{cin2_pim,survival}/notebooks/reporte_subgrupos.ipynb: chart names and computed results only, a `parameters` cell, `#| echo: false` cells. models.reports.templates lists those notebooks with the scenarios each serves and reads one by id, for the WebApi's /governance/notebook-templates. The Jupyter renderer now drops the code of `#| echo: false` cells, as Quarto does. plotly>=5.18 joins the `survival-curves` extra (installed by the WebApi) and the dev group. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- README.md | 7 +- models/cacu/cin2_pim/model.toml | 2 +- .../notebooks/reporte_subgrupos.ipynb | 123 ++++++++ models/cacu/cin2_pim/report.py | 268 ++++++++++++++++++ .../cacu/cin2_pim_post_colposcopy/model.toml | 2 +- .../cacu/cin2_pim_post_treatment/model.toml | 2 +- models/cacu/survival/model.py | 5 +- models/cacu/survival/model.toml | 3 +- .../notebooks/reporte_subgrupos.ipynb | 119 ++++++++ models/cacu/survival/population.py | 9 +- models/cacu/survival/report.py | 136 +++++++++ models/dags/training.py | 6 +- models/io/adapters.py | 9 +- models/io/tracking.py | 6 + models/reports/rendering.py | 16 +- models/reports/templates.py | 67 +++++ pyproject.toml | 5 +- tests/cacu/test_cacu_survival.py | 63 +++- tests/cacu/test_cin2_pim.py | 83 +++++- tests/reports/test_rendering.py | 21 ++ tests/reports/test_templates.py | 36 +++ 21 files changed, 964 insertions(+), 24 deletions(-) create mode 100644 models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb create mode 100644 models/cacu/cin2_pim/report.py create mode 100644 models/cacu/survival/notebooks/reporte_subgrupos.ipynb create mode 100644 models/cacu/survival/report.py create mode 100644 models/reports/templates.py create mode 100644 tests/reports/test_rendering.py create mode 100644 tests/reports/test_templates.py diff --git a/README.md b/README.md index 5dfd432..ebe4ded 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ WebApi. | `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). | | `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`) and their hashes (`file_sha256`, `table_sha256`, `cohort_reference`), dbt's manifest (`read_queries`), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: `KitBuild`, a kit build read now from the domain's database (nothing written), or `CohortFile`, an exported file, behind one contract (`frame`, `lineage`, `reference`). | | `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed `models` package, `code_version`), a model's hash (`model_sha`), and `matches`, the one rule for "already done". | -| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). | +| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `log_analysis` keeps what a run found about its cohort as `analisis/.json`, and `log_report` a self-contained page as `reportes/.html` (aggregates only). `run_files`/`run_file` list and download a run's files (a folder as a zip). | | `io/registry.py` | `registry`: versiones en MLflow (`-`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). | | `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. | | `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. | @@ -30,14 +30,15 @@ WebApi. | `reports/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. | | `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. | | `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. | -| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. | +| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, its `routines`, `population` (`analisis/`) and `reports` (`reportes/`) when the dataflow has them, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. | | `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. | | `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. | | `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. | | `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | | `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. | +| `cacu/cin2_pim/report.py` | The subgroup report of every PIM scenario: per combination of the model's features, Turnbull's interval-censored estimate (prevalent at 0, free in `(l, r]`, unknown baseline in `[0, r]`) with a bootstrap band against the mixture refitted on every coded member with its delta-method band (inverse Hessian, log scale), and E/O at each horizon with log(E/O) taken as normal. `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. | | `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). | -| `cacu/survival/` | CaCu's all-cause survival prototype: the mortality at 1, 3 and 5 years from the cancer diagnosis (provisionally the first biopsy reported as invasive carcinoma, `primera_biopsia_invasora` in `[config.index]`: both the inclusion criterion and the index date), from the age group at the diagnosis and the most recent cytology (KPNC's categories) and HPV up to it, with the SEER pipeline's interval survival as `cama/survival` runs it (LR and Bayesian network per interval, stacked) and its population record (`analisis/curvas.json`: KM with Greenwood, adjusted KM, Weibull, and LR/HBN/combined points with bootstrap intervals). The nodes that don't depend on the covariates are CaMa's, called from here; `encode`, `interval_cohort`, `IntervalSurvival`, `labelled_members`, `missing_data`, `analytic_method` and `survival_frame` are copies over CaCu's covariates (issue #9). The death is the timeline's `defuncion` event, which CaCu's dbt timeline doesn't emit yet. | +| `cacu/survival/` | CaCu's all-cause survival prototype: the mortality at 1, 3 and 5 years from the cancer diagnosis (provisionally the first biopsy reported as invasive carcinoma, `primera_biopsia_invasora` in `[config.index]`: both the inclusion criterion and the index date), from the age group at the diagnosis and the most recent cytology (KPNC's categories) and HPV up to it, with the SEER pipeline's interval survival as `cama/survival` runs it (LR and Bayesian network per interval, stacked) and its population record (`analisis/curvas.json`: KM with Greenwood, adjusted KM, Weibull, and LR/HBN/combined points with bootstrap intervals). The nodes that don't depend on the covariates are CaMa's, called from here; `encode`, `interval_cohort`, `IntervalSurvival`, `labelled_members`, `missing_data`, `analytic_method` and `survival_frame` are copies over CaCu's covariates (issue #9). A version also keeps a subgroup report (`report.py`): per combination of the covariates, the Kaplan-Meier with its Greenwood band against the model's survival with the SEER subgroups' bootstrap interval (`sv_sub_points`), as `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. The death is the timeline's `defuncion` event, emitted by the CaCu dbt timeline (monorepo, same branch). | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `/notebooks/`, fuera del paquete instalado. | | `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-[-]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. | | `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-[-]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. | diff --git a/models/cacu/cin2_pim/model.toml b/models/cacu/cin2_pim/model.toml index 23e6191..7dd38df 100644 --- a/models/cacu/cin2_pim/model.toml +++ b/models/cacu/cin2_pim/model.toml @@ -5,7 +5,7 @@ outcome = "cin2" # What a registered version needs to load and predict, pinned to the installed versions when it's logged. requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] # The modules whose functions are the graph's nodes, in `with_modules`. -modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"] +modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"] description = """ Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \ modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \ diff --git a/models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb b/models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb new file mode 100644 index 0000000..67bfde2 --- /dev/null +++ b/models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb @@ -0,0 +1,123 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "8368c95d", + "metadata": { + "tags": [ + "parameters" + ] + }, + "outputs": [], + "source": [ + "#| echo: false\n", + "#| tags: [parameters]\n", + "turnbull_bootstrap = 200\n", + "report_panels = 24" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "718e1a82", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "from IPython.display import HTML, Markdown, display\n", + "from models.cacu.cin2_pim import report\n", + "from models.dags.training import Scenario, dataflow\n", + "from models.notebook import experiment\n", + "\n", + "exp = experiment()\n", + "scenario = Scenario.load(exp.domain, exp.scenario)\n", + "horizons = scenario.config[\"horizons_years\"]\n", + "risks = dataflow(*scenario.modules, config=scenario.config).execute(\n", + " [\"combination_risks\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage(),\n", + " \"turnbull_bootstrap\": turnbull_bootstrap})[\"combination_risks\"]\n", + "ratios = [e for r in risks for e in r[\"e_o\"] if e[\"E_O\"] is not None]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "107af899", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(Markdown(\n", + " f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(risks)} · pacientes: {sum(r['n'] for r in risks)} · \"\n", + " f\"prevalentes: {sum(r['prevalent'] for r in risks)} · incidentes: {sum(r['incident'] for r in risks)} · \"\n", + " f\"E/O con IC sin 1: {sum(not e['low'] <= 1 <= e['high'] for e in ratios)} de {len(ratios)}\"))" + ] + }, + { + "cell_type": "markdown", + "id": "5d1c43a8", + "metadata": {}, + "source": [ + "## Riesgo acumulado de CIN2+ por combinación: Turnbull y mezcla prevalencia-incidencia" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5d5a1559", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(HTML(report._figure(risks, horizons, report_panels).to_html(full_html=False, include_plotlyjs=True)))" + ] + }, + { + "cell_type": "markdown", + "id": "dc145546", + "metadata": {}, + "source": [ + "## E/O por combinación y horizonte" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "23665b08", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(report._table(risks))" + ] + }, + { + "cell_type": "markdown", + "id": "98091470", + "metadata": {}, + "source": [ + "## Métodos" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "474e00f9", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/models/cacu/cin2_pim/report.py b/models/cacu/cin2_pim/report.py new file mode 100644 index 0000000..2f28b64 --- /dev/null +++ b/models/cacu/cin2_pim/report.py @@ -0,0 +1,268 @@ +"""The subgroup report of a prevalence–incidence training run (every `cin2_pim` scenario): for each combination of the +model's features (KPNC's index cytology, HPV and, with a history, its feature), the model's cumulative risk of CIN2+ +with its delta-method band against the combination's own Turnbull estimate with its bootstrap band, and the ratio of +expected to observed risk (E/O) at each horizon with its interval. A version keeps the record (`analisis/subgrupos.json`, +with the methods it used) and the page (`reportes/subgrupos.html`, Plotly, self-contained). + +- The model is the scenario's mixture refitted on every interval-coded member (not only the training part), so that it + and the empirical estimate describe the same members. +- The empirical estimate is Turnbull's nonparametric maximum likelihood for interval-censored data (self-consistency, + as `bayes-pim/informe/resultados/24/simular_protocolo.py`), with the members coded as the mixture's likelihood reads + them: a prevalent case is the mass at 0, a member found free is censored in `(l, r]`, and one whose baseline is + unknown in `[0, r]` (prevalent or incident). It respects the interval censoring: a CIN2+ is known only between the + last negative and the biopsy, never at a date. Its band and variance are the percentiles and variance of + `turnbull_bootstrap` resamples of the combination's members. +- The model's band is the delta method over the likelihood: Var(CR(t)) = g' Σ g, with Σ the inverse of the observed + information (the numerical Hessian `likelihood.fit` already inverts) and g the numerical gradient of CR(t) in the + stratum's parameters; a parameter at the boundary has no variance in Σ and counts as fixed. The band is on the log + scale, E exp(±1.96 SE(E)/E). +- E/O: log(E/O) taken as normal, with SE^2 = Var(E)/E^2 + Var(O)/O^2. Empty where O is 0. + +Aggregates only: counts, curves and points, never a member's row. +""" + +import numpy as np +import pandas as pd + +from models.cacu.cin2_pim import likelihood +from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture, _features, _levels + +Z = 1.959963984540054 # the normal's 97.5 % quantile +GRID_STEP = 0.1 # years between the points of the model's curve +UNKNOWN = "NA" +NOTICE = "Prototipo sin validación clínica." +METHODS = { + "empirica": "Turnbull (estimador no paramétrico de máxima verosimilitud con censura por intervalos, autoconsistencia): " + "prevalente = masa en 0, libre de CIN2+ = censura en (l, r], basal desconocida = [0, r]; banda e " + "varianza por bootstrap de las pacientes de la combinación", + "modelo": "mezcla prevalencia-incidencia reajustada en todas las pacientes codificadas; banda por método delta sobre " + "la verosimilitud (inversa del Hessiano numérico, gradiente numérico del riesgo acumulado), en escala log; " + "un parámetro en la frontera cuenta como fijo", + "E/O": "riesgo esperado por el modelo entre el observado (Turnbull) a cada horizonte; IC 95 % suponiendo log(E/O) " + "normal, SE² = Var(E)/E² + Var(O)/O²", +} + + +def _turnbull(c: np.ndarray, l: np.ndarray, r: np.ndarray, iters: int = 5000, tol: float = 1e-10): + """(support, cumulative mass) of Turnbull's estimate for members coded `(c, l, r)`: the support is 0, every finite + right end and infinity; a prevalent member's set is {0}, a free one's the points in `(l, r]`, an unknown baseline's + the points in `[0, r]`.""" + finite = r[np.isfinite(r)] + support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]])) + low = np.where(c == 0, l, -np.inf) + high = np.where(c == 1, 0.0, r) + A = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None]) + patterns, counts = np.unique(A, 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() + if np.max(np.abs(new - p)) < tol: + p = new + break + p = new + return support, np.cumsum(p) + + +def _at(support: np.ndarray, cumulative: np.ndarray, t) -> np.ndarray: + """The estimate's cumulative risk at each of `t` (a step function, right-continuous).""" + idx = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1 + return np.where(idx < 0, 0.0, cumulative[np.maximum(idx, 0)]) + + +def _label_value(feature: str, value) -> str: + if value is None or (isinstance(value, float) and np.isnan(value)): + return UNKNOWN + if feature == "hpv_positive": + return "positivo" if float(value) == 1.0 else "negativo" + return str(value) + + +def report_mixture(interval_coded_members: pd.DataFrame, horizons_years: list[float], incidence: dict, + incidence_features: list[str], strata: list[str], cytology: dict, + history: dict) -> PrevalenceIncidenceMixture: + """The scenario's mixture refitted on every interval-coded member, the model the report sets against Turnbull.""" + features = _features(history) + return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence, + _levels(cytology, history)).fit(interval_coded_members[features], + interval_coded_members[["c", "l", "r"]]) + + +def _risk_with_variance(mixture: PrevalenceIncidenceMixture, row: pd.DataFrame, years: np.ndarray): + """The model's cumulative risk of one combination (`row`, one row) at `years`, and its delta-method variance.""" + key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else () + if key not in mixture.fits_: + return None, None + seen = mixture.seen_[key] + if not mixture._placed(row, seen).all(): + return None, None + fit = mixture.fits_[key] + X, Zd = mixture._design(row, seen) + n_x, n_z = len(fit["theta"]), len(fit["beta"]) + + def risk(params): + found = {"theta": params[:n_x], "beta": params[n_x:n_x + n_z], "baseline": fit["baseline"], + "baseline_params": params[n_x + n_z:]} + return likelihood.cumulative_risk(found, X, Zd, years)[0] + + params = np.asarray(fit["params"], dtype=float) + point = risk(params) + gradient = np.empty((len(params), len(years))) + for k in range(len(params)): + step = 1e-5 * max(1.0, abs(params[k])) + up, down = params.copy(), params.copy() + up[k] += step + down[k] -= step + gradient[k] = (risk(up) - risk(down)) / (2 * step) + covariance = np.nan_to_num(np.asarray(fit["covariance"], dtype=float), nan=0.0) + variance = np.einsum("ki,kl,li->i", gradient, covariance, gradient) + return point, np.maximum(variance, 0.0) + + +def combination_risks(interval_coded_members: pd.DataFrame, report_mixture: PrevalenceIncidenceMixture, + horizons_years: list[float], history: dict, turnbull_bootstrap: int = 200) -> list[dict]: + """Per combination of the features present among the coded members, largest first: its members and prevalent + and incident cases, its Turnbull estimate with the bootstrap band, the model's cumulative risk with the delta-method + band (none for a combination the model can't place: a cytology outside KPNC's categories, a stratum unseen) and + E/O at each horizon (see the module's docstring).""" + features = _features(history) + members = interval_coded_members.reset_index(drop=True) + labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label_value(f, v)) for f in features}) + table = labels.drop_duplicates().reset_index(drop=True) + horizons = np.asarray(horizons_years, dtype=float) + grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6) + rng = np.random.default_rng(20261122) + records = [] + for _, row in table.iterrows(): + mask = (labels == row).all(axis=1).to_numpy() + group = members[mask] + c, l, r = group["c"].to_numpy(int), group["l"].to_numpy(float), group["r"].to_numpy(float) + support, cumulative = _turnbull(c, l, r) + boot_grid, boot_h = [], [] + for _ in range(turnbull_bootstrap): + pick = rng.integers(0, len(group), len(group)) + s_b, c_b = _turnbull(c[pick], l[pick], r[pick]) + boot_grid.append(_at(s_b, c_b, grid)) + boot_h.append(_at(s_b, c_b, horizons)) + boot_grid, boot_h = np.array(boot_grid), np.array(boot_h) + O = _at(support, cumulative, horizons) + var_O = boot_h.var(axis=0, ddof=1) if turnbull_bootstrap > 1 else np.full(len(horizons), np.nan) + empirical = {"years": grid.tolist(), "CR": _at(support, cumulative, grid).tolist(), + "low": np.percentile(boot_grid, 2.5, axis=0).tolist() if turnbull_bootstrap else None, + "high": np.percentile(boot_grid, 97.5, axis=0).tolist() if turnbull_bootstrap else None} + + model, ratios = None, [] + probe = group.iloc[[0]][features] + E, var_E = _risk_with_variance(report_mixture, probe, horizons) + curve, var_curve = _risk_with_variance(report_mixture, probe, grid) + if curve is not None: + rel = np.where(curve > 0, np.sqrt(var_curve) / np.maximum(curve, 1e-300), 0.0) + model = {"years": grid.tolist(), "CR": curve.tolist(), + "low": np.clip(curve * np.exp(-Z * rel), 0, 1).tolist(), + "high": np.clip(curve * np.exp(Z * rel), 0, 1).tolist()} + for k, h in enumerate(horizons): + entry = {"years": float(h), "E": None if E is None else float(E[k]), "O": float(O[k]), + "E_O": None, "low": None, "high": None} + if E is not None and E[k] > 0 and O[k] > 0 and np.isfinite(var_O[k]): + se = float(np.sqrt(var_E[k] / E[k] ** 2 + var_O[k] / O[k] ** 2)) + value = float(E[k] / O[k]) + entry.update(E_O=value, low=value * float(np.exp(-Z * se)), high=value * float(np.exp(Z * se))) + ratios.append(entry) + records.append({"combination": row.to_dict(), "n": int(mask.sum()), "prevalent": int((c == 1).sum()), + "incident": int(((c != 1) & np.isfinite(r)).sum()), "empirical": empirical, + "model": model, "e_o": ratios}) + return sorted(records, key=lambda x: (-x["n"], list(x["combination"].values()))) + + +def _label(combination: dict) -> str: + names = {"cytology": "citología", "hpv_positive": "VPH"} + return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items()) + + +def _figure(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24): + """The figure: one panel per combination (the `report_panels` largest), Turnbull's step curve with its band and the + model's curve with its band (a Plotly `Figure`; the page and the notebook draw it).""" + import plotly.graph_objects as go + from plotly.subplots import make_subplots + + shown = combination_risks[:report_panels] + columns = 3 + rows = max(1, -(-len(shown) // columns)) + figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True, + subplot_titles=[f"{_label(r['combination'])}
n = {r['n']}, prevalentes = {r['prevalent']}, " + f"incidentes = {r['incident']}" for r in shown]) + for k, record in enumerate(shown): + row, col, first = k // columns + 1, k % columns + 1, k == 0 + emp, model = record["empirical"], record["model"] + if emp["low"] is not None: + figure.add_trace(go.Scatter(x=emp["years"], y=emp["high"], mode="lines", line={"width": 0, "shape": "hv"}, + hoverinfo="skip", showlegend=False), row=row, col=col) + figure.add_trace(go.Scatter(x=emp["years"], y=emp["low"], mode="lines", line={"width": 0, "shape": "hv"}, + fill="tonexty", fillcolor="rgba(120,130,140,0.30)", hoverinfo="skip", + name="IC 95 % Turnbull (bootstrap)", legendgroup="emp_band", showlegend=first), + row=row, col=col) + figure.add_trace(go.Scatter(x=emp["years"], y=emp["CR"], mode="lines", line={"color": "#242628", "width": 2, + "shape": "hv"}, + name="Turnbull", legendgroup="emp", showlegend=first, + hovertemplate="%{x:.1f} años: %{y:.3f}Turnbull"), row=row, col=col) + if model is not None: + figure.add_trace(go.Scatter(x=model["years"], y=model["high"], mode="lines", line={"width": 0}, + hoverinfo="skip", showlegend=False), row=row, col=col) + figure.add_trace(go.Scatter(x=model["years"], y=model["low"], mode="lines", line={"width": 0}, + fill="tonexty", fillcolor="rgba(111,53,165,0.18)", hoverinfo="skip", + name="IC 95 % modelo (método delta)", legendgroup="model_band", + showlegend=first), row=row, col=col) + figure.add_trace(go.Scatter(x=model["years"], y=model["CR"], mode="lines", line={"color": "#6f35a5", + "width": 2}, + name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first, + hovertemplate="%{x:.1f} años: %{y:.3f}modelo"), row=row, col=col) + figure.update_xaxes(range=[0, max(horizons_years) + 0.05]) + figure.update_yaxes(rangemode="tozero") + figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110}, + title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables
" + f"Años desde la fecha índice; {NOTICE}"}, + legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0}) + return figure + + +def _ratio(e: dict) -> str: + if e["E_O"] is None: + return "—" + flag = "" if e["low"] <= 1 <= e["high"] else " *" + return f"{e['E_O']:.2f} ({e['low']:.2f}–{e['high']:.2f}){flag}" + + +def _table(combination_risks: list[dict]) -> pd.DataFrame: + """Every combination's counts and E/O at each horizon (`*`: its interval leaves out 1).""" + return pd.DataFrame([{**r["combination"], "n": r["n"], "prevalentes": r["prevalent"], "incidentes": r["incident"], + **{f"E/O {e['years']:g} a": _ratio(e) for e in r["e_o"]}} for r in combination_risks]) + + +def subgroup_report(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24) -> str: + """The page: the figure, the table of every combination's counts and E/O, and the methods.""" + figure = _figure(combination_risks, horizons_years, report_panels) + shown = combination_risks[:report_panels] + + table = _table(combination_risks) + omitted = len(combination_risks) - len(shown) + notes = (f"

{omitted} combinaciones más, sin panel (solo en la tabla).

" if omitted > 0 else "") + ( + "

* el IC de E/O no incluye 1. — sin casos observados a ese horizonte o combinación que el modelo no " + "ubica.

Métodos

    " + "".join(f"
  • {k}: {v}
  • " for k, v in METHODS.items()) + "
") + return ("CIN2+ por subgrupo" + "" + figure.to_html(full_html=False, include_plotlyjs=True) + + notes + "

Combinaciones

" + table.to_html(index=False, border=0) + "") + + +def subgroups(combination_risks: list[dict]) -> dict: + """The report's record, with the methods it used.""" + return {"version": 1, "metodos": METHODS, "combinations": combination_risks} + + +def population(subgroups: dict) -> dict: + """What the saver publishes under `analisis/`, by file name.""" + return {"subgrupos": subgroups} + + +def reports(subgroup_report: str) -> dict: + """What the saver publishes under `reportes/`, by name.""" + return {"subgrupos": subgroup_report} diff --git a/models/cacu/cin2_pim_post_colposcopy/model.toml b/models/cacu/cin2_pim_post_colposcopy/model.toml index cfb2378..d65bb39 100644 --- a/models/cacu/cin2_pim_post_colposcopy/model.toml +++ b/models/cacu/cin2_pim_post_colposcopy/model.toml @@ -4,7 +4,7 @@ cohort = "cacu/cohorte_total" outcome = "cin2" requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] # The same dataflow as `cin2_pim`; only the cohort and the config change. -modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"] +modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"] description = """ Prototipo: riesgo acumulado de CIN2+ desde la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+, en la visita y a \ 1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \ diff --git a/models/cacu/cin2_pim_post_treatment/model.toml b/models/cacu/cin2_pim_post_treatment/model.toml index 6c0e247..6070d92 100644 --- a/models/cacu/cin2_pim_post_treatment/model.toml +++ b/models/cacu/cin2_pim_post_treatment/model.toml @@ -4,7 +4,7 @@ cohort = "cacu/cohorte_post_tratamiento" outcome = "cin2" requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] # The same dataflow as `cin2_pim`; only the cohort and the config change. -modules = ["models.cacu.cin2_pim.model"] +modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report"] description = """ Prototipo: riesgo acumulado de CIN2+ desde la primera citología después del tratamiento, en la visita y a 1, 3 y 5 años \ (escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \ diff --git a/models/cacu/survival/model.py b/models/cacu/survival/model.py index 6f810ed..1ec213e 100644 --- a/models/cacu/survival/model.py +++ b/models/cacu/survival/model.py @@ -26,7 +26,7 @@ from hamilton.function_modifiers import extract_fields from sklearn.pipeline import Pipeline from models.annotations import checked_frame -from models.cacu.survival import estimator +from models.cacu.survival import estimator, report from models.cacu.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures from models.cama.seer_survival.settings import SurvivalSettings from models.cama.survival import estimator as cama_estimator @@ -121,7 +121,8 @@ def analytic_method(fitted_survival: IntervalSurvival, survival_settings: Surviv "hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES, "stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()} for row in fitted_survival.stacking_], - "hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_]} + "hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_], + "subgroup_report": report.METHODS} def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict: diff --git a/models/cacu/survival/model.toml b/models/cacu/survival/model.toml index c5de318..f75b63d 100644 --- a/models/cacu/survival/model.toml +++ b/models/cacu/survival/model.toml @@ -5,7 +5,8 @@ outcome = "muerte" # What a registered version needs to load and predict, pinned to the installed versions when it's logged. requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] # The modules whose functions are the graph's nodes, in `with_modules`. -modules = ["models.cacu.survival.model", "models.cacu.survival.population", "models.steps.indexing"] +modules = ["models.cacu.survival.model", "models.cacu.survival.population", "models.cacu.survival.report", + "models.steps.indexing"] description = """ Prototipo: mortalidad por cualquier causa a 1, 3 y 5 años del diagnóstico de cáncer (provisional: la primera biopsia \ con carcinoma invasor), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \ diff --git a/models/cacu/survival/notebooks/reporte_subgrupos.ipynb b/models/cacu/survival/notebooks/reporte_subgrupos.ipynb new file mode 100644 index 0000000..3a9c1f9 --- /dev/null +++ b/models/cacu/survival/notebooks/reporte_subgrupos.ipynb @@ -0,0 +1,119 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "43f4f2cf", + "metadata": { + "tags": [ + "parameters" + ] + }, + "outputs": [], + "source": [ + "#| echo: false\n", + "#| tags: [parameters]\n", + "report_panels = 24" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6f01c5ec", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "from IPython.display import HTML, Markdown, display\n", + "from models.cacu.survival import report\n", + "from models.dags.training import Scenario, dataflow\n", + "from models.notebook import experiment\n", + "\n", + "exp = experiment()\n", + "scenario = Scenario.load(exp.domain, exp.scenario)\n", + "found = dataflow(*scenario.modules, config=scenario.config).execute(\n", + " [\"combination_survival\", \"survival_settings\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage()})\n", + "survival, settings = found[\"combination_survival\"], found[\"survival_settings\"]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "61c183ea", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(Markdown(\n", + " f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(survival)} · pacientes: {sum(r['n'] for r in survival)} · \"\n", + " f\"defunciones: {sum(r['deaths'] for r in survival)} · horizontes: {', '.join(f'{h} m' for h in settings.horizons)}\"))" + ] + }, + { + "cell_type": "markdown", + "id": "fd940976", + "metadata": {}, + "source": [ + "## Supervivencia por combinación: Kaplan-Meier y modelo" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3498c913", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(HTML(report._figure(survival, scenario.config['etiquetas'], settings, report_panels).to_html(full_html=False, include_plotlyjs=True)))" + ] + }, + { + "cell_type": "markdown", + "id": "2d917e18", + "metadata": {}, + "source": [ + "## Pacientes y defunciones por combinación" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1870121a", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(report._table(survival))" + ] + }, + { + "cell_type": "markdown", + "id": "2ef312c0", + "metadata": {}, + "source": [ + "## Métodos" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c63b624", + "metadata": {}, + "outputs": [], + "source": [ + "#| echo: false\n", + "display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/models/cacu/survival/population.py b/models/cacu/survival/population.py index a02cf19..e02d26b 100644 --- a/models/cacu/survival/population.py +++ b/models/cacu/survival/population.py @@ -80,7 +80,8 @@ def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_k bootstrap_points, population_weights, survival_settings, etiquetas) -def population(population_curves: dict) -> dict: - """What the saver publishes under `analisis/`: the curves only (CaMa adds its SEER development stages, which need - covariates CaCu doesn't have).""" - return population_curves +def population(population_curves: dict, subgroups: dict) -> dict: + """What the saver publishes under `analisis/`, by file name: the curves, and each combination of the covariates' + Kaplan-Meier and model survival with the methods used (`report.subgroups`). CaMa adds its SEER development stages + instead, which need covariates CaCu doesn't have.""" + return {**population_curves, "subgrupos": subgroups} diff --git a/models/cacu/survival/report.py b/models/cacu/survival/report.py new file mode 100644 index 0000000..ea6008e --- /dev/null +++ b/models/cacu/survival/report.py @@ -0,0 +1,136 @@ +"""The subgroup report of a training run: for each combination of the covariates (age group, latest cytology, latest +HPV), the model's survival at each horizon with its 95 % interval against the combination's own Kaplan-Meier curve with +its Greenwood band. A version keeps the record (`subgroups`, in `analisis/subgrupos.json`, with the methods it used) +and the page (`reportes/subgrupos.html`, Plotly, self-contained). + +The methods are the SEER pipeline's for its subgroups, called as they are (`models.cama.seer_survival.survival_curves`): +the models are fitted on every member of the indexed cohort (the population curves' cohort, `population.curve_cohort`), +each subgroup has its own stacking weights out of sample (`sv_sub_weights`), and the model's survival of a subgroup is +its members' mean with a bootstrap percentile interval (`sv_sub_points`: `survival.n_boot_sub` resamples, the HBN's +parents of the full fit kept). The Kaplan-Meier curve of a combination is over its members only +(`fractional_weibull.km_curva`, Greenwood on the log-log scale), month by month up to its longest follow-up; death times +are exact (to the month), so it respects their censoring. Aggregates only: counts, curves and points, never a +member's row. +""" + +import numpy as np +import pandas as pd + +from models.cacu.survival.estimator import FEATURES +from models.cama.seer_survival import fractional_weibull as fw +from models.cama.seer_survival import survival_curves as luis +from models.cama.seer_survival import survival_models as sm +from models.cama.seer_survival.settings import SurvivalSettings + +NOTICE = "Prototipo sin validación clínica." + + +METHODS = { + "empirica": "Kaplan-Meier por combinación de covariables, IC 95 % de Greenwood en escala log-log " + "(models.cama.seer_survival.fractional_weibull.km_curva)", + "modelo": "supervivencia por intervalos (LR y red bayesiana, combinadas con pesos fuera de muestra por subgrupo) " + "ajustada en toda la cohorte; media de la combinación con IC 95 % bootstrap percentil " + "(models.cama.seer_survival.survival_curves.sv_sub_weights y sv_sub_points)", +} + + +def combination_survival(survival_frame: luis.SurvivalFrame, curve_cohort: sm.Cohort, luis_points: luis.Points, + survival_settings: SurvivalSettings) -> list[dict]: + """Per combination of the covariates present in the cohort, largest first: its members and deaths, its + Kaplan-Meier curve with the Greenwood band, and the combined model's survival at each horizon with its bootstrap + interval (see the module's docstring).""" + s, df = survival_settings, survival_frame.df.reset_index(drop=True) + combos = df[FEATURES].astype(str) + table = combos.drop_duplicates().reset_index(drop=True) + masks = {str(j): (combos == row).all(axis=1).to_numpy() for j, row in table.iterrows()} + weights = luis.sv_sub_weights(curve_cohort, masks, luis.sv_oof(curve_cohort, s), s) + points = luis.sv_sub_points(curve_cohort, masks, weights, luis_points, s) + months, event = df["meses_int"].to_numpy(int), df["evento"].to_numpy(bool) + name = "COMB" if s.combine_active else "LR" + records = [] + for j, row in table.iterrows(): + members = masks[str(j)] + follow = int(months[members].max()) + km, km_low, km_high = fw.km_curva(months[members], event[members], follow) + model = points[str(j)].query("modelo == @name").sort_values("meses") + records.append({ + "combination": row.to_dict(), "n": int(members.sum()), "deaths": int(event[members].sum()), + "km": {"months": list(range(follow + 1)), "S": km.tolist(), "low": km_low.tolist(), "high": km_high.tolist()}, + "model": {"months": [0, *map(int, model["meses"])], "S": [1.0, *map(float, model["S"])], + "low": [1.0, *map(float, model["IC_inf"])], "high": [1.0, *map(float, model["IC_sup"])]}, + }) + return sorted(records, key=lambda r: (-r["n"], list(r["combination"].values()))) + + +def _label(combination: dict) -> str: + names = {"age_group": "edad", "cytology": "citología", "hpv": "VPH"} + return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items()) + + +def _figure(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings, + report_panels: int = 24): + """The figure: one panel per combination (the `report_panels` largest), the Kaplan-Meier step curve with its band + and the model's points with their intervals (a Plotly `Figure`; the page and the notebook draw it).""" + import plotly.graph_objects as go + from plotly.subplots import make_subplots + + shown = combination_survival[:report_panels] + columns = 3 + rows = max(1, -(-len(shown) // columns)) + figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.08 / max(rows, 1) * 3, + subplot_titles=[f"{_label(r['combination'])}
n = {r['n']}, defunciones = {r['deaths']}" + for r in shown]) + for k, record in enumerate(shown): + row, col, first = k // columns + 1, k % columns + 1, k == 0 + km, model = record["km"], record["model"] + figure.add_trace(go.Scatter(x=km["months"], y=km["high"], mode="lines", line={"width": 0, "shape": "hv"}, + hoverinfo="skip", showlegend=False, legendgroup="km"), row=row, col=col) + figure.add_trace(go.Scatter(x=km["months"], y=km["low"], mode="lines", line={"width": 0, "shape": "hv"}, + fill="tonexty", fillcolor="rgba(120,130,140,0.30)", name="IC 95 % Greenwood", + legendgroup="km", showlegend=first, hoverinfo="skip"), row=row, col=col) + figure.add_trace(go.Scatter(x=km["months"], y=km["S"], mode="lines", line={"color": "#242628", "width": 2, "shape": "hv"}, + name=etiquetas.get("km_crudo", "Kaplan-Meier"), legendgroup="kmline", showlegend=first, + hovertemplate="mes %{x}: S = %{y:.3f}KM"), row=row, col=col) + S, low, high = np.array(model["S"]), np.array(model["low"]), np.array(model["high"]) + figure.add_trace(go.Scatter(x=model["months"], y=S, mode="lines+markers", line={"color": "#6f35a5", "dash": "dot"}, + marker={"symbol": "diamond", "size": 9}, + error_y={"type": "data", "symmetric": False, "array": high - S, "arrayminus": S - low}, + name=etiquetas.get("puntos", "Modelo (IC 95 % bootstrap)"), legendgroup="model", + showlegend=first, hovertemplate="mes %{x}: S = %{y:.3f}modelo"), + row=row, col=col) + figure.update_xaxes(range=[0, max(survival_settings.horizons) + 1], title_text=None) + figure.update_yaxes(range=[0, 1.03]) + figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110}, + title={"text": f"{etiquetas.get('titulo', 'Supervivencia')} — por combinación de covariables
" + f"{etiquetas.get('eje_x', 'Meses')}; {NOTICE}"}, + legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0}) + return figure + + +def _table(combination_survival: list[dict]) -> pd.DataFrame: + """Every combination's counts.""" + return pd.DataFrame([{**r["combination"], "n": r["n"], "defunciones": r["deaths"]} for r in combination_survival]) + + +def subgroup_report(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings, + report_panels: int = 24) -> str: + """The page: the figure, the table of every combination's counts and the methods.""" + figure = _figure(combination_survival, etiquetas, survival_settings, report_panels) + counts = _table(combination_survival) + omitted = max(0, len(combination_survival) - report_panels) + note = (f"

{omitted} combinaciones más, sin panel (solo en la tabla).

" if omitted > 0 else "") + ( + "

Métodos

    " + "".join(f"
  • {k}: {v}
  • " for k, v in METHODS.items()) + "
") + return ("Supervivencia por subgrupo" + "" + + figure.to_html(full_html=False, include_plotlyjs=True) + + note + "

Combinaciones

" + counts.to_html(index=False, border=0) + "") + + +def subgroups(combination_survival: list[dict]) -> dict: + """The report's record, with the methods it used.""" + return {"version": 1, "metodos": METHODS, "combinations": combination_survival} + + +def reports(subgroup_report: str) -> dict: + """What the saver publishes under `reportes/`, by name.""" + return {"subgrupos": subgroup_report} diff --git a/models/dags/training.py b/models/dags/training.py index d92f3b9..b098336 100644 --- a/models/dags/training.py +++ b/models/dags/training.py @@ -78,9 +78,9 @@ def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Dri return builder.build() -# What the saver receives: the fitted model and its metrics, and the routines' records and the population results when the -# dataflow has them. -SAVED = {"fitted_model", "metrics", "routines", "population"} +# What the saver receives: the fitted model and its metrics, and the routines' records, the population results and the +# reports' pages when the dataflow has them. +SAVED = {"fitted_model", "metrics", "routines", "population", "reports"} def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]: diff --git a/models/io/adapters.py b/models/io/adapters.py index 0474f5d..118a4fa 100644 --- a/models/io/adapters.py +++ b/models/io/adapters.py @@ -6,9 +6,10 @@ anything runs and nothing in the model imports MLflow: - `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage", source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file). -- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population"], ...)`: - records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the version's `analisis/` - files when it has one (`TrainingRun.log_analysis`), logs the fitted model in the open `TrainingRun` (`tracking`), +- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population", + "reports"], ...)`: records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the + version's `analisis/` files and its `reports` as its `reportes/` pages when it has them (`TrainingRun.log_analysis`, + `TrainingRun.log_report`), logs the fitted model in the open `TrainingRun` (`tracking`), records the metrics and the config, closes the run, and registers and describes the version (`registry`). Its value is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote it (`ROUTINE_KINDS`). @@ -117,6 +118,8 @@ class RegisteredModelSaver(DataSaver): self.run.log_routine(kind, record) for name, record in data.get("population", {}).items(): self.run.log_analysis(name, record) + for name, page in data.get("reports", {}).items(): + self.run.log_report(name, page) packages = _own_packages(model) for package in packages: cloudpickle.register_pickle_by_value(package) diff --git a/models/io/tracking.py b/models/io/tracking.py index 03fc1fa..4046448 100644 --- a/models/io/tracking.py +++ b/models/io/tracking.py @@ -51,6 +51,7 @@ ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" MODEL_PATH = "model" ROUTINES_PATH = "rutinas" ANALYSIS_PATH = "analisis" +REPORTS_PATH = "reportes" # The routines §5 of the requirements names; a version is promoted only when its run recorded each one. ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO, ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA) @@ -197,6 +198,11 @@ class TrainingRun: population results a dashboard draws, which are not a prediction of any member.""" self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, default=str), f"{ANALYSIS_PATH}/{name}.json") + def log_report(self, name: str, page: str) -> None: + """A page the run wrote about its cohort, `reportes/.html` (self-contained: its scripts inside), which the + version keeps for whoever reviews it. Like `log_analysis`, aggregates only.""" + self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html") + def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str: """Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input example, so no patient data diff --git a/models/reports/rendering.py b/models/reports/rendering.py index 34408af..4898569 100644 --- a/models/reports/rendering.py +++ b/models/reports/rendering.py @@ -85,6 +85,9 @@ class QuartoRenderer(NotebookRenderer): return page.read_text() +HIDE_INPUT_TAG = "remove_input" # what a `#| echo: false` cell gets before the page is exported + + @register_renderer class JupyterRenderer(NotebookRenderer): """The kernel is the one the notebook names, which must be installed beside this package (`python3` is this @@ -121,7 +124,18 @@ class JupyterRenderer(NotebookRenderer): @staticmethod def _page(exporter, node) -> str: - body, _ = exporter(embed_images=True).from_notebook_node(node) + """The page, without the code of the cells that ask for it as Quarto does (`#| echo: false`), so a notebook + renders the same with either renderer.""" + from nbconvert.preprocessors import TagRemovePreprocessor + + for cell in node.cells: + if cell.cell_type == "code" and any(line.replace(" ", "") == "#|echo:false" for line in cell.source.splitlines()): + tags = cell.metadata.setdefault("tags", []) + if HIDE_INPUT_TAG not in tags: + tags.append(HIDE_INPUT_TAG) + page = exporter(embed_images=True) + page.register_preprocessor(TagRemovePreprocessor(remove_input_tags={HIDE_INPUT_TAG}, enabled=True), enabled=True) + body, _ = page.from_notebook_node(node) return body diff --git a/models/reports/templates.py b/models/reports/templates.py new file mode 100644 index 0000000..b53b7af --- /dev/null +++ b/models/reports/templates.py @@ -0,0 +1,67 @@ +"""The notebooks kept in the code, ready to run from the platform: `models///notebooks/*.ipynb`. + +A template's id is `//` (its file without `.ipynb`). It runs like an uploaded notebook +(`models.reports.experiment`), on a build's file and for a scenario: the one of its folder, or any other whose dataflow +lists a module of that folder's package (the PIM report serves `cin2_pim`, `cin2_pim_post_colposcopy` and +`cin2_pim_post_treatment`). Only files under that layout are read: an id that names anything else is refused. +""" + +import json +import re +import tomllib +from pathlib import Path + +from models.io.lineage import DOMAINS +from models.reports.experiment import check_notebook + +ROOT = Path(__file__).resolve().parent.parent +FOLDER = "notebooks" +TEMPLATE_ID = re.compile(r"(?P[a-z]+)/(?P[\w-]+)/(?P[\w.-]+)") + + +def _modules(domain: str) -> dict[str, list[str]]: + """Each scenario of `domain` and the modules its `model.toml` lists.""" + found = {} + for toml in sorted((ROOT / domain).glob("*/model.toml")): + found[toml.parent.name] = list(tomllib.loads(toml.read_text()).get("modules", [])) + return found + + +def notebook_templates(domain: str | None = None) -> list[dict]: + """Every template, by domain and folder: `id`, `domain`, `scenario` (its folder), `name`, `scenarios` (those it + can run for) and `title` (its first heading, else its name).""" + found = [] + for dom in ([domain] if domain else sorted(DOMAINS)): + if dom not in DOMAINS: + raise ValueError(f"dominio desconocido: {dom!r}") + modules = _modules(dom) + for path in sorted((ROOT / dom).glob(f"*/{FOLDER}/*.ipynb")): + scenario, package = path.parent.parent.name, f"models.{dom}.{path.parent.parent.name}." + serves = sorted(s for s, mods in modules.items() if s == scenario or any(m.startswith(package) for m in mods)) + found.append({"id": f"{dom}/{scenario}/{path.stem}", "domain": dom, "scenario": scenario, "name": path.stem, + "scenarios": serves, "title": _title(path) or path.stem}) + return found + + +def _title(path: Path) -> str | None: + try: + cells = json.loads(path.read_text()).get("cells", []) + except (OSError, json.JSONDecodeError): + return None + for cell in cells: + if cell.get("cell_type") == "markdown": + for line in "".join(cell.get("source", "")).splitlines(): + if line.startswith("#"): + return line.lstrip("#").strip() + return None + + +def template_notebook(template_id: str) -> tuple[str, dict]: + """(name, notebook) of a template; `LookupError` if there's no such template, `ValueError` if the id isn't one.""" + match = TEMPLATE_ID.fullmatch(template_id or "") + if not match or match["domain"] not in DOMAINS: + raise ValueError(f"plantilla inválida: {template_id!r}") + path = (ROOT / match["domain"] / match["scenario"] / FOLDER / f"{match['name']}.ipynb").resolve() + if ROOT not in path.parents or not path.is_file(): + raise LookupError(f"no hay plantilla {template_id!r}") + return match["name"], check_notebook(json.loads(path.read_text())) diff --git a/pyproject.toml b/pyproject.toml index 57d6540..7822b97 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,10 +40,12 @@ seer-survival = [ "matplotlib>=3.8", "lifelines>=0.28", # the recurrence analysis' penalised Cox model (`models.cama.recurrence`) ] -# The population curves of a CaMa training run (`models.cama.survival.population`): the fractional Weibull's series. +# The population curves of a survival training run (`models.cama.survival.population`): the fractional Weibull's series; +# plotly for the CaCu survival scenario's subgroup page. survival-curves = [ "scipy>=1.11", "mpmath>=1.3", + "plotly>=5.18", # the CaCu survival scenario's subgroup report page (`models.cacu.survival.report`) ] seer-survival-dca = ["dcurves>=1.1"] @@ -72,6 +74,7 @@ dev = [ "networkx>=3.0", "mpmath>=1.3", "matplotlib>=3.8", + "plotly>=5.18", "nbclient>=0.10", "nbconvert>=7.16", "ipykernel>=6.29", diff --git a/tests/cacu/test_cacu_survival.py b/tests/cacu/test_cacu_survival.py index 32c3798..ca6de1e 100644 --- a/tests/cacu/test_cacu_survival.py +++ b/tests/cacu/test_cacu_survival.py @@ -128,7 +128,8 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort(): assert required == {"source_cohort", "cohort_lineage", "age_cuts", "cytology", "etiquetas", "horizons_years", "index", "survival", "train_fraction"} - assert optional == {"calibration_bins"} # `index` is required: the registered model re-indexes a build with it + # `index` is required: the registered model re-indexes a build with it. + assert optional == {"calibration_bins", "report_panels"} def test_the_index_is_the_first_carcinoma_biopsy_and_its_rules_leave_out_who_they_should(cohort_frame): @@ -214,10 +215,68 @@ def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_mode resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version) assert wrote and resolved.version == version - assert "analisis/curvas.json" in [f["path"] for f in registry.artifacts("cacu", "survival", version)] + files = [f["path"] for f in registry.artifacts("cacu", "survival", version)] + assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html"} <= set(files) risks = pq.read_table(output).to_pandas() assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1)) frame = read_cohort(cohort_file) diagnosis = frame[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "CARCINOMA") & (frame["pac_id"] == 1)] assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == diagnosis["fecha"].iloc[0] assert read_metadata(output)["desenlace"] == "muerte" + + +def test_the_subgroup_report_sets_each_combinations_model_against_its_kaplan_meier(cohort_frame): + """Pins down the report: one record per combination of the covariates present, with its members and deaths adding + up to the cohort, its Kaplan-Meier with a band that holds it, and the model's survival at 0, 12, 36 and 60 months + with its bootstrap interval (the SEER pipeline's subgroups); the model sets HSIL+ below NILM (same age and HPV), + the record names its methods, and the page is Plotly's with a panel per combination. Fails if a combination goes + missing, a band is inverted, the methods go unrecorded, the record stops being JSON, or the page stops drawing the + two series.""" + result = dataflow(*SCENARIO.modules, config=QUICK).execute( + ["population", "reports"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE}) + combos = result["population"]["subgrupos"]["combinations"] + + assert sum(c["n"] for c in combos) == N and sum(c["deaths"] for c in combos) == result["population"]["curvas"]["events"] + for c in combos: + km, model = c["km"], c["model"] + assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(km["low"], km["S"], km["high"])) + assert model["months"] == [0, 12, 36, 60] and model["S"][0] == 1.0 + assert all(0 <= lo <= hi <= 1 for lo, hi in zip(model["low"], model["high"])) + assert set(result["population"]["subgrupos"]["metodos"]) == {"empirica", "modelo"} + by = {tuple(c["combination"].values()): c["model"]["S"][-1] for c in combos} + pairs = [(by[(a, "NILM", h)], by[(a, "HSIL+", h)]) for a, _, h in by if (a, "NILM", h) in by and (a, "HSIL+", h) in by] + assert pairs and all(hsil < nilm for nilm, hsil in pairs) + json.dumps(combos) + page = result["reports"]["subgrupos"] + assert page.startswith("") and "plotly" in page.lower() and "IC 95 % Greenwood" in page + assert "Métodos" in page and "sv_sub_points" in page + + +def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters): + """Runs a notebook's code cells in this process, as the platform's runner would on a build's file (`COHORT_FILE`, + `MODELS_DOMAIN`, `MODELS_SCENARIO`), with `parameters` replacing its parameters cell; returns its namespace.""" + import nbformat + + monkeypatch.setenv("COHORT_FILE", str(cohort_file)) + monkeypatch.setenv("MODELS_DOMAIN", domain) + monkeypatch.setenv("MODELS_SCENARIO", scenario) + namespace = {} + for cell in nbformat.read(path, as_version=4).cells: + if cell.cell_type != "code": + continue + exec(cell.source, namespace) + if "parameters" in cell.metadata.get("tags", []): + namespace.update(parameters) + return namespace + + +def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch): + """Pins down the survival report's notebook (`models/cacu/survival/notebooks/reporte_subgrupos.ipynb`): its cells run + on a build's file with the platform's environment and compute every indexed member's combination. Fails if the + notebook drifts from the report's functions or the scenario's config.""" + from pathlib import Path + + path = Path(estimator.__file__).parent / "notebooks" / "reporte_subgrupos.ipynb" + found = _run_notebook(path, cohort_file, "cacu", "survival", monkeypatch) + + assert sum(r["n"] for r in found["survival"]) == N diff --git a/tests/cacu/test_cin2_pim.py b/tests/cacu/test_cin2_pim.py index b1027ff..d227669 100644 --- a/tests/cacu/test_cin2_pim.py +++ b/tests/cacu/test_cin2_pim.py @@ -7,6 +7,7 @@ prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest) `predict_without_repository` (conftest). """ +import json from datetime import date, datetime, timedelta, timezone import mlflow.pyfunc @@ -161,7 +162,8 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort(): assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence", "incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata", "train_fraction"} - assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index + # `index` from the config (a scenario without one keeps its cohort's index); the report's settings have defaults. + assert optional == {"index", "report_panels", "turnbull_bootstrap"} def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame): @@ -278,3 +280,82 @@ def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame): assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found) assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento" + + + +def test_the_subgroup_report_sets_each_combinations_mixture_against_turnbull(cohort_frame): + """Pins down the report of every PIM scenario: one record per combination of the features present, its members + adding up to the coded members; Turnbull's cumulative risk never falls and stays in [0, 1] inside its band; the + model's risk sits inside its delta-method band; E/O, where Turnbull observed a case, equals E over O inside its + interval; the record names its methods and the page is Plotly's. Fails if a combination goes missing, Turnbull + stops respecting the intervals' ordering, a band is inverted, E/O loses its interval, or the methods go + unrecorded.""" + config = {**CONFIG} + result = training.dataflow(*SCENARIO.modules, config=config).execute( + ["population", "reports", "interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}, + "turnbull_bootstrap": 40}) + record = result["population"]["subgrupos"] + combos = record["combinations"] + + assert sum(c["n"] for c in combos) == len(result["interval_coded_members"]) + assert set(record["metodos"]) == {"empirica", "modelo", "E/O"} + for c in combos: + emp = c["empirical"] + assert np.all(np.diff(emp["CR"]) >= -1e-12) and 0 <= emp["CR"][0] and emp["CR"][-1] <= 1 + 1e-12 + assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(emp["low"], emp["CR"], emp["high"])) + if c["model"] is not None: + m = c["model"] + assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(m["low"], m["CR"], m["high"])) + for e in c["e_o"]: + if e["E_O"] is not None: + assert e["low"] <= e["E_O"] <= e["high"] and e["E_O"] == pytest.approx(e["E"] / e["O"]) + assert any(e["E_O"] is not None for c in combos for e in c["e_o"]) + json.dumps(record) + page = result["reports"]["subgrupos"] + assert page.startswith("") and "Turnbull" in page and "método delta" in page + + +def test_turnbull_puts_a_prevalent_case_at_zero_and_an_interval_case_inside_its_interval(): + """Pins down Turnbull's coding: a prevalent member is mass at 0, a member found free and then a case is mass inside + `(l, r]`, a member free to the end carries mass beyond every finite point. Fails if the prevalence leaks past 0 or + a case is placed outside its interval.""" + from models.cacu.cin2_pim.report import _at, _turnbull + + c = np.array([1, 0, 0, 0]) + l = np.array([0.0, 1.0, 2.0, 3.0]) + r = np.array([0.0, 2.0, np.inf, np.inf]) + support, cumulative = _turnbull(c, l, r) + + assert _at(support, cumulative, [0.0])[0] == pytest.approx(0.25) + assert _at(support, cumulative, [2.0])[0] == pytest.approx(0.5) + assert _at(support, cumulative, [1.5])[0] == pytest.approx(0.25) + + +def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters): + """Runs a notebook's code cells in this process, as the platform's runner would on a build's file (`COHORT_FILE`, + `MODELS_DOMAIN`, `MODELS_SCENARIO`), with `parameters` replacing its parameters cell; returns its namespace.""" + import nbformat + + monkeypatch.setenv("COHORT_FILE", str(cohort_file)) + monkeypatch.setenv("MODELS_DOMAIN", domain) + monkeypatch.setenv("MODELS_SCENARIO", scenario) + namespace = {} + for cell in nbformat.read(path, as_version=4).cells: + if cell.cell_type != "code": + continue + exec(cell.source, namespace) + if "parameters" in cell.metadata.get("tags", []): + namespace.update(parameters) + return namespace + + +def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch): + """Pins down the PIM report's notebook (`models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb`): its cells run on a + build's file with the platform's environment, compute the same combinations the dataflow does and draw them. Fails + if the notebook drifts from the report's functions or the scenario it is run for.""" + from pathlib import Path + + path = Path(model.__file__).parent / "notebooks" / "reporte_subgrupos.ipynb" + found = _run_notebook(path, cohort_file, "cacu", "cin2_pim", monkeypatch, turnbull_bootstrap=20) + + assert found["risks"] and sum(r["n"] for r in found["risks"]) > 0 and found["turnbull_bootstrap"] == 20 diff --git a/tests/reports/test_rendering.py b/tests/reports/test_rendering.py new file mode 100644 index 0000000..d217227 --- /dev/null +++ b/tests/reports/test_rendering.py @@ -0,0 +1,21 @@ +"""What this module covers: `models.reports.rendering.JupyterRenderer`'s page keeps out the code of a cell that asks for +it as Quarto does (`#| echo: false`) and keeps its output, so a notebook renders the same with either renderer. +No kernel runs: the cells carry their outputs already.""" + +import nbformat +from nbconvert import HTMLExporter + +from models.reports.rendering import JupyterRenderer + + +def test_a_cell_with_echo_false_shows_its_output_and_not_its_code(): + """Pins down: the hidden cell's source (a marker in its code) is not on the page, its output is, and a cell without + the option still shows its code. Fails if the Jupyter renderer stops honouring `#| echo: false`.""" + hidden = nbformat.v4.new_code_cell("#| echo: false\nsecret_marker_in_code = 1\nprint('salida visible')") + hidden.outputs = [nbformat.v4.new_output("stream", name="stdout", text="salida visible\n")] + shown = nbformat.v4.new_code_cell("codigo_que_se_ve = 2") + node = nbformat.v4.new_notebook(cells=[hidden, shown]) + + page = JupyterRenderer._page(HTMLExporter, node) + + assert "salida visible" in page and "secret_marker_in_code" not in page and "codigo_que_se_ve" in page diff --git a/tests/reports/test_templates.py b/tests/reports/test_templates.py new file mode 100644 index 0000000..bb6912a --- /dev/null +++ b/tests/reports/test_templates.py @@ -0,0 +1,36 @@ +"""What this module covers: `models.reports.templates`: the notebooks kept in the code are listed by domain with the +scenarios they can run for, read by id, and an id outside their layout is refused.""" + +import pytest + +from models.reports.templates import notebook_templates, template_notebook + + +def test_the_cacu_templates_are_listed_with_the_scenarios_they_serve(): + """Pins down: CaCu's subgroup reports are listed; the PIM one serves every scenario whose dataflow lists its + report, the survival one only its own. Fails if a template stops being found or its scenarios stop following the + `model.toml` modules.""" + found = {t["id"]: t for t in notebook_templates("cacu")} + + pim, survival = found["cacu/cin2_pim/reporte_subgrupos"], found["cacu/survival/reporte_subgrupos"] + assert pim["scenarios"] == ["cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"] + assert survival["scenarios"] == ["survival"] and survival["domain"] == "cacu" and survival["title"] + + +def test_a_template_is_read_by_its_id(): + """Pins down: an id gives the template's name and its notebook (nbformat 4). Fails if the id stops naming the + file under `models///notebooks/`.""" + name, notebook = template_notebook("cacu/survival/reporte_subgrupos") + + assert name == "reporte_subgrupos" and notebook["nbformat"] == 4 and notebook["cells"] + + +@pytest.mark.parametrize("template_id, error", [ + ("cacu/survival/../../io/x", ValueError), ("cacu/../../etc/passwd", ValueError), ("otro/survival/x", ValueError), + ("cacu/survival/no_existe", LookupError), ("", ValueError), +]) +def test_an_id_outside_the_templates_is_refused(template_id, error): + """Pins down: an id with other characters, another domain, or no such file is refused before anything is read. + Fails if a crafted id reaches a file outside the templates.""" + with pytest.raises(error): + template_notebook(template_id)