Compare commits

..

79 Commits

Author SHA1 Message Date
alberto 3908ddf74d Merge pull request 'TEA EEG: cluster choice for training and analysis, text EEG ids, run progress' (#16) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:29 -06:00
ulises 2a04ee8c8e TEA EEG: training and analysis choose the cluster, EEG ids are text, run progress snapshots; tea library pointer 2026-11-23 09:29:41 -06:00
Roberto Treviño Cervantes f9d97f4d12 Scenarios: batch_estimates turns off the cycle's per-member scoring; off for CaMa recurrence, answered per clinical scenario 2026-11-23 00:14:14 -06:00
Roberto Treviño Cervantes 674bdc4bb2 CaMa survival figure: every point from the pipeline's survival stage, the whole cohort's included 2026-11-22 23:46:57 -06:00
Roberto Treviño Cervantes 678c02b79d Merge dev into the CaMa consolidation branch 2026-11-22 23:27:34 -06:00
edgar 1c445286eb Merge pull request 'CaCu models: survival interval, yearly PIM horizons, registry listing of production scenarios' (#14) from integration/cacu-indicadores into dev
Reviewed-on: #14
2026-11-22 23:24:57 -06:00
Roberto Treviño Cervantes 706f7510c5 CaMa survival: the scenario points from the pipeline's depuration and survival stage over the current members 2026-11-22 23:22:31 -06:00
Roberto Treviño Cervantes 07c91adbe6 CaMa survival figure: Weibull fits on the scenario's own deaths and the pipeline's published points, as its survival stage draws a subgroup 2026-11-22 22:59:47 -06:00
alberto 8545c36bc4 Merge pull request 'TEA: ADOS-2 scoring command and library pointer' (#13) from feature/tea-eeg-analysis into dev
Reviewed-on: #13
2026-11-22 22:13:32 -06:00
ulises 6d653e9f17 TEA: score ADOS-2 evaluations from their items (calibrated severity score and classification) with a score-ados2 command; tea library pointer 2026-11-22 22:01:50 -06:00
ulises a9ab8612f8 TEA: ADOS-2 association job, EEG zone values, spike minutes as exposure and the count baselines' reference range; tea library 0.3.0 2026-11-22 21:47:15 -06:00
edgar ccaa6fca12 Registry: list a domain's scenarios with a version in production 2026-11-22 20:34:38 -06:00
edgar e1f388c702 Read the CaCu PIM curves at every year from 0 to 5
The horizons are evaluation points of the fitted I-spline curve, so the fit is unchanged; each batch gains the 2- and 4-year rows.
2026-11-22 20:26:47 -06:00
edgar 55d675c8a8 CaCu survival: each risk comes with its combination's bootstrap interval
The covariates are categorical, so every member of a combination gets the same mortality. Training keeps, per
combination of its members, the percentiles of the mortality of `risk_interval_replicas` refits on bootstrap resamples
(`risk_interval_level`, 0.95), and estimating writes it as each risk's interval. A combination training never saw has
none.
2026-11-22 20:10:40 -06:00
Roberto Treviño Cervantes b3e02f0980 CaMa recurrence trains on the loaded METABRIC and SCAN-B patients in the total cohort, not on bundled files; the second survival scenario is retired 2026-11-22 19:51:20 -06:00
edgar c676dde0d0 CaCu survival: a case is a carcinoma, invasive or in situ
The scenario's diagnosis is the first biopsy reported as CIS or invasive carcinoma (`event_grades`), so in situ cases
are followed too and a CIS before an invasive carcinoma is the index date.
2026-11-22 19:16:05 -06:00
Roberto Treviño Cervantes 5a10be44d0 CaMa survival: no member is followed past today 2026-11-22 18:04:57 -06:00
edgar 34b26d8c85 CaCu survival: an estimand that shows the probability of surviving
The model gives the probability of dying (`muerte`, like every batch the probability of its outcome); `complement =
"supervivencia"` tells the screens to show its complement as the probability of surviving, from the first invasive
biopsy, with its covariates.
2026-11-22 15:04:03 -06:00
edgar f00dd31450 CaCu PIM estimands: a probability, its covariates, and the surveillance index in short
The quantity is "Probabilidad"; each scenario names the covariates it uses, which the patient's record writes under
the table; the surveillance and cancer scenarios name their index as the latest cytology with cytology and HPV
results.
2026-11-22 15:04:03 -06:00
edgar 547ceedea3 Merge pull request 'CaCu PIM: risk intervals, estimand, latest-cytology index, cancer outcome; pipeline drawings' (#12) from integration/cacu-indicadores into dev
Reviewed-on: #12
2026-11-22 13:46:19 -06:00
Roberto Treviño Cervantes d91ac7c14b CaMa survival: the members' stage, surgery and adjuvant treatments, read by the clinical scenarios and the development stages 2026-11-22 11:36:52 -06:00
edgar 28858c6966 CaCu: the surveillance PIM with cancer as the outcome (cancer_pim)
The same dataflow, cohort, index and prediction index as the CIN2+ surveillance model, with carcinoma as the only
event, like the cancer column of KPNC's tables: the patient's two risks are of the same visit. The subgroup report
template serves it too.
2026-11-22 09:34:35 -06:00
edgar 835817930d CaCu PIM: the estimand says what the number is, not how its interval is computed
The interval's method (delta method on the log scale) is the version's subgroup report's; the screens that show the
estimand don't need it.
2026-11-22 09:34:35 -06:00
Roberto Treviño Cervantes 94c7cf93dc Merge the CaMa SEER survival and METABRIC/SCAN-B recurrence work into dev's CaMa models 2026-11-22 09:18:15 -06:00
ulises 73c5176482 CaMa recurrence: the METABRIC and SCAN-B analysis as a model over the loaded cohorts
Luis's recurrence scripts are kept as experiments. `models/cama/recurrence` holds the variable dictionary, the
scenarios and the settings as data (`model.toml`), the writer of each cohort file as CaMa import files, the recode of the
timeline into the per-patient frame and the analysis (Cramér's-V pruning, logistic terms and Bayesian-network parents per
horizon, the scenario figures). The variable reader of the survival model is public so both share it. Includes the survival
pipeline work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:39 -06:00
edgar 7928b478f9 CaCu PIM subgroup report: risks in percent, one scale per panel, the empirical method in plain words
The figure drew proportions with no unit, which read as a risk a hundred times smaller than the table's and the
patient's. Each panel now has its own y scale, so a low-risk combination isn't flattened by a high-risk one, and the
methods describe Turnbull's curve by what each patient contributes to it.
2026-11-22 07:38:47 -06:00
edgar 46bc6bcf39 CaCu PIM: risk intervals, what the number is, and the surveillance risk from the latest cytology
- The registered mixture gives each risk's interval at `risk_interval_level` (delta method on the log scale, from
  the fit's inverse Hessian), so the patient's risk carries it.
- `[estimand]` in `model.toml` says what the model's number is (quantity, outcome, index date, unit of the horizons,
  interval), read into `Scenario.estimand` for the screens that show it.
- The surveillance scenario predicts from each patient's latest cytology with both cytology and HPV results, before
  any colposcopy (`prediction_index = "ultima_citologia"`): every new complete sample is a new index date, and a
  sample still missing a result gives way to the one before. Patients past a colposcopy are the post-colposcopy
  scenario's. Training keeps the first cytology in the window. The rule runs inside the registered model, so it loads
  without this repository.
2026-11-22 07:38:39 -06:00
edgar 78a4748592 Estimates: each risk's interval when the model gives one; a member it can't place has no rows
A run with `risk_interval_level` has a model that gives, after the risk at each horizon, its interval's lower and
upper ends; the estimate keeps them as `ic_bajo` and `ic_alto`, the contract checks that they hold the risk, and the
batch stores them. `scored_frame` is the one place that reads the run and calls the model, for the command and the
WebApi's cycle. A member whose risk is NaN (a combination the model never saw) is left out instead of stopping the
whole batch.
2026-11-22 07:38:17 -06:00
edgar 271c799d0a Tests: the PIM likelihood gives KPNC's published risks to machine precision
A fixture of the published cumulative risks at 0-5 years of KPNC's tables 1, 17, 18, 24 and 25 (CIN2+ and CIN3+),
with the knots, spline coefficients and proportional factors that reproduce them, checked against
`cumulative_risk` to 1e-12. Aggregates of public tables only.
2026-11-22 07:38:07 -06:00
edgar d090bb0f9f Governance: each version stores the drawing of its dataflow as files of its own
Training stores the scenario's Hamilton graph as `diagramas/pipeline.dot` and, when Graphviz's `dot` is installed,
`diagramas/pipeline.svg`, listed next to the version's other files. Without the `graphviz` package there is no
drawing and training goes on.
2026-11-22 07:38:07 -06:00
luis 9c7c718a7b Tests for the SEER survival pipeline's stages and runner 2026-11-22 03:28:04 -06:00
luis 42161eb612 CaMa SEER survival pipeline: the six scripts as Hamilton DAGs, one module of nodes per stage and the heavy routines apart
Stages 01-06 (depuration, MCA balancing and categorization, bootstrap indices, stepwise LR and hybrid Bayesian network, survival curves, risk factors), settings in model.toml, run.py writing each stage's files and pipeline.py as the runner that replaces ejecutar_pipeline.py. New extras seer-survival and seer-survival-dca; experiments/ excluded from the wheel.
2026-11-22 03:28:04 -06:00
luis c70aef2a04 Keep the original SEER survival scripts as experiments (not packaged) 2026-11-22 03:28:01 -06:00
edgar 0b25a5687e Merge pull request 'CaCu survival: all-cause mortality at 1, 3 and 5 years and subgroup reports' (#10) from integration/cacu-indicadores into dev
Reviewed-on: #10
2026-11-22 01:00:39 -06:00
edgar e8c264e571 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 22:41:04 -06:00
edgar 9cba11c2ec CaCu survival: all-cause mortality at 1, 3 and 5 years from the cancer diagnosis
A new scenario, models/cacu/survival, from the total cohort. PROVISIONAL index: the first biopsy reported as invasive
carcinoma (`primera_biopsia_invasora` with `CARCINOMA`), both the inclusion criterion and the index date; out without
a birth date or with a death on or before it. The covariates are the most recent observations up to the diagnosis:
the age group at it, the latest cytology sample in KPNC's categories and the latest HPV result. The outcome is the
timeline's `defuncion` (emitted by the monorepo's CaCu timeline on its own branch).

The fit is the SEER pipeline's interval survival as cama/survival runs it (LR and Bayesian network per interval,
stacked), and a version publishes the same population record, `analisis/curvas.json` (KM with Greenwood, adjusted KM,
Weibull, LR/HBN/combined points with bootstrap intervals): the survival panel a collaborator's proof of concept asked
for, without its synthetic covariates or its fixed 50:50 mix.

CaMa's code is not changed. The nodes that don't depend on the covariates call CaMa's; encode, interval_cohort,
IntervalSurvival, labelled_members, missing_data, analytic_method and survival_frame are copies over CaCu's covariates,
because CaMa's read its FEATURES as a module constant. Issue #9 records the duplication and how to remove it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 21:37:43 -06:00
edgar feb934da2f ML-01a: the training run is the registered routine; its routine records are reported, not required
Not every model has each of the five routine records (a prevalence-incidence mixture has no class balance or
classifier calibration), so requiring all of them blocked promotion of models whose run is in order. The check now
passes when the version comes from its training run and its detail says which records the run holds
("registros de rutina: k de 5 (...)"). A version declared over the API still can't be promoted: it has no saved
model (ML-01b).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 19:17:45 -06:00
angel b608dc0b53 Merge pull request 'CaMa: survival and recurrence models, the live scenario figures, and their training from governance' (#7) from feature/cama-roundtrip into dev
Reviewed-on: #7
2026-11-21 15:03:33 -06:00
rockdrigo 1b9afb22ea CaMa: the SEER stages see the molecular subtype; the subtype derivation is shared; the live menu reads the scenarios that can be drawn 2026-11-21 14:43:46 -06:00
rockdrigo 3fdc59df6d CaMa recurrence: the CLI entry imports its data folder; test of the entry a governance job runs 2026-11-21 13:43:19 -06:00
rockdrigo 9fe1f86c8b CaMa recurrence: a version trains, registers and publishes its figures (test) 2026-11-21 13:41:15 -06:00
rockdrigo 0804937578 CaMa recurrence: the METABRIC and SCAN-B analysis as a trainable scenario, with its scenario figures and a patient-to-scenario match 2026-11-21 13:34:56 -06:00
rockdrigo e99eb499d6 CaMa survival: the live figure is the clinical scenario's, over the production model and the live cohort 2026-11-21 13:14:06 -06:00
rockdrigo b1006a97d7 CaMa survival: the clinical scenarios are a shared module and stage 6 lists each scenario's risk factors; the live figure drops the unused options 2026-11-21 13:03:19 -06:00
rockdrigo 997aebd068 CaMa survival: a saved model is rehydrated with the current class before scoring 2026-11-21 12:15:22 -06:00
rockdrigo b8936522be CaMa survival: the figure for a selection of members, scored with the production model over the live cohort; the pipeline's chart wording 2026-11-21 12:07:21 -06:00
rockdrigo ec430c3ee3 CaMa survival: the published figure runs the SEER pipeline's stage-5 functions, and the production model keeps its structure settings 2026-11-21 10:33:48 -06:00
rockdrigo 0cf3e60341 CaMa survival: the published figure carries no test-data note 2026-11-21 10:13:47 -06:00
rockdrigo 4c8b559557 CaMa development record: tables carry their column order 2026-11-21 05:03:52 -06:00
rockdrigo f3be09467f CaMa survival: the SEER pipeline is imported only when a run develops the model 2026-11-21 03:33:44 -06:00
rockdrigo 9cccec5274 CaMa survival: lesion-size feature and the SEER development stages published with each version 2026-11-21 03:28:13 -06:00
rockdrigo 67787adfd4 Merge the SEER survival pipeline
# Conflicts:
#	README.md
#	models/cama/seer_survival/survival_models.py
#	pyproject.toml
2026-11-21 02:07:49 -06:00
rockdrigo edda0fd7b7 Merge CaMa survival scenario and its population results 2026-11-21 02:07:45 -06:00
rockdrigo acc8c371bc CaMa survival: the SEER interval-survival pipeline as a scenario with population results
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping
their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the
total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the
cohort's events, fits the interval survival, writes the five routines and publishes the population curves
(analisis/curvas.json) with the version. An estimate may carry the model's own index date.
2026-11-21 02:07:34 -06:00
edgar 941ae15a3e A risk carries the model's index date for its member
Risk and risk_rows give (pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto), the shape a batch now
stores: the horizons count from the model's index date, taken from the estimate's rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:46 -06:00
edgar 410de1d3b7 Each scenario's index and rules in its pipeline, matching dbt's cohorts
models/steps/indexing.py: a scenario that lists it gets its source cohort as `source_cohort`, and the node `cohort`
re-indexes it by `[config.index]` of its model.toml: the surveillance kind (first cytology) and the post-colposcopy
kind (visit k), with dbt's rules in dbt's order and names, the recruitment window taken from the source cohort's
parameters. Every kind ends with `observacion_previa_insuficiente`, a threshold on the days observed before the index
(0 for now: the data are left-truncated, so rules on earlier events read only what was recorded). On the synthetic
copy the pipeline gives dbt's patients, index dates and attrition for cin2_pim and cin2_logistic (surveillance) and
cin2_pim_post_colposcopy (visit 1, now on cacu/cohorte_total). cin2_logistic's MUESTREO records the index attrition and
the prior history; a stored build's lineage carries its parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 21:54:47 -06:00
edgar 0880181219 Merge dev into feature/cohorts-dbt-canonical: TEA EEG analysis and baselines
Conflicts: the README keeps this branch's rows and adds TEA's; `__main__` keeps the Scenario-based commands and adds
`_own_steps`; pyproject keeps the reports/ paths and adds the `eeg-reference` extra. `GIT_COMMIT_TAG` comes back in
`models.io.lineage` as the name of MLflow's own tag, which `models.tea.eeg.bundle` reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:05:13 -06:00
edgar ea6db36b23 dbt is the only definition of a cohort: the stored build runs dbt's queries
The WebApi cycle's build (models.cohorts.build.build_of) runs the cohort's queries from dbt's manifest with the same
chain as the export, instead of a Python frame per cohort; the TOML definitions, their frames and definition.py are
removed. A cohort may have no exclusions (cacu/cohorte_total, for models whose rules don't fit SQL) and an optional
`variables` query; the population meta carries the cohort's version. cohort_urls lists a domain's cohorts in the
manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 19:52:05 -06:00
edgar 06829a4498 Post-colposcopy scenario reads the cohort of the first surveillance visit
cin2_pim_post_colposcopy now reads cacu/cohorte_post_colposcopia_visita_1 (dbt): Cheung et al. 2020 index the risk at
the first surveillance visit with a cotest, not at the first cytology. Its description states the provisional
assumption that a colposcopy without a biopsy order is below CIN2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 19:52:02 -06:00
luis c42f544173 Tests for the SEER survival pipeline's stages and runner 2026-11-20 13:40:06 -06:00
luis 305e855a15 CaMa SEER survival pipeline: the six scripts as Hamilton DAGs, one module of nodes per stage and the heavy routines apart
Stages 01-06 (depuration, MCA balancing and categorization, bootstrap indices, stepwise LR and hybrid Bayesian network, survival curves, risk factors), settings in model.toml, run.py writing each stage's files and pipeline.py as the runner that replaces ejecutar_pipeline.py. New extras seer-survival and seer-survival-dca; experiments/ excluded from the wheel.
2026-11-20 13:40:06 -06:00
luis 76d6b96409 Keep the original SEER survival scripts as experiments (not packaged) 2026-11-20 13:40:06 -06:00
edgar 7d50786ac2 cin2_pim post-colposcopy and post-treatment scenarios, and their kit cohorts
Two TOML-only scenarios on cin2_pim's dataflow (KPNC's scenarios 4 and 5): CIN2+, KPNC's three post cytology groups,
the referral grade as history after colposcopy, and the strata that reproduce KPNC's tables 17 and 24 (one mixture per
referral grade; one mixture). The kit definitions of both cohorts mirror the dbt rules, so the WebApi cycle can build
them and KitBuild read them. A notebook describes the scenarios, their encoders and the shared DAG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:09:40 -06:00
edgar bde02109ab Surveillance cohort: a glandular-only index result counts as an index result
Mirror of the dbt rule no_index_result, which now reads the timeline's glandular rows (AGC, ADENOCARCINOMA) next to
the Bethesda and HPV ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:09:28 -06:00
edgar 3e72063e3f cin2_pim with PIMixture's I-spline baseline, frequency weights, HPV strata and KPNC's cytology categories
The incidence baseline is chosen in model.toml (Weibull or I-splines of order 4 with knots at quantiles, equal to
PIMixture's Ispline); identical rows are fitted once with their count as weight; one mixture per stratum, a member of
an unseen stratum or level gets NaN. The index cytology goes into KPNC's six categories, glandular results included and
the most severe winning; an optional history feature is read from the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:06:05 -06:00
AlbertoPMDM 200cb106e1 Merge feature/tea-eeg-analysis into feature/tea-eeg-baseline-bundles 2026-11-20 09:40:20 -06:00
AlbertoPMDM 70646e64b6 TEA EEG baselines trained on a local cohort and moved between installations as a bundle of group numbers 2026-11-20 09:36:41 -06:00
AlbertoPMDM 8eac071778 Loading a TEA EEG baseline leaves sys.path as it was, so later Dask workers still import tea.pipeline 2026-11-20 09:33:21 -06:00
AlbertoPMDM 7b8a4e8499 TEA EEG baselines keep their artifacts under MLFLOW_ARTIFACT_ROOT, not in the working directory 2026-11-19 23:17:42 -06:00
edgar 01e4406838 The notebook runner moves to reports/: experiment, notebook_jobs and notebook_import next to rendering and eda
They run a notebook on a build's file and keep it as an MLflow run, as eda does; io/ keeps the storage and MLflow
boundary and pipelines/ the cohort pipelines. Moved whole with git mv, imports repointed; models.notebook, the API
notebooks import, stays where it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:50:46 -06:00
edgar dce29670a4 The classifier's routines join the fitting steps: analytic_method, class_balance, output_confidence and routines
They depend only on the fitted pipeline and the split, so every scenario that lists models.steps.model_fitting
records them; sampling and missing_data stay in cin2_logistic, which owns windowed_outcomes and index_sample_results.
Moved as written in the merge (git blame -C follows them to 1b45bc6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:46:50 -06:00
edgar 6fbf573999 Merge dev into the Hamilton dataflow: the governance routines and the notebook runner on scenarios declared in model.toml
dev's 1b45bc6 (governance requirements, sandboxed notebooks) was written on the per-scenario driver that this branch
replaced with models.dags; it is carried over in that shape:

- cin2_logistic: the five ML-01a routines (sampling, missing_data, analytic_method, class_balance, output_confidence)
  and `routines` are nodes of the scenario's dataflow, on its node names (windowed_outcomes, train_set, test_set,
  fitted_pipeline, test_probabilities); `calibration_bins` is a config input with a default.
- io/adapters, dags/training: the saver writes each routine with TrainingRun.log_routine before logging the model;
  the driver hands it `routines` when the dataflow has that node. Without it a scenario still trains, but the registry
  won't promote it (ROUTINE_KINDS).
- io/tracking: dev's log_routine, run_files and run_file next to this branch's log_model (scikit-learn or pyfunc,
  pinned requirements).
- reports/rendering: dev's Quarto and Jupyter renderers (io/rendering.py, followed as a rename) with this branch's
  notebook hash; notebook_jobs and experiment import it from there, and cohort_reference and file_sha256 from
  io/storage.
- cin2_logistic/train.py: a delegate to models.dags.training for callers of the old driver.
- Persistance's English names from dev: persistance.edges.gold, cohort_repository.

Tests: 219 passed against the monorepo's dev Persistance, Extraction and Core (OCR with tesseract deselected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:44:34 -06:00
edgar fe7f881ade CIN2+ PIM coding as KPNC's: a visit is free of CIN2+ with HPV-negative and NILM or ASC-US, a positive without histology leaves it unknown
known_negative takes lists per key; the last negative carries every earlier one, and follow-up without a test isn't
counted. docs/codificacion_pim.md gives the six example patients, each with its unit test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:23:36 -06:00
AlbertoPMDM 3669aa9eae TEA EEG analysis at the age the EDF header gives, the patient's rows as fallback; tea library 0.2.0 2026-11-19 19:20:29 -06:00
AlbertoPMDM 25c460f80e feat(tea): EEG analysis and age baselines on the tea library, installed from the libs/tea submodule 2026-11-19 15:43:27 -06:00
Roberto Treviño Cervantes 7b2eae2782 wording fixes 2026-11-17 02:17:31 -06:00
roberto fc77fd625e Merge pull request 'Kit exit: CaCu model support for the entrenar/promote cycle' (#6) from feature/kit-exit-integration into dev
Reviewed-on: #6
2026-11-16 21:07:37 -06:00
edgar 0be622c12d Models as a dataflow with Hamilton adapters: scenarios declared in model.toml, cohort read from the database or a file, a scikit-learn model registered with its requirements, estimates per horizon, and the CIN2+ prevalence-incidence scenario 2026-11-11 23:27:38 -06:00
edgar c9eb68ee42 Fitting steps every scenario shares: a temporal split, the classifier chosen by config, the fit and its metrics 2026-11-11 23:27:38 -06:00
172 changed files with 24595 additions and 846 deletions
+3
View File
@@ -0,0 +1,3 @@
[submodule "tea"]
path = libs/tea
url = ssh://git@10.0.10.41:2222/alberto/tea.git
+23 -13
View File
@@ -2,9 +2,11 @@
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
los trabajos de OCR de reportes. Las cohortes se definen solo en dbt
(`Transformation/models/<dominio>/cohorts/`); el ciclo de la WebApi guarda un
armado de ellas (`cohorte_armado`, en la base de cada dominio, por
`models/cohorts/build.py`), y con ese armado se entrena y se estima. Las reglas
que no caben en SQL son del modelo, sobre `cacu/cohorte_total`. Lee y escribe por los mismos repositorios de `Persistance` que usa
WebApi.
| Módulo | Qué hace |
@@ -13,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. `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). `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. |
| `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/<name>.json`, and `log_report` a self-contained page as `reportes/<name>.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 (`<dominio>-<escenario>`), 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. |
@@ -21,20 +23,28 @@ WebApi.
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). |
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohort_repository`: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
| `reports/` (`rendering.py`, `eda.py`) | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `<scenario>/notebooks/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Renderers are classes in `rendering.py` (`RENDERERS`, `register_renderer`): `quarto` (`QUARTO_BIN`, and a Python with Jupyter in `QUARTO_PYTHON`) and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
| `pipelines/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
| `io/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
| `io/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. |
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
| `reports/` (`rendering.py`, `eda.py`) | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `<scenario>/notebooks/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). Rendering: Runs a notebook and renders its page. Renderers are classes (`RENDERERS`, `register_renderer`): `quarto` and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
| `reports/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
| `reports/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
| `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 `<domain>-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` (which refuses a build with no rows or with a member, a date or an event missing: `MODEL_COHORT`, pandera) 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, its metrics and the routine records every classifier shares (`sampling`, `analytic_method`, `class_balance`, `output_confidence`), gathered by `routines` with the scenario's `missing_data` (ML-01a). |
| `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`, `fitted_model`: a scikit-learn `Pipeline` that takes the long frame, and its `missing_data` routine record). Training records its five routines. 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 incidence, `likelihood.py`), fitted to each member's code and interval; the clinical settings (windows, known-negative results) in `model.toml`. Its dataflow records its own five routines. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `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). 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 `<escenario>/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-<biomarker>[-<stage>]`): 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-<biomarker>[-<stage>]` 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. |
| `tea/eeg/reference.py`, `tea/eeg/bundle.py` | Training the baselines where the EEGs live and shipping only the result. `models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60]` trains on a folder of EDFs on this machine (ages from the table's `archivo` and `edad_meses` or `edad_anos`, or from each EDF header); file names stay in the listing, keyed by position. `models tea export-baselines --out baselines.zip [--environment prod] [--production]` writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; `models tea import-baselines baselines.zip` checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports. |
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
| `cama/seer_survival/` | CaMa's SEER survival pipeline, ported from six scripts into Hamilton DAGs, one per stage (extra `seer-survival`). Settings in `model.toml` (`settings.py`); paths are inputs, never settings. Each stage is a module of nodes plus, where the routine is heavy, a module of plain functions apart (as `tea/eeg/analyze.py`): `depuration.py` + `depuration_stats.py` (01: Theil's U and GVIF redundancy screen and its threshold calibration), `balancing.py` + `balancing_stats.py` and `categorization.py` + `categorization_stats.py` (02: 18-month outcome, MCA undersampling, Bayesian change-point grouping of age and tumor size, categorization proposals), `bootstrap.py` (03: resample indices), `modeling.py` + `lr_selection.py`, `hbn.py`, `natural.py`, `resampling.py` + `replica.py` (04: stepwise LR, hybrid Bayesian network, natural-population LR, bootstrap and proposal replicas), `survival_curves.py` + `survival_models.py`, `fractional_weibull.py` (05: Kaplan-Meier, classic and Kilbas-Saigo Weibull, stacked LR + HBN survival, subgroups) and `risk_factors.py` + `risk_factor_stats.py` (06: four-criteria risk factors). `run.py` writes each stage's files; `pipeline.py` runs them in order, skipping the current ones: `python -m models.cama.seer_survival --data DIR [--solo 05] [--desde 02] [--forzar 02 04] [--todo]`. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+172
View File
@@ -0,0 +1,172 @@
# Codificación de la línea de tiempo para el modelo prevalencia–incidencia
Cómo la historia de cada paciente se resume en un código $C$ y un intervalo $(L, R]$, qué factor aporta a la
verosimilitud y en qué columnas del *Enrollment table* de KPNC cae. La codificación la hace
`models.cacu.cin2_pim.model.interval_coded_members`; cada ejemplo de abajo tiene su prueba unitaria en
`tests/cacu/test_cin2_pim.py` (`test_patient_1_…` a `test_patient_6_…`, más VPH−/ASC-US como negativo y
VPH+/NILM como desconocido).
## Modelo
- $\pi(x) = \operatorname{expit}(x^\top\theta)$: probabilidad de NIC2+ en la visita índice (prevalencia, logística).
- $S(t \mid z) = \exp\{-\Lambda_0(t)\, e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (riesgos
proporcionales), con $\Lambda_0$ Weibull, $(t/\lambda)^k$, o los I-splines de PIMixture, $\sum_j e^{\gamma_j} I_j(t)$
(`incidence` en `model.toml`). Una mezcla por estrato (`strata`: VPH en el tamizaje,
grado de la referencia después de colposcopía, ninguno después de tratamiento), con la citología índice en las
categorías de KPNC.
- Riesgo acumulado: $CR(t) = \pi + (1-\pi)\,[1 - S(t)]$.
El tiempo se cuenta en años desde la visita índice $T_0$.
## Reglas de codificación
- $R$: fecha de la **primera biopsia NIC2+** (o $\infty$ si no hay).
- $L$: fecha del **último hallazgo libre de NIC2+ antes de $R$**: una biopsia menor a NIC2+, o una visita con
visita con VPH negativo y citología NILM o ASC-US (el negativo sin histología de KPNC; `known_negative` en
`model.toml`). Una prueba positiva sin histología (VPH+, o LSIL o peor) deja el estado desconocido. Si cae dentro
de la ventana basal (`prevalent_window_months`), $L = 0$.
- $C = 1$ si $R$ cae dentro de la ventana basal; $C = 0$ si hubo al menos un hallazgo libre; si no, $C = -999$.
- El seguimiento sin prueba no cuenta: nadie se considera libre hasta el corte de datos, solo hasta su último negativo.
## Factor de verosimilitud por paciente
| $C$ | $(L, R]$ | Factor $\mathcal{L}_i$ | Logística | Incidencia |
|---|---|---|---|---|
| 1 | $(0, 0]$ | $\pi$ | caso | — |
| 0 | $(L, R]$, $R<\infty$ | $(1-\pi)\,[S(L) - S(R)]$ | control | censura por intervalo |
| 0 | $(L, \infty)$ | $(1-\pi)\,S(L)$ | control | censura derecha en $L$ ($L=0$: nada) |
| −999 | $(0, R]$ | $\pi + (1-\pi)\,[1 - S(R)]$ | latente | latente |
| −999 | $(0, \infty)$ | $1$ | — | — |
Con $C$ conocido el logaritmo se separa en una logística y un modelo de supervivencia con censura por intervalo:
$$
\ell = \underbrace{\sum_{C=1}\log\pi + \sum_{C=0}\log(1-\pi)}_{\text{logística}}
+ \underbrace{\sum_{C=0}\log[S(L)-S(R)]}_{\text{incidencia}}
+ \sum_{C=-999}\log\{\pi + (1-\pi)[1-S(R)]\}.
$$
Solo los desconocidos acoplan las dos partes. La probabilidad posterior de que un desconocido diagnosticado en $R$
fuera prevalente es $w = \pi / \{\pi + (1-\pi)[1-S(R)]\}$.
### Por qué varias visitas dan un solo factor
Con enfermedad absorbente (no regresa), negativos verdaderos (sensibilidad 1) y calendario de visitas no informativo,
para negativos en $t_1 < \dots < L$ y NIC2+ en $R$:
$$
P(\text{neg } t_1,\dots,\text{neg } L,\ \text{pos } R) = P(T > L,\ T \le R) = S(L) - S(R).
$$
El último negativo implica todos los anteriores. Si la sensibilidad es menor que 1 o la lesión puede regresar, cada
visita aporta su propio factor (verosimilitud con filtro hacia adelante, como en el modelo generativo de `bayes-pim`).
## Ejemplos
Todas las pacientes tienen ASC-US/VPH+ en $T_0$, así que entran en la celda **VPH+ / ASC-US** del Enrollment table
(la celda la define el resultado índice; visitas posteriores no crean otra fila en esta tabla).
| Paciente | Historia | $(C, L, R]$ | Factor | Logística | Incidencia | Columnas del Excel |
|---|---|---|---|---|---|---|
| 1 | $T_1$ (1 mes): colposcopía, NIC3 | $(1, 0, 0]$ | $\pi$ | caso | — | n, informativa, caso, prevalente |
| 2 | $T_1$: biopsias normales; $T_2$ (1 año): cotest negativo; $T_3$: ASC-US/VPH+; $T_4$: NIC3 | $(0, T_2, T_4]$ | $(1-\pi)[S(T_2)-S(T_4)]$ | control | intervalo $(T_2, T_4]$ | n, informativa, caso, incidente |
| 3 | Colposcopía omitida; $T_1$: ASC-US/VPH+; $T_2$: NIC3 | $(-999, 0, T_2]$ | $\pi + (1-\pi)[1-S(T_2)]$ | latente (peso $w$) | latente (peso $1-w$) | n, informativa, caso, desconocido |
| 4 | Colposcopía omitida; $T_1$ (1 año): cotest negativo | $(0, T_1, \infty)$ | $(1-\pi)\,S(T_1)$ | control | censura derecha en $T_1$ | n, informativa |
| 5 | $T_1$ (1 mes): biopsias normales; sin más visitas | $(0, 0, \infty)$ | $1-\pi$ | control | — | n, informativa |
| 6 | Colposcopía omitida; no regresa | $(-999, 0, \infty)$ | $1$ | — | — | n |
Prevalente, incidente y desconocido reparten solo a los **casos**; las no-caso informativas (4 y 5) no tienen
columna propia.
Notas:
- **Paciente 2.** El ASC-US/VPH+ de $T_3$ no es un negativo: la lesión pudo existir desde $T_3$. La biopsia normal de
$T_1$ queda implicada por el negativo de $T_2$.
- **Paciente 3.** No es $L = R = T_2$ (eso diría que la lesión apareció justo en $T_2$). Es censura izquierda en
$T_2$: $T \le T_2$, incluida la masa en cero (prevalente).
- **Paciente 4.** Depende de que la lesión no regrese: razonable para NIC3+, discutible para NIC2 (que regresa con
frecuencia), y de que el cotest negativo sea verdadero. $R = \infty$; el $-999$ es el código de $C$, no de $R$.
- **Paciente 5.** El negativo cae en la ventana basal, $L = 0$ y $S(0) = 1$: solo informa la prevalencia.
- **Paciente 6.** No aporta, siempre que la pérdida de seguimiento sea no informativa (MAR); si quienes omiten la
colposcopía tienen otro riesgo, el modelo no lo detecta.
## Protocolo clínico de KPNC y definiciones de la tabla
Cheung LC, Egemen D, Chen X, et al. *2019 ASCCP Risk-Based Management Consensus Guidelines: Methods for Risk
Estimation, Recommended Management, and Validation*. J Low Genit Tract Dis 2020;24(2):90–101.
doi:10.1097/LGT.0000000000000528 (PMC7147416). Las tablas de riesgo están en Egemen D, et al., J Low Genit Tract Dis
2020;24(2):132–143, doi:10.1097/LGT.0000000000000529, y las de genotipificación (VPH16/18) en Demarco M, et al., J Low
Genit Tract Dis 2020;24(2):144–147, doi:10.1097/LGT.0000000000000530.
**Protocolo** (sección *Screening Tests and Clinical Management in the KPNC*):
> "Patients with cytologic abnormalities were referred to colposcopy per Kaiser guidelines, which closely resembled US
> consensus recommendations. However, those without abnormalities, specifically patients who tested HPV negative/NILM
> (cotest negative) were asked to return for testing in 3 years. […] Patients with HPV-negative/ASC-US or
> HPV-positive/NILM results were monitored annually and referred to colposcopy for either a subsequent abnormal
> cytology result or HPV positivity (after 2005)."
Cotest (HC2 + citología) desde 2003 en ≥ 30 años, desde 2013 en 25–29; tratamiento de NIC2+ con LEEP.
**Qué mide el riesgo** (sección *Risk Estimation and Definition of Intervals…*):
> "The CIN 2+ and CIN 3+ risks represent precancers and cancers that are detectable through colposcopy with multiple
> biopsies (not just targeted to the single worst appearing region)."
**Definiciones de prevalente, incidente y desconocido** (misma sección):
> "We define prevalent CIN 3+ as CIN 3+ detected after colposcopic referral because of the baseline (current) test
> results. We define a patient as having <CIN 3 at a visit if the diagnosis was either (1) directly confirmed through
> histopathology or, in the absence of histopathologic outcomes, (2) if neither HPV nor cytology tests were positive
> (i.e., HPV negative/NILM or HPV negative/ASC-US). […] patients with positive test results (HPV-positive or ≥LSIL
> cytology results), but without histopathologic outcomes or a future <CIN 3 to rule out CIN 3+, are considered to
> have unknown (in statistical terms, "latent") histologic status at that screen."
> "(1) prevalent (left-censored at the current test), (2) incident (interval-censored between the last result <CIN 3
> and the time of CIN 3+ detection), or (3) unknown prevalent or incident (CIN 3+ detected in follow-up but cannot rule
> out disease prevalence). Patients who never had CIN 3+ detected were considered right censored at the time of the
> last <CIN 3 visit. Individuals who were never defined as <CIN 3 or CIN 3+ at any time points did not contribute to
> risk estimation."
Ejemplos de historias codificadas: apéndice C (material suplementario) del mismo artículo.
**Supuestos declarados** (Discusión): (1) VPH−/NILM y VPH−/ASC-US son <NIC3; (2) la histopatología es correcta;
(3) el NIC3+ diagnosticado no regresa; (4) censura independiente y no informativa; (5) que un caso de seguimiento sea
prevalente o incidente depende solo de covariables conocidas (MAR).
**Genotipificación.** VPH16/18 solo se midió en una submuestra en dos fases (estudio PaP); se ponderó cada paciente
por el inverso de su fracción de muestreo ("survey weights") para reconstituir la cohorte.
### Diferencias con nuestro protocolo
- **Biopsia.** KPNC define el riesgo respecto a colposcopía con biopsias múltiples. Aquí solo se biopsia si la
impresión colposcópica es LIEBG+. Una colposcopía con impresión normal y sin biopsia no es "<CIN 3 confirmado por
histopatología": bajo las definiciones de KPNC la visita queda **desconocida**, no negativa. Tratarla como negativa
exige modelar la sensibilidad de la impresión colposcópica (modelo por visita). Además, el riesgo "inmediato" que
estimemos es el detectable con biopsia dirigida, menor que el de KPNC: una razón O/E < 1 frente a sus tablas no
significa por sí sola menor riesgo.
- **Negativo sin histología.** Alineado con KPNC (2026-11-13): VPH−/NILM y VPH−/ASC-US, en la basal y en el
seguimiento, en `models-pim` (`known_negative`) y en la simulación de `bayes-pim` (`cells.NEGATIVE_CYTOLOGY`,
`generative.pim_codes`). Antes solo NILM/VPH−; la simulación además contaba como negativo un resultado "leve"
del seguimiento (VPH+/NILM, VPH−/LSIL), que ahora deja el estado desconocido.
- **Genotipificación.** Nuestras submuestras con VPH16/18 no vienen de un diseño con fracciones conocidas: la
probabilidad de estar tipificada (por unidad, periodo, laboratorio, resultado) tendría que estimarse, y el IPW con
pesos estimados (que Hyun et al. 2017 contemplan) solo corrige si la tipificación es MAR dadas esas variables.
## Referencia y estimación
Hyun N, Cheung LC, Pan Q, Schiffman M, Katki HA. *Flexible risk prediction models for left or interval-censored data
from electronic health records*. Ann Appl Stat 2017;11(2):1063–1084. doi:10.1214/17-AOAS1036.
- Los desconocidos se tratan **dentro de la verosimilitud** como $C$ faltante bajo MAR: su factor es la mezcla de la
tabla y el mecanismo de faltante es ignorable. No se imputan ni se ponderan.
- El **IPW** del artículo es para otra cosa: la tipificación de VPH se hizo solo en una submuestra estratificada en dos
fases (9,258 de 33,295 mujeres), y cada mujer de la submuestra se pondera por el inverso de su probabilidad de
inclusión para representar a la cohorte. Sin submuestreo, todos los pesos valen 1 y se recupera la verosimilitud de
arriba.
- El **algoritmo iterativo** es el del estimador semiparamétrico (logística-Cox con $\Lambda$ no paramétrica): alterna
(i) $\Lambda$ con el *iterative convex minorant* (ICM) dados los coeficientes y (ii) los coeficientes
$(\theta, \beta)$ con IRLS dado $\Lambda$, hasta converger. El modelo débilmente paramétrico ($\Lambda$ con B-splines
integrados) se ajusta con Newton–Raphson. Nuestro Weibull maximiza la misma verosimilitud directamente.
- Supuestos que el propio artículo declara: enfermedad progresiva (sin regresión) y verificación perfecta del
desenlace; ambos se relajan solo con un modelo por visita.
File diff suppressed because one or more lines are too long
Submodule
+1
Submodule libs/tea added at ed31baf70f
+143 -10
View File
@@ -4,8 +4,10 @@ Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit
command that needs them, so `--help` stays immediate.
"""
import argparse
import json
import sys
from collections.abc import Sequence
from dataclasses import asdict
def _show_help(parser: argparse.ArgumentParser) -> int:
@@ -25,6 +27,17 @@ def _scenario(args: argparse.Namespace):
return None
def _own_steps(args: argparse.Namespace):
"""A scenario that isn't trained on a cohort build runs its own steps: its `model.run_steps`, or `None`."""
from importlib import import_module
try:
model = import_module(f"models.{args.domain}.{args.scenario}.model")
except ModuleNotFoundError:
return None
return getattr(model, "run_steps", None)
def _cohort_file(args: argparse.Namespace, scenario):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
@@ -137,11 +150,11 @@ def _report_eda(args: argparse.Namespace) -> int:
def _serve_notebooks(args: argparse.Namespace) -> int:
"""The runner container's loop (`models.io.notebook_jobs.serve`)."""
"""The runner container's loop (`models.reports.notebook_jobs.serve`)."""
import os
from pathlib import Path
from models.io.notebook_jobs import JOBS_DIR_ENV, serve
from models.reports.notebook_jobs import JOBS_DIR_ENV, serve
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
if not folder:
@@ -151,6 +164,82 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
return 0
def _tea_analyze(args: argparse.Namespace) -> int:
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
if args.ids is not None and (args.all or args.limit is not None):
print("--ids cannot be combined with --all or --limit", file=sys.stderr)
return 2
ids = [value.strip() for value in args.ids.split(",")] if args.ids is not None else None
if ids is not None and not all(ids):
print("--ids requires a comma-separated list of EEG ids", file=sys.stderr)
return 2
from models.eeg_analysis import analyze_pending
try:
s = analyze_pending(everything=args.all, limit=args.limit, ids=ids, cluster=args.cluster)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
print(f"summary: {json.dumps(asdict(s))}")
return 1 if s.failed else 0
def _tea_score_ados2(args: argparse.Namespace) -> int:
"""The ADOS-2 CSS and classification from the stored item scores (`models.ados2_scoring`)."""
from models.ados2_scoring import score_pending
s = score_pending(overwrite=args.all)
print(f"{s.evaluations} evaluations: {s.scored} scored, {s.unscored} without enough to score")
return 0
def _tea_relate_ados2(args: argparse.Namespace) -> int:
"""The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`)."""
from models.ados2_relation import relate
s = relate()
if s.unchanged:
print(f"{s.children} children: the cohort is that of {s.version}, nothing written")
elif s.version is None:
print(f"{s.children} children: no association could be estimated, nothing written")
else:
print(f"{s.version}: {s.children} children, level {s.level}, {s.associations} associations, "
f"{s.scored} patient probabilities")
return 0
def _tea_export_baselines(args: argparse.Namespace) -> int:
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, export
from models.tea.eeg.settings import settings
try:
done = export(settings(), args.out, environment=args.environment.upper(), production=args.production)
except BundleError as error:
print(f"not exported: {error}", file=sys.stderr)
return 1
for scenario, version in done.versions.items():
print(f"{scenario}: version {version}")
print(f"written: {done.path} (sha256 {done.sha256})")
return 0
def _tea_import_baselines(args: argparse.Namespace) -> int:
"""The age baselines of a bundle, registered (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, import_
from models.tea.eeg.settings import settings
try:
done = import_(settings(), args.bundle)
except BundleError as error:
print(f"not imported: {error}", file=sys.stderr)
return 1
for scenario, (version, new) in done.items():
print(f"{scenario}: {'imported as' if new else 'already registered as'} version {version}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build with a registered version and writes the output file."""
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
@@ -159,10 +248,12 @@ def _estimate(args: argparse.Namespace) -> int:
def _promote_step(args: argparse.Namespace, version: str) -> int:
"""Promotes through the same gate the WebApi's promote route uses (MLD-01/01b):
a version missing its checklist (validation reports, routine records, a saved
model) is rejected here exactly as it would be there, rather than set directly."""
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
from mlflow import MlflowException
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
name = registered_name(args.domain, args.scenario)
try:
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
@@ -171,7 +262,12 @@ def _promote_step(args: argparse.Namespace, version: str) -> int:
if str(current) == str(version):
print(f"already in production: version {version}")
return 0
registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
try:
registry.promote(args.domain, args.scenario, version)
except PromotionBlocked as blocked:
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
print(f"not promoted, missing: {failed}", file=sys.stderr)
return 1
print(f"in production: version {version}")
return 0
@@ -180,6 +276,8 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (own := _own_steps(args)) is not None:
return own(args)
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
@@ -381,7 +479,7 @@ def build_parser() -> argparse.ArgumentParser:
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
show.add_argument("domain", choices=["cacu", "cama", "tea"])
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
show.add_argument("--build", type=int, required=True, help="the build's number")
show.set_defaults(run=_cohort_show)
@@ -390,7 +488,7 @@ def build_parser() -> argparse.ArgumentParser:
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
train.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
train.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
@@ -402,7 +500,7 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--output", required=True, help="the Parquet file to write")
estimate.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
estimate.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
estimate.add_argument("--version", help="the model version; the one in production by default")
@@ -417,7 +515,7 @@ def build_parser() -> argparse.ArgumentParser:
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
@@ -437,15 +535,50 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
run.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.add_argument("--reference-dir", help="tea eeg: train on the EDFs of this folder instead of the configured cohort")
run.add_argument("--reference-ages", help="tea eeg: CSV of `archivo` and `edad_meses` (or `edad_anos`); "
"without it, each EDF header's age")
run.add_argument("--reference-name", help="tea eeg: a name for that cohort (no names or dates of people)")
run.add_argument("--line-hz", type=float, help="tea eeg: the mains frequency where it was recorded (60)")
run.set_defaults(run=lambda args: _run(run, args))
tea = commands.add_parser("tea", help="TEA's EEG analysis")
tea.set_defaults(run=lambda args: _show_help(tea))
tea_actions = tea.add_subparsers(dest="action", metavar="<action>")
analyze = tea_actions.add_parser(
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
analyze.add_argument("--ids", help="comma-separated EEG IDs to analyse again")
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
analyze.set_defaults(run=_tea_analyze)
score_ados2 = tea_actions.add_parser(
"score-ados2", help="compute the ADOS-2 CSS and classification from the item scores, module and age")
score_ados2.add_argument("--all", action="store_true", help="also recompute values already stored")
score_ados2.set_defaults(run=_tea_score_ados2)
relate_ados2 = tea_actions.add_parser(
"relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version")
relate_ados2.set_defaults(run=_tea_relate_ados2)
export_baselines = tea_actions.add_parser(
"export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child")
export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)")
export_baselines.add_argument("--environment", choices=["dev", "prod"], default="prod")
export_baselines.add_argument("--production", action="store_true",
help="the versions in production, instead of the newest trained in --environment")
export_baselines.set_defaults(run=_tea_export_baselines)
import_baselines = tea_actions.add_parser(
"import-baselines", help="register the age baselines of a bundle; promotion still needs their reports")
import_baselines.add_argument("bundle", help="the bundle `export-baselines` wrote")
import_baselines.set_defaults(run=_tea_import_baselines)
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
+189
View File
@@ -0,0 +1,189 @@
"""The ADOS-2 association against the TEA database: the cohort from bronze, the `tea` library's fit, and its rows in
`relacion_ados2` and `relacion_ados2_paciente`.
The cohort is one row per child with a valid analysed EEG and an ADOS-2: the child's first valid EEG with some
predictor (its zone z and metric z, its age) and first ADOS-2 (module, item scores, CSS). Every valid EEG of those
children is then scored, so the study's EEG has its probabilities whichever EEG it is.
A fit is a version `tea-<UTC time>-<fingerprint>`: the time keeps versions in order (the gold view shows the
greatest), the fingerprint is that of the scored EEGs, which of them the fit used, and the module and level. Inputs
equal to the latest version's write nothing. Versions are
written unvalidated (`rel_validado` 0) until the domain expert validates them.
"""
from __future__ import annotations
import hashlib
import math
from dataclasses import dataclass
from datetime import datetime, timezone
import pandas as pd
from sqlmodel import Session, col, select
from core.tea.enums import NivelRelacionAdos2
from core.tea.models import (
ADOS2_ITEMS,
Ados2,
Eeg,
EegMetrica,
EegMetricaZona,
RelacionAdos2,
RelacionAdos2Paciente,
)
from models.tea.ados2.settings import Settings, settings
VERSION_PREFIX = "tea-"
LEVELS = {"item": NivelRelacionAdos2.ITEM.value, "domain": NivelRelacionAdos2.DOMINIO.value}
ZONED = ("spikes", "spindles")
@dataclass
class Summary:
version: str | None = None
level: str | None = None
children: int = 0
associations: int = 0
scored: int = 0
unchanged: bool = False
def _predictors(session: Session, eeg_ids: list[str], s: Settings) -> pd.DataFrame:
"""One row per EEG with a column per predictor: `z_<biomarker>_<zone>` and `z_<biomarker>`."""
codes = {code: b for b, code in s.biomarkers.items()}
metrics = session.exec(select(EegMetrica.met_id, EegMetrica.met_eeg_id, EegMetrica.met_codigo, EegMetrica.met_z)
.where(col(EegMetrica.met_eeg_id).in_(eeg_ids))
.where(col(EegMetrica.met_codigo).in_(list(codes)))).all()
values: dict[str, dict[str, float]] = {e: {} for e in eeg_ids}
zoned = {}
for met_id, eeg_id, code, z in metrics:
biomarker = codes[code]
if biomarker in ZONED:
zoned[met_id] = (eeg_id, biomarker)
elif z is not None:
values[eeg_id][f"z_{biomarker}"] = z
if zoned:
for met_id, zone, z in session.exec(select(EegMetricaZona.mez_met_id, EegMetricaZona.mez_zona,
EegMetricaZona.mez_z)
.where(col(EegMetricaZona.mez_met_id).in_(list(zoned)))).all():
if z is not None:
eeg_id, biomarker = zoned[met_id]
values[eeg_id][f"z_{biomarker}_{zone}"] = z
return pd.DataFrame.from_dict(values, orient="index")
def cohort(session: Session, s: Settings) -> tuple[pd.DataFrame, pd.DataFrame]:
"""The fit's cohort (the first valid EEG of each child with an ADOS-2) and the table to score (every valid EEG
of those children), both keyed by EEG id, in the library's columns."""
eegs = session.exec(select(Eeg.eeg_id, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, Eeg.eeg_edad_meses)
.where(Eeg.eeg_valido == 1).where(col(Eeg.eeg_edad_meses).is_not(None))).all()
ados = session.exec(select(Ados2).where(col(Ados2.ado_pac_id).is_not(None))).all()
first: dict[int, Ados2] = {}
for a in sorted(ados, key=lambda a: (a.ado_fecha is None, a.ado_fecha, a.ado_id)):
first.setdefault(a.ado_pac_id, a)
rows = []
for eeg_id, pac_id, fecha, edad in eegs:
a = first.get(pac_id)
if a is None:
continue
rows.append({"key": eeg_id, "pac_id": pac_id, "fecha": fecha, "age_months": float(edad),
"ados_module": a.ado_modulo, "css": a.ado_css,
**{code: getattr(a, f"ado_{code}") for code in ADOS2_ITEMS}})
columns = ["key", "pac_id", "fecha", "age_months", "ados_module", "css", *ADOS2_ITEMS]
scored = pd.DataFrame(rows, columns=columns)
if len(scored):
z = _predictors(session, scored["key"].tolist(), s)
scored = scored.join(z, on="key")
scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(drop=True)
predictors = [c for c in scored.columns if c.startswith("z_")]
with_predictors = scored[predictors].notna().any(axis=1) if predictors else pd.Series(False, index=scored.index)
fit = scored[with_predictors].drop_duplicates("pac_id").reset_index(drop=True)
return fit.drop(columns=["pac_id", "fecha"]), scored.drop(columns=["pac_id", "fecha"])
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
"""Eight hex digits of the scored EEGs, which of them the fit used, and `module` (name, version, level);
independent of row and column order."""
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
return hashlib.sha256(text.encode()).hexdigest()[:8]
def _latest(session: Session) -> str | None:
versions = session.exec(select(RelacionAdos2.rel_version)
.where(col(RelacionAdos2.rel_version).startswith(VERSION_PREFIX))).all()
return max(versions, default=None)
def _finite(value) -> float | None:
"""The value as a float, or none when missing or infinite (an open interval): not every engine stores inf."""
if value is None or pd.isna(value):
return None
value = float(value)
return value if math.isfinite(value) else None
def _row_id(*parts) -> str:
from models.eeg_analysis import row_id
return row_id("relacion-ados2", *parts)
def rows(module, version: str, associations: pd.DataFrame, scores: pd.DataFrame,
s: Settings) -> tuple[list[RelacionAdos2], list[RelacionAdos2Paciente]]:
"""The estimated associations as `relacion_ados2` rows and their scores as `relacion_ados2_paciente` rows."""
level = LEVELS[module.fitted["level"]]
# An odds ratio rounded to 0 or never estimated is no association to show (`rel_or` is above 0).
estimated = associations[associations["odds_ratio"].astype(float) > 0]
models, ids = [], {}
for a in estimated.itertuples():
rel_id = _row_id(version, a.biomarker, a.zone, a.outcome_code)
ids[a.biomarker, a.zone, a.outcome_code] = rel_id
models.append(RelacionAdos2(
rel_id=rel_id, rel_version=version, rel_nivel=level, rel_validado=0,
rel_n_cohorte=int(module.fitted["n"]), rel_biomarcador=s.biomarkers[a.biomarker], rel_zona=a.zone,
rel_tipo=LEVELS[a.kind], rel_resultado=a.outcome_code, rel_evento=a.event, rel_or=_finite(a.odds_ratio),
rel_ic_inf=_finite(a.ci_low), rel_ic_sup=_finite(a.ci_high), rel_q=_finite(a.q)))
patients = []
for r in scores.itertuples():
rel_id = ids.get((r.biomarker, r.zone, r.outcome_code))
if rel_id is None:
continue
patients.append(RelacionAdos2Paciente(
rap_id=_row_id(rel_id, r.key), rap_rel_id=rel_id, rap_eeg_id=r.key, rap_valor_z=float(r.z),
rap_probabilidad=float(r.probability), rap_probabilidad_referencia=float(r.reference_probability)))
return models, patients
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def relate(*, settings_: Settings | None = None, at: datetime | None = None) -> Summary:
"""Fits the association on the current cohort and writes it as a new version, unless the cohort is the latest
version's. Nothing is written when no association could be estimated."""
from tea.pipeline import registry
from persistance.tea import relacion_ados2_repository
s = settings_ or settings()
with relacion_ados2_repository.open_session() as session:
fit, scored = cohort(session, s)
summary = Summary(children=len(fit))
if not len(fit):
return summary
module = type(registry.association(s.association, s.impl))(level=s.level)
mark = fingerprint(fit, scored, f"{module.name}/{module.version}/{module.impl}/{s.level}")
latest = _latest(session)
if latest is not None and latest.endswith(f"-{mark}"):
return Summary(version=latest, children=len(fit), unchanged=True)
module.fit(fit)
version = f"{VERSION_PREFIX}{(at or _now()):%Y%m%dT%H%M%S}-{mark}"
models, patients = rows(module, version, module.associations(), module.score(scored), s)
summary.level = module.fitted["level"]
if not models:
return summary
session.add_all([*models, *patients])
session.commit()
summary.version, summary.associations, summary.scored = version, len(models), len(patients)
return summary
+61
View File
@@ -0,0 +1,61 @@
"""The ADOS-2 CSS and classification against the TEA database: each evaluation's item scores, module, algorithm and
the child's age at the evaluation go through `tea.scoring`, and the result is written to `ado_css` and
`ado_clasificacion`.
A value a source already gave is kept unless `overwrite` is set. An evaluation without items or module is left as
it is.
"""
from __future__ import annotations
from dataclasses import dataclass
from sqlmodel import Session, select
from core.tea.models import ADOS2_ITEMS, Ados2, Pacientes
from tea.scoring import score
DAYS_PER_MONTH = 30.4375
@dataclass
class Summary:
evaluations: int = 0
scored: int = 0
unscored: int = 0
def age_months(born, on) -> float | None:
if born is None or on is None:
return None
return (on - born).days / DAYS_PER_MONTH
def score_all(session: Session, *, overwrite: bool = False) -> Summary:
"""Scores every evaluation in the session's database and commits."""
births = dict(session.exec(select(Pacientes.pac_id, Pacientes.pac_fecha_nacimiento)).all())
summary = Summary()
for row in session.exec(select(Ados2)).all():
summary.evaluations += 1
if not overwrite and row.ado_css is not None and row.ado_clasificacion is not None:
continue
items = {code: getattr(row, f"ado_{code}") for code in ADOS2_ITEMS}
result = score(row.ado_modulo, items, age_months=age_months(births.get(row.ado_pac_id), row.ado_fecha),
algorithm=row.ado_algoritmo)
if result is None or (result.css is None and result.classification is None):
summary.unscored += 1
continue
if overwrite or row.ado_css is None:
row.ado_css = result.css if result.css is not None else row.ado_css
if overwrite or row.ado_clasificacion is None:
row.ado_clasificacion = result.classification or row.ado_clasificacion
session.add(row)
summary.scored += 1
session.commit()
return summary
def score_pending(*, overwrite: bool = False) -> Summary:
from persistance.tea import relacion_ados2_repository
with relacion_ados2_repository.open_session() as session:
return score_all(session, overwrite=overwrite)
+7 -5
View File
@@ -12,8 +12,6 @@ import pandera.pandas as pandera
from hamilton.data_quality.base import DataValidator, ValidationResult
from hamilton.function_modifiers import check_output_custom
from models.io.contracts import failed_checks
class FrameCheck(DataValidator):
"""A pandera schema as a Hamilton validator whose message carries no data values."""
@@ -33,9 +31,13 @@ class FrameCheck(DataValidator):
return "frame_check"
def validate(self, dataset: Any) -> ValidationResult:
failed = failed_checks(self.schema, dataset)
if failed:
return ValidationResult(False, f"{self.description()} doesn't hold: {failed}")
try:
self.schema.validate(dataset, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
summary = "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return ValidationResult(False, f"{self.description()} doesn't hold: {summary}")
return ValidationResult(True, f"{self.description()}: holds")
View File
+72
View File
@@ -0,0 +1,72 @@
domain = "cacu"
scenario = "cancer_pim"
cohort = "cacu/cohorte_vigilancia"
outcome = "cancer"
# 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.cacu.cin2_pim.report", "models.steps.indexing"]
description = """
Prototipo: riesgo acumulado de cáncer cervicouterino (biopsia de 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 \
citología índice en las categorías de KPNC como covariable, como la columna de cáncer de las tablas de KPNC (Cheung et al. 2020), \
con la misma cohorte y la misma fecha índice que el modelo de CIN2+ de vigilancia. Sin \
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga cáncer cervicouterino en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "Cáncer: biopsia de carcinoma"
index_date = "la última citología con resultado de citología y de VPH"
horizons_unit = "años"
covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC"
[config]
horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results)
# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's
# index (the first cytology in the window). None predicts from the cohort's index too.
prediction_index = "ultima_citologia"
event_grades = ["CARCINOMA"]
train_fraction = 0.7
# Provisional: a carcinoma biopsy within this window of the index date counts as prevalent.
prevalent_window_months = 6
# The index sample's results: the first ones within these days of the index date.
index_sample_days = 30
# The results that make a visit free of the outcome without a biopsy: every key with one of its values (KPNC: HPV-negative
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric
# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The
# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC
# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6).
incidence = { family = "ispline", knots = 3, order = 4 }
# One mixture per value of these features; the other features enter the prevalence, and those listed here the
# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020).
strata = ["hpv_positive"]
incidence_features = ["cytology"]
# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance.
history = {}
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma
# has no KPNC row: it goes with the high-grade and malignant results.
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
[config.index]
kind = "primera_citologia"
event_grades = ["CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
+31 -17
View File
@@ -6,8 +6,9 @@ it's scored but left out of training and evaluation. The predictors are the inde
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
nothing after them is used.
The split, the classifier, the fit, the metrics and the routine records (ML-01a) are `models.steps.model_fitting`'s,
listed with this module in `model.toml`; `missing_data` and `members_left_out` are this scenario's part of them. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
The split, the classifier, the fit, the metrics and the classifier's routines (ML-01a) are
`models.steps.model_fitting`'s, listed with this module in `model.toml`; `sampling` and `missing_data`, the routines
that depend on this scenario's members and predictors, are here. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
scikit-learn `Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through
loaders, and registering is the driver's saver (`models.dags.training`).
"""
@@ -73,21 +74,6 @@ def labelled_members(index_sample_results: pd.DataFrame, windowed_outcomes: pd.D
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
def members_left_out(windowed_outcomes: pd.DataFrame) -> int:
"""The members scored but not trained on: their outcome isn't known yet."""
return int((~windowed_outcomes["known"]).sum())
def missing_data(index_sample_results: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
predictor_columns: list[str]) -> dict:
"""DATOS_FALTANTES: how many lacked each predictor, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int((frame[name] == MISSING).sum()) for name in predictor_columns}
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
class IndexSampleResults(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member, in `pac_id` order, with the index sample's results. Learns
nothing."""
@@ -105,3 +91,31 @@ class IndexSampleResults(TransformerMixin, BaseEstimator):
def fitted_model(fitted_pipeline: Pipeline, predictor_columns: list[str]) -> Pipeline:
"""What's registered: the fitted pipeline behind `IndexSampleResults`."""
return Pipeline([("index_sample", IndexSampleResults(predictor_columns)), ("classifier", fitted_pipeline)])
def _dates(frame: pd.DataFrame) -> dict:
if frame.empty:
return {"n": 0}
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
"last_index_date": str(frame["fecha_indice"].max())}
def sampling(windowed_outcomes: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float, index_attrition: list, prior_observation: dict) -> dict:
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"train_fraction": train_fraction, "members": len(windowed_outcomes),
"left_out_unknown_outcome": int((~windowed_outcomes["known"]).sum()), "train": _dates(train_set),
"test": _dates(test_set)}
def missing_data(index_sample_results: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
predictor_columns: list[str]) -> dict:
"""DATOS_FALTANTES: how many lacked each predictor, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int((frame[name] == MISSING).sum()) for name in predictor_columns}
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
+11 -1
View File
@@ -5,7 +5,7 @@ outcome = "cin2_12m"
# 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_logistic.model", "models.steps.model_fitting"]
modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting", "models.steps.indexing"]
description = """
Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \
a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \
@@ -21,3 +21,13 @@ predictor_columns = ["bethesda", "vph", "vph_16_18"]
# window leaves no member with a complete window; 1 year leaves 5,231 known members, 162 with the event.
horizons_years = [1.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
[config.index]
kind = "primera_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
+7
View File
@@ -0,0 +1,7 @@
"""Kept for callers of the old per-scenario driver: training is `models.dags.training`'s, with this scenario's
`model.toml`. `train(source, environment)` and `find_trained(source, environment)` take a `models.io.storage` source."""
from functools import partial
from models.dags.training import Scenario, find_trained as _find_trained, train as _train
train, find_trained = (partial(f, Scenario.load("cacu", "cin2_logistic")) for f in (_train, _find_trained))
+144 -32
View File
@@ -8,11 +8,21 @@ Each row has a code `c` and an interval `(l, r]` in years since the index visit:
- `c = -999`: unknown at the index visit (no colposcopy). Contributes `pi + (1 - pi) * (S(l) - S(r))`, usually
with `l = 0`.
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-(t / scale) ** shape * exp(Z @ beta))` the Weibull
survival of the incidence (proportional hazards in `Z`).
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-H0(t) * exp(Z @ beta))` the survival of the incidence
(proportional hazards in `Z`). The baseline cumulative hazard `H0` is a family:
- `Weibull`: `H0(t) = (t / scale) ** shape`, the default;
- `ISpline`: PIMixture's weakly-parametric `H0(t) = sum_j exp(gamma_j) I_j(t)`, with `I_j` the I-spline basis on knots
at quantiles of the observed times. Each `I_j` rises from 0 to 1, so `H0` is flat after the last knot.
Each row may carry a frequency weight `w` (identical rows collapsed into one); the standard errors (`-H^-1`) are those
of frequency weights, not of sampling weights.
"""
from dataclasses import dataclass
import numpy as np
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
@@ -38,6 +48,71 @@ def weibull_survival(t, log_scale, log_shape, beta, Z):
return survival
def ispline_basis(t, order: int, knots) -> np.ndarray:
"""(len(t) x (len(knots) + order - 2)) I-spline basis: `I_j(t) = sum_{m >= j} B_m(t)`, the B-splines of degree
`order` on `knots` with repeated boundaries. Equals PIMixture's `Ispline(t, order, knots)`, transposed."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], order + 1), knots[1:-1], np.repeat(knots[-1], order + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
bsplines = BSpline.design_matrix(inside, full, order, 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
def quantile_knots(l, r, n_knots: int) -> tuple[float, ...]:
"""PIMixture's knots: quantiles of the unique observed times, the `l` (zeros included) and the finite `r`."""
l, r = np.asarray(l, dtype=float), np.asarray(r, dtype=float)
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))
@dataclass(frozen=True)
class Weibull:
"""`H0(t) = (t / scale) ** shape`; params `[log_scale, log_shape]`."""
n_params = 2
def cumulative_hazard(self, t, params):
with np.errstate(over="ignore", invalid="ignore"):
return (np.asarray(t, dtype=float) / np.exp(params[0])) ** np.exp(params[1])
def start(self, c, l, r):
return np.array([_starting_log_scale(c, l, r), 0.0])
@dataclass(frozen=True)
class ISpline:
"""`H0(t) = sum_j exp(gamma_j) I_j(t)`; params `gamma`, one per basis function."""
knots: tuple[float, ...]
order: int = 3
@property
def n_params(self):
return len(self.knots) + self.order - 2
def cumulative_hazard(self, t, params):
return ispline_basis(t, self.order, self.knots) @ np.exp(params)
def start(self, c, l, r):
"""The exponential start's `H0` at the last knot, shared equally among the basis functions."""
rate = np.exp(-_starting_log_scale(c, l, r))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
WEIBULL = Weibull()
def survival(t, baseline_params, beta, Z, baseline=WEIBULL):
"""S(t) for any baseline family. S(0) = 1 and S(inf) = 0."""
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
cumulative = baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta)
found = np.exp(-cumulative)
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def split_params(params, n_x, n_z):
"""params = [theta (n_x), beta (n_z), log_scale, log_shape]."""
theta = params[:n_x]
@@ -47,24 +122,25 @@ def split_params(params, n_x, n_z):
return theta, beta, log_scale, log_shape
def neg_loglik(params, c, l, r, X, Z):
theta, beta, log_scale, log_shape = split_params(params, X.shape[1], Z.shape[1])
def neg_loglik(params, c, l, r, X, Z, baseline=WEIBULL, w=None):
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:]
w = np.ones(len(c)) if w is None else np.asarray(w, dtype=float)
pi = prevalence(theta, X)
interval = weibull_survival(l, log_scale, log_shape, beta, Z) - weibull_survival(r, log_scale, log_shape, beta, Z)
interval = survival(l, rest, beta, Z, baseline) - survival(r, rest, beta, Z, baseline)
interval = np.maximum(interval, TINY)
total = 0.0
row = np.zeros(len(c))
prevalent = c == 1
total += np.sum(np.log(pi[prevalent] + TINY))
row[prevalent] = np.log(pi[prevalent] + TINY)
not_prevalent = c == 0
total += np.sum(np.log(1 - pi[not_prevalent] + TINY))
total += np.sum(np.log(interval[not_prevalent]))
row[not_prevalent] = np.log(1 - pi[not_prevalent] + TINY) + np.log(interval[not_prevalent])
unknown = c == UNKNOWN
total += np.sum(np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY))
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -total
return -np.sum(w * row)
def numerical_hessian(f, x, step=1e-4):
@@ -84,52 +160,88 @@ def numerical_hessian(f, x, step=1e-4):
return hessian
def fit(c, l, r, X, Z):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
def _starting_log_scale(c, l, r):
"""log of an exponential scale: time at risk / incident events. With a rare outcome the scale is thousands of
years; starting BFGS at the median detection time (a few years) left it in a much worse local optimum."""
at_risk = c != 1
finite = np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
return float(np.log(max(exposure, 1e-6) / (events + 0.5)))
def _starting_theta(c, X, ridge=1e-3):
"""Prevalence coefficients of a logistic regression of "prevalent" on X among the members whose baseline is
known, with a small ridge so a group with no prevalent case gets a large negative value instead of -inf."""
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
def fit(c, l, r, X, Z, baseline=WEIBULL, w=None):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors; with the
Weibull also `log_scale` and `log_shape`."""
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
n_x, n_z = X.shape[1], Z.shape[1]
start = np.zeros(n_x + n_z + 2)
finite = r[np.isfinite(r) & (r > 0)]
start[n_x + n_z] = np.log(np.median(finite)) if len(finite) else 0.0
result = minimize(neg_loglik, start, args=(c, l, r, X, Z), method="BFGS")
theta, beta, log_scale, log_shape = split_params(result.x, n_x, n_z)
# Two starts, the better optimum kept: the likelihood of a rare outcome has poor local optima (all the risk put in
# the prevalence and none in the incidence, or the other way round).
start = baseline.start(c, l, r)
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x), np.zeros(n_z), start]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
theta, beta, rest = result.x[:n_x], result.x[n_x:n_x + n_z], result.x[n_x + n_z:]
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
# likelihood, a zero row in the Hessian, and makes the whole matrix singular. It gets no standard error (NaN) and
# the others are computed without it.
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), result.x)
hessian = numerical_hessian(lambda p: neg_loglik(p, *args), result.x)
free = np.abs(result.x) < BOUNDARY
standard_errors = np.full(len(result.x), np.nan)
covariance = np.full((len(result.x), len(result.x)), np.nan)
try:
covariance = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)
covariance[np.ix_(free, free)] = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)[free]
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
return {
found = {
"theta": theta,
"beta": beta,
"log_scale": log_scale,
"log_shape": log_shape,
"baseline": baseline,
"baseline_params": rest,
"params": result.x,
"se": standard_errors,
"covariance": covariance,
"neg_loglik": result.fun,
# BFGS with a numerical gradient often stops with "precision loss" at the optimum; what matters is that
# the gradient is ~0 there.
"converged": bool(np.max(np.abs(result.jac)) < 1e-3),
# A coefficient at the boundary (see above) keeps a small slope there; only the free ones must be flat.
"converged": bool(np.max(np.abs(result.jac[free]), initial=0.0) < 1e-3),
"message": result.message,
}
if isinstance(baseline, Weibull):
found["log_scale"], found["log_shape"] = float(rest[0]), float(rest[1])
return found
def cumulative_risk(fitted, X, Z, years):
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence."""
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence. A `fitted` without
`baseline` (built by hand) is a Weibull with `log_scale` and `log_shape`."""
pi = prevalence(fitted["theta"], X)
columns = []
for t in years:
survival = weibull_survival(np.full(len(X), float(t)), fitted["log_scale"], fitted["log_shape"],
fitted["beta"], Z)
columns.append(pi + (1 - pi) * (1 - survival))
baseline = fitted.get("baseline", WEIBULL)
rest = fitted.get("baseline_params")
if rest is None:
rest = np.array([fitted["log_scale"], fitted["log_shape"]])
columns = [pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), rest, fitted["beta"], Z, baseline))
for t in years]
return np.column_stack(columns)
+291 -108
View File
@@ -1,30 +1,34 @@
"""CaCu CIN2+ prevalence–incidence prototype: the cumulative risk of CIN2+ at the index visit and at later horizons.
Each member becomes a code `c` and an interval `(l, r]` in years (`likelihood`'s convention), from the index sample's
results and the biopsies after it:
Each member becomes a code `c` and an interval `(l, r]` in years since the index date (`likelihood`'s convention),
from the first CIN2+ biopsy and the last time the member was found free of it before that biopsy. Found free means a
biopsy below CIN2+, or a visit whose results each take one of their `known_negative` values (HPV-negative with NILM or
ASC-US). CIN2+ is taken as absorbing
and a negative as true, so the last negative carries every earlier one:
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`;
- otherwise, a known negative baseline (`known_negative` results, or a biopsy in the window below CIN2+): `c = 0`, with
`(0, t_event]` if a later biopsy is CIN2+ and `(follow-up, inf)` if none is;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]` or `(0, inf)`.
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`, `(0, 0]`;
- otherwise, found free at least once: `c = 0`, with `l` the last negative (0 if it's within the window, the baseline
workup) and `r` the CIN2+ biopsy, or infinity if there's none;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]`, or `(0, inf)`, which carries no information.
The interval's left end is 0 for a later event: the last negative visit before it isn't looked for.
Follow-up without a test isn't counted: a member is free only as far as her last negative, never up to the cut-off.
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
π logistic in every feature and the incidence S(t) Weibull with proportional hazards in `incidence_features`.
The routine records (ML-01a) are nodes too: `sampling`, `missing_data`, `analytic_method`, `class_balance` and
`output_confidence`, gathered by `routines`. `fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort and its lineage through loaders, and registering is the
π logistic in every feature (KPNC's cytology categories as indicators) and the incidence S(t) with proportional
hazards in `incidence_features` over a Weibull or I-spline baseline (`incidence`), one mixture per stratum (`strata`).
`fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort through a loader, and registering is the
driver's saver (`models.dags.training`).
"""
from datetime import date
import copy
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from scipy.stats import norm
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
@@ -34,7 +38,21 @@ from models.cacu.cin2_pim import likelihood
from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
FEATURES = ["abnormal_cytology", "hpv_positive"]
FEATURES = ["cytology", "hpv_positive"]
# The member's prediction index (days since 1970-01-01), when `IndexResults` picks it: the first column of the output.
INDEX_COLUMN = "fecha_indice_modelo"
EPOCH = pd.Timestamp("1970-01-01")
PREDICTION_INDEXES = ("ultima_citologia",)
def _features(history: dict) -> list[str]:
"""The model's features: the index results', and the history's one if the scenario has a history."""
return FEATURES + ([history["feature"]] if history else [])
def _levels(cytology: dict, history: dict) -> dict:
"""The levels of each categorical feature, the reference first."""
return {"cytology": list(cytology), **({history["feature"]: list(history["levels"])} if history else {})}
INTERVAL_CODED = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"c": pandera.Column(int, pandera.Check.isin([1, 0, likelihood.UNKNOWN])),
@@ -48,43 +66,92 @@ def _days(cohort: pd.DataFrame) -> pd.Series:
return (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first Bethesda and HPV results within `index_sample_days` of the
index date, and the features taken from them."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "vph"])]
def _most_severe(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per `pac_id` (the index of `codes`), the most severe of `cytology`'s categories among the codes; None if none."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
ranks = codes.map(severity).groupby(level=0).max()
names = list(cytology)
return pd.Series([None if np.isnan(rank) else names[int(rank)] for rank in ranks], index=ranks.index,
dtype=object)
def _history(cohort: pd.DataFrame, members: pd.DataFrame, cytology: dict, history: dict) -> pd.Series:
"""The history feature: the grade of the results in the `lookback_days` up to the member's first `event` (KPNC's
referral before the colposcopy). `high` if a category of `high`; else `low` if one of `low`, or of
`low_if_hpv_positive` with a positive HPV; else None (no referral result, or one that wouldn't refer)."""
event = cohort[cohort["tipo"] == history["event"]].groupby("pac_id")["fecha"].min()
timed = cohort.assign(event=cohort["pac_id"].map(event))
before = (pd.to_datetime(timed["event"]) - pd.to_datetime(timed["fecha"])).dt.days
near = timed[before.between(0, history["lookback_days"])]
results = near[near["tipo"].isin(["bethesda", "glandular"])].set_index("pac_id")["valor_codigo"]
worst = pd.Series(_most_severe(results, cytology).reindex(members["pac_id"]).to_numpy(), index=members.index)
hpv = near[(near["tipo"] == "vph") & (near["valor_codigo"] == "POSITIVO")]["pac_id"].unique()
positive = members["pac_id"].isin(hpv).to_numpy()
grade = np.where(worst.isin(history["high"]), "high",
np.where(worst.isin(history["low"]) | (worst.isin(history["low_if_hpv_positive"]) & positive),
"low", None))
return pd.Series(grade, index=members.index, dtype=object)
def index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict, history: dict | None = None) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first squamous (Bethesda), glandular and HPV results within
`index_sample_days` of the index date, and the features taken from them. `cytology` maps KPNC's categories, from
least to most severe, to the codes of either result; with both results the more severe category wins, and a
member with neither, or with codes in no category, gets None. With a `history`, its feature too (`_history`)."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "glandular", "vph"])]
wide = near.sort_values("fecha").pivot_table(index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
members = cohort.groupby("pac_id", as_index=False)["fecha_indice"].first()
members = members.merge(wide.reindex(columns=["bethesda", "vph"]), left_on="pac_id", right_index=True, how="left")
members["abnormal_cytology"] = (members["bethesda"].notna() & (members["bethesda"] != "NORMAL")).astype(float)
members = members.merge(wide.reindex(columns=["bethesda", "glandular", "vph"]), left_on="pac_id", right_index=True,
how="left")
codes = members.set_index("pac_id")[["bethesda", "glandular"]].stack()
found = _most_severe(codes, cytology).reindex(members["pac_id"]).tolist()
members["cytology"] = pd.Series([v if isinstance(v, str) else None for v in found], index=members.index,
dtype=object)
members["hpv_positive"] = (members["vph"] == "POSITIVO").astype(float)
if history:
members[history["feature"]] = _history(cohort, members, cytology, history)
return members
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
def _negative_days(cohort: pd.DataFrame, days: pd.Series, event_grades: list[str], known_negative: dict,
index_sample_days: int) -> pd.DataFrame:
"""`pac_id` and day of every time a member was found free of CIN2+: a biopsy below CIN2+, or a visit with a result
of every `known_negative` key among its values, within `index_sample_days` of each other, dated at the last."""
timed = cohort.assign(days=days.astype(float))[days >= 0]
biopsies = timed[(timed["tipo"] == "biopsia") & ~timed["valor_codigo"].isin(event_grades)][["pac_id", "days"]]
visits = None
for name, values in known_negative.items():
found = timed[(timed["tipo"] == name) & timed["valor_codigo"].isin(values)][["pac_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(visits.sort_values("days"), found.rename(columns={"days": name}).sort_values(name),
left_on="days", right_on=name, by="pac_id", direction="nearest",
tolerance=float(index_sample_days)).dropna(subset=[name])
visits = paired.assign(days=paired[["days", name]].max(axis=1))[["pac_id", "days"]]
return pd.concat([biopsies, visits], ignore_index=True)
@checked_frame(INTERVAL_CODED)
def interval_coded_members(cohort: pd.DataFrame, cohort_cutoff: date, event_grades: list[str],
prevalent_window_months: int, index_sample_days: int, known_negative: dict) -> pd.DataFrame:
def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], prevalent_window_months: int,
index_sample_days: int, known_negative: dict, cytology: dict, history: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
biopsies = cohort[(cohort["tipo"] == "biopsia") & (days >= 0)].assign(days=days)
window = prevalent_window_months * DAYS_PER_YEAR / 12
first_event = biopsies[biopsies["valor_codigo"].isin(event_grades)].groupby("pac_id")["days"].min()
negative_biopsy = biopsies[~biopsies["valor_codigo"].isin(event_grades) & (biopsies["days"] <= window)]
events = cohort[(cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & (days >= 0)]
first_event = days[events.index].groupby(events["pac_id"]).min()
negatives = _negative_days(cohort, days, event_grades, known_negative, index_sample_days)
before_event = ~(negatives["days"] >= negatives["pac_id"].map(first_event))
last_negative = negatives[before_event].groupby("pac_id")["days"].max()
coded = index_results(cohort, index_sample_days)
results_negative = np.logical_and.reduce([coded[name] == value for name, value in known_negative.items()])
event_days = coded["pac_id"].map(first_event)
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(coded["fecha_indice"])).dt.days / DAYS_PER_YEAR
coded = index_results(cohort, index_sample_days, cytology, history)
event_days, free_until = coded["pac_id"].map(first_event), coded["pac_id"].map(last_negative)
prevalent = event_days <= window
baseline_negative = results_negative | coded["pac_id"].isin(negative_biopsy["pac_id"])
found_free = free_until.notna() & ~prevalent
later_event = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(baseline_negative, 0, likelihood.UNKNOWN))
coded["l"] = np.where(~prevalent & baseline_negative & ~later_event, follow_up, 0.0)
coded["c"] = np.where(prevalent, 1, np.where(found_free, 0, likelihood.UNKNOWN))
coded["l"] = np.where(found_free & (free_until > window), free_until / DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
return coded
@@ -96,37 +163,150 @@ def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float
class PrevalenceIncidenceMixture(BaseEstimator):
"""Logistic prevalence and Weibull incidence fitted by maximum likelihood (`likelihood.fit`)."""
"""Logistic prevalence and proportional-hazards incidence fitted by maximum likelihood (`likelihood.fit`).
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",)):
`incidence` picks the baseline: `{"family": "weibull"}` or `{"family": "ispline", "knots": k, "order": o}`, with
`k` knots at quantiles of each stratum's observed times (PIMixture's weakly-parametric model). With `strata`, one
mixture per combination of their values, as in Cheung et al. 2020 (stratified by HPV, cytology as covariate): the
strata leave both designs and a member of a stratum not seen in training gets NaN. A feature listed in `levels`
is categorical: one indicator per level but the first (the reference), keeping in each stratum only the levels
seen in its training; a member of a level not seen there, or of none, gets NaN and is left out of the fit.
Identical rows are collapsed into frequency weights, which `sample_weight` multiplies.
"""
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
incidence=None, levels=None, interval_level=None):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.incidence = incidence
self.levels = levels
self.interval_level = interval_level
def _design(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), X.to_numpy(dtype=float)])
return prevalence, X[list(self.incidence_features)].to_numpy(dtype=float)
def _baseline(self, y: pd.DataFrame):
settings = dict(self.incidence or {"family": "weibull"})
family = settings.pop("family")
if family == "weibull":
return likelihood.WEIBULL
if family == "ispline":
return likelihood.ISpline(likelihood.quantile_knots(y["l"], y["r"], settings["knots"]),
settings.get("order", 3))
raise ValueError(f"unknown incidence family {family!r}")
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
prevalence, incidence = self._design(X)
found = likelihood.fit(y["c"], y["l"], y["r"], prevalence, incidence)
self.theta_, self.beta_ = found["theta"], found["beta"]
self.log_scale_, self.log_shape_ = float(found["log_scale"]), float(found["log_shape"])
self.standard_errors_, self.neg_loglik_, self.converged_ = found["se"], found["neg_loglik"], found["converged"]
def _seen(self, X: pd.DataFrame) -> dict:
"""Each categorical feature's levels present in `X`, in `levels`' order."""
return {f: [v for v in values if (X[f] == v).any()] for f, values in (self.levels or {}).items()
if f in X.columns and f not in self.strata}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
"""Rows whose categorical features take a level in `seen`."""
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0) if seen \
else np.ones(len(X), dtype=bool)
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)))]
return [(key if isinstance(key, tuple) else (key,), rows)
for key, rows in X.groupby(list(self.strata), sort=True).indices.items()]
def fit(self, X: pd.DataFrame, y: pd.DataFrame, sample_weight=None):
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1)
rows["w"] = 1.0 if sample_weight is None else np.asarray(sample_weight, dtype=float)
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)].groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
self.seen_[key] = seen
self.fits_[key] = likelihood.fit(group["c"].to_numpy(), group["l"].to_numpy(), group["r"].to_numpy(),
prevalence, incidence, self._baseline(group), 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 risk_with_variance(self, key: tuple, prevalence: np.ndarray, incidence: np.ndarray, years) -> tuple:
"""CR(t) of each design row of stratum `key` at `years`, and its delta-method variance (central differences
of CR in every parameter, with the fit's inverse Hessian)."""
fit = self.fits_[key]
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, prevalence, incidence, years)
params = np.asarray(fit["params"], dtype=float)
gradient = np.empty((len(params), len(prevalence), 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)
return risk(params), np.maximum(np.einsum("kij,kl,lij->ij", gradient, covariance, gradient), 0.0)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
prevalence, incidence = self._design(X)
fitted = {"theta": self.theta_, "beta": self.beta_, "log_scale": self.log_scale_, "log_shape": self.log_shape_}
return likelihood.cumulative_risk(fitted, prevalence, incidence, self.horizons_years)
"""One column per horizon: CR(t). The column of t = 0 is the prevalence. With `INDEX_COLUMN` in `X`, its days
since 1970-01-01 come first and a member without that date gets no risk. With `interval_level`, two more
blocks of as many columns: the interval's lower and upper ends, CR · exp(∓z · SE / CR) (delta method on the
log scale, clipped to [0, 1])."""
if INDEX_COLUMN in X.columns:
dates = pd.to_datetime(X[INDEX_COLUMN])
risks = self.predict_proba(X.drop(columns=INDEX_COLUMN))
risks[dates.isna().to_numpy()] = np.nan
return np.column_stack([(dates - EPOCH).dt.days.to_numpy(dtype=float), risks])
h = len(self.horizons_years)
risks = np.full((len(X), 3 * h if self.interval_level else h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2) if self.interval_level else None
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])
rows = index[placed]
if not self.interval_level:
risks[rows] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, self.horizons_years)
continue
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
point, variance = self.risk_with_variance(key, unique[:, :prevalence.shape[1]],
unique[:, prevalence.shape[1]:], 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)])
risks[rows] = band[inverse.ravel()]
return risks
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float]) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years).fit(train_set[FEATURES], train_set[["c", "l", "r"]])
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float], incidence: dict,
incidence_features: list[str], strata: list[str], cytology: dict,
history: dict) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
_levels(cytology, history)).fit(train_set[_features(history)],
train_set[["c", "l", "r"]])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[FEATURES])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame,
history: dict) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[_features(history)])
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
@@ -144,7 +324,7 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
"converged": float(fitted_mixture.converged_)}
for column, horizon in enumerate(horizons_years):
status = _status_at(test_set, horizon)
known = ~np.isnan(status)
known = ~np.isnan(status) & ~np.isnan(test_cumulative_risks[:, column]) # NaN: a stratum unseen in training
y, p = status[known], test_cumulative_risks[known, column]
tag = f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
@@ -157,73 +337,76 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
return found
def sampling(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: every member is used; the split is `models.steps.model_fitting`'s."""
return model_fitting.sampling(interval_coded_members, train_set, test_set, train_fraction)
RESULT_TYPES = ("bethesda", "glandular", "vph")
REFERRED = ("colposcopia", "biopsia") # a patient with either is past the surveillance model
def missing_data(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many lacked each index result or a known baseline, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {"bethesda": int(frame["bethesda"].isna().sum()), "vph": int(frame["vph"].isna().sum()),
"unknown_baseline": int((frame["c"] == likelihood.UNKNOWN).sum())}
return {"method": "sin Bethesda no cuenta como citología anormal y sin VPH no cuenta como positivo; una línea "
"basal desconocida entra a la verosimilitud como mezcla de prevalente y no prevalente; nadie se "
"excluye",
"members": missing(interval_coded_members), "train": missing(train_set), "test": missing(test_set)}
def latest_precolposcopy_cytology(cohort: pd.DataFrame) -> pd.DataFrame:
"""Per patient with no colposcopy and no biopsy in the frame, the date of her latest cytology sample with a
cytology result (Bethesda or glandular) and an HPV result, linked to it by its source row: `pac_id`, `fecha`. A
sample still missing either result gives way to the one before it; a patient with none, or referred, is absent.
Self-contained: it runs inside the registered model, without this repository."""
referred = set(cohort.loc[cohort["tipo"].isin(REFERRED), "pac_id"])
key = ["pac_id", "fuente_tabla", "fuente_id"]
samples = cohort.loc[(cohort["tipo"] == "citologia") & ~cohort["pac_id"].isin(referred), [*key, "fecha"]]
results = cohort[cohort["tipo"].isin(RESULT_TYPES) & cohort["valor_codigo"].notna()]
has = results.pivot_table(index=key, columns="tipo", values="valor_codigo", aggfunc="first")
has = has.reindex(columns=list(RESULT_TYPES))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["vph"].notna()].index
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete)].reset_index()
latest = samples.sort_values(["pac_id", "fecha", "fuente_id"]).groupby("pac_id", as_index=False).last()
return latest[["pac_id", "fecha"]].reset_index(drop=True)
def analytic_method(fitted_mixture: PrevalenceIncidenceMixture) -> dict:
"""METODO_ANALITICO: the fitted mixture and its parameters."""
return {"method": "mezcla de prevalencia (logística) e incidencia (Weibull de riesgos proporcionales) por máxima "
"verosimilitud con censura por intervalo",
"estimator": type(fitted_mixture).__name__, "settings": fitted_mixture.get_params(),
"prevalence_coefficients": dict(zip(["intercept", *FEATURES], map(float, fitted_mixture.theta_))),
"incidence_coefficients": dict(zip(fitted_mixture.incidence_features, map(float, fitted_mixture.beta_))),
"log_scale": fitted_mixture.log_scale_, "log_shape": fitted_mixture.log_shape_,
"neg_loglik": float(fitted_mixture.neg_loglik_), "converged": bool(fitted_mixture.converged_)}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: how many members have each baseline code (1 prevalent, 0 known negative, -999 unknown)."""
def counts(frame: pd.DataFrame) -> dict:
return {str(code): int(n) for code, n in frame["c"].value_counts().sort_index().items()}
return {"method": "ninguno: los códigos se usan en su proporción observada", "train": counts(train_set),
"test": counts(test_set)}
def output_confidence(metrics: dict, horizons_years: list[float]) -> dict:
"""CONFIANZA_SALIDA: per horizon, among the test members whose status at it is known, the expected risk against
the observed rate."""
names = {"n_known": "n", "expected": "mean_probability", "observed": "observed_rate", "brier": "brier"}
return {"method": "calibración en la prueba por horizonte: riesgo acumulado medio contra frecuencia observada, "
"entre quienes tienen estado conocido en ese horizonte",
"horizons": [{"years": horizon, **{name: metrics[f"{key}_{horizon:g}y"] for key, name in names.items()
if f"{key}_{horizon:g}y" in metrics}} for horizon in horizons_years]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return model_fitting.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
def latest_index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict,
history: dict | None = None) -> pd.DataFrame:
"""`index_results` at each member's latest complete cytology before any colposcopy
(`latest_precolposcopy_cytology`), with that date in `INDEX_COLUMN`; one row per member in `pac_id`
order, with no features and no date for a member without such a sample."""
chosen = latest_precolposcopy_cytology(cohort).set_index("pac_id")["fecha"]
members = pd.DataFrame({"pac_id": sorted(cohort["pac_id"].unique())})
eligible = cohort[cohort["pac_id"].isin(chosen.index)]
if len(eligible):
found = index_results(eligible.assign(fecha_indice=eligible["pac_id"].map(chosen)), index_sample_days,
cytology, history)
members = members.merge(found[["pac_id", *_features(history)]], on="pac_id", how="left")
else:
members = members.assign(**{f: np.nan for f in _features(history)})
members[INDEX_COLUMN] = pd.to_datetime(members["pac_id"].map(chosen))
return members
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing. By default at the
cohort's index date, as in training; with `prediction_index = "ultima_citologia"` at each member's latest
complete cytology before any colposcopy (`latest_index_results`), with that date as `INDEX_COLUMN`."""
def __init__(self, index_sample_days: int = 30):
def __init__(self, index_sample_days: int = 30, cytology=None, history=None, prediction_index=None):
self.index_sample_days = index_sample_days
self.cytology = cytology
self.history = history
self.prediction_index = prediction_index
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days)[FEATURES]
if self.prediction_index is None:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
if self.prediction_index not in PREDICTION_INDEXES:
raise ValueError(f"unknown prediction_index {self.prediction_index!r}; known: {PREDICTION_INDEXES}")
found = latest_index_results(X, self.index_sample_days, self.cytology, self.history)
return found[[*_features(self.history), INDEX_COLUMN]].reset_index(drop=True)
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days)), ("mixture", fitted_mixture)])
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict, risk_interval_level: float | None = None,
prediction_index: str | None = None) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`, giving each risk's interval at
`risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run), from the
index `prediction_index` names (the cohort's when none)."""
registered = copy.copy(fitted_mixture)
registered.interval_level = risk_interval_level
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history, prediction_index)),
("mixture", registered)])
+52 -5
View File
@@ -5,20 +5,67 @@ 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"]
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 (Weibull) a partir de la citología y el VPH índice. Sin \
modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
citología índice en las categorías de KPNC como covariable (Cheung et al. 2020). Sin \
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la última citología con resultado de citología y de VPH"
horizons_unit = "años"
covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC"
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results)
# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's
# index (the first cytology in the window). None predicts from the cohort's index too.
prediction_index = "ultima_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
prevalent_window_months = 6
# The index sample's results: the first ones within these days of the index date.
index_sample_days = 30
# The results that make a baseline known negative without a biopsy.
known_negative = { bethesda = "NORMAL", vph = "NEGATIVO" }
# The results that make a visit free of CIN2+ without a biopsy: every key with one of its values (KPNC: HPV-negative
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric
# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The
# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC
# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6).
incidence = { family = "ispline", knots = 3, order = 4 }
# One mixture per value of these features; the other features enter the prevalence, and those listed here the
# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020).
strata = ["hpv_positive"]
incidence_features = ["cytology"]
# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance.
history = {}
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma
# has no KPNC row: it goes with the high-grade and malignant results.
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
[config.index]
kind = "primera_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
@@ -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
}
+279
View File
@@ -0,0 +1,279 @@
"""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": "curva empírica de Turnbull: el estimador no paramétrico del riesgo acumulado cuando solo se sabe entre "
"qué dos visitas apareció el CIN2+ (censura por intervalos), calculado con el algoritmo EM de Turnbull "
"(1976). Cada paciente aporta el intervalo donde pudo estar su evento: un caso prevalente, el instante "
"0 (así la curva arranca en la prevalencia observada, comparable con la del modelo); una paciente "
"vista libre de CIN2+, el intervalo entre su último negativo y su biopsia CIN2+ (o sin fin); una sin "
"negativo previo, desde 0 hasta su biopsia. Banda y 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 _percent(values) -> list[float]:
return [100 * v for v in values]
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), in percent like the table and
the patient's risk. Each panel has its own y scale, so a combination of low risk isn't flattened by one of high
risk."""
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=False,
subplot_titles=[f"{_label(r['combination'])}<br>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=_percent(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=_percent(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=_percent(emp["CR"]), mode="lines", line={"color": "#242628", "width": 2,
"shape": "hv"},
name="Turnbull", legendgroup="emp", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>Turnbull</extra>"), row=row, col=col)
if model is not None:
figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["high"]), mode="lines", line={"width": 0},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=_percent(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=_percent(model["CR"]), mode="lines", line={"color": "#6f35a5",
"width": 2},
name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>modelo</extra>"), row=row, col=col)
figure.update_xaxes(range=[0, max(horizons_years) + 0.05])
figure.update_yaxes(rangemode="tozero", ticksuffix=" %")
figure.update_yaxes(title_text="Riesgo acumulado (%)", col=1)
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables<br>"
f"<sup>Años desde la fecha índice; {NOTICE}</sup>"},
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"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<p>* el IC de E/O no incluye 1. — sin casos observados a ese horizonte o combinación que el modelo no "
"ubica.</p><h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>CIN2+ por subgrupo</title></head>"
"<body style=\"font-family:sans-serif;margin:16px\">" + figure.to_html(full_html=False, include_plotlyjs=True)
+ notes + "<h3>Combinaciones</h3>" + table.to_html(index=False, border=0) + "</body></html>")
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}
@@ -0,0 +1,69 @@
domain = "cacu"
scenario = "cin2_pim_post_colposcopy"
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.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 \
de la referencia (bajo o alto), con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, \
como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \
sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+"
horizons_unit = "años"
covariates = "grado de la citología que la refirió a colposcopía (un ajuste por grado), VPH y citología de la visita índice en tres categorías de KPNC"
[config]
horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
index_sample_days = 30
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
incidence = { family = "ispline", knots = 3, order = 4 }
# Chapter 25 of bayes-pim: table 17 is reproduced exactly with one baseline per referral grade, the six HPV × cytology
# curves proportional within it; one baseline per HPV result is not (residual 4e-3).
strata = ["referral_grade"]
incidence_features = ["cytology", "hpv_positive"]
# KPNC groups the post-colposcopy cytology in three: NILM, ASC-US/LSIL and high grade (ASC-H, AGC, HSIL+).
# The scenario's index and rules over the total cohort (models/steps/indexing.py), the same as dbt's
# cacu/cohorte_post_colposcopia_visita_1 (Cheung et al. 2020): the first surveillance visit with a cotest after the
# first colposcopy's result, before any later colposcopy. PROVISIONAL: a colposcopy without a biopsy order is below
# CIN2. The recruitment window is the source cohort's (the surveillance cohort's).
[config.index]
kind = "post_colposcopia"
visita = 1
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
referral_lookback_days = 365
hysterectomy_cie = ["Z907"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
[config.cytology]
NILM = ["NORMAL"]
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
# The referral before the colposcopy (Egemen et al. 2020, doi:10.1097/LGT.0000000000000529): low grade is ASC-US,
# LSIL or HPV-positive NILM; high grade is ASC-H, AGC or HSIL+. The results in `lookback_days` up to the first
# colposcopy, as the cohort's `no_referral_result` rule reads them; a member without one gets none.
[config.history]
feature = "referral_grade"
event = "colposcopia"
lookback_days = 365
levels = ["low", "high"]
low = ["ASC-US/LSIL"]
low_if_hpv_positive = ["NILM"]
high = ["High Grade"]
@@ -0,0 +1,44 @@
domain = "cacu"
scenario = "cin2_pim_post_treatment"
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", "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 \
base, con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, como reproduce exactamente \
la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \
la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera citología después del tratamiento"
horizons_unit = "años"
covariates = "VPH y citología de la citología índice en tres categorías de KPNC"
[config]
horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
index_sample_days = 30
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
incidence = { family = "ispline", knots = 3, order = 4 }
# Chapter 25 of bayes-pim: table 24 is reproduced exactly with one baseline for its six HPV × cytology curves (and also
# with one per HPV result); the coarser one is kept.
strata = []
incidence_features = ["cytology", "hpv_positive"]
history = {}
# KPNC groups the post-treatment cytology in three: NILM, ASC-US/LSIL and high grade.
[config.cytology]
NILM = ["NORMAL"]
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
View File
+199
View File
@@ -0,0 +1,199 @@
"""What the CaCu survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates and the index date; the rest keep their row, empty. The index is the diagnosis
(provisionally the first biopsy reported as invasive carcinoma) and the covariates are the member's most recent
observations up to it: her age group at the index, the cytology of her latest sample (KPNC's categories, the more severe
of its squamous and glandular results) and her latest HPV result. `IntervalSurvival` is CaMa's
(`models.cama.survival.estimator`): per interval of `survival.horizons`, a logistic regression and a Bayesian network
with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`), stacked with
out-of-sample weights; a patient's survival to each horizon is the product of the intervals'.
DUPLICATED (issue #9): `encode`, `interval_cohort` and `IntervalSurvival` are CaMa's with the covariates as `FEATURES`
of this module instead of CaMa's; CaMa's read its own `FEATURES` as a module constant, so they can't be reused without
changing CaMa. The outcome (`outcome_table`) and the settings (`survival_settings`) are CaMa's, imported.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.survival.estimator import EPOCH, INDEX_COLUMN, UNKNOWN, WINDOW_KEYS, _band, survival_settings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
FEATURES = ["age_group", "cytology", "hpv"]
NUMERIC = ["age_years"] # the age before banding
def _latest_cytology(prior: pd.DataFrame, cytology: dict) -> pd.Series:
"""Per `pac_id`, KPNC's category of her latest cytology sample: the more severe of its squamous and glandular
results; None when no result falls in a category."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
results = prior[prior["tipo"].isin(["bethesda", "glandular"]) & prior["valor_codigo"].notna()]
latest = results[results["fecha"] == results.groupby("pac_id")["fecha"].transform("max")]
ranks = latest["valor_codigo"].map(severity).groupby(latest["pac_id"]).max()
names = list(cytology)
return ranks.map(lambda rank: None if pd.isna(rank) else names[int(rank)])
def member_table(cohort: pd.DataFrame, age_cuts: list, cytology: dict) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice`, the covariates in `FEATURES` and the
age in years. Each covariate is the member's most recent observation up to the index (the index day included): her
age at the index from her `nacimiento`, her latest cytology sample's category (`_latest_cytology`) and her latest HPV
result; empty where the build has none."""
frame = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
prior = frame[frame["fecha"] <= frame["fecha_indice"]]
members["cytology"] = _latest_cytology(prior, cytology).reindex(members.index).astype(object)
hpv = prior[(prior["tipo"] == "vph") & prior["valor_codigo"].notna()].sort_values(["fecha", "fuente_id"])
members["hpv"] = hpv.groupby("pac_id")["valor_codigo"].last().reindex(members.index)
members = members.astype({"cytology": object, "hpv": object})
return members[["fecha_indice", *FEATURES, *NUMERIC]]
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""CaMa's `encode` over this module's `FEATURES` (DUPLICATED, issue #9): `(X_dum, X_int, categories, dummy_columns)`.
With no `categories` they are learned from `frame`; with them, a value the fit never saw takes the unknown
category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings):
"""CaMa's `interval_cohort` over this module's `FEATURES` (DUPLICATED, issue #9)."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(35, 45, 55), cytology=None):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.cytology = cytology
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), self.cytology) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
def _combinations(X: pd.DataFrame) -> pd.DataFrame:
"""Each member's combination of the covariates, as `encode` reads them (a missing value is `UNKNOWN`)."""
return X[FEATURES].astype(object).where(X[FEATURES].notna(), UNKNOWN).astype(str).reset_index(drop=True)
def _frame(combinations: pd.DataFrame) -> pd.DataFrame:
return combinations.replace(UNKNOWN, None)
class IntervalSurvival(BaseEstimator):
"""CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked;
the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with
`months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too.
With `interval_level`, two more blocks follow the mortality: its interval's lower and upper ends. The covariates
are categorical, so every member of a combination gets the same mortality, and so the same interval: `fit` keeps
one per combination of the training members (`interval_table_`), the percentiles of the mortality of
`interval_replicas` refits of this same model on bootstrap resamples of them (seeded by `seed`). A combination the
training never saw has no interval."""
def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0), interval_level=None, interval_replicas=100,
seed=0):
self.survival = survival
self.horizons_years = horizons_years
self.interval_level = interval_level
self.interval_replicas = interval_replicas
self.seed = seed
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
self.interval_table_ = self._interval_table(X, y) if self.interval_level else {}
return self
def _interval_table(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = _combinations(X).drop_duplicates()
rng = np.random.default_rng(self.seed)
replicas = []
for _ in range(int(self.interval_replicas)):
rows = rng.integers(0, len(X), len(X))
refit = IntervalSurvival(self.survival, self.horizons_years)
refit.fit(X.iloc[rows].reset_index(drop=True), y.iloc[rows].reset_index(drop=True))
replicas.append(1.0 - refit.survival_proba(_frame(combinations)))
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def mortality_interval(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each member's interval ends at each horizon: her combination's, empty for one the training never saw."""
empty = ([np.nan] * len(self.horizons_years),) * 2
ends = [self.interval_table_.get(tuple(c), empty) for c in _combinations(X).itertuples(index=False)]
return (np.array([e[0] for e in ends], dtype=float).reshape(len(X), -1),
np.array([e[1] for e in ends], dtype=float).reshape(len(X), -1))
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if self.interval_level:
mortality = np.column_stack([mortality, *self.mortality_interval(X)])
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
__all__ = ["FEATURES", "INDEX_COLUMN", "IntervalSurvival", "MemberFeatures", "WINDOW_KEYS", "encode", "interval_cohort",
"member_table"]
+154
View File
@@ -0,0 +1,154 @@
"""CaCu survival prototype: the all-cause mortality at 1, 3 and 5 years from the cancer diagnosis.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): PROVISIONAL, the diagnosis is the first biopsy reported as invasive carcinoma, which is both the
inclusion criterion and the index date. Each member's covariates are her most recent observations up to it: her age
group at the index, her latest cytology (KPNC's categories) and her latest HPV result; her outcome is the months from
the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts the
follow-up). The fit is the SEER pipeline's interval survival, as CaMa's survival scenario runs it
(`models.cama.survival`): per interval a logistic regression and a Bayesian network, stacked. A member without a result
has it as a category of its own.
The nodes that don't depend on the covariates are CaMa's, called from here: Hamilton takes as nodes only the functions
defined in a listed module, and listing CaMa's would bring its covariate-bound nodes too. Those bound to the covariates
(`labelled_members`, `missing_data`, `analytic_method`) are copies over this scenario's `FEATURES` (DUPLICATED, issue
#9). `fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
`Pipeline` that takes a build's long frame.
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
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
from models.cama.survival import model as cama
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""CaMa's: the build's cut-off."""
return cama.cohort_cutoff(cohort_lineage)
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""CaMa's: the pipeline's survival settings, whose horizons in months must be `horizons_years`."""
return cama.survival_settings(survival, horizons_years)
def member_features(cohort: pd.DataFrame, age_cuts: list[int], cytology: dict) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates (her most recent
observations up to it)."""
return estimator.member_table(cohort, age_cuts, cytology)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""CaMa's: one row per member, by `pac_id`: months of follow-up and whether she died in them."""
return cama_estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float],
risk_interval_level: float | None = None, risk_interval_replicas: int = 100) -> IntervalSurvival:
"""The interval survival fitted on the training members, with each combination's bootstrap interval at
`risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run)."""
return IntervalSurvival(survival, tuple(horizons_years), risk_interval_level, risk_interval_replicas).fit(
train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance)."""
return 1.0 - fitted_survival.survival_proba(train_set[FEATURES])
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""CaMa's: aggregates only, over the test members' member-intervals, and the apparent AUC at each horizon."""
return cama.metrics(train_set, test_set, test_interval_survival, train_mortality, survival_settings, fitted_survival)
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""CaMa's MUESTREO: who could be used and how they were split."""
return cama.sampling(index_attrition, prior_observation, train_set, test_set, train_fraction)
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it (DUPLICATED, issue #9)."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept
(DUPLICATED, issue #9)."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"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_],
"subgroup_report": report.METHODS}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""CaMa's BALANCE_CLASES: deaths and members followed without one in each part."""
return cama.class_balance(train_set, test_set)
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CaMa's CONFIANZA_SALIDA: the predicted survival of each interval against the observed one, by quantiles."""
return cama.output_confidence(test_set, test_interval_survival, survival_settings, calibration_bins)
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return cama.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
cytology: dict) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), dict(cytology))),
("survival", fitted_survival)])
+102
View File
@@ -0,0 +1,102 @@
domain = "cacu"
scenario = "survival"
cohort = "cacu/cohorte_total"
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.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 o in situ), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \
recientes hasta él. Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana combinadas), \
como la de CaMa. Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la \
registra."""
# What the model's number is, as the patient's screen shows it. The model gives the probability of dying; the screen
# shows its complement, the probability of surviving, with the interval's ends swapped.
[estimand]
quantity = "Probabilidad de supervivencia"
description = "Probabilidad de que la paciente siga viva a cada horizonte desde el diagnóstico de cáncer."
outcome = "Muerte por cualquier causa"
index_date = "la primera biopsia con carcinoma invasor o in situ"
horizons_unit = "años"
covariates = "grupo de edad al diagnóstico, citología (categorías de KPNC) y VPH más recientes hasta él"
complement = "supervivencia"
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [1.0, 3.0, 5.0]
# The level of each risk's interval: per combination of the covariates, the percentiles of `risk_interval_replicas`
# refits on bootstrap resamples of the training members. None gives no interval.
risk_interval_level = 0.95
risk_interval_replicas = 100
# The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance.
age_cuts = [35, 45, 55]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). PROVISIONAL: the diagnosis is the
# first biopsy reported as carcinoma, invasive or in situ (`CARCINOMA`, `CIS`), which is both the inclusion criterion and
# the index date; out: no birth date (no age), a death on or before the biopsy. The recruitment window is the source
# cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with CaMa's settings but the
# horizons, the follow-up cap and the HBN's parents.
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [35, 45, 55]
hbn_fixed_parents = [] # no expert parents defined for CaCu yet: learned by the BDeu score
hbn_age_parent = false
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [12, 36, 60] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 60
cap_months = 60 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says (provisional: to be defined with the clinicians).
[config.etiquetas]
titulo = "Supervivencia después de la biopsia con carcinoma invasor o in situ"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result (as `cin2_pim`); with both results the more severe category wins.
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
@@ -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
}
+87
View File
@@ -0,0 +1,87 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon, as CaMa's survival scenario publishes them (`models.cama.survival.population`).
Over every member of the indexed cohort: the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted
curve, the classic and the fractional Weibull fitted to it, and the mean survival at each horizon by the logistic
regression, the Bayesian network and their stacked combination, each with a 95 % bootstrap interval. The record is the
version's `analisis/curvas.json`; its labels come from `[config.etiquetas]`.
Every node but `survival_frame` is CaMa's, called from here (Hamilton takes only the functions defined in a listed
module). `survival_frame` is a copy over this scenario's `FEATURES` (DUPLICATED, issue #9).
"""
import numpy as np
import pandas as pd
from models.cacu.survival.estimator import FEATURES
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
from models.cama.survival import population as cama
from models.cama.survival.estimator import UNKNOWN
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts
as alive) and the covariates as categories (DUPLICATED, issue #9)."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
return cama.curve_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
return cama.km_raw(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
return cama.km_curve(km_raw)
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
return cama.adjusted_km(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
return cama.population_weights(curve_cohort, survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
return cama.luis_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return cama.point_estimates(luis_points)
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
return cama.bootstrap_points(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
return cama.weibull_fits(adjusted_km, survival_frame, survival_settings)
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""CaMa's: the `curvas` record the dashboard draws."""
return cama.population_curves(labelled_members, km_curve, adjusted_km, weibull_fits, point_estimates,
bootstrap_points, population_weights, survival_settings, etiquetas)
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}
+136
View File
@@ -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'])}<br>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}<extra>KM</extra>"), 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}<extra>modelo</extra>"),
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<br>"
f"<sup>{etiquetas.get('eje_x', 'Meses')}; {NOTICE}</sup>"},
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"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>Supervivencia por subgrupo</title>"
"</head><body style=\"font-family:sans-serif;margin:16px\">"
+ figure.to_html(full_html=False, include_plotlyjs=True)
+ note + "<h3>Combinaciones</h3>" + counts.to_html(index=False, border=0) + "</body></html>")
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}
@@ -0,0 +1,71 @@
import json
import os
import numpy as np
import pandas as pd
CSV_ENTRADA = "./brca_metabric_clinical_data.tsv"
DIR_INT = "./intermedios_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
V_MAX = 0.80
d = pd.read_csv(CSV_ENTRADA, sep="\t")
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
def con_desconocido(s):
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def cortar(s, cortes, etiquetas):
c = pd.cut(s, cortes, labels=etiquetas, right=False)
return con_desconocido(c.astype("object"))
out["Edad"] = cortar(d["Age at Diagnosis"], [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
out["Tamano_tumor"] = cortar(d["Tumor Size"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
out["Ganglios_positivos"] = cortar(d["Lymph nodes examined positive"], [0, 1, 4, 1e3], ["0", "1-3", "4+"])
out["Grado_histologico"] = con_desconocido(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
mc = d["Mutation Count"]
q = mc.quantile([1 / 3, 2 / 3]).values
out["Carga_mutacional"] = cortar(mc, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
for nombre, col in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
out[nombre] = con_desconocido(d[col])
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento")]
def cramer_v(a, b):
t = pd.crosstab(a, b)
from scipy.stats import chi2_contingency
chi2 = chi2_contingency(t, correction=False)[0]
n = t.values.sum()
k = min(t.shape) - 1
return np.sqrt(chi2 / (n * k)) if k > 0 else 0.0
eliminadas = []
cand = [c for c in covariables if c not in TRATAMIENTO]
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
for v, a, b in pares:
if v < V_MAX:
break
if a in eliminadas or b in eliminadas:
continue
na_a, na_b = (out[a] == "Desconocido").mean(), (out[b] == "Desconocido").mean()
quitar = a if na_a >= na_b else b
eliminadas.append(quitar)
covariables.remove(quitar)
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia.csv", index=False)
out = out[["paciente", "tiempo_meses", "evento"] + covariables]
out.to_csv(f"{DIR_INT}/cohorte_recurrencia.csv", index=False)
with open(f"{DIR_INT}/covariables_recurrencia.json", "w", encoding="utf8") as f:
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,70 @@
import json
import os
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
CSV_ENTRADA = "./scanb_clinical_metadata.txt"
V_MAX = 0.80
DIAS_POR_MES = 30.4375
DIR_INT = "./intermedios_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
d = pd.read_csv(CSV_ENTRADA, sep="\t", low_memory=False)
d = d[d["Gender"] == "F"]
d = d.dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]})
out["tiempo_meses"] = d["RFI_days"].astype(float) / DIAS_POR_MES
out["evento"] = d["RFI_event"].astype(int)
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
def con_desconocido(s):
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def cortar(s, cortes, etiquetas):
return con_desconocido(pd.cut(s, cortes, labels=etiquetas, right=False).astype("object"))
out["Edad"] = cortar(d["Age_5year_bin"].astype(float) - 2, [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
out["Tamano_tumor"] = cortar(d["TumorSize_mm"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
out["Ganglios_positivos"] = con_desconocido(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
out["Grado_histologico"] = con_desconocido(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
for nombre, col in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
out[nombre] = con_desconocido(d[col])
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento", "muerte_sin_recaida")]
def cramer_v(a, b):
t = pd.crosstab(a, b)
chi2 = chi2_contingency(t, correction=False)[0]
k = min(t.shape) - 1
return np.sqrt(chi2 / (t.values.sum() * k)) if k > 0 else 0.0
eliminadas = []
cand = [c for c in covariables if c not in TRATAMIENTO]
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
for v, a, b in pares:
if v < V_MAX:
break
if a in eliminadas or b in eliminadas:
continue
quitar = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
eliminadas.append(quitar)
covariables.remove(quitar)
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia_scanb.csv", index=False)
out = out[["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] + covariables]
out.to_csv(f"{DIR_INT}/cohorte_recurrencia_scanb.csv", index=False)
with open(f"{DIR_INT}/covariables_recurrencia_scanb.json", "w", encoding="utf8") as f:
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,261 @@
import json
import os
import sys
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.calibration import calibration_curve
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.estimators import HillClimbSearch, BDeu
from pgmpy.causal_discovery import ExpertKnowledge
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import networkx as nx
warnings.filterwarnings("ignore")
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
os.makedirs(DIR_FIG, exist_ok=True)
SEMILLA = 42
N_BOOTSTRAP = int(os.environ.get("N_BOOTSTRAP", 100 if COHORTE == "metabric" else 40))
BDEU_ESS = 10
MAX_PADRES = 6
ALFA_IN, ALFA_OUT, ALFA_PREFILTRO = 0.10, 0.15, 0.10
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
covariables = meta["covariables"]
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
TIER_DEMOGRAFIA = ["Edad", "Estado_menopausico"]
TIER_TUMOR = ["Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Cluster_integrativo", "Lateralidad",
"Ki67", "Subtipo_clinico", "Estadio_clinico"]
TIER_TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- funciones ----
def orden_temporal(cols):
tiers = [[c for c in t if c in cols] for t in (TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, ["outcome"])]
sin = [c for c in cols if c not in sum(tiers, [])]
return ([sin] if sin else []) + [t for t in tiers if t]
def codificar(df):
X = pd.get_dummies(df[covariables], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def ajuste_logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prefiltro(X, y):
keep = []
for c in X.columns:
m = ajuste_logit(y, X[[c]])
if m is not None and m.pvalues[c] < ALFA_PREFILTRO:
keep.append(c)
return keep
def stepwise(X, y):
incl = []
for _ in range(200):
cambio = False
mejor, p_mejor = None, ALFA_IN
for c in [c for c in X.columns if c not in incl]:
m = ajuste_logit(y, X[incl + [c]])
if m is not None and m.pvalues[c] < p_mejor:
mejor, p_mejor = c, m.pvalues[c]
if mejor is not None:
incl.append(mejor)
cambio = True
if incl:
m = ajuste_logit(y, X[incl])
if m is not None:
p = m.pvalues.drop("const")
if p.max() > ALFA_OUT:
incl.remove(p.idxmax())
cambio = True
if not cambio:
break
return incl
def lr_completo(df_train, df_test):
Xall = codificar(pd.concat([df_train, df_test]))
Xtr, Xte = Xall.loc[df_train.index], Xall.loc[df_test.index]
Xtr = Xtr.loc[:, Xtr.nunique() > 1]
Xte = Xte[Xtr.columns]
cand = prefiltro(Xtr, df_train["y"])
sel = stepwise(Xtr[cand], df_train["y"]) if cand else []
if not sel:
return None, [], np.full(len(df_test), df_train["y"].mean())
m = ajuste_logit(df_train["y"], Xtr[sel])
return m, sel, m.predict(sm.add_constant(Xte[sel], has_constant="add")).values
def variable_de(t):
return next((c for c in sorted(covariables, key=len, reverse=True) if t.startswith(c + "_")), t)
def padres_outcome(train, candidatos):
sc = BDeu(train, equivalent_sample_size=BDEU_ESS)
padres, actual = [], sc.local_score("outcome", [])
while len(padres) < MAX_PADRES:
mejor, ganancia = None, 0
for c in candidatos:
if c in padres:
continue
g = sc.local_score("outcome", padres + [c]) - actual
if g > ganancia:
mejor, ganancia = c, g
if mejor is None:
break
padres.append(mejor)
actual += ganancia
return padres
def prob_hbn(train, test, padres):
if not padres:
return np.full(len(test), (train["outcome"] == "1").mean())
q = int(np.prod([train[p].nunique() for p in padres]))
alpha = BDEU_ESS / (2 * q)
g = train.groupby(padres)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
p_glob = (train["outcome"] == "1").mean()
tabla = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
return np.array([tabla.get(k, p_glob) for k in map(tuple, test[padres].values)])
def tabla_bn(df):
t = df[covariables].astype(str).copy()
t["outcome"] = df["y"].astype(int).astype(str)
return t
def cohorte_a_horizonte(H):
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
libre = coh_total["tiempo_meses"] > H
d = coh_total[recurre | libre].reset_index(drop=True)
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
return d
# ---- Cox de referencia (tiempo completo) ----
cox_df = pd.get_dummies(coh_total[["tiempo_meses", "evento"] + covariables], columns=covariables, drop_first=True).astype(float)
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
ctr, cte = train_test_split(cox_df, test_size=0.3, random_state=SEMILLA, stratify=cox_df["evento"])
_ok = [c for c in ctr.columns if c in ("tiempo_meses", "evento") or 10 <= ctr[c].sum() <= len(ctr) - 10]
ctr, cte = ctr[_ok], cte[_ok]
cox = CoxPHFitter(penalizer=0.05).fit(ctr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
c_index = concordance_index(cte["tiempo_meses"], -cox.predict_partial_hazard(cte), cte["evento"])
# ---- modelos por horizonte ----
filas_auc, modelos_json, curvas = [], {}, {}
for H in HORIZONTES:
coh = cohorte_a_horizonte(H)
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=SEMILLA, stratify=coh["y"])
tr, te = coh.loc[tr_idx], coh.loc[te_idx]
modelo_lr, sel_lr, p_lr = lr_completo(tr, te)
auc_lr = roc_auc_score(te["y"], p_lr)
bn_tr, bn_te = tabla_bn(tr), tabla_bn(te)
padres = padres_outcome(bn_tr, covariables)
p_hbn = prob_hbn(bn_tr, bn_te, padres)
auc_hbn = roc_auc_score(te["y"], p_hbn)
if H == max(HORIZONTES):
expert = ExpertKnowledge(temporal_order=orden_temporal(list(bn_tr.columns)))
estructura = HillClimbSearch(bn_tr).estimate(scoring_method=BDeu(bn_tr, equivalent_sample_size=BDEU_ESS), max_indegree=4,
expert_knowledge=expert, show_progress=False)
arcos_red = [(u, v) for u, v in estructura.edges() if u != "outcome" and v != "outcome"] + [(p, "outcome") for p in padres]
G = nx.DiGraph(arcos_red)
plt.figure(figsize=(10, 7))
nx.draw(G, nx.spring_layout(G, seed=SEMILLA, k=0.9), with_labels=True, node_color="lightblue", node_size=2200, font_size=7, arrowsize=14)
plt.title(f"Estructura de la red bayesiana ({COHORTE}, {H} meses)")
plt.tight_layout()
plt.savefig(f"{DIR_FIG}/hbn_estructura_{COHORTE}.png", dpi=150)
plt.close()
rng = np.random.default_rng(SEMILLA)
aucs, cuenta_lr, cuenta_hbn, n_lr, n_hbn = [], {}, {}, 0, 0
for b in range(N_BOOTSTRAP):
db = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
try:
dtr, dte = train_test_split(db, test_size=0.3, random_state=SEMILLA + b, stratify=db["y"])
m, sel, p = lr_completo(dtr, dte)
a_lr = roc_auc_score(dte["y"], p)
btr, bte = tabla_bn(dtr), tabla_bn(dte)
pa = padres_outcome(btr, covariables)
a_h = roc_auc_score(dte["y"], prob_hbn(btr, bte, pa))
except Exception:
continue
aucs.append((a_lr, a_h))
n_lr += 1
n_hbn += 1
if m is not None:
for v in {variable_de(t) for t in m.params.drop("const").index}:
cuenta_lr[v] = cuenta_lr.get(v, 0) + 1
for v in pa:
cuenta_hbn[v] = cuenta_hbn.get(v, 0) + 1
aucs = np.array(aucs)
for j, (nombre, auc_int) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": H, "modelo": nombre, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
"AUC_validacion_interna": auc_int, "AUC_bootstrap_medio": aucs[:, j].mean(),
"AUC_bootstrap_IC95_inf": np.percentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.percentile(aucs[:, j], 97.5),
"replicas_bootstrap": len(aucs)})
ci = modelo_lr.conf_int()
modelos_json[str(H)] = {"terminos_lr": list(sel_lr), "padres_hbn": padres, "n_replicas": n_lr,
"seleccion_lr": cuenta_lr, "seleccion_hbn": cuenta_hbn,
"arcos_hbn": [list(a) for a in (arcos_red if H == max(HORIZONTES) else [(p, "outcome") for p in padres])]}
curvas[H] = (te["y"].values, p_lr, p_hbn)
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(coh_total),
"recurrencias": int(coh_total["evento"].sum()), "AUC_validacion_interna": c_index})
json.dump(modelos_json, open(f"{DIR_INT}/modelos{SFX}.json", "w", encoding="utf8"), indent=1, ensure_ascii=False)
# ---- consolidado de AUC (un solo archivo con las dos cohortes) ----
nuevo = pd.DataFrame(filas_auc)
destino = "./auc_recurrencia.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
previo = previo[~((previo["cohorte"] == COHORTE) & (previo["horizonte_meses"].astype(str).isin([str(h) for h in HORIZONTES] + ["completo"])))]
nuevo = pd.concat([previo, nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
# ---- figuras: ROC y calibracion (un panel por horizonte) ----
for nombre_fig, tipo in [("roc", "roc"), ("calibracion", "cal")]:
fig, axs = plt.subplots(1, len(HORIZONTES), figsize=(5.2 * len(HORIZONTES), 5), squeeze=False)
for ax, H in zip(axs[0], HORIZONTES):
y, pl, ph = curvas[H]
for nom, p in [("LR", pl), ("HBN", ph)]:
if tipo == "roc":
f, t, _ = roc_curve(y, p)
ax.plot(f, t, label=f"{nom} (AUC {roc_auc_score(y, p):.3f})")
else:
fr, mp = calibration_curve(y, p, n_bins=8, strategy="quantile")
ax.plot(mp, fr, "o-", label=nom)
ax.plot([0, 1], [0, 1], "k:")
ax.set_title(f"{COHORTE}: {H} meses")
ax.set_xlabel("1 - especificidad" if tipo == "roc" else "probabilidad predicha de recurrencia")
ax.set_ylabel("sensibilidad" if tipo == "roc" else "frecuencia observada")
ax.legend()
fig.tight_layout()
fig.savefig(f"{DIR_FIG}/{nombre_fig}_{COHORTE}.png", dpi=150)
plt.close(fig)
@@ -0,0 +1,158 @@
import sys
import os
import json
import numpy as np
import pandas as pd
import statsmodels.api as sm
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT = "./intermedios_recurrencia"
ALFA = 0.05
FREQ_MIN = 0.80
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
variables = meta["covariables"]
tratamiento = meta["tratamiento"]
intrinsecas = [v for v in variables if v not in tratamiento]
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in variables})
# ---- funciones ----
def bh(p):
p = np.asarray(p, float)
orden = np.argsort(p)
aj = np.empty_like(p)
m = len(p)
prev = 1.0
for rango, i in zip(range(m, 0, -1), orden[::-1]):
prev = min(prev, p[i] * m / rango)
aj[i] = prev
return aj
def variable_de(termino, vars_modelo):
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
def km_en(m, e, h):
T = int(m.max()) + 2
d = np.bincount(m[e], minlength=T)
c = np.bincount(m[~e], minlength=T)
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def procesar_horizonte(H):
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
libre = coh_total["tiempo_meses"] > H
datos_km = coh_total.copy()
coh = coh_total[recurre | libre].reset_index(drop=True)
datos = coh[variables].astype(str)
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
meses = np.floor(np.minimum(datos_km["tiempo_meses"].values, H + 1)).astype(int)
evento = ((datos_km["evento"] == 1) & (datos_km["tiempo_meses"] <= H)).values
datos_km = datos_km[variables].astype(str)
def referencia(v):
return datos[v].value_counts().idxmax()
def ajustar_or(vars_modelo):
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
modelo = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ic = modelo.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(modelo.params[X.columns].values),
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
"p": modelo.pvalues[X.columns].values})
def delta_s(v, cat, ref):
a = (datos_km[v] == cat).values
b = (datos_km[v] == ref).values
Sa, ea = km_en(meses[a], evento[a], H)
Sb, eb = km_en(meses[b], evento[b], H)
d = Sa - Sb
es = np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
def completar(t, vars_modelo):
t = t.copy()
t["variable"] = [variable_de(x, vars_modelo) for x in t["termino"]]
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
t["referencia"] = [referencia(v) for v in t["variable"]]
t["p_ajustado_BH"] = bh(t["p"])
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab = completar(ajustar_or(intrinsecas), intrinsecas)
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
mh = modelos.get(str(H), {})
n_rep = mh.get("n_replicas", 0)
sel = mh.get("seleccion_lr", {})
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: sel.get(v, 0) / n_rep if n_rep else np.nan)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
manta = set(mh.get("padres_hbn", []))
tab["en_manta_markov"] = tab["variable"].isin(manta)
tab["c3_manta_markov"] = tab["en_manta_markov"]
crit = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[crit].astype(bool).sum(axis=1)
def clasificar(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(clasificar, axis=1)
tab["tipo"] = "factor de riesgo"
if tratamiento:
tr = ajustar_or(intrinsecas + tratamiento)
tr["_v"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
tr = tr[tr["_v"].isin(tratamiento) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
tr = completar(tr, tratamiento)
tr["tipo"] = "tratamiento"
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"] = COHORTE
tab["horizonte_meses"] = H
return tab
columnas = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "clasificacion"]
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
nuevo = pd.concat([procesar_horizonte(H) for H in HORIZONTES], ignore_index=True)
nuevo["_t"] = (nuevo["tipo"] != "factor de riesgo").astype(int)
nuevo["_o"] = nuevo["clasificacion"].map(orden).fillna(5)
nuevo = nuevo.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[columnas]
destino = "./factores_riesgo_recurrencia.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
previo = previo[previo["cohorte"] != COHORTE]
nuevo = pd.concat([previo, nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
@@ -0,0 +1,450 @@
import sys
import os
import re
import json
import time
import subprocess
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.optimize import minimize
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
try:
import mpmath as mp
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
import mpmath as mp
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
os.makedirs(DIR_FIG, exist_ok=True)
SEMILLA = 42
B_BOOT = int(os.environ.get("N_BOOT_CALC", 200))
MIN_EVENTOS = 15
TOPE_MESES = 72
BDEU_ESS = 10
COLOR_PUNTOS, MARCA_PUNTOS = "#6a3d9a", "D"
SUBGRUPOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
}[COHORTE]
# ---- ajuste parametrico (Weibull y Weibull fraccional de Kilbas-Saigo) ----
from functools import lru_cache
from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
for i in range(N - 1):
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
return tuple(c)
def _log_terms(az, rho, m, l, N):
i = np.arange(N - 1)
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
n = np.arange(N)
with np.errstate(divide="ignore"):
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
return lt
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
az = np.abs(z)
N = 400
lt = _log_terms(az, rho, m, l, N)
lmax, llast = lt.max(axis=1), lt[:, -1]
zero = az == 0
out[zero] = 1.0
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
if okf.any():
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
terms[:, 0] = 1.0
out[okf] = terms.sum(axis=1)
rest = np.where(~zero & ~okf)[0]
if rest.size:
with np.errstate(over="ignore"):
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
est = np.maximum(est, lmax[rest])
use = rest[est <= logmax_cap]
if use.size:
est_u = est[est <= logmax_cap]
dps = 30 + int(est_u.max() / 2.3) + 10
zmax = float(az[use].max())
with np.errstate(over="ignore"):
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
N2 = max(N2, 60)
while True:
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
mp.mp.dps = dps
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
if last < tol or N2 >= nmax:
break
N2 *= 2
if last < tol:
cr = list(c)[::-1]
for j in use:
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
return out
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full_like(t, np.nan)
m = s/beta + 1; l = s/beta
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
with np.errstate(divide="ignore", invalid="ignore"):
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
z = np.where(t > 0, z, 0.0)
res = np.ones_like(t)
pos = t > 0
if pos.any():
res[pos] = kilbas_saigo(z[pos], beta, m, l)
return np.clip(res, 0.0, 1.0)
def S_weibull(t, k, lam):
t = np.asarray(t, float)
return np.exp(-(t/lam)**k)
def tabla_eventos(meses, evento):
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
T = int(meses.max()) + 2
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
return d, c
def _nll_from_S(Sfun, d, c):
T = len(d)
grid = np.arange(0, T + 1, dtype=float)
Sg = Sfun(grid)
mid = Sfun(np.arange(T) + 0.5)
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
return 1e12
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def ajustar_weibull(d, c):
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50., 200., 1000.):
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
if best is None or r.fun < best.fun: best = r
k, lam = np.exp(best.x)
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
S=lambda t: S_weibull(t, k, lam))
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
amin = max(0.0, 1.0 - k_fijo) + 1e-6
def unpack(p):
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
T_max = float(len(d))
t_fin = time.time() + max_seg
agotado = [False]
def f(p):
if time.time() > t_fin:
agotado[0] = True
return 1e12
a, b, lam = unpack(p)
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
return 1e12
try:
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
except Exception:
return 1e12
lams = [lam_ref] if lam_ref else []
lams += [100., 500.]
best = None
inicios = []
if lam_ref:
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
for l0 in lams:
for a0 in (0.3, 1.0):
for b0 in (0.5, 0.9):
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
for p0 in inicios:
if time.time() > t_fin and best is not None: break
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
if best is None or r.fun < best.fun: best = r
a, b, lam = unpack(best.x)
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
S=lambda t: S_ks(t, k_fijo, a, b, lam))
def km_curva(meses_int, evento, T):
d, c = tabla_eventos(meses_int, evento)
L = max(len(d), T + 1)
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
with np.errstate(divide="ignore", invalid="ignore"):
se = np.sqrt(V) / np.abs(np.log(S))
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
return S, lo, hi
# ---- datos y modelos ya seleccionados en 03_modelado.py ----
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
covariables = meta["covariables"]
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
df = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
N = len(df)
meses_int = np.floor(df["tiempo_meses"].values).astype(int)
evento = (df["evento"] == 1).values
tiempo, ev_num = df["tiempo_meses"].values, df["evento"].values
X_dum = pd.get_dummies(df[covariables], drop_first=True).astype(float)
codigos = {v: pd.factorize(df[v])[0] for v in covariables}
niveles = {v: int(codigos[v].max()) + 1 for v in covariables}
def ajuste_logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prob_lr(idx_ent, y_ent, terminos):
if not terminos:
return np.full(N, y_ent.mean())
m = ajuste_logit(y_ent, X_dum.iloc[idx_ent][terminos])
if m is None:
return None
return m.predict(sm.add_constant(X_dum[terminos], has_constant="add")).values
def clave(padres, filas):
k = np.zeros(len(filas), dtype=np.int64)
for p in padres:
k = k * niveles[p] + codigos[p][filas]
return k
def prob_hbn(idx_ent, y_ent, padres):
if not padres:
return np.full(N, y_ent.mean())
q = int(np.prod([niveles[p] for p in padres]))
alpha = BDEU_ESS / (2 * q)
k_ent = clave(padres, idx_ent)
n = pd.Series(1, index=k_ent).groupby(level=0).sum()
n1 = pd.Series(y_ent, index=k_ent).groupby(level=0).sum()
tabla = (n1 + alpha) / (n + 2 * alpha)
p_glob = y_ent.mean()
return tabla.reindex(clave(padres, np.arange(N))).fillna(p_glob).values
def riesgos(idx, H):
t, e = tiempo[idx], ev_num[idx]
rec = (e == 1) & (t <= H)
ok = rec | (t > H)
ent = idx[ok]
y = rec[ok].astype(int)
mh = modelos[str(H)]
pl = prob_lr(ent, y, mh["terminos_lr"])
ph = prob_hbn(ent, y, mh["padres_hbn"])
if pl is None:
return None
return pl, ph
def riesgo_subgrupo(idx, masks):
out = {n: np.full(len(HORIZONTES), np.nan) for n in masks}
for j, H in enumerate(HORIZONTES):
r = riesgos(idx, H)
if r is None:
return None
comb = (r[0] + r[1]) / 2
for n, mk in masks.items():
sel = mk[idx]
if sel.any():
out[n][j] = comb[idx][sel].mean()
return out
# ---- subgrupos y bootstrap ----
MASCARAS = {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in SUBGRUPOS.items()}
todos = np.arange(N)
puntos = riesgo_subgrupo(todos, MASCARAS)
rng = np.random.default_rng(SEMILLA)
boots = {n: [] for n in MASCARAS}
for b in range(B_BOOT):
r = riesgo_subgrupo(rng.integers(0, N, N), MASCARAS)
if r is None:
continue
for n in MASCARAS:
boots[n].append(r[n])
def graficar(nombre, mk):
sub = df[mk]
n_, ev_ = len(sub), int(sub["evento"].sum())
if n_ == 0 or ev_ < MIN_EVENTOS:
return None
m_s, e_s = meses_int[mk], evento[mk]
d_, c_ = tabla_eventos(m_s, e_s)
w_ = ajustar_weibull(d_, c_)
ks_ = ajustar_ks(d_, c_, k_fijo=w_["k"], lam_ref=w_["lam"], max_seg=60)
Tm = int(m_s.max())
Sk, lok, hik = km_curva(m_s, e_s, Tm)
tt = np.arange(Tm + 1)
r = 1 - puntos[nombre]
B = np.array(boots[nombre])
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(HORIZONTES)), np.nan)
fig, ax = plt.subplots(figsize=(9, 5.2))
ax.fill_between(tt, lok, hik, step="post", color="#9aa5b1", alpha=.3, lw=0)
ax.step(tt, Sk, where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
for ajuste, col, ls, lb in [(w_, "#1f77b4", "-", "Weibull"), (ks_, "#d1495b", "--", "Weibull fraccional")]:
t_in = np.linspace(0, Tm, 300)
t_ex = np.linspace(Tm, TOPE_MESES, 200)
ax.plot(t_in, ajuste["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
ax.plot(t_ex, ajuste["S"](t_ex), color=col, lw=1.4, ls=":")
ax.errorbar(HORIZONTES, r, yerr=[np.clip(r - ic[0], 0, None), np.clip(ic[1] - r, 0, None)], fmt=MARCA_PUNTOS, color=COLOR_PUNTOS,
ms=9, capsize=4, lw=1.8, mec="white", mew=1, label="LR + HBN combinado (IC 95 % bootstrap)", zorder=5)
x1 = TOPE_MESES + 0.8
xs = np.linspace(0, x1, 400)
v = np.concatenate([w_["S"](xs), ks_["S"](xs), Sk[:int(min(x1, Tm)) + 1], lok[:int(min(x1, Tm)) + 1], r, ic.ravel()])
v = v[np.isfinite(v)]
mg = (v.max() - v.min()) * .06
ax.set_xlim(0, x1)
ax.set_ylim(max(0, v.min() - mg), min(1.005, v.max() + mg))
ax.set_xlabel("Meses desde el diagnóstico")
ax.set_ylabel("Libre de recaída S(t)")
ax.grid(alpha=.25)
ax.set_title(f"{nombre}\n{'SCAN-B' if COHORTE == 'scanb' else 'METABRIC'} · n={n_:,}, recaídas={ev_:,}", fontsize=11)
ax.legend(frameon=False, loc="lower left", fontsize=9)
for sp in ("top", "right"):
ax.spines[sp].set_visible(False)
fig.tight_layout()
arch = re.sub(r"[^A-Za-z0-9]+", "_", nombre.replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt")
.replace("−", "neg").replace("+", "pos").replace("ñ", "n").replace("á", "a").replace("í", "i").replace("é", "e")).strip("_")
fig.savefig(f"{DIR_FIG}/subgrupo_{COHORTE}_{arch}.png", dpi=170)
plt.close(fig)
filas = []
for j, H in enumerate(HORIZONTES):
filas.append({"cohorte": COHORTE, "subgrupo": nombre, "n": n_, "recaidas": ev_, "horizonte_meses": H,
"S_libre_LR_HBN": r[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - r[j],
"S_libre_KM": Sk[min(H, Tm)] if H <= Tm else np.nan, "replicas_bootstrap": len(B)})
return filas
filas = []
for nombre, mk in MASCARAS.items():
f = graficar(nombre, mk)
if f:
filas += f
nuevo = pd.DataFrame(filas)
destino = "./calculadora_recurrencia_subgrupos.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
nuevo = pd.concat([previo[previo["cohorte"] != COHORTE], nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
# ---- escenarios clinicos: factores de riesgo que incluye cada subgrupo ----
PCT_DEFINITORIA = 0.95
PCT_MAYORITARIA = 0.50
PCT_PRESENTE = 0.10
def nivel_presencia(p):
if p >= PCT_DEFINITORIA:
return "definitoria"
if p >= PCT_MAYORITARIA:
return "mayoritaria"
return "presente" if p >= PCT_PRESENTE else "minoritaria"
def definicion(cond):
return "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
if os.path.exists("./factores_riesgo_recurrencia.csv"):
fr = pd.read_csv("./factores_riesgo_recurrencia.csv", dtype={"categoria": str})
fr = fr[(fr["cohorte"] == COHORTE) & fr["horizonte_meses"].isin(HORIZONTES)]
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
filas_esc, filas_res = [], []
for nombre, mk in MASCARAS.items():
n_sub = int(mk.sum())
if n_sub == 0:
continue
cond = SUBGRUPOS[nombre]
pct = {}
for v, c in set(zip(fr["variable"], fr["categoria"])):
pct[(v, c)] = (float((df.loc[mk, v] == c).mean()), float((df[v] == c).mean()))
det = fr.copy()
det["pct_en_escenario"] = [pct[(v, c)][0] for v, c in zip(det["variable"], det["categoria"])]
det["pct_en_cohorte"] = [pct[(v, c)][1] for v, c in zip(det["variable"], det["categoria"])]
det["presencia"] = det["pct_en_escenario"].map(nivel_presencia)
det["en_definicion"] = [c in cond.get(v, []) for v, c in zip(det["variable"], det["categoria"])]
det.insert(0, "escenario", nombre)
det.insert(1, "definicion", definicion(cond))
det.insert(2, "n_escenario", n_sub)
columnas = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte",
"presencia", "en_definicion"]
filas_esc.append(det[det["pct_en_escenario"] >= PCT_PRESENTE][columnas])
for H in HORIZONTES:
d = det[det["horizonte_meses"] == H]
fila = {"cohorte": COHORTE, "escenario": nombre, "definicion": definicion(cond), "n_escenario": n_sub, "horizonte_meses": H}
for tipo in ("riesgo", "protector", "tratamiento"):
for nivel, etiqueta in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
s_ = d[(d["tipo_efecto"] == tipo) & (d["presencia"] == nivel)]
fila[f"{tipo}_{etiqueta}"] = "; ".join(
f"{v}={c} ({k.split()[-1] if tipo != 'tratamiento' else 'asociacion'}, {p:.0%})"
for v, c, k, p in zip(s_["variable"], s_["categoria"], s_["clasificacion"], s_["pct_en_escenario"]))
fila["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
fila["incluye_factor_riesgo"] = fila["n_factores_riesgo_incluidos"] > 0
filas_res.append(fila)
for archivo, filas_x in (("./escenarios_factores_riesgo_recurrencia.csv", pd.concat(filas_esc, ignore_index=True)),
("./escenarios_resumen_recurrencia.csv", pd.DataFrame(filas_res))):
if os.path.exists(archivo):
previo = pd.read_csv(archivo)
filas_x = pd.concat([previo[previo["cohorte"] != COHORTE], filas_x], ignore_index=True)
filas_x.round(4).to_csv(archivo, index=False)
@@ -0,0 +1,33 @@
import argparse
import csv
import subprocess
import sys
import time
ap = argparse.ArgumentParser()
ap.add_argument("--cohorte", choices=["metabric", "scanb"])
ap.add_argument("--horizontes", nargs="+", default=["12", "36", "60"])
a = ap.parse_args()
cohortes = [a.cohorte] if a.cohorte else ["metabric", "scanb"]
prep = {"metabric": "01_preparacion_metabric.py", "scanb": "02_preparacion_scanb.py"}
pasos = []
for c in cohortes:
pasos.append((f"preparacion_{c}", [prep[c]]))
pasos.append((f"03_modelado_{c}", ["03_modelado.py", c] + a.horizontes))
pasos.append((f"04_factores_riesgo_{c}", ["04_factores_riesgo.py", c] + a.horizontes))
pasos.append((f"05_calculadora_{c}", ["05_calculadora.py", c] + a.horizontes))
bit = []
for nombre, cmd in pasos:
t0 = time.time()
r = subprocess.run([sys.executable, "-W", "ignore"] + cmd, capture_output=True, text=True)
bit.append([nombre, "ok" if r.returncode == 0 else "ERROR", round(time.time() - t0, 1)])
with open("bitacora_recurrencia.csv", "w", newline="", encoding="utf8") as f:
w = csv.writer(f)
w.writerow(["paso", "estado", "segundos"])
w.writerows(bit)
if r.returncode != 0:
sys.stderr.write(f"\n[{nombre}] fallo:\n{r.stderr[-3000:]}\n")
sys.exit(1)
@@ -0,0 +1,443 @@
import matplotlib
matplotlib.use("Agg")
import os, json, itertools
import numpy as np
import pandas as pd
INPUT_CSV = "./dataframe_recodificado.csv"
OUTPUT_CSV = "./dataframe_depurado.csv"
OUT_DIR = "./depuracion_resultados_1"
EXCLUDE = ["Outcome_cat"] # nunca se analiza ni se toca
AUTO_EXTRA = ["Age_group", "Tumor_group"] # se incluyen si existen
EXTRA_COLS = []
PROTEGIDAS = [] # p. ej. ["Estadio_cat"]: nunca se eliminan
PREFERIR = ["Tumor_group", "Age_group"] # en un empate/duplicada, gana la que esté aquí (son las discretizaciones propias del proyecto)
DROP_RAW_SOURCES = True # también quita la columna cruda de SEER de la variable eliminada (evita que el balanceo la reintroduzca por palabra clave)
MAPEO_JSON = "./mapeo_columnas_recodificadas.json"
UNKNOWN_LABEL = "Desconocido"
DUP_U = 0.90 # paso A
U_REDUND = 0.80 # paso B
GVIF_DROP = 2.24 # paso C: GVIF^(1/2gl) (equivale a VIF 5)
MAX_ITER_GVIF = 20
os.makedirs(OUT_DIR, exist_ok=True)
df_raw = pd.read_csv(INPUT_CSV, dtype=str)
cols = [c for c in df_raw.columns if c.endswith("_cat") and c not in EXCLUDE]
for c in AUTO_EXTRA + EXTRA_COLS:
if c in df_raw.columns and c not in cols and c not in EXCLUDE:
cols.append(c)
df = df_raw[cols].fillna(UNKNOWN_LABEL)
cols = [c for c in cols if df[c].nunique() >= 2]
df = df[cols]
def theil_u_matrix(d, columnas):
U = pd.DataFrame(np.nan, index=columnas, columns=columnas)
H = {}
for c in columnas:
p = d[c].value_counts(normalize=True).values
H[c] = float(-(p * np.log(p)).sum())
for a, b in itertools.combinations(columnas, 2):
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
pxy /= pxy.sum()
nz = pxy[pxy > 0]
hxy = float(-(nz * np.log(nz)).sum())
mi = H[a] + H[b] - hxy
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
return U
def design(d, columnas):
bloques = {}
for c in columnas:
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
ind = ind.drop(columns=ind.sum().idxmax())
ind = ind.loc[:, ind.std() > 0]
if ind.shape[1] > 0:
bloques[c] = ind
X = pd.concat(bloques.values(), axis=1)
return X, bloques
def gvif_table(d, columnas):
X, bloques = design(d, columnas)
R = np.corrcoef(X.values, rowvar=False)
pos = {n: i for i, n in enumerate(X.columns)}
s, ld = np.linalg.slogdet(R)
if not (s > 0 and np.isfinite(ld) and ld > -30):
cand = []
for c, b in bloques.items():
otros = [x for x in X.columns if x not in b.columns]
A = np.column_stack([X[otros].values, np.ones(len(X))])
for x in b.columns:
y = X[x].values
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
if r2 >= 0.9999:
cand.append((b.shape[1], c)); break
return None, sorted(cand)
filas = []
for c, b in bloques.items():
idx = [pos[n] for n in b.columns]
resto = [i for i in range(len(pos)) if i not in set(idx)]
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
s2, l2 = np.linalg.slogdet(R[np.ix_(resto, resto)]) if resto else (1, 0.0)
gv = float(np.exp(l1 + l2 - ld))
filas.append({"variable": c, "gl": len(idx), "GVIF": gv,
"GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
return pd.DataFrame(filas).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
import itertools, json, datetime
from scipy.cluster.hierarchy import linkage, cophenet, fcluster
from scipy.spatial.distance import squareform
# ===================== PARÁMETROS DE LA CALIBRACIÓN (independientes de los datos) =====================
UMBRALES_AUTO = False # True: aplica las sugerencias a DUP_U / U_REDUND / GVIF_DROP / clustering
N_MAX_CAL = 300_000 # si hay más filas, se calibra sobre una submuestra reproducible
NULL_PERM = 100 # permutaciones para el piso por azar de U
K_AZAR = 5 # U_REDUND debe ser >= K_AZAR x (U máximo por azar)
U_CONVENCIONAL = 0.80 # valor de respaldo si los datos no permiten calibrar
U_GAP_DESDE = 0.70 # se buscan brechas cuyo borde superior sea >= este U
U_GAP_MIN_BRECHA = 0.10 # brecha mínima para considerarla "natural"
U_RANGO_PLAUSIBLE = (0.60, 0.95) # límites del umbral sugerido
VIF_CORTE = 5 # 5 (R2=0.80) o 10 (R2=0.90)
R_GRANDE = 0.5 # Cohen (1988): |phi| 0.1 pequeño, 0.3 mediano, 0.5 grande
MIN_N_CAT = 30 # categorías con menos pacientes se excluyen del clustering
MAX_CAT_CLUSTER = 400 # tope de columnas (categorías) en la matriz del clustering
CLUSTER_DIST = "signed" # "signed": d = 1-r | "abs": d = 1-|r|
SEMILLA_CAL = 0
GVIF_GRID = sorted({round(1.5, 2), 2.0, round(float(np.sqrt(VIF_CORTE)), 2), 2.5, round(float(np.sqrt(10)), 2)})
CLUSTER_METODO = "average" # se recalcula abajo
PAR_R_MIN = R_GRANDE
CLUSTER_CORTE = round(1 - R_GRANDE, 2)
rng_cal = np.random.default_rng(SEMILLA_CAL)
REPORTE = {"fecha": datetime.datetime.now().isoformat(timespec="seconds"), "advertencias": [], "parametros": {
"NULL_PERM": NULL_PERM, "K_AZAR": K_AZAR, "U_CONVENCIONAL": U_CONVENCIONAL, "U_GAP_DESDE": U_GAP_DESDE,
"U_GAP_MIN_BRECHA": U_GAP_MIN_BRECHA, "U_RANGO_PLAUSIBLE": list(U_RANGO_PLAUSIBLE), "VIF_CORTE": VIF_CORTE,
"R_GRANDE": R_GRANDE, "MIN_N_CAT": MIN_N_CAT, "SEMILLA": SEMILLA_CAL}}
def _aviso(msg):
REPORTE["advertencias"].append(msg)
# ===================== preparación y diagnóstico de los datos =====================
if len(cols) < 2:
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
df_cal = df if len(df) <= N_MAX_CAL else df.sample(N_MAX_CAL, random_state=SEMILLA_CAL)
CODES = {c: pd.factorize(df_cal[c])[0] for c in cols}
KCAT = {c: int(df_cal[c].nunique()) for c in cols}
n_cal = len(df_cal)
celdas_med = float(np.median([n_cal / (KCAT[a] * KCAT[b]) for a, b in itertools.combinations(cols, 2)]))
if n_cal < 1000: _aviso(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
if celdas_med < 5: _aviso(f"tablas de contingencia dispersas (mediana {celdas_med:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
if len(cols) < 4: _aviso("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
if max(KCAT.values()) > 30: _aviso(f"variable con {max(KCAT.values())} categorías: considera agruparlas antes de depurar.")
REPORTE["datos"] = {"n": int(len(df)), "n_calibracion": int(n_cal), "n_variables": len(cols), "categorias_por_variable": KCAT,
"pacientes_por_celda_mediana": celdas_med}
# ===================== 1. U de Theil: pares, exactitud y piso por azar =====================
def _h(p):
p = p[p > 0]; return float(-(p * np.log(p)).sum())
def info_par(cx, cy, kx, ky):
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
n = j.sum(); px = j.sum(1) / n; py = j.sum(0) / n
hxy = _h((j / n).ravel()); hx = _h(px); hy = _h(py)
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
base_x=px.max(), base_y=py.max())
filas, techo = [], []
for a, b in itertools.combinations(cols, 2):
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
mi_null = np.array([info_par(CODES[a], rng_cal.permutation(CODES[b]), KCAT[a], KCAT[b])["mi"] for _ in range(NULL_PERM)])
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]), (b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
u = ip["mi"] / hx if hx > 0 else np.nan
u_null = mi_null.max() / hx if hx > 0 else np.nan
filas.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null, "exactitud_X_desde_Y": acc, "exactitud_base_X": base})
techo.append(u_null)
PARES_U = pd.DataFrame(filas).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
PARES_U["brecha_al_siguiente"] = PARES_U["U(X|Y)"] - PARES_U["U(X|Y)"].shift(-1)
techo_azar = float(np.nanmax(techo))
PARES_U.to_csv(f"{OUT_DIR}/calibracion_U_pares.csv", index=False)
# ---- regla de sugerencia para U_REDUND (piso por azar + brecha natural + respaldo convencional)
def sugerir_U(pares_u, techo_azar, gap_desde=None, gap_min=None):
gap_desde = U_GAP_DESDE if gap_desde is None else gap_desde
gap_min = U_GAP_MIN_BRECHA if gap_min is None else gap_min
v = np.sort(pares_u["U(X|Y)"].dropna().round(4).unique())[::-1]
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
mejor = None
for i in range(len(v) - 1):
if v[i] >= gap_desde and (mejor is None or v[i] - v[i + 1] > mejor[0]):
mejor = (v[i] - v[i + 1], v[i], v[i + 1])
if mejor is not None and mejor[0] >= gap_min:
mid = float(np.clip((mejor[1] + mejor[2]) / 2, *U_RANGO_PLAUSIBLE))
out.update(metodo="brecha natural", U=mid, brecha=round(float(mejor[0]), 3), borde_sup=round(float(mejor[1]), 3),
borde_inf=round(float(mejor[2]), 3), confianza="alta")
else:
out["U"] = U_CONVENCIONAL
out["motivo"] = ("no hay pares con U >= %.2f" % gap_desde) if mejor is None else ("la mayor brecha (%.3f) < %.2f" % (mejor[0], gap_min))
piso = K_AZAR * techo_azar
if out["U"] < piso:
out["U"] = float(min(piso, 0.99)); out["metodo"] += " + piso por azar"; out["confianza"] = "revisar"
out["U"] = round(float(out["U"]), 2)
return out
SUG_U = sugerir_U(PARES_U, techo_azar)
# ===================== 2. Sensibilidad: ¿qué variables se eliminan al mover cada umbral, y con qué regla? =====================
_pct_unk = {c: float((df_cal[c] == UNKNOWN_LABEL).mean()) for c in cols}
_ncat = {c: int(df_cal[c].nunique()) for c in cols}
_orden = {c: i for i, c in enumerate(cols)}
def _perdedora(a, b):
if a in PROTEGIDAS and b in PROTEGIDAS: return None
if a in PROTEGIDAS: return b, a
if b in PROTEGIDAS: return a, b
if a in PREFERIR and b not in PREFERIR: return b, a
if b in PREFERIR and a not in PREFERIR: return a, b
k = lambda c: (_pct_unk[c], _ncat[c], _orden[c])
return (a, b) if k(a) > k(b) else (b, a)
_cacheU, _cacheG = {}, {}
def _Umat(cols_t):
if cols_t not in _cacheU:
M_ = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
for a, b in itertools.combinations(cols_t, 2):
ip = info_par(CODES[a], CODES[b], KCAT[a], KCAT[b])
M_.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
M_.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
_cacheU[cols_t] = M_
return _cacheU[cols_t]
def _Gtab(cols_t):
if cols_t not in _cacheG: _cacheG[cols_t] = gvif_table(df_cal, list(cols_t))
return _cacheG[cols_t]
_chk = theil_u_matrix(df_cal, cols); _fast = _Umat(tuple(cols))
assert np.allclose(_chk.values.astype(float), _fast.loc[cols, cols].values.astype(float), equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
def depurar_con(dup_u, u_redund, gvif_drop):
# Reproduce A, B y C con otros umbrales. Devuelve ({variable: paso}, activas).
activas, out = list(cols), {}
U = _Umat(tuple(activas)) # A
for a, b in itertools.combinations(list(activas), 2):
if a not in activas or b not in activas: continue
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
r = _perdedora(a, b)
if r: activas.remove(r[0]); out[r[0]] = "A"
U = _Umat(tuple(activas)); cand = [] # B
for x in activas:
for y in activas:
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund: cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
activas.remove(x); out[x] = "B"
for _ in range(MAX_ITER_GVIF): # C
if len(activas) < 3: break
tabla, exactas = _Gtab(tuple(activas))
if tabla is None:
ex = [c for _, c in exactas if c not in PROTEGIDAS]
if not ex: break
activas.remove(ex[0]); out[ex[0]] = "C"; continue
cd = tabla[(tabla["GVIF_ajustado"] >= gvif_drop) & (~tabla["variable"].isin(PROTEGIDAS))]
if cd.empty: break
v_ = cd.iloc[0]["variable"]; activas.remove(v_); out[v_] = "C"
return out, activas
def _etq(d): return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
base_out, base_act = depurar_con(DUP_U, U_REDUND, GVIF_DROP)
# decisión del umbral sugerido y su estabilidad
dup_sug = round(min(max(0.90, SUG_U["U"] + 0.05), 0.99), 2)
out_sug, _ = depurar_con(dup_sug, SUG_U["U"], GVIF_DROP)
mismo = set(out_sug) == set(base_out)
SUG_U["misma_decision_que_config"] = bool(mismo)
if not mismo and SUG_U["confianza"] == "alta": SUG_U["confianza"] = "revisar"
if not mismo: _aviso("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
# ---- D) Barrido de los parámetros de la REGLA de brecha: U_GAP_DESDE y U_GAP_MIN_BRECHA son CONVENCIONES (no salen de los datos).
# Se verifica si cambiarlos modifica el umbral sugerido o las variables que se eliminan.
GAP_DESDE_GRID = [0.50, 0.60, 0.70, 0.80, 0.90]
GAP_MIN_GRID = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30]
_filas_gap = []
for gd in GAP_DESDE_GRID:
for gm in GAP_MIN_GRID:
s_ = sugerir_U(PARES_U, techo_azar, gd, gm)
dup_s = round(min(max(0.90, s_["U"] + 0.05), 0.99), 2)
o_, _ = depurar_con(dup_s, s_["U"], GVIF_DROP)
_filas_gap.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": s_["U"], "método": s_["metodo"],
"misma decisión": set(o_) == set(base_out), "elimina [regla]": _etq(o_)})
SENS_GAP = pd.DataFrame(_filas_gap)
_frac = float(SENS_GAP["misma decisión"].mean())
_umin, _umax = float(SENS_GAP["U_REDUND sugerido"].min()), float(SENS_GAP["U_REDUND sugerido"].max())
_dist = SENS_GAP[~SENS_GAP["misma decisión"]]
if len(_dist):
_aviso(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(_dist)} de {len(SENS_GAP)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
REPORTE["sensibilidad_regla_brecha"] = {"grilla_U_GAP_DESDE": GAP_DESDE_GRID, "grilla_U_GAP_MIN_BRECHA": GAP_MIN_GRID,
"proporcion_misma_decision": _frac, "U_sugerido_min": _umin, "U_sugerido_max": _umax}
# ===================== 3. GVIF: equivalencia con VIF y R^2, y margen =====================
GVIF_DROP_SUG = round(float(np.sqrt(VIF_CORTE)), 2)
eq = pd.DataFrame({"GVIF ajustado (umbral)": GVIF_GRID})
eq["VIF = GVIF_aj^2"] = eq["GVIF ajustado (umbral)"] ** 2
eq["R^2 de la variable con las demás"] = 1 - 1 / eq["VIF = GVIF_aj^2"]
tab_k, _ = _Gtab(tuple(base_act))
margen_g = None
if tab_k is not None and len(tab_k):
tab_k = tab_k.copy(); tab_k["margen_al_umbral"] = GVIF_DROP - tab_k["GVIF_ajustado"]
margen_g = float(tab_k["margen_al_umbral"].min())
if margen_g < 0.15: _aviso("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
# ===================== 4. Clustering: método de enlace (cofenética) y corte (Cohen) =====================
def _cat_matrix(d, columnas, min_n):
X = pd.get_dummies(d[columnas], prefix_sep="=", dtype=np.float32); s = X.sum()
X = X.loc[:, (s >= min_n) & (s <= len(X) - min_n)]
if X.shape[1] > MAX_CAT_CLUSTER:
X = X[X.sum().sort_values(ascending=False).index[:MAX_CAT_CLUSTER]]
_aviso(f"demasiadas categorías para el clustering: se usan las {MAX_CAT_CLUSTER} más frecuentes.")
return X
min_n_eff = MIN_N_CAT
_X = _cat_matrix(df_cal, cols, min_n_eff)
if _X.shape[1] < 6:
min_n_eff = max(5, int(0.005 * n_cal)); _X = _cat_matrix(df_cal, cols, min_n_eff)
_aviso(f"muy pocas categorías con >= {MIN_N_CAT} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
CLUSTER_OK = _X.shape[1] >= 4
metodo_sug, coph, CLUSTER_CORTE_SIL, tab_corte = CLUSTER_METODO, {}, None, pd.DataFrame()
if not CLUSTER_OK:
_aviso("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
else:
_nom = list(_X.columns); _var = np.array([c.split("=", 1)[0] for c in _nom])
_V = _X.values.astype(np.float32); _V -= _V.mean(0); _cov = _V.T @ _V; _sd = np.sqrt(np.diag(_cov)); _R = (_cov / np.outer(_sd, _sd)).astype(float)
_D = 1 - _R if CLUSTER_DIST == "signed" else 1 - np.abs(_R)
_D = np.clip((_D + _D.T) / 2, 0, None); np.fill_diagonal(_D, 0); _cond = squareform(_D, checks=False)
for m_ in ["single", "complete", "average", "weighted"]:
coph[m_] = float(cophenet(linkage(_cond, method=m_), _cond)[0])
metodo_sug = max(coph, key=coph.get)
try:
from sklearn.metrics import silhouette_score; _hay_sil = True
except Exception:
_hay_sil = False
Zc = linkage(_cond, method=metodo_sug); filas = []
for t_ in np.round(np.arange(0.30, 1.01, 0.05), 2):
lab = fcluster(Zc, t=float(t_), criterion="distance"); ng = len(set(lab))
multi = sum(1 for g in set(lab) if len(set(_var[lab == g])) >= 2)
sil = float(silhouette_score(_D, lab, metric="precomputed")) if _hay_sil and 2 <= ng <= len(lab) - 1 else np.nan
filas.append({"corte (dist.)": t_, "r medio exigido": round(1 - t_, 2), "n_grupos": ng, "grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
tab_corte = pd.DataFrame(filas)
if tab_corte["silueta"].notna().any(): CLUSTER_CORTE_SIL = float(tab_corte.loc[tab_corte["silueta"].idxmax(), "corte (dist.)"])
tab_corte.to_csv(f"{OUT_DIR}/calibracion_clustering_corte.csv", index=False)
# ===================== 5. Resumen, decisión y reporte JSON =====================
resumen = pd.DataFrame([
{"parámetro": "U_REDUND", "configurado": U_REDUND, "sugerido": SUG_U["U"], "criterio": SUG_U["metodo"], "confianza": SUG_U["confianza"]},
{"parámetro": "DUP_U", "configurado": DUP_U, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)", "confianza": SUG_U["confianza"]},
{"parámetro": "GVIF_DROP", "configurado": GVIF_DROP, "sugerido": GVIF_DROP_SUG, "criterio": f"sqrt(VIF {VIF_CORTE}) (R2={1-1/VIF_CORTE:.2f})",
"confianza": "alta" if (margen_g is None or margen_g >= 0.15) else "revisar"},
{"parámetro": "CLUSTER_METODO", "configurado": CLUSTER_METODO, "sugerido": metodo_sug, "criterio": "máx. correlación cofenética", "confianza": "alta" if CLUSTER_OK else "revisar"},
{"parámetro": "CLUSTER_CORTE", "configurado": CLUSTER_CORTE, "sugerido": round(1 - R_GRANDE, 2), "criterio": f"Cohen: r medio >= {R_GRANDE}", "confianza": "alta"},
{"parámetro": "PAR_R_MIN", "configurado": PAR_R_MIN, "sugerido": R_GRANDE, "criterio": "Cohen: efecto grande", "confianza": "alta"}])
if UMBRALES_AUTO:
U_REDUND, DUP_U, GVIF_DROP, CLUSTER_METODO = SUG_U["U"], dup_sug, GVIF_DROP_SUG, metodo_sug
CLUSTER_CORTE = round(1 - R_GRANDE, 2); PAR_R_MIN = R_GRANDE
def _jsonable(o):
if isinstance(o, (np.floating,)): return float(o)
if isinstance(o, (np.integer,)): return int(o)
if isinstance(o, (set, tuple)): return list(o)
return str(o)
REPORTE.update({"piso_azar_U": techo_azar, "sugerencia_U": SUG_U, "resumen": resumen.to_dict(orient="records"),
"umbrales_en_uso": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP, "CLUSTER_METODO": CLUSTER_METODO,
"CLUSTER_CORTE": CLUSTER_CORTE, "PAR_R_MIN": PAR_R_MIN, "AUTO": bool(UMBRALES_AUTO)},
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
with open(f"{OUT_DIR}/calibracion_umbrales.json", "w", encoding="utf-8") as fh:
json.dump(REPORTE, fh, ensure_ascii=False, indent=2, default=_jsonable)
eliminadas = [] # (variable, paso, motivo, a_favor_de)
activas = list(cols)
pct_unk = {c: float((df[c] == UNKNOWN_LABEL).mean()) for c in cols}
ncat = {c: int(df[c].nunique()) for c in cols}
orden = {c: i for i, c in enumerate(cols)}
def quitar(var, paso, motivo, favor):
activas.remove(var)
eliminadas.append({"variable": var, "paso": paso, "motivo": motivo, "a_favor_de": favor})
def elegir_perdedora(a, b):
if a in PROTEGIDAS and b in PROTEGIDAS: return None
if a in PROTEGIDAS: return b, a
if b in PROTEGIDAS: return a, b
if a in PREFERIR and b not in PREFERIR: return b, a
if b in PREFERIR and a not in PREFERIR: return a, b
clave = lambda c: (pct_unk[c], ncat[c], orden[c])
return (a, b) if clave(a) > clave(b) else (b, a)
# ---------------- PASO A: duplicadas ----------------
U = theil_u_matrix(df, activas)
for a, b in itertools.combinations(list(activas), 2):
if a not in activas or b not in activas: continue
if U.loc[a, b] >= DUP_U and U.loc[b, a] >= DUP_U:
r = elegir_perdedora(a, b)
if r:
quitar(r[0], "A duplicada", f"U({a}|{b})={U.loc[a,b]:.2f}, U({b}|{a})={U.loc[b,a]:.2f}", r[1])
# ---------------- PASO B: derivadas ----------------
U = theil_u_matrix(df, activas)
cand = []
for x in activas:
for y in activas:
if x != y and U.loc[x, y] >= U_REDUND and U.loc[y, x] < U_REDUND:
cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in activas and y in activas and x not in PROTEGIDAS and x not in PREFERIR:
quitar(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y,x]:.2f}", y)
for it in range(MAX_ITER_GVIF):
if len(activas) < 3: break
tabla, exactas = gvif_table(df, activas)
if tabla is None:
exactas = [c for _, c in exactas if c not in PROTEGIDAS]
if not exactas: break
quitar(exactas[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
continue
cand = tabla[(tabla["GVIF_ajustado"] >= GVIF_DROP) & (~tabla["variable"].isin(PROTEGIDAS))]
if cand.empty: break
v = cand.iloc[0]
quitar(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {GVIF_DROP}", "(el resto)")
conservadas = list(activas)
rep = pd.DataFrame(eliminadas, columns=["variable", "paso", "motivo", "a_favor_de"])
# ---------------- Verificación final ----------------
tabla, exactas = gvif_table(df, conservadas)
U_fin = theil_u_matrix(df, conservadas)
# ---------------- Guardar ----------------
a_quitar = [c for c in rep["variable"]]
crudas = []
if DROP_RAW_SOURCES and os.path.exists(MAPEO_JSON):
with open(MAPEO_JSON, encoding="utf-8") as f:
_map = json.load(f)
crudas = [_map[v] for v in a_quitar if v in _map and _map[v] in df_raw.columns]
out = df_raw.drop(columns=a_quitar + crudas)
out.to_csv(OUTPUT_CSV, index=False)
rep.to_csv(f"{OUT_DIR}/variables_eliminadas.csv", index=False)
with open(f"{OUT_DIR}/variables_conservadas.json", "w", encoding="utf-8") as f:
json.dump({"entrada": INPUT_CSV, "conservadas": conservadas, "eliminadas": a_quitar, "crudas_eliminadas": crudas,
"umbrales": {"DUP_U": DUP_U, "U_REDUND": U_REDUND, "GVIF_DROP": GVIF_DROP}},
f, ensure_ascii=False, indent=2)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
import numpy as np
import pandas as pd
RANDOM_STATE = 42
rng = np.random.default_rng(RANDOM_STATE)
CSV_PATH = "./dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
df = pd.read_csv(CSV_PATH, dtype=str)
n = len(df)
N_BOOTSTRAP = 200
bootstrap_indices = np.empty((N_BOOTSTRAP, n), dtype=np.int64)
for b in range(N_BOOTSTRAP):
bootstrap_indices[b] = rng.integers(0, n, size=n)
import json
np.save("./bootstrap_indices.npy", bootstrap_indices)
metadata = {
"source_csv": CSV_PATH,
"n_filas": int(n),
"n_bootstrap": int(N_BOOTSTRAP),
"random_state": int(RANDOM_STATE),
}
with open("./bootstrap_metadata.json", "w") as f:
json.dump(metadata, f, indent=2)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,828 @@
import matplotlib
matplotlib.use("Agg")
import os
os.environ.setdefault("TQDM_DISABLE", "1")
import sys, subprocess, time, re, warnings
import numpy as np, pandas as pd
warnings.filterwarnings("ignore")
try:
from tqdm.auto import tqdm
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "tqdm"]); from tqdm.auto import tqdm
INPUT_CSV = "./dataframe_depurado.csv" # salida de 03 (cohorte completa; debe traer meses de seguimiento y estado vital)
EDAD_MODO = "categorizada" # cómo entra la edad a la LR: "categorizada" | "continua" (lineal) | "continua_cuadratica". La edad numérica es el punto medio del grupo de 5 años de SEER.
# (la HBN solo usa variables discretas: con la edad continua, la HBN no incluye la edad)
INCLUIR_EDAD = True # agrega la edad agrupada (Edad_cat) a las covariables si no hay ya una columna de edad categórica
CORTES_EDAD = [45, 60, 75] # cortes de la edad agrupada
HBN_PADRES_FIJOS = ["Estadio", "Tipo_histologico", "Tratamiento_quirurgico", "Quimioterapia", "Radioterapia"] # padres del desenlace en la HBN ya aprendida en 06 (se buscan por palabra clave entre las covariables); None = aprenderlos aquí (BDeu)
HBN_EDAD_PADRE = True # True: agrega la edad agrupada como padre del desenlace en la HBN (decisión de experto / conocimiento previo; el algoritmo de 06 no la eligió). False: solo los padres de HBN_PADRES_FIJOS
HBN_PADRES = "fijos" # "fijos": los padres de la HBN se aprenden una vez y se mantienen en el bootstrap (IC más estable) | "reaprender": se buscan de nuevo en cada réplica
COVARIABLES = None # None = todas las columnas que terminan en "_cat" (menos el desenlace); o una lista explícita de columnas
HORIZONTES = [6, 12, 18] # meses en los que se muestran los puntos de LR y HBN
CENSURA_MODELOS = "riesgo" # "riesgo": un modelo por intervalo (0-6, 6-12, 12-18) que usa todo el seguimiento | "ipcw": pondera | "excluir": descarta las vivas con seguimiento < h (definición del proyecto)
COMBINAR = True # un solo indicador LR+HBN (combinación por intervalo con pesos de apilamiento fuera de muestra); solo con CENSURA_MODELOS = "riesgo"
MOSTRAR_INDIVIDUALES = False # además del combinado, dibuja LR y HBN por separado
STACK_FOLDS = 5 # pliegues de la validación cruzada que decide los pesos
STACK_SHRINK = 20 # contracción hacia 50/50 con pocas muertes: lambda = STACK_SHRINK / (STACK_SHRINK + muertes del intervalo)
DIAGNOSTICO = True # imprime los puntos con los tres tratamientos de la censura (sin bootstrap) junto a Kaplan-Meier
B_BOOT = 100 # réplicas bootstrap para el IC de LR y HBN (200 = más fino, más lento)
SEMILLA = 42
HBN_ESS = 1000 # tamaño de muestra equivalente del prior BDeu
HBN_MAX_PADRES = 5 # máximo de padres del desenlace en la HBN
K_IDENT = "clasico" # k fijo del Weibull fraccional: "clasico" = k del Weibull clásico | o un número
CURVAS = "ajustada" # "ajustada": KM y Weibull fraccional estandarizados por las mismas covariables que LR/HBN (Cox) | "cruda": KM y Weibull sin ajustar
PASO_AJUSTE = 3 # meses por intervalo de la curva ajustada (más corto = más fina y más lenta)
MOSTRAR_KM_CRUDO = True # dibuja además, en gris fino, el KM sin ajustar como referencia
YLIM_PRINCIPAL = None # p. ej. (0.94, 1.0) para hacer zoom en el eje y de la figura principal; None = automático
INSET_ZOOM = False # recuadro con zoom a los primeros INSET_MESES meses (donde están los puntos de LR y HBN)
INSET_MESES = 18 # tope del panel de zoom (último horizonte)
TOPE_MESES = 24 # el análisis de las curvas llega solo hasta este mes: el seguimiento se trunca ahí (muertes posteriores y seguimiento restante cuentan como vivas/censuradas en TOPE_MESES). None = sin tope
MESES_MAX = TOPE_MESES or 60 # hasta dónde se dibuja el eje de tiempo
SUF = "" if EDAD_MODO == "categorizada" else f"_edad_{EDAD_MODO}" # sufijo de los archivos de salida para no sobrescribir
TAG = "" if EDAD_MODO == "categorizada" else f" [edad {EDAD_MODO.replace('_', ' ')}]"
SALIDA_PNG = f"./curva_supervivencia_KM_KS_LR_HBN{SUF}.png"
SALIDA_CSV = f"./curva_supervivencia_puntos_LR_HBN{SUF}.csv"
df = pd.read_csv(INPUT_CSV, dtype=str)
def find_col(df, keywords, exclude=()):
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords) and not any(e in d for e in exclude):
return col
return None
COL_MESES = find_col(df, ["survival months"])
COL_VITAL = find_col(df, ["vital status"])
assert COL_MESES and COL_VITAL, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
df["meses"] = pd.to_numeric(df[COL_MESES], errors="coerce")
df["evento"] = df[COL_VITAL].astype(str).str.lower().str.contains("dead")
df = df[df["meses"].notna()].reset_index(drop=True)
df["meses_int"] = df["meses"].astype(int)
if TOPE_MESES: # truncar el seguimiento en TOPE_MESES: solo cuentan las muertes ocurridas antes del tope
df["evento"] = df["evento"] & (df["meses_int"] < TOPE_MESES)
df["meses_int"] = np.minimum(df["meses_int"], TOPE_MESES)
def _edad(v):
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
_hay_edad_cat = any(re.search(r"(^|_)age(_|$)|edad", c.lower()) for c in df.columns if c.endswith("_cat")) # (no confundir con "Stage")
if INCLUIR_EDAD and not _hay_edad_cat:
if df["_edad"].notna().mean() > 0.5:
_b = [-np.inf] + list(CORTES_EDAD) + [np.inf]
_l = [f"<{CORTES_EDAD[0]}"] + [f"{a}-{b-1}" for a, b in zip(CORTES_EDAD[:-1], CORTES_EDAD[1:])] + [f"≥{CORTES_EDAD[-1]}"]
df["Edad_cat"] = pd.cut(df["_edad"], _b, right=False, labels=_l).astype(object)
if COVARIABLES is None:
COVARIABLES = [c for c in df.columns if c.endswith("_cat") and "outcome" not in c.lower()]
elif INCLUIR_EDAD and "Edad_cat" in df.columns and "Edad_cat" not in COVARIABLES:
COVARIABLES = list(COVARIABLES) + ["Edad_cat"]
def _edad_media(v):
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
if not n_: return np.nan
return n_[0] + 2.5 if "+" in str(v) else float(np.mean(n_[:2]))
_ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
df["_edad_z"] = ((_ed - _ed.mean()) / _ed.std()).fillna(0.0); df["_edad_cuad"] = df["_edad_z"] ** 2
COLS_NUM = []
if EDAD_MODO != "categorizada":
assert _ed.notna().mean() > 0.5, "EDAD_MODO continua: no se pudo leer la edad numérica de la columna de edad."
COVARIABLES = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())] # la edad categórica sale de las covariables
COLS_NUM = ["_edad_z"] + (["_edad_cuad"] if EDAD_MODO == "continua_cuadratica" else [])
def construir_X_dum():
M_ = pd.get_dummies(df[COVARIABLES], drop_first=True).values.astype(np.float32) # referencia = primera categoría
return np.column_stack([M_, df[COLS_NUM].values.astype(np.float32)]) if COLS_NUM else M_
assert COVARIABLES, "No hay covariables: define COVARIABLES con los nombres de columna."
for c in COVARIABLES:
df[c] = df[c].fillna("NA").astype(str).str.strip()
import sys, subprocess, numpy as np
try:
import mpmath as mp
except ImportError: # el kernel de Jupyter no lo trae: se instala solo
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
import mpmath as mp
from functools import lru_cache
from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
for i in range(N - 1):
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
return tuple(c)
def _log_terms(az, rho, m, l, N):
i = np.arange(N - 1)
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
n = np.arange(N)
with np.errstate(divide="ignore"):
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
return lt
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
az = np.abs(z)
N = 400
lt = _log_terms(az, rho, m, l, N)
lmax, llast = lt.max(axis=1), lt[:, -1]
zero = az == 0
out[zero] = 1.0
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
if okf.any():
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
terms[:, 0] = 1.0
out[okf] = terms.sum(axis=1)
rest = np.where(~zero & ~okf)[0]
if rest.size:
with np.errstate(over="ignore"):
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
est = np.maximum(est, lmax[rest])
use = rest[est <= logmax_cap]
if use.size:
est_u = est[est <= logmax_cap]
dps = 30 + int(est_u.max() / 2.3) + 10
zmax = float(az[use].max())
with np.errstate(over="ignore"):
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
N2 = max(N2, 60)
while True:
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
mp.mp.dps = dps
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
if last < tol or N2 >= nmax:
break
N2 *= 2
if last < tol:
cr = list(c)[::-1]
for j in use:
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
return out
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full_like(t, np.nan)
m = s/beta + 1; l = s/beta
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
with np.errstate(divide="ignore", invalid="ignore"):
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
z = np.where(t > 0, z, 0.0)
res = np.ones_like(t)
pos = t > 0
if pos.any():
res[pos] = kilbas_saigo(z[pos], beta, m, l)
return np.clip(res, 0.0, 1.0)
def S_weibull(t, k, lam):
t = np.asarray(t, float)
return np.exp(-(t/lam)**k)
import time
import numpy as np
from scipy.optimize import minimize
def tabla_eventos(meses, evento):
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
T = int(meses.max()) + 2
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
return d, c
def _nll_from_S(Sfun, d, c):
T = len(d)
grid = np.arange(0, T + 1, dtype=float)
Sg = Sfun(grid)
mid = Sfun(np.arange(T) + 0.5)
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
return 1e12 # región inválida / no calculable
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def ajustar_weibull(d, c):
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50., 200., 1000.):
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
if best is None or r.fun < best.fun: best = r
k, lam = np.exp(best.x)
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
S=lambda t: S_weibull(t, k, lam))
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
amin = max(0.0, 1.0 - k_fijo) + 1e-6
def unpack(p):
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
T_max = float(len(d))
t_fin = time.time() + max_seg
agotado = [False]
def f(p):
if time.time() > t_fin:
agotado[0] = True
return 1e12
a, b, lam = unpack(p)
# penaliza regiones degeneradas (|z| enorme en el último mes -> serie costosa e inestable)
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
return 1e12
try:
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
except Exception:
return 1e12
lams = [lam_ref] if lam_ref else []
lams += [100., 500.]
best = None
inicios = []
if lam_ref: # primero el punto que reproduce el Weibull clásico (alpha=1, beta~1): como el clásico es un caso particular, el fraccional nunca queda peor
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
for l0 in lams:
for a0 in (0.3, 1.0):
for b0 in (0.5, 0.9):
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
for p0 in inicios:
if time.time() > t_fin and best is not None: break
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
if best is None or r.fun < best.fun: best = r
a, b, lam = unpack(best.x)
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
S=lambda t: S_ks(t, k_fijo, a, b, lam))
def km_curva(meses_int, evento, T):
d, c = tabla_eventos(meses_int, evento)
L = max(len(d), T + 1)
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
with np.errstate(divide="ignore", invalid="ignore"):
se = np.sqrt(V) / np.abs(np.log(S))
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
return S, lo, hi
T_KM = max(MESES_MAX, max(HORIZONTES))
S_km, lo_km, hi_km = km_curva(df["meses_int"].values, df["evento"].values, T_KM)
d_t, c_t = tabla_eventos(df["meses_int"].values, df["evento"].values)
w_fit = ajustar_weibull(d_t, c_t)
k_f = w_fit["k"] if K_IDENT == "clasico" else float(K_IDENT)
ks_fit = ajustar_ks(d_t, c_t, k_fijo=k_f, lam_ref=w_fit["lam"])
from sklearn.linear_model import LogisticRegression
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
X_dum = construir_X_dum()
def curva_ajustada(idx, T, paso=PASO_AJUSTE):
m, e = MESES_V[idx], EV_V[idx]
bordes = list(range(0, T + 1, paso))
if bordes[-1] < T: bordes.append(T)
S_i = np.ones(len(idx)); S_b = [1.0]
for a, b in zip(bordes[:-1], bordes[1:]):
sel = np.where(m >= a)[0]
y = np.where(e[sel] & (m[sel] < b), 0, 1); w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
if y.min() == y.max():
S_i = S_i * y.mean()
else:
lr = LogisticRegression(C=10.0, max_iter=300).fit(X_dum[idx][sel], y, sample_weight=w)
S_i = S_i * lr.predict_proba(X_dum[idx])[:, 1]
S_b.append(S_i.mean())
S_b = np.minimum.accumulate(np.array(S_b))
S = np.interp(np.arange(T + 1), bordes, np.log(np.maximum(S_b, 1e-12)))
return np.exp(S)
S_aj = curva_ajustada(np.arange(len(df)), T_KM)
def ajustar_a_curva(S, N_eq):
d = np.maximum(N_eq * (S[:-1] - S[1:]), 0.0); T = len(d)
d = np.concatenate([d, [0.0, 0.0]]); c = np.zeros(T + 2); c[T] = N_eq * S[-1]
w = ajustar_weibull(d, c)
ks = ajustar_ks(d, c, k_fijo=(w["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w["lam"])
return w, ks
if CURVAS == "ajustada":
S_base = S_aj; lo_base = hi_base = None
_, ks_plot = ajustar_a_curva(S_aj, len(df))
else:
S_base, lo_base, hi_base, ks_plot = S_km, lo_km, hi_km, ks_fit
from scipy.special import gammaln
from sklearn.linear_model import LogisticRegression
def pesos_y(meses, evento, h, modo):
m = np.asarray(meses, int); e = np.asarray(evento, bool)
conocido = e | (m >= h)
y = (m >= h).astype(int)
w = np.ones(len(m))
if modo == "ipcw":
T = int(m.max()) + 2
cen = np.bincount(m[~e], minlength=T); mu = np.bincount(m, minlength=T)
nr = len(m) - np.concatenate([[0], np.cumsum(mu)[:-1]])
G = np.concatenate([[1.0], np.cumprod(1 - cen / np.maximum(nr, 1))]) # G[t] = P(no censurada antes del mes t)
G = np.clip(G, 0.05, 1.0)
w = 1.0 / G[np.minimum(m, h)]
return conocido, y, w
# Matriz de covariables: codificación entera por covariable y dummies para la LR
X_int = np.column_stack([pd.factorize(df[c])[0] for c in COVARIABLES]).astype(int)
niv = X_int.max(axis=0) + 1
X_dum = construir_X_dum()
def bdeu(codigo, y, w, q, ess):
n = np.bincount(codigo * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
nj = n.sum(1); aj = ess / q; ajk = aj / 2
return float(np.sum(gammaln(aj) - gammaln(aj + nj) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)))
def buscar_padres(X, niv, y, w, ess=HBN_ESS, max_padres=HBN_MAX_PADRES):
padres, cod, q = [], np.zeros(len(y), int), 1
mejor = bdeu(cod, y, w, q, ess)
while len(padres) < max_padres:
cand = None
for j in range(X.shape[1]):
if j in padres or q * niv[j] > 200_000: continue
c2 = cod * niv[j] + X[:, j]; s = bdeu(c2, y, w, q * niv[j], ess)
if s > mejor + 1e-9 and (cand is None or s > cand[0]): cand = (s, j, c2, q * niv[j])
if cand is None: break
mejor, j, cod, q = cand; padres.append(j)
return padres
PADRES_FIJOS_IDX = None
if HBN_PADRES_FIJOS:
PADRES_FIJOS_IDX = []
_kws = list(HBN_PADRES_FIJOS) + (["Edad"] if HBN_EDAD_PADRE and not any(re.search(r"(^|_)age(_|$)|edad", k.lower()) for k in HBN_PADRES_FIJOS) else [])
for kw in _kws:
hit = [j for j, c in enumerate(COVARIABLES) if kw.lower() in c.lower()]
assert hit, f"HBN_PADRES_FIJOS: no hay una covariable que contenga '{kw}' en {COVARIABLES}"
PADRES_FIJOS_IDX.append(hit[0])
def ajustar_hbn(X, niv, y, w, ess=HBN_ESS, pad=None):
if pad is None and PADRES_FIJOS_IDX is not None: pad = PADRES_FIJOS_IDX
pad = buscar_padres(X, niv, y, w, ess) if pad is None else list(pad)
q = int(np.prod([niv[j] for j in pad])) if pad else 1
cod = np.zeros(len(y), int)
for j in pad: cod = cod * niv[j] + X[:, j]
n = np.bincount(cod * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj = ess / q
pbar = (n[:, 1].sum() + 0.5) / (n.sum() + 1) # prior centrado en la supervivencia marginal (evita sesgar hacia 0.5)
return pad, (n[:, 1] + aj * pbar) / (n.sum(1) + aj) # P(Y=1 | padres), suavizada hacia la marginal
def predecir_hbn(modelo, X, niv):
pad, cpt = modelo
cod = np.zeros(len(X), int)
for j in pad: cod = cod * niv[j] + X[:, j]
return cpt[cod]
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
MESES_V, EV_V = df["meses_int"].values, df["evento"].values
def pred_h(idx, h, modo, pad=None):
m, e = MESES_V[idx], EV_V[idx]
kn, y, w = pesos_y(m, e, h, modo)
sel = np.where(kn)[0]
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(X_dum[idx][sel], y[sel], sample_weight=w[sel])
mod = ajustar_hbn(X_int[idx][sel], niv, y[sel], w[sel], pad=pad)
return lr.predict_proba(X_dum[idx])[:, 1], predecir_hbn(mod, X_int[idx], niv), list(mod[0])
BORDES = [0] + list(HORIZONTES)
def pred_riesgo_int(idx, padres=None, test=None):
test = idx if test is None else test
m, e = MESES_V[idx], EV_V[idx]
P_lr, P_hb, pads = [], [], []
for i_, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
sel = np.where(m >= a)[0] # llegan vivas al inicio del intervalo
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = sobrevive el intervalo
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censura dentro del intervalo: medio riesgo
lr = LogisticRegression(C=1e6, max_iter=500).fit(X_dum[idx][sel], y, sample_weight=w)
mod = ajustar_hbn(X_int[idx][sel], niv, y, w, pad=None if padres is None else padres[i_])
P_lr.append(lr.predict_proba(X_dum[test])[:, 1]); P_hb.append(predecir_hbn(mod, X_int[test], niv)); pads.append(list(mod[0]))
return np.column_stack(P_lr), np.column_stack(P_hb), pads
def pred_riesgo(idx, padres=None):
Pl, Ph, pads = pred_riesgo_int(idx, padres)
return np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1), pads
def predecir_pacientes(idx, modo, padres=None):
if modo == "riesgo":
return pred_riesgo(idx, padres)
r = [pred_h(idx, h, modo, None if padres is None else padres[i_]) for i_, h in enumerate(HORIZONTES)]
return np.column_stack([x[0] for x in r]), np.column_stack([x[1] for x in r]), [x[2] for x in r]
def estimar(idx, modo, padres=None):
P_lr, P_hb, pads = predecir_pacientes(idx, modo, padres)
return P_lr.mean(axis=0), P_hb.mean(axis=0), pads
from scipy.optimize import minimize_scalar
ESTILO_MOD = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
N = len(df); todas = np.arange(N)
COMB_ACTIVO = bool(COMBINAR) and CENSURA_MODELOS == "riesgo"
MODS_PLOT = (["LR", "HBN", "COMB"] if MOSTRAR_INDIVIDUALES else ["COMB"]) if COMB_ACTIVO else ["LR", "HBN"]
# ---- Robustez fuera de muestra: predicciones por pliegues (cada paciente se predice con modelos que no la vieron)
if COMB_ACTIVO:
_fold = np.random.default_rng(SEMILLA + 7).permutation(N) % STACK_FOLDS
OOF_lr = np.zeros((N, len(HORIZONTES))); OOF_hb = np.zeros_like(OOF_lr)
for k in range(STACK_FOLDS):
te = np.where(_fold == k)[0]; tr = np.where(_fold != k)[0]
Pl_, Ph_, _ = pred_riesgo_int(tr, None, te); OOF_lr[te] = Pl_; OOF_hb[te] = Ph_
def pesos_apilados(mask, shrink=STACK_SHRINK):
filas_ = []
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
idx_ = np.where(mask & (MESES_V >= a))[0]
e_, m_ = EV_V[idx_], MESES_V[idx_]
y = np.where(e_ & (m_ < b), 0, 1); wt = np.where((~e_) & (m_ < b), 0.5, 1.0)
p1 = np.clip(OOF_lr[idx_, j], 1e-9, 1 - 1e-9); p2 = np.clip(OOF_hb[idx_, j], 1e-9, 1 - 1e-9)
muertes = int((y == 0).sum())
if len(idx_) == 0:
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=0, muertes=0, w_LR=0.5, w_LR_sin_contraer=0.5, dLL_LR_menos_HBN=0.0, z=0.0, decision="mezcla")); continue
def nll(w_):
p = np.clip(w_ * p1 + (1 - w_) * p2, 1e-9, 1 - 1e-9)
return -np.sum(wt * (y * np.log(p) + (1 - y) * np.log1p(-p)))
w_star = float(minimize_scalar(nll, bounds=(0, 1), method="bounded").x)
lam = shrink / (shrink + muertes); w_fin = (1 - lam) * w_star + lam * 0.5
d = wt * (y * (np.log(p1) - np.log(p2)) + (1 - y) * (np.log1p(-p1) - np.log1p(-p2))) # log-score LR - HBN por paciente
z = d.sum() / (np.sqrt(len(d)) * d.std(ddof=1)) if len(d) > 2 and d.std(ddof=1) > 0 else 0.0
dec = "solo LR" if w_fin >= 0.95 else "solo HBN" if w_fin <= 0.05 else "mezcla"
filas_.append(dict(intervalo=f"{a}-{b}", n_riesgo=len(idx_), muertes=muertes, w_LR=w_fin, w_LR_sin_contraer=w_star,
dLL_LR_menos_HBN=float(d.sum()), z=float(z), decision=dec))
return pd.DataFrame(filas_)
def estimar4(idx, padres, W):
Pl, Ph, pads_ = pred_riesgo_int(idx, padres)
Sc = np.cumprod(W[None, :] * Pl + (1 - W[None, :]) * Ph, axis=1)
return np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), Sc.mean(0), pads_
rng = np.random.default_rng(SEMILLA)
if COMB_ACTIVO:
TAB_W_ALL = pesos_apilados(np.ones(N, bool)); W_ALL = TAB_W_ALL["w_LR"].values
p_lr, p_hbn, p_cmb, pads = estimar4(todas, None, W_ALL)
else:
p_lr, p_hbn, pads = estimar(todas, CENSURA_MODELOS); p_cmb = None
PADRES_REF = pads if HBN_PADRES == "fijos" else None # padres de la HBN aprendidos en la cohorte completa
if DIAGNOSTICO: # mismos puntos con los otros tratamientos de la censura (sin bootstrap), para ver cuánto depende el resultado de él
diag = {"KM crudo": [S_km[h] for h in HORIZONTES], "KM ajustada": [S_aj[h] for h in HORIZONTES]}
for modo in ("riesgo", "ipcw", "excluir"):
r = estimar(todas, modo); diag[f"LR ({modo})"] = r[0]; diag[f"HBN ({modo})"] = r[1]
boots = []
for b in tqdm(range(B_BOOT), desc="Bootstrap"):
idx_b = rng.integers(0, N, N)
if COMB_ACTIVO:
r = estimar4(idx_b, PADRES_REF, W_ALL); boots.append(np.concatenate([r[0], r[1], r[2]]))
else:
r = estimar(idx_b, CENSURA_MODELOS, PADRES_REF); boots.append(np.concatenate([r[0], r[1]]))
SERIES = [("LR", p_lr), ("HBN", p_hbn)] + ([("COMB", p_cmb)] if COMB_ACTIVO else [])
nh = len(HORIZONTES)
boots = np.array(boots) if B_BOOT > 0 else np.full((1, len(SERIES) * nh), np.nan)
ic = np.nanpercentile(boots, [2.5, 97.5], axis=0)
filas = []
for j, (nom, vals_) in enumerate(SERIES):
for i, h in enumerate(HORIZONTES):
filas.append(dict(modelo=nom, meses=h, S=vals_[i], IC_inf=ic[0, j * nh + i], IC_sup=ic[1, j * nh + i]))
tabla = pd.DataFrame(filas)
tabla["KM_crudo"] = [S_km[h] for h in tabla["meses"]]
tabla["KM_ajustada"] = [S_aj[h] for h in tabla["meses"]]
tabla.to_csv(SALIDA_CSV, index=False)
if COMB_ACTIVO: TAB_W_ALL.to_csv(f"./pesos_combinacion_cohorte{SUF}.csv", index=False)
import matplotlib.pyplot as plt
tt = np.arange(0, MESES_MAX + 1)
tc = np.linspace(0, MESES_MAX, 600)
if INSET_ZOOM:
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.6), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
fig, ax = plt.subplots(figsize=(9.5, 5.6))
xx = np.arange(T_KM + 1)
if CURVAS == "ajustada":
if MOSTRAR_KM_CRUDO: ax.step(xx, S_km, where="post", color="#9aa5b1", lw=1.0, ls=":", label="Kaplan-Meier crudo (referencia)")
ax.step(xx, S_aj, where="post", color="#3d4852", lw=1.8, label="Kaplan-Meier ajustada por covariables")
lbl_ks = "Weibull fraccional (ajustado a la curva ajustada)"
else:
ax.fill_between(xx, lo_km, hi_km, step="post", color="#9aa5b1", alpha=.35, lw=0, label="Kaplan-Meier (IC 95 % Greenwood)")
ax.step(xx, S_km, where="post", color="#3d4852", lw=1.6, label="Kaplan-Meier")
lbl_ks = "Weibull fraccional (Kilbas-Saigo)"
ax.plot(tc, ks_plot["S"](tc), color="#d1495b", lw=2.4, label=lbl_ks)
for nom in MODS_PLOT:
col, mk, lb = ESTILO_MOD[nom]
s = tabla[tabla["modelo"] == nom]
ax.errorbar(s["meses"], s["S"], yerr=[np.clip(s["S"] - s["IC_inf"], 0, None), np.clip(s["IC_sup"] - s["S"], 0, None)], fmt=mk, color=col, ms=9 if nom == "COMB" else 8,
capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
tabla_p = tabla[tabla["modelo"].isin(MODS_PLOT)]
ax.set_xlim(0, MESES_MAX + (0.8 if TOPE_MESES else 0)); ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)")
vals = np.concatenate([S_base[:MESES_MAX + 1], tabla_p["IC_inf"].values, [ks_plot["S"](np.array([float(MESES_MAX)]))[0]]])
ax.set_ylim(max(0.0, np.nanmin(vals) - 0.03), 1.005)
if YLIM_PRINCIPAL: ax.set_ylim(*YLIM_PRINCIPAL)
ax.set_xticks(range(0, MESES_MAX + 1, 3 if TOPE_MESES else 6)); ax.grid(alpha=.25)
if INSET_ZOOM:
xi = np.arange(INSET_MESES + 1)
axi.step(xi, S_aj[:INSET_MESES + 1] if CURVAS == "ajustada" else S_km[:INSET_MESES + 1], where="post", color="#3d4852", lw=1.4)
if CURVAS == "ajustada" and MOSTRAR_KM_CRUDO: axi.step(xi, S_km[:INSET_MESES + 1], where="post", color="#9aa5b1", lw=1.0, ls=":")
tci = np.linspace(0, INSET_MESES, 200); axi.plot(tci, ks_plot["S"](tci), color="#d1495b", lw=2)
for nom in MODS_PLOT:
col, mk, lb = ESTILO_MOD[nom]; s_ = tabla[tabla["modelo"] == nom]
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
_v = np.concatenate([S_base[:INSET_MESES + 1], tabla_p["IC_inf"].values, tabla_p["IC_sup"].values]); _m = (_v.max() - _v.min()) * .08
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(_v.min() - _m, min(1.002, _v.max() + _m)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
ax.set_title(f"Supervivencia de la cohorte completa (n = {N:,}){TAG}"); ax.legend(loc="lower left", frameon=False)
for s in ("top", "right"): ax.spines[s].set_visible(False)
fig.tight_layout(); fig.savefig(SALIDA_PNG, dpi=200)
import matplotlib.pyplot as _p; _p.close("all")
MESES_EXTRAP = TOPE_MESES or 120 # hasta dónde se extrapola (punteado) fuera del seguimiento observado
YLIM_SUB = {} # zoom manual en y por subgrupo, p. ej. {"Estadio I": (0.97, 1.0)}; los que no estén usan el automático
XLIM_SUB = None # p. ej. (0, 72) para no mostrar la extrapolación; None = (0, MESES_EXTRAP)
MIN_EVENTOS_SUB = 5 # mínimo de fallecimientos para ajustar un subgrupo
B_BOOT_SUB = B_BOOT # réplicas bootstrap de los modelos en los subgrupos (es otro bucle completo; baja el número si tarda mucho)
COL_EST = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
COL_SUB = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
_cands = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
COL_EDAD = sorted(_cands, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0] if _cands else None
def _edad(v):
m_ = re.search(r"\d+", str(v)); return float(m_.group()) if m_ else np.nan
def _estadio(v):
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS": return 0
for p_, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(p_): return val
return np.nan
df["_edad"] = df[COL_EDAD].map(_edad) if COL_EDAD else np.nan
df["_estadio"] = df[COL_EST].map(_estadio) if COL_EST else np.nan
COL_CX = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
df["_her2neg"] = df[COL_SUB].astype(str).str.contains("HER2-", regex=False) if COL_SUB else False # sin HER2+ (HER2 negativo)
df["_triple_neg"] = df[COL_SUB].astype(str).str.contains("HR-/HER2-", regex=False) if COL_SUB else False # HR− / HER2−
df["_cons"] = df[COL_CX].astype(str).str.lower().str.contains("conserv") if COL_CX else False # cirugía conservadora
df["_her2pos"] = df[COL_SUB].astype(str).str.contains("HER2+", regex=False) if COL_SUB else False
# Edita aquí los subgrupos (nombre -> máscara booleana sobre df)
SUBGRUPOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": lambda d: d["_her2pos"] & (d["_edad"] >= 60) & d["_estadio"].isin([3, 4]),
"HER2+ · <60 años · estadio 0–II (Bajo)": lambda d: d["_her2pos"] & (d["_edad"] < 60) & d["_estadio"].isin([0, 1, 2]),
"Estadio IV": lambda d: d["_estadio"] == 4,
"Estadio I": lambda d: d["_estadio"] == 1,
"≥ 75 años": lambda d: d["_edad"] >= 75,
"< 45 años": lambda d: d["_edad"] < 45,
# --- combinaciones adicionales ---
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] < 45) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"HER2− · estadio 0–II · cirugía conservadora": lambda d: d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"HER2+ · estadio 0–II · cirugía conservadora": lambda d: d["_her2pos"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
"Jóvenes (<45) · estadio 0–II": lambda d: (d["_edad"] < 45) & d["_estadio"].isin([0, 1, 2]),
"Jóvenes (<45) · HER2−": lambda d: (d["_edad"] < 45) & d["_her2neg"],
"Triple negativo (HR−/HER2−) · estadio 0–II": lambda d: d["_triple_neg"] & d["_estadio"].isin([0, 1, 2]),
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": lambda d: (d["_edad"] >= 65) & d["_her2neg"] & d["_estadio"].isin([0, 1, 2]) & d["_cons"],
}
MASCARAS = {n: np.asarray(f(df).fillna(False), dtype=bool) for n, f in SUBGRUPOS.items()}
# LR, HBN y su combinación en los subgrupos: se ajustan en la cohorte completa y se promedian las predicciones dentro de cada subgrupo
rng_sub = np.random.default_rng(SEMILLA + 1)
MODELOS_SUB = ["LR", "HBN"] + (["COMB"] if COMB_ACTIVO else [])
nm = len(MODELOS_SUB)
if COMB_ACTIVO: # pesos de la combinación por subgrupo (robustez fuera de muestra dentro del subgrupo)
W_SUB = {n: pesos_apilados(mk) for n, mk in MASCARAS.items()}
else:
W_SUB = {}
def medias_subgrupo(idx, padres):
out = {}
if COMB_ACTIVO:
Pl, Ph, _ = pred_riesgo_int(idx, padres)
Sl, Sh = np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1)
for n, mk in MASCARAS.items():
mm = mk[idx]
if not mm.any(): out[n] = np.full(nm * nh, np.nan); continue
W_ = W_SUB[n]["w_LR"].values[None, :]
Sc = np.cumprod(W_ * Pl[mm] + (1 - W_) * Ph[mm], axis=1)
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0), Sc.mean(0)])
else:
Sl, Sh, _ = predecir_pacientes(idx, CENSURA_MODELOS, padres)
for n, mk in MASCARAS.items():
mm = mk[idx]
out[n] = np.concatenate([Sl[mm].mean(0), Sh[mm].mean(0)]) if mm.any() else np.full(nm * nh, np.nan)
return out
PT_SUB = medias_subgrupo(todas, None)
_boots = {n: [] for n in MASCARAS}
for b in tqdm(range(B_BOOT_SUB), desc="Bootstrap subgrupos"):
r_ = medias_subgrupo(rng_sub.integers(0, N, N), PADRES_REF)
for n in MASCARAS: _boots[n].append(r_[n])
MOD_SUB = {}
for n, mk in MASCARAS.items():
B_ = np.array(_boots[n]) if B_BOOT_SUB > 0 else np.full((1, nm * nh), np.nan)
ic_ = np.nanpercentile(B_, [2.5, 97.5], axis=0) if mk.any() else np.full((2, nm * nh), np.nan)
pt = PT_SUB[n]
MOD_SUB[n] = pd.DataFrame([dict(modelo=nom, meses=h, S=pt[j * nh + i], IC_inf=ic_[0, j * nh + i], IC_sup=ic_[1, j * nh + i])
for j, nom in enumerate(MODELOS_SUB) for i, h in enumerate(HORIZONTES)])
import matplotlib.pyplot as plt
def aic(nll, k): return 2 * k + 2 * nll
RES_SUB = {}
def ajustar_subgrupo(nombre):
mk = MASCARAS[nombre]; sub = df[mk]
n_, ev_ = len(sub), int(sub["evento"].sum())
if n_ == 0 or ev_ < MIN_EVENTOS_SUB:
return None
d_, c_ = tabla_eventos(sub["meses_int"].values, sub["evento"].values)
w_ = ajustar_weibull(d_, c_)
ks_ = ajustar_ks(d_, c_, k_fijo=(w_["k"] if K_IDENT == "clasico" else float(K_IDENT)), lam_ref=w_["lam"], max_seg=180)
Tm = int(sub["meses_int"].max())
Sk, lok, hik = km_curva(sub["meses_int"].values, sub["evento"].values, Tm)
grid = np.arange(0, Tm + 1, dtype=float)
fila = {"subgrupo": nombre, "n": n_, "fallecidos": ev_, "seguim. máx. (m)": Tm, "k Weibull": w_["k"],
"k KS / α / β": f"{ks_['k']:.2f} / {ks_['alpha']:.2f} / {ks_['beta']:.2f}",
"AIC Weibull": aic(w_["nll"], 2), "AIC fraccional": aic(ks_["nll"], 3), "ΔAIC (W − F)": aic(w_["nll"], 2) - aic(ks_["nll"], 3),
"máx|KM−Weibull|": np.abs(w_["S"](grid) - Sk).max(), "máx|KM−fracc.|": np.abs(ks_["S"](grid) - Sk).max()}
return dict(nombre=nombre, n=n_, ev=ev_, w=w_, ks=ks_, Sk=Sk, lok=lok, hik=hik, Tm=Tm, fila=fila, modelos=MOD_SUB[nombre], pesos=W_SUB.get(nombre))
def graficar_subgrupo(a):
if a is None: return
mp = a["modelos"][a["modelos"]["modelo"].isin(MODS_PLOT)]
Tm = a["Tm"]; tt = np.arange(Tm + 1)
if INSET_ZOOM:
fig, (ax, axi) = plt.subplots(1, 2, figsize=(15, 5.2), gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
fig, ax = plt.subplots(figsize=(9, 5.2))
ax.fill_between(tt, a["lok"], a["hik"], step="post", color="#9aa5b1", alpha=.3, lw=0)
ax.step(tt, a["Sk"], where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
for key, col, ls, lb in [("w", "#1f77b4", "-", "Weibull"), ("ks", "#d1495b", "--", "Weibull fraccional")]:
t_in = np.linspace(0, Tm, 300); t_ex = np.linspace(Tm, MESES_EXTRAP, 200)
ax.plot(t_in, a[key]["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
ax.plot(t_ex, a[key]["S"](t_ex), color=col, lw=1.4, ls=":")
if not TOPE_MESES: ax.axvline(Tm, color="#888", lw=.8, ls=":")
for nom in MODS_PLOT:
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
ax.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk_, color=col, ms=9 if nom == "COMB" else 8, capsize=4, lw=1.8, mec="white", mew=1, label=f"{lb} (IC 95 % bootstrap)", zorder=5)
x0, x1 = XLIM_SUB if XLIM_SUB else (0, MESES_EXTRAP + (0.8 if TOPE_MESES else 0))
xs = np.linspace(x0, x1, 400)
vis = [a["w"]["S"](xs), a["ks"]["S"](xs), a["Sk"][int(x0):int(min(x1, Tm)) + 1], a["lok"][int(x0):int(min(x1, Tm)) + 1],
mp["IC_inf"].values, mp["IC_sup"].values]
v = np.concatenate([np.ravel(u) for u in vis]); v = v[np.isfinite(v)]
mg = (v.max() - v.min()) * .06
ylim = YLIM_SUB.get(a["nombre"], (max(0, v.min() - mg), min(1.005, v.max() + mg)))
ax.set_xlim(x0, x1); ax.set_ylim(*ylim)
if INSET_ZOOM:
xi = np.arange(INSET_MESES + 1)
axi.fill_between(xi, a["lok"][:INSET_MESES + 1], a["hik"][:INSET_MESES + 1], step="post", color="#9aa5b1", alpha=.3, lw=0)
axi.step(xi, a["Sk"][:INSET_MESES + 1], where="post", color="#222", lw=1.3)
tci = np.linspace(0, INSET_MESES, 200)
axi.plot(tci, a["w"]["S"](tci), color="#1f77b4", lw=2); axi.plot(tci, a["ks"]["S"](tci), color="#d1495b", lw=2, ls="--")
for nom in MODS_PLOT:
col, mk_, lb = ESTILO_MOD[nom]; s_ = mp[mp["modelo"] == nom]
axi.errorbar(s_["meses"], s_["S"], yerr=[np.clip(s_["S"] - s_["IC_inf"], 0, None), np.clip(s_["IC_sup"] - s_["S"], 0, None)],
fmt=mk_, color=col, ms=6, capsize=3, lw=1.5, mec="white", mew=.8, zorder=5)
vi = np.concatenate([a["Sk"][:INSET_MESES + 1], a["lok"][:INSET_MESES + 1], mp["IC_inf"].values, mp["IC_sup"].values, a["w"]["S"](tci)])
vi = vi[np.isfinite(vi)]; mi = (vi.max() - vi.min()) * .08
axi.set_xlim(0, INSET_MESES + 0.8); axi.set_ylim(vi.min() - mi, min(1.002, vi.max() + mi)); axi.set_xticks(range(0, INSET_MESES + 1, 6))
axi.grid(alpha=.25); axi.set_title(f"Zoom: primeros {INSET_MESES} meses", fontsize=10); axi.set_xlabel("Meses desde el diagnóstico"); axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, INSET_MESES, color="#888", alpha=.08, lw=0)
ax.set_xlabel("Meses desde el diagnóstico"); ax.set_ylabel("Supervivencia S(t)"); ax.grid(alpha=.25)
ax.set_title(f"{a['nombre']}{TAG}\nn={a['n']:,}, fallecidos={a['ev']:,}", fontsize=11)
ax.legend(frameon=False, loc="lower left", fontsize=9)
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
fig.tight_layout()
nom_arch = re.sub(r"[^A-Za-z0-9]+", "_", a["nombre"].replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt").replace("ñ", "n").replace("–", "-")).strip("_")
fig.savefig(f"./subgrupo_{nom_arch}{SUF}.png", dpi=170)
import matplotlib.pyplot as _p; _p.close("all")
RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'] = ajustar_subgrupo('HER2+ · ≥60 años · estadio III–IV (Alto)'); graficar_subgrupo(RES_SUB['HER2+ · ≥60 años · estadio III–IV (Alto)'])
RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'] = ajustar_subgrupo('HER2+ · <60 años · estadio 0–II (Bajo)'); graficar_subgrupo(RES_SUB['HER2+ · <60 años · estadio 0–II (Bajo)'])
RES_SUB['Estadio IV'] = ajustar_subgrupo('Estadio IV'); graficar_subgrupo(RES_SUB['Estadio IV'])
RES_SUB['Estadio I'] = ajustar_subgrupo('Estadio I'); graficar_subgrupo(RES_SUB['Estadio I'])
RES_SUB['≥ 75 años'] = ajustar_subgrupo('≥ 75 años'); graficar_subgrupo(RES_SUB['≥ 75 años'])
RES_SUB['< 45 años'] = ajustar_subgrupo('< 45 años'); graficar_subgrupo(RES_SUB['< 45 años'])
RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora'])
RES_SUB['HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2− · estadio 0–II · cirugía conservadora'])
RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('HER2+ · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['HER2+ · estadio 0–II · cirugía conservadora'])
RES_SUB['Jóvenes (<45) · estadio 0–II'] = ajustar_subgrupo('Jóvenes (<45) · estadio 0–II'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · estadio 0–II'])
RES_SUB['Jóvenes (<45) · HER2−'] = ajustar_subgrupo('Jóvenes (<45) · HER2−'); graficar_subgrupo(RES_SUB['Jóvenes (<45) · HER2−'])
RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'] = ajustar_subgrupo('Triple negativo (HR−/HER2−) · estadio 0–II'); graficar_subgrupo(RES_SUB['Triple negativo (HR−/HER2−) · estadio 0–II'])
RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'] = ajustar_subgrupo('≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'); graficar_subgrupo(RES_SUB['≥ 65 años · HER2− · estadio 0–II · cirugía conservadora'])
tabla_sub = pd.DataFrame([a["fila"] for a in RES_SUB.values() if a is not None])
tabla_sub.to_csv(f"./subgrupos_KM_Weibull_fraccional{SUF}.csv", index=False)
pd.concat([a["modelos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_puntos_LR_HBN{SUF}.csv", index=False)
if COMB_ACTIVO:
pd.concat([a["pesos"].assign(subgrupo=a["nombre"]) for a in RES_SUB.values() if a is not None]).to_csv(f"./subgrupos_pesos_combinacion{SUF}.csv", index=False)
# Prueba: edad como variable numérica (punto medio de su grupo de 5 años) en la LR, frente a la edad categorizada
def _edad_media(v):
n_ = [float(x) for x in re.findall(r"\d+", str(v))]
if not n_: return np.nan
if "+" in str(v): return n_[0] + 2.5
return float(np.mean(n_[:2]))
ed = df[COL_EDAD].map(_edad_media).astype(float) if COL_EDAD else pd.Series(np.nan, index=df.index)
assert ed.notna().mean() > 0.5, "No se pudo leer la edad numérica"
z = ((ed - ed.mean()) / ed.std()).fillna(0.0).values # edad estandarizada (faltantes -> media)
cols_sin_edad = [c for c in COVARIABLES if not re.search(r"(^|_)age(_|$)|edad", c.lower())]
Xb = pd.get_dummies(df[cols_sin_edad], drop_first=True).values.astype(np.float32)
if "Edad_cat" in df.columns:
Xcat = np.column_stack([Xb, pd.get_dummies(df[["Edad_cat"]], drop_first=True).values.astype(np.float32)])
else:
Xcat = X_dum if EDAD_MODO == "categorizada" else None
VARIANTES = {
"sin edad": Xb,
"edad categorizada": Xcat,
"edad continua": np.column_stack([Xb, z]).astype(np.float32),
"edad continua + cuadrática": np.column_stack([Xb, z, z ** 2]).astype(np.float32),
}
if Xcat is None: VARIANTES.pop("edad categorizada")
REF_V = "edad categorizada" if "edad categorizada" in VARIANTES else "sin edad"
def lr_int(Xm, idx, test):
P = []
for a, b in zip(BORDES[:-1], BORDES[1:]):
sel = np.where(MESES_V[idx] >= a)[0]
y = np.where(EV_V[idx][sel] & (MESES_V[idx][sel] < b), 0, 1); w = np.where((~EV_V[idx][sel]) & (MESES_V[idx][sel] < b), 0.5, 1.0)
P.append(LogisticRegression(C=1e6, max_iter=500).fit(Xm[idx][sel], y, sample_weight=w).predict_proba(Xm[test])[:, 1])
return np.column_stack(P)
_fold2 = np.random.default_rng(SEMILLA + 11).permutation(N) % STACK_FOLDS
PT, OOF = {}, {}
for nom, Xm in VARIANTES.items():
PT[nom] = np.cumprod(lr_int(Xm, todas, todas), axis=1) # ajuste en toda la cohorte
O = np.zeros((N, len(HORIZONTES)))
for k in range(STACK_FOLDS):
te = np.where(_fold2 == k)[0]; tr = np.where(_fold2 != k)[0]; O[te] = lr_int(Xm, tr, te)
OOF[nom] = O
def ll_oof(O, mask):
tot = 0.0
for j, (a, b) in enumerate(zip(BORDES[:-1], BORDES[1:])):
i_ = np.where(mask & (MESES_V >= a))[0]
y = np.where(EV_V[i_] & (MESES_V[i_] < b), 0, 1); w = np.where((~EV_V[i_]) & (MESES_V[i_] < b), 0.5, 1.0)
p = np.clip(O[i_, j], 1e-9, 1 - 1e-9); tot += np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
return tot
# 1) Supervivencia media predicha por variante vs Kaplan-Meier, por subgrupo
filas = []
for n_, mk in [("Cohorte completa", np.ones(N, bool))] + list(MASCARAS.items()):
if mk.sum() == 0: continue
Sk_, _, _ = km_curva(MESES_V[mk], EV_V[mk], max(HORIZONTES))
for i, h in enumerate(HORIZONTES):
f_ = {"subgrupo": n_, "meses": h, "KM": Sk_[h]}
for nom in VARIANTES: f_[nom] = PT[nom][mk, i].mean()
filas.append(f_)
T1 = pd.DataFrame(filas)
# 2) Resumen: error vs KM y verosimilitud fuera de muestra
res = []
for nom in VARIANTES:
err = (T1[nom] - T1["KM"]).abs()
ll_c = ll_oof(OOF[nom], np.ones(N, bool)); ll_ref = ll_oof(OOF[REF_V], np.ones(N, bool))
res.append({"variante": nom, "error abs. medio vs KM (todos los subgrupos y horizontes)": err.mean(), "error abs. máx.": err.max(),
"log-verosimilitud fuera de muestra (cohorte)": ll_c, f"Δ vs {REF_V}": ll_c - ll_ref})
T2 = pd.DataFrame(res)
T1.to_csv(f"./prueba_edad_continua_vs_categorizada{SUF}.csv", index=False); T2.to_csv(f"./prueba_edad_resumen{SUF}.csv", index=False)
@@ -0,0 +1,228 @@
import json
import numpy as np
import pandas as pd
import statsmodels.api as sm
# Definicion de factores de riesgo a partir de cuatro criterios:
# c1 OR multivariable en la poblacion natural (IC 95% sin cruzar 1 y p ajustado por Benjamini-Hochberg < ALFA)
# c2 estabilidad en bootstrap: la variable entra al stepwise de la LR en al menos FREQ_MIN de las replicas
# c3 la variable esta en la manta de Markov del desenlace en la red bayesiana
# c4 diferencia absoluta de supervivencia a HORIZONTE meses (Kaplan-Meier) frente a la categoria de referencia
# Las variables de tratamiento son una decision clinica: no se clasifican como factores de riesgo
# y no entran al modelo de c1; se reportan aparte en asociaciones_tratamiento.csv.
CSV_NATURAL = "./dataframe_poblacion_natural.csv"
CSV_SELECCION = "./seleccion_bootstrap.csv"
CSV_ARCOS = "./hbn_arcos.csv"
ALFA = 0.05
FREQ_MIN = 0.80
HORIZONTE = 18
TOPE_MESES = 24
TRATAMIENTO = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
CANONICAL_MAP = {
"Age_group": "Edad", "Tumor_group": "Tamano_tumor", "Tamano_tumor_cat": "Tamano_tumor",
"Estadio_cat": "Estadio", "Grado_histologico_cat": "Grado_histologico",
"Subtipo_molecular_cat": "Subtipo_molecular", "Receptor_estrogeno_cat": "Receptor_estrogeno",
"Receptor_progesterona_cat": "Receptor_progesterona", "Metastasis_cat": "Metastasis",
"Localizacion_mama_cat": "Localizacion_mama", "Lateralidad_cat": "Lateralidad",
"Tipo_histologico_cat": "Tipo_histologico", "Tratamiento_quirurgico_cat": "Tratamiento_quirurgico",
"Radioterapia_cat": "Radioterapia", "Quimioterapia_cat": "Quimioterapia", "Estado_civil_cat": "Estado_civil",
"Ganglios_positivos_cat": "Ganglios_positivos", "Invasion_linfovascular_cat": "Invasion_linfovascular",
"Margenes_cat": "Margenes", "Densidad_BIRADS_cat": "Densidad_BIRADS", "Masa_espiculada_cat": "Masa_espiculada",
"Microcalcificaciones_cat": "Microcalcificaciones", "Multifocalidad_cat": "Multifocalidad",
"BRCA_cat": "BRCA", "HER2_IHQ_cat": "HER2_IHQ",
}
def find_col(df, keywords):
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
nat = pd.read_csv(CSV_NATURAL, dtype=str)
nat = nat[nat["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
col_meses = find_col(nat, ["survival months"])
col_vital = find_col(nat, ["vital status"])
col_race = find_col(nat, ["race"])
datos = pd.DataFrame({v: nat[k].fillna("Desconocido").astype(str) for k, v in CANONICAL_MAP.items() if k in nat.columns})
if col_race is not None and col_race not in CANONICAL_MAP:
datos["Race"] = nat[col_race].fillna("Desconocido").astype(str)
variables = list(datos.columns)
intrinsecas = [v for v in variables if v not in TRATAMIENTO]
tratamiento = [v for v in variables if v in TRATAMIENTO]
muerte = (nat["Outcome_cat"] == "Muerte").astype(int).values
meses = np.minimum(pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).astype(int).values, TOPE_MESES)
evento = nat[col_vital].astype(str).str.lower().str.contains("dead").values & (pd.to_numeric(nat[col_meses], errors="coerce").fillna(0).values < TOPE_MESES)
# ---- c1: OR multivariable (referencia = categoria mas frecuente) ----
def referencia(v):
return datos[v].value_counts().idxmax()
def ajustar_or(vars_modelo):
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
modelo = sm.GLM(muerte, sm.add_constant(X), family=sm.families.Binomial()).fit()
ic = modelo.conf_int()
t = pd.DataFrame({"termino": X.columns, "OR_muerte": np.exp(modelo.params[X.columns].values),
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
"p": modelo.pvalues[X.columns].values})
return t
def variable_de(termino, vars_modelo):
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
def bh(p):
p = np.asarray(p, float)
orden = np.argsort(p)
aj = np.empty_like(p)
m = len(p)
prev = 1.0
for rango, i in zip(range(m, 0, -1), orden[::-1]):
prev = min(prev, p[i] * m / rango)
aj[i] = prev
return aj
tab = ajustar_or(intrinsecas)
tab["variable"] = [variable_de(t, intrinsecas) for t in tab["termino"]]
tab["categoria"] = [t[len(v) + 1:] for t, v in zip(tab["termino"], tab["variable"])]
tab["referencia"] = [referencia(v) for v in tab["variable"]]
tab["p_ajustado_BH"] = bh(tab["p"])
tab["direccion"] = np.where(tab["OR_muerte"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
# ---- c4: diferencia de supervivencia (Kaplan-Meier) frente a la referencia ----
def km_en(m, e, h):
T = int(m.max()) + 2
d = np.bincount(m[e], minlength=T)
c = np.bincount(m[~e], minlength=T)
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def delta_s(v, cat, ref):
a = (datos[v] == cat).values
b = (datos[v] == ref).values
Sa, ea = km_en(meses[a], evento[a], HORIZONTE)
Sb, eb = km_en(meses[b], evento[b], HORIZONTE)
d = Sa - Sb
es = np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S18_categoria": Sa, "S18_referencia": Sb, "delta_S18": d,
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
def tabla_delta(filas):
return pd.DataFrame([delta_s(v, c, r) for v, c, r in filas])
ds = tabla_delta(zip(tab["variable"], tab["categoria"], tab["referencia"]))
tab = pd.concat([tab.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S18"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
# ---- c2: estabilidad en bootstrap ----
freq = pd.Series(np.nan, index=intrinsecas)
try:
sel = pd.read_csv(CSV_SELECCION)
lr = sel[sel["modelo"] == "LR"]
n_rep = (lr["termino"] == "(replica)").sum()
if n_rep > 0:
por_var = lr[lr["termino"] != "(replica)"].groupby("variable")["replica"].nunique()
freq = pd.Series({v: por_var.get(v, 0) / n_rep for v in intrinsecas})
except FileNotFoundError:
n_rep = 0
tab["freq_seleccion_bootstrap"] = tab["variable"].map(freq)
tab["c2_estabilidad"] = (tab["freq_seleccion_bootstrap"] >= FREQ_MIN).astype(object).where(tab["freq_seleccion_bootstrap"].notna(), np.nan)
# ---- c3: manta de Markov del desenlace en la HBN ----
manta = None
try:
arcos = pd.read_csv(CSV_ARCOS)
padres = set(arcos.loc[arcos["destino"] == "outcome", "origen"])
hijos = set(arcos.loc[arcos["origen"] == "outcome", "destino"])
conyuges = set(arcos.loc[arcos["destino"].isin(hijos) & (arcos["origen"] != "outcome"), "origen"])
manta = padres | hijos | conyuges
except FileNotFoundError:
pass
tab["en_manta_markov"] = tab["variable"].map(lambda v: (v in manta) if manta is not None else np.nan)
tab["c3_manta_markov"] = tab["en_manta_markov"].astype(object)
# ---- clasificacion ----
CRITERIOS = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
disponibles = [c for c in CRITERIOS if tab[c].notna().all()]
tab["criterios_cumplidos"] = tab[disponibles].apply(lambda c: c.map(lambda x: x is True or x == True)).sum(axis=1)
tab["criterios_evaluados"] = len(disponibles)
min_robusto = min(3, len(disponibles))
def clasificar(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= min_robusto:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(clasificar, axis=1)
columnas = ["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
"freq_seleccion_bootstrap", "en_manta_markov", "S18_categoria", "S18_referencia", "delta_S18",
"delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "criterios_evaluados", "clasificacion"]
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
tab["_o"] = tab["clasificacion"].map(orden).fillna(5)
tab = tab.sort_values(["_o", "OR_muerte"], ascending=[True, False])[columnas]
tab.round(4).to_csv("./factores_riesgo.csv", index=False)
resumen = tab[tab["clasificacion"] != "no aplica (categoria desconocida)"].groupby("variable").agg(
categorias_robustas=("clasificacion", lambda s: int(s.str.contains("robusto").sum())),
categorias_sugerentes=("clasificacion", lambda s: int(s.str.contains("sugerente").sum())),
freq_seleccion_bootstrap=("freq_seleccion_bootstrap", "first"),
en_manta_markov=("en_manta_markov", "first"),
OR_max=("OR_muerte", "max"), OR_min=("OR_muerte", "min"),
).sort_values(["categorias_robustas", "categorias_sugerentes"], ascending=False)
resumen.round(4).to_csv("./factores_riesgo_resumen_variables.csv")
# ---- tratamiento: asociaciones descriptivas, sin clasificar (decision clinica) ----
if tratamiento:
tr = ajustar_or(intrinsecas + tratamiento)
tr["variable"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
tr = tr[tr["variable"].isin(tratamiento)].copy()
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
tr["referencia"] = [referencia(v) for v in tr["variable"]]
tr["p_ajustado_BH"] = bh(tr["p"])
ds_t = tabla_delta(zip(tr["variable"], tr["categoria"], tr["referencia"]))
tr = pd.concat([tr.reset_index(drop=True), ds_t.reset_index(drop=True)], axis=1)
tr["nota"] = "asociacion ajustada por las demas variables; no implica efecto causal (confusion por indicacion)"
tr[["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
"S18_categoria", "S18_referencia", "delta_S18", "delta_IC95_inf", "delta_IC95_sup", "nota"]].round(4).to_csv(
"./asociaciones_tratamiento.csv", index=False)
with open("./factores_riesgo_criterios.json", "w", encoding="utf8") as f:
json.dump({"alfa": ALFA, "freq_min_bootstrap": FREQ_MIN, "horizonte_meses": HORIZONTE, "tope_meses": TOPE_MESES,
"replicas_bootstrap_validas": int(n_rep), "criterios_evaluados": disponibles,
"variables_tratamiento_excluidas": tratamiento}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,65 @@
"""Ejecuta las etapas del pipeline en orden (cada una en su propio proceso).
Uso (desde la carpeta que contiene los scripts y los datos):
python ejecutar_pipeline.py # todas las etapas, saltando las que estan vigentes
python ejecutar_pipeline.py --solo 05 # solo esa etapa
python ejecutar_pipeline.py --desde 02 # desde esa etapa en adelante
python ejecutar_pipeline.py --forzar 02 04 # corre esas aunque esten vigentes
python ejecutar_pipeline.py --todo # corre todas, sin saltar ninguna
Una etapa se salta solo si sus salidas existen y son mas recientes que su script y que sus entradas.
Escribe bitacora_pipeline.csv (etapa, estado, segundos). Sin mensajes en pantalla salvo errores.
"""
import argparse, csv, subprocess, sys, time
from pathlib import Path
BALANCEADO = "dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
ETAPAS = [
dict(id="01", script="01_depuracion.py", requiere=["dataframe_recodificado.csv", "mapeo_columnas_recodificadas.json"],
produce=["dataframe_depurado.csv"]),
dict(id="02", script="02_balanceo_categorizacion.py", requiere=["dataframe_depurado.csv"],
produce=[BALANCEADO, "propuestas_categorizacion.csv", "dataframe_poblacion_natural.csv"]),
dict(id="03", script="03_bootstrapping.py", requiere=[BALANCEADO], produce=["bootstrap_indices.npy", "bootstrap_metadata.json"]),
dict(id="04", script="04_modelado.py",
requiere=[BALANCEADO, "propuestas_categorizacion.csv", "bootstrap_indices.npy", "bootstrap_metadata.json", "dataframe_poblacion_natural.csv"],
produce=[]), # sin salida unica verificable: siempre se corre
dict(id="05", script="05_curvas_supervivencia.py", requiere=["dataframe_depurado.csv"],
produce=["curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"]),
dict(id="06", script="06_factores_riesgo.py",
requiere=["dataframe_poblacion_natural.csv", "seleccion_bootstrap.csv", "hbn_arcos.csv"],
produce=["factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"]),
]
def mtime(p): return Path(p).stat().st_mtime
def vigente(e):
if not e["produce"] or not all(Path(p).exists() and Path(p).stat().st_size > 0 for p in e["produce"]): return False
ref = max([mtime(e["script"])] + [mtime(p) for p in e["requiere"] if Path(p).exists()])
return min(mtime(p) for p in e["produce"]) >= ref
def guardar(bit):
with open("bitacora_pipeline.csv", "w", newline="", encoding="utf8") as f:
w = csv.writer(f); w.writerow(["etapa", "estado", "segundos"]); w.writerows(bit)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--solo", nargs="+"); ap.add_argument("--desde")
ap.add_argument("--forzar", nargs="+", default=[]); ap.add_argument("--todo", action="store_true")
a = ap.parse_args()
sel = [e for e in ETAPAS if (not a.solo or e["id"] in a.solo) and (not a.desde or e["id"] >= a.desde)]
bit = []; rehacer = False
for e in sel:
faltan = [p for p in e["requiere"] if not Path(p).exists()]
if faltan: sys.exit(f"Etapa {e['id']}: faltan entradas {faltan}")
if not (a.todo or e["id"] in a.forzar or rehacer) and vigente(e):
bit.append((e["id"], "saltada", 0)); continue
t0 = time.time(); r = subprocess.run([sys.executable, e["script"]])
bit.append((e["id"], "ok" if r.returncode == 0 else f"error({r.returncode})", round(time.time() - t0)))
guardar(bit)
if r.returncode != 0: sys.exit(r.returncode)
rehacer = rehacer or bool(e["produce"]) # si una etapa con salidas se rehizo, las siguientes tambien
guardar(bit)
if __name__ == "__main__":
main()
View File
+243
View File
@@ -0,0 +1,243 @@
"""Luis's recurrence analysis of one cohort over its frame (`cohort.recode`): the covariates that survive the
collinearity pruning, the logistic regression and the Bayesian network's outcome parents of each horizon, and the figure
of each clinical scenario (Kaplan-Meier with its Greenwood band, the Weibull and the fractional Weibull, and the
combined estimate at each horizon with its bootstrap interval).
Every number a stage uses is the model's (`modeling`, `calculator` of `model.toml`).
"""
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from pgmpy.estimators import BDeu
from scipy.stats import chi2_contingency
from sklearn.model_selection import train_test_split
from models.cama.seer_survival.fractional_weibull import ajustar_ks, ajustar_weibull, km_curva, tabla_eventos
warnings.filterwarnings("ignore")
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
k = min(table.shape) - 1
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
def prune_covariates(frame: pd.DataFrame, covariates: list[str], treatment: list[str], settings: dict) -> tuple[list, list]:
"""Of each pair of non-treatment covariates with Cramér's V at or above the limit, the one with more unknowns goes."""
unknown = settings["unknown_label"]
kept, dropped = list(covariates), []
candidates = [c for c in covariates if c not in treatment]
pairs = sorted(((cramer_v(frame[a], frame[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]),
reverse=True)
for v, a, b in pairs:
if v < settings["cramer_v_max"]:
break
if a in dropped or b in dropped:
continue
out = a if (frame[a] == unknown).mean() >= (frame[b] == unknown).mean() else b
dropped.append(out)
kept.remove(out)
return kept, dropped
def horizon_cohort(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients who recurred by the horizon or are free beyond it; the rest were censored before it and are left out."""
recurred = (frame["evento"] == 1) & (frame["tiempo_meses"] <= horizon)
free = frame["tiempo_meses"] > horizon
out = frame[recurred | free].reset_index(drop=True)
out["y"] = ((out["evento"] == 1) & (out["tiempo_meses"] <= horizon)).astype(int)
return out
def _encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def _logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def _prefilter(X: pd.DataFrame, y, alpha: float) -> list[str]:
keep = []
for c in X.columns:
fit = _logit(y, X[[c]])
if fit is not None and fit.pvalues[c] < alpha:
keep.append(c)
return keep
def _stepwise(X: pd.DataFrame, y, alpha_in: float, alpha_out: float) -> list[str]:
chosen: list[str] = []
for _ in range(200):
changed = False
best, best_p = None, alpha_in
for c in [c for c in X.columns if c not in chosen]:
fit = _logit(y, X[chosen + [c]])
if fit is not None and fit.pvalues[c] < best_p:
best, best_p = c, fit.pvalues[c]
if best is not None:
chosen.append(best)
changed = True
if chosen:
fit = _logit(y, X[chosen])
if fit is not None:
p = fit.pvalues.drop("const")
if p.max() > alpha_out:
chosen.remove(p.idxmax())
changed = True
if not changed:
break
return chosen
def logistic_terms(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
both = _encode(pd.concat([train, test]), covariates)
X = both.loc[train.index]
X = X.loc[:, X.nunique() > 1]
candidates = _prefilter(X, train["y"], settings["alpha_prefilter"])
return _stepwise(X[candidates], train["y"], settings["alpha_in"], settings["alpha_out"]) if candidates else []
def outcome_parents(frame: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
"""The outcome's parents by greedy BDeu, at most `max_parents`."""
table = frame[covariates].astype(str).copy()
table["outcome"] = frame["y"].astype(int).astype(str)
score = BDeu(table, equivalent_sample_size=settings["bdeu_ess"])
parents, current = [], score.local_score("outcome", [])
while len(parents) < settings["max_parents"]:
best, gain = None, 0
for c in covariates:
if c in parents:
continue
g = score.local_score("outcome", parents + [c]) - current
if g > gain:
best, gain = c, g
if best is None:
break
parents.append(best)
current += gain
return parents
def select_models(frame: pd.DataFrame, covariates: list[str], horizons: list[int], settings: dict) -> dict:
"""The logistic terms and the Bayesian network's outcome parents of each horizon, selected on the 70/30 split."""
models = {}
for horizon in horizons:
cohort = horizon_cohort(frame, horizon)
train_idx, test_idx = train_test_split(cohort.index, test_size=settings["test_share"], random_state=settings["seed"],
stratify=cohort["y"])
train, test = cohort.loc[train_idx], cohort.loc[test_idx]
models[horizon] = {"lr_terms": logistic_terms(train, test, covariates, settings),
"hbn_parents": outcome_parents(train, covariates, settings)}
return models
class Calculator:
"""The combined estimate (mean of the logistic regression and the Bayesian network) of a group of patients, refitting
both on any resample of the cohort with the terms and parents selected for each horizon."""
def __init__(self, frame: pd.DataFrame, covariates: list[str], models: dict, horizons: list[int], ess: int):
self.frame, self.horizons, self.models, self.ess = frame, horizons, models, ess
self.n = len(frame)
self.time = frame["tiempo_meses"].to_numpy()
self.event = frame["evento"].to_numpy()
self.dummies = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
self.levels = {v: int(self.codes[v].max()) + 1 for v in covariates}
def _lr(self, rows, y, terms):
if not terms:
return np.full(self.n, y.mean())
fit = _logit(y, self.dummies.iloc[rows][terms])
if fit is None:
return None
return fit.predict(sm.add_constant(self.dummies[terms], has_constant="add")).to_numpy()
def _key(self, parents, rows):
key = np.zeros(len(rows), dtype=np.int64)
for p in parents:
key = key * self.levels[p] + self.codes[p][rows]
return key
def _hbn(self, rows, y, parents):
if not parents:
return np.full(self.n, y.mean())
q = int(np.prod([self.levels[p] for p in parents]))
alpha = self.ess / (2 * q)
key = self._key(parents, rows)
n = pd.Series(1, index=key).groupby(level=0).sum()
n1 = pd.Series(y, index=key).groupby(level=0).sum()
table = (n1 + alpha) / (n + 2 * alpha)
return table.reindex(self._key(parents, np.arange(self.n))).fillna(y.mean()).to_numpy()
def risk(self, rows: np.ndarray, masks: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None:
"""For each group, its members' mean combined risk at every horizon, fitted on `rows` (a resample or all)."""
out = {name: np.full(len(self.horizons), np.nan) for name in masks}
for j, horizon in enumerate(self.horizons):
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
fit_rows = rows[recurred | (t > horizon)]
y = recurred[recurred | (t > horizon)].astype(int)
model = self.models[horizon]
lr = self._lr(fit_rows, y, model["lr_terms"])
if lr is None:
return None
combined = (lr + self._hbn(fit_rows, y, model["hbn_parents"])) / 2
for name, mask in masks.items():
chosen = mask[rows]
if chosen.any():
out[name][j] = combined[rows][chosen].mean()
return out
def bootstrap(self, masks: dict[str, np.ndarray], replicas: int, seed: int) -> dict[str, list]:
rng = np.random.default_rng(seed)
draws = {name: [] for name in masks}
for _ in range(replicas):
risk = self.risk(rng.integers(0, self.n, self.n), masks)
if risk is None:
continue
for name in masks:
draws[name].append(risk[name])
return draws
def scenario_masks(frame: pd.DataFrame, scenarios: list[dict]) -> dict[str, np.ndarray]:
return {s["name"]: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in s["when"].items()]) for s in scenarios}
def scenario_figure(frame: pd.DataFrame, name: str, mask: np.ndarray, point: np.ndarray, draws: list,
horizons: list[int], settings: dict) -> dict | None:
"""The figure record of a scenario, or None when it has fewer recurrences than the calculator draws."""
members = frame[mask]
events = int(members["evento"].sum())
if len(members) == 0 or events < settings["min_events"]:
return None
months = np.floor(members["tiempo_meses"].to_numpy()).astype(int)
event = (members["evento"] == 1).to_numpy()
d, c = tabla_eventos(months, event)
weibull = ajustar_weibull(d, c)
fractional = ajustar_ks(d, c, k_fijo=weibull["k"], lam_ref=weibull["lam"], max_seg=settings["fractional_weibull_budget_s"])
last = int(months.max())
survival, low, high = km_curva(months, event, last)
t = np.arange(0, settings["cap_months"] * 4 + 1) / 4
free = 1 - point
boot = np.array(draws)
interval = 1 - np.nanpercentile(boot, [97.5, 2.5], axis=0) if len(boot) else np.full((2, len(horizons)), np.nan)
clean = lambda a: [None if not np.isfinite(x) else float(x) for x in a]
return {
"escenario": name, "n": int(len(members)), "recaidas": events, "observado_hasta": last,
"months_max": settings["cap_months"], "horizons_months": horizons, "bootstrap_replicas": len(boot),
"km": {"months": list(range(last + 1)), "S": clean(survival), "low": clean(low), "high": clean(high)},
"weibull": {"t": t.tolist(), "S": clean(weibull["S"](t))},
"weibull_fractional": {"t": t.tolist(), "S": clean(fractional["S"](t))},
"points": {"COMB": {"S": clean(free), "low": clean(interval[0]), "high": clean(interval[1])}},
}
+223
View File
@@ -0,0 +1,223 @@
"""The recurrence calculator: for each clinical scenario of a cohort (a subgroup defined by covariates), the figure the
dashboard shows: the Kaplan-Meier curve of the scenario's patients with its Greenwood band, the classic and the fractional
Weibull fitted to it (dotted past the follow-up), and the recurrence-free probability at each horizon by the combination of
the LR and the HBN of that horizon, with a bootstrap interval. Ported from `05_calculadora.py`; the Weibull routines are the
survival analysis' (`models.cama.seer_survival.fractional_weibull`).
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.factors import ORDER # noqa: F401 (the classification vocabulary is shared)
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
from models.cama.seer_survival import fractional_weibull as fw
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
PCT_DEFINING, PCT_MAJORITY, PCT_PRESENT = 0.95, 0.50, 0.10
@dataclass(frozen=True)
class CalculatorSettings:
seed: int = 42
n_boot: int = 200
min_events: int = 15
cap_months: int = 72
bdeu_ess: int = 10
ks_seconds: int = 60
class _Calculator:
def __init__(self, prepared: Prepared, fitted: CohortModels, s: CalculatorSettings):
self.s, self.fitted, self.covariates = s, fitted, prepared.covariates
df = prepared.cohort
self.df, self.N = df, len(df)
self.time, self.event_num = df["tiempo_meses"].values, df["evento"].values
self.X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(df[v])[0] for v in self.covariates}
self.levels = {v: int(self.codes[v].max()) + 1 for v in self.covariates}
@staticmethod
def _logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def _p_lr(self, train_idx, y, terms):
if not terms:
return np.full(self.N, y.mean())
m = self._logit(y, self.X.iloc[train_idx][terms])
return None if m is None else m.predict(sm.add_constant(self.X[terms], has_constant="add")).values
def _key(self, parents, rows):
k = np.zeros(len(rows), dtype=np.int64)
for p in parents:
k = k * self.levels[p] + self.codes[p][rows]
return k
def _p_hbn(self, train_idx, y, parents):
if not parents:
return np.full(self.N, y.mean())
q = int(np.prod([self.levels[p] for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
k_train = self._key(parents, train_idx)
n = pd.Series(1, index=k_train).groupby(level=0).sum()
n1 = pd.Series(y, index=k_train).groupby(level=0).sum()
table = (n1 + alpha) / (n + 2 * alpha)
return table.reindex(self._key(parents, np.arange(self.N))).fillna(y.mean()).values
def _risks(self, idx, H):
t, e = self.time[idx], self.event_num[idx]
recurs = (e == 1) & (t <= H)
ok = recurs | (t > H)
train, y = idx[ok], recurs[ok].astype(int)
mh = self.fitted.models[str(H)]
p_lr, p_hbn = self._p_lr(train, y, mh["terminos_lr"]), self._p_hbn(train, y, mh["padres_hbn"])
return None if p_lr is None else (p_lr, p_hbn)
def mean_risk(self, idx, masks, horizons):
out = {n: np.full(len(horizons), np.nan) for n in masks}
for j, H in enumerate(horizons):
r = self._risks(idx, H)
if r is None:
return None
combined = (r[0] + r[1]) / 2
for n, mask in masks.items():
sel = mask[idx]
if sel.any():
out[n][j] = combined[idx][sel].mean()
return out
def scenario_masks(df: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in scenarios.items()}
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def calculator(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], settings: CalculatorSettings,
scenarios: dict | None = None) -> tuple[list[dict], pd.DataFrame]:
"""The figure record of each scenario with enough recurrences, and the table of their points."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
c = _Calculator(prepared, fitted, settings)
masks = scenario_masks(prepared.cohort, scenarios)
everyone = np.arange(c.N)
points = c.mean_risk(everyone, masks, horizons)
rng = np.random.default_rng(settings.seed)
boots = {n: [] for n in masks}
for _ in range(settings.n_boot):
r = c.mean_risk(rng.integers(0, c.N, c.N), masks, horizons)
if r is None:
continue
for n in masks:
boots[n].append(r[n])
months_int = np.floor(c.time).astype(int)
event = c.event_num == 1
records, rows = [], []
for scenario, mask in masks.items():
n_sub, events = int(mask.sum()), int(prepared.cohort.loc[mask, "evento"].sum())
if n_sub == 0 or events < settings.min_events:
continue
m_s, e_s = months_int[mask], event[mask]
d, cen = fw.tabla_eventos(m_s, e_s)
classic = fw.ajustar_weibull(d, cen)
fractional = fw.ajustar_ks(d, cen, k_fijo=classic["k"], lam_ref=classic["lam"], max_seg=settings.ks_seconds)
observed = int(m_s.max())
S, low, high = fw.km_curva(m_s, e_s, observed)
free = 1 - points[scenario]
B = np.array(boots[scenario])
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(horizons)), np.nan)
grid = np.linspace(0, settings.cap_months, 289)
records.append({
"cohorte": name, "cohorte_nombre": LABELS[name], "escenario": scenario, "condiciones": scenarios[scenario],
"n": n_sub, "recaidas": events, "horizons_months": horizons, "observado_hasta": observed, "months_max": settings.cap_months,
"km": {"months": list(range(observed + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": {"COMB": {"S": free.tolist(), "low": np.clip(ic[0], 0, 1).tolist(), "high": np.clip(ic[1], 0, 1).tolist()}},
"bootstrap_replicas": len(B)})
for j, H in enumerate(horizons):
rows.append({"cohorte": name, "subgrupo": scenario, "n": n_sub, "recaidas": events, "horizonte_meses": H,
"S_libre_LR_HBN": free[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - free[j],
"S_libre_KM": S[min(H, observed)] if H <= observed else np.nan, "replicas_bootstrap": len(B)})
return records, pd.DataFrame(rows).round(4)
def scenario_risk_factors(name: str, prepared: Prepared, factors: pd.DataFrame, horizons: list[int],
scenarios: dict | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Which classified risk factors, protectors and treatments make up each scenario: a category nearly all of it has
defines it, most of it describes it. Returns the detail and the per-scenario summary."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
df = prepared.cohort
masks = scenario_masks(df, scenarios)
fr = factors[(factors["cohorte"] == name) & factors["horizonte_meses"].isin(horizons)]
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
details, summary = [], []
for scenario, mask in masks.items():
n_sub = int(mask.sum())
if n_sub == 0 or fr.empty:
continue
cond = scenarios[scenario]
shares = {(v, cat): (float((df.loc[mask, v] == cat).mean()), float((df[v] == cat).mean())) for v, cat in set(zip(fr["variable"], fr["categoria"]))}
det = fr.copy()
det["pct_en_escenario"] = [shares[(v, cat)][0] for v, cat in zip(det["variable"], det["categoria"])]
det["pct_en_cohorte"] = [shares[(v, cat)][1] for v, cat in zip(det["variable"], det["categoria"])]
det["presencia"] = det["pct_en_escenario"].map(_presence)
det["en_definicion"] = [cat in cond.get(v, []) for v, cat in zip(det["variable"], det["categoria"])]
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
det.insert(0, "escenario", scenario)
det.insert(1, "definicion", definition)
det.insert(2, "n_escenario", n_sub)
cols = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte", "presencia", "en_definicion"]
details.append(det[det["pct_en_escenario"] >= PCT_PRESENT][cols])
for H in horizons:
d = det[det["horizonte_meses"] == H]
row = {"cohorte": name, "escenario": scenario, "definicion": definition, "n_escenario": n_sub, "horizonte_meses": H}
for kind in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
part = d[(d["tipo_efecto"] == kind) & (d["presencia"] == level)]
row[f"{kind}_{label}"] = "; ".join(
f"{v}={cat} ({k.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for v, cat, k, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return (pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame()), pd.DataFrame(summary)
+86
View File
@@ -0,0 +1,86 @@
"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence
event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `cohorts.toml`).
The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from
it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to
`window_days_after_index` after the index; a category no rule gives is the variable's `missing` one.
"""
import tomllib
from pathlib import Path
import pandas as pd
from models.cama.seer_survival.variables import Reader, category_of
TOML = Path(__file__).with_name("cohorts.toml")
SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"}
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
def _spec(dictionary: dict, name: str, cohort: str) -> dict:
spec = dictionary[name]
own = spec.get(cohort, {})
return {**spec, "rules": own["rules"]} if "rules" in own else spec
def _cut(values: pd.Series, cuts: list, labels: list, missing: str) -> pd.Series:
cut = pd.cut(values, cuts, labels=labels, right=False)
return cut.astype("object").where(cut.notna(), missing).astype(str)
def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool = True, follow_up: bool = True) -> pd.DataFrame:
"""One row per patient. `of_source` keeps only the patients whose record comes from this cohort's source (a patient of
another source is read with the same variables when it is false); `follow_up` drops those with no recurrence or
last contact, whose time is unknown."""
dictionary = model["variables"]
index = dictionary["index"]
events = events.copy()
events["fecha"] = pd.to_datetime(events["fecha"])
events["fecha_indice"] = pd.to_datetime(events["fecha_indice"])
if of_source:
source = events[events["tipo"] == "fuente"].groupby("pac_id")["valor_codigo"].last()
patients = pd.Index(sorted(source[source == SOURCE_CODE[cohort]].index), name="pac_id")
else:
patients = pd.Index(sorted(events["pac_id"].unique()), name="pac_id")
events = events[events["pac_id"].isin(patients)]
start = events.groupby("pac_id")["fecha_indice"].first().reindex(patients)
recurrence = events[events["tipo"] == index["recurrence_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
contact = events[events["tipo"] == index["last_contact_source"]].groupby("pac_id")["fecha"].max().reindex(patients)
end = recurrence.fillna(contact)
birth = events[events["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
window = pd.Timedelta(days=int(dictionary["window_days_after_index"]))
visible = events[events["fecha"] <= events["pac_id"].map(start) + window]
reader = Reader(visible, patients, {})
result = pd.DataFrame(index=patients)
result["paciente"] = patients.to_numpy()
result["tiempo_meses"] = ((end - start).dt.days / index["days_per_month"]).to_numpy()
result["evento"] = recurrence.notna().astype(int).to_numpy()
unknown = dictionary["Edad"]["missing"]
for name in model["cohorts"][cohort]["covariates"]:
spec = _spec(dictionary, name, cohort)
if name == "Edad":
age = (start - birth).dt.days / 365.25
result[name] = _cut(age, spec["cuts"], spec["labels"], unknown).to_numpy()
elif "rules" in spec:
category = category_of(spec, reader)
labels = spec.get(cohort, {}).get("labels", {})
result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy()
elif spec.get("terciles"):
count = reader.value(spec["source"], True)
if count.notna().sum() == 0:
result[name] = spec["missing"]
continue
q = count.quantile([1 / 3, 2 / 3]).to_numpy()
result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy()
else:
result[name] = _cut(reader.value(spec["source"], True), spec["cuts"], spec["labels"], spec["missing"]).to_numpy()
keep = start.notna().to_numpy() & (end.notna().to_numpy() if follow_up else True)
result = result[keep]
return result.reset_index(drop=True)
+180
View File
@@ -0,0 +1,180 @@
"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import
schemas take, to be uploaded through the platform's import like any other source.
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR [--diagnosis-from 2018-01-01 --spread-days 540
--censor 2026-11-21]
What goes where is the dictionary's (`[variables.*]` of `cohorts.toml`): each source category is stored as the catalog value
the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day
of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the
follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps
the month it falls in and its side of every horizon.
`--diagnosis-from` places the diagnoses in a window of the platform's own (spread over `--spread-days` days, the same day for
the same patient on every run) in place of the dictionary's fixed year, and `--censor` ends every follow-up by that day: a
recurrence after it is not known yet, and the patient is a last contact on that day.
"""
import argparse
import hashlib
import math
import tomllib
from pathlib import Path
import numpy as np
import pandas as pd
TOML = Path(__file__).with_name("cohorts.toml")
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos",
"SeguimientoMama": "seguimientos"}
FEMALE = "Femenino"
UNKNOWN = {"", "NA", "nan", "NaN", "None"}
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
def follow_up_days(months: float, horizons: list[int], days_per_month: float) -> int:
"""The whole days nearest to `months` that keep floor(months) and, for each horizon, whether the follow-up is within it."""
exact = months * days_per_month
month = math.floor(months)
low = math.ceil(month * days_per_month)
high = math.ceil((month + 1) * days_per_month) - 1
sides = [months <= h for h in horizons]
first = int(round(exact))
for step in range(0, high - low + 2):
for day in (first - step, first + step):
if low <= day <= high and math.floor(day / days_per_month) == month \
and [day / days_per_month <= h for h in horizons] == sides:
return day
return first
def _known(raw: pd.Series) -> pd.Series:
return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN)
def _spread(ids: pd.Series, days: int) -> pd.Series:
"""A day in [0, days) per patient, fixed by her identifier."""
return ids.map(lambda i: int.from_bytes(hashlib.sha256(str(i).encode()).digest()[:4], "big") % days)
def convert(raw: pd.DataFrame, cohort: str, model: dict, *, diagnosis_from: str | None = None, spread_days: int = 1,
censor: str | None = None) -> dict[str, pd.DataFrame]:
dictionary = model["variables"]
index = dictionary["index"]
cfg = dictionary["cohorts"][cohort]
covariates = model["cohorts"][cohort]["covariates"]
horizons = model["config"]["horizons_months"]
dpm = index["days_per_month"]
frame = raw
if cfg["sex_filter"]:
frame = frame[frame[cfg["sex_filter"]["column"]] == cfg["sex_filter"]["value"]]
frame = frame[_known(frame[cfg["months"]]) & _known(frame[cfg["event"]])].copy()
if cohort == "scanb":
days = pd.to_numeric(frame[cfg["months"]]).round().astype(int)
event = pd.to_numeric(frame[cfg["event"]]).astype(int)
else:
months = pd.to_numeric(frame[cfg["months"]])
days = pd.Series([follow_up_days(m, horizons, dpm) for m in months], index=frame.index)
event = frame[cfg["event"]].astype(str).str.startswith(cfg["event_prefix"]).astype(int)
age = pd.to_numeric(frame[cfg["diagnosis_age"]], errors="coerce") + cfg.get("diagnosis_age_offset", 0)
frame, days, event, age = (x[age.notna()] for x in (frame, days, event, age))
if "diagnosis_year_column" in cfg:
year = pd.to_numeric(frame[cfg["diagnosis_year_column"]], errors="coerce").fillna(2000).astype(int)
else:
year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index)
diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"])
if diagnosis_from:
diagnosis = pd.Timestamp(diagnosis_from) + pd.to_timedelta(_spread(frame[cfg["id"]], spread_days), unit="D")
birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D")
end = diagnosis + pd.to_timedelta(days, unit="D")
if censor:
late = end > pd.Timestamp(censor)
event = event.where(~late, 0)
end = end.where(~late, pd.Timestamp(censor))
ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d")
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
tables["Paciente"]["pac_sexo"] = FEMALE
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
tables["Paciente"]["pac_fuente"] = "SCANB" if cohort == "scanb" else "METABRIC"
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
treatments = []
for name in covariates:
spec = dictionary[name]
source = spec.get(cohort)
if not source or "column" not in source:
continue
column = frame[source["column"]]
known = _known(column)
if "treatment" in spec:
code = column.astype(str).map(source["values"])
code = code.where(~known | code.notna(), source.get("absent")).where(known)
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": spec["treatment"], "trat_fecha": date(diagnosis),
"trat_detalle": code})[code.notna()]
if spec["treatment"] == "cirugia":
rows["trat_lateralidad"] = None
treatments.append(rows)
continue
if "bronze" not in spec:
continue
entity, target = spec["bronze"].split(".")
if "number_values" in source:
value = column.astype(str).map(source["number_values"])
elif "values" in source:
value = column.astype(str).map(source["values"])
else:
value = pd.to_numeric(column.where(known), errors="coerce")
tables[entity][target] = value.where(known)
tables["BiopsiaMama"]["bx_grado_histologico"] = "CARCINOMA_INVASOR"
if "Cirugia" in covariates and "bx_lateralidad" in tables["BiopsiaMama"]:
for rows in treatments:
if (rows["trat_tipo"] == "cirugia").any():
rows["trat_lateralidad"] = tables["BiopsiaMama"]["bx_lateralidad"].reindex(rows.index)
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
notes = tables["NotaMedica"]
notes["nm_id_hospital"] = ident + "-dx"
notes["nm_fecha"] = date(diagnosis)
notes["nm_tipo_nota"] = "CONSULTA"
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(end),
"nm_tipo_nota": "EGRESO"})
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
recurred = event.eq(1)
contact = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["last_contact_source"], "seg_fecha": date(end),
"seg_detalle": "VIVA"})[~recurred]
recurrence = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["recurrence_source"], "seg_fecha": date(end),
"seg_detalle": "NO_ESPECIFICADO"})[recurred]
tables["SeguimientoMama"] = pd.concat([recurrence, contact], ignore_index=True)
return tables
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("cohort", choices=["metabric", "scanb"])
ap.add_argument("file")
ap.add_argument("out_dir")
ap.add_argument("--diagnosis-from", help="first day of the diagnoses (YYYY-MM-DD); the dictionary's year without it")
ap.add_argument("--spread-days", type=int, default=1, help="days over which the diagnoses are spread")
ap.add_argument("--censor", help="last day of follow-up (YYYY-MM-DD)")
args = ap.parse_args(argv)
raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False)
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(raw, args.cohort, load(), diagnosis_from=args.diagnosis_from,
spread_days=args.spread_days, censor=args.censor).items():
table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False)
if __name__ == "__main__":
main()
+400
View File
@@ -0,0 +1,400 @@
# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and
# clinical scenarios, as in his scripts; the cohorts are not pooled.
domain = "cama"
scenario = "recurrence"
cohort = "cama/cohorte_total"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"]
settings_tables = ["modeling", "calculator", "variables"]
description = """
Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \
sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico."""
[config]
horizons_months = [12, 36, 60]
# ---- settings of the stages (Luis's scripts 03, 04 and 05) ----
[modeling]
seed = 42
unknown_label = "Desconocido"
cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped
alpha_prefilter = 0.10 # univariate prefilter of the logistic regression
alpha_in = 0.10 # stepwise: p to enter
alpha_out = 0.15 # stepwise: p to leave
bdeu_ess = 10
max_parents = 6
test_share = 0.30 # the 70/30 split of the AUC
[calculator]
min_events = 15 # a scenario is drawn only with at least this many recurrences
bootstrap_replicas = 200
cap_months = 72 # the curves are drawn dotted past the follow-up up to here
fractional_weibull_budget_s = 60
# ---- the variable dictionary ----
# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give
# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed).
# `<cohort>.column` is the source file's column; `<cohort>.values` maps its values to the codes the loader sends;
# `<cohort>.labels` renames the rules' category where the source names it differently (neutral label = source label);
# `[variables.X.<cohort>]` replaces the rules for a variable whose categories differ between the cohorts.
[variables]
window_days_after_index = 365
[variables.index]
id_column = "paciente"
months_column = "tiempo_meses"
event_column = "evento"
death_source = "defuncion"
birth_source = "nacimiento"
recurrence_source = "recurrencia"
last_contact_source = "ultimo_contacto"
days_per_month = 30.4375
[variables.cohorts.metabric]
id = "Patient ID"
months = "Relapse Free Status (Months)"
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
event_prefix = "1"
diagnosis_age = "Age at Diagnosis" # years
sex_filter = {}
diagnosis_month_day = "07-01"
diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it
# Per covariate, the source columns and category cuts as the preparation script defines them.
[variables.cohorts.scanb]
id = "PatientName"
months = "RFI_days" # days, divided by days_per_month
months_divisor = 30.4375
event = "RFI_event"
sex_filter = { column = "Gender", value = "F" }
diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script
diagnosis_age_offset = -2
diagnosis_month_day = "07-01"
diagnosis_year_column = "dxYear"
# Cuts shared by both cohorts (pd.cut with the right edge open).
[variables.Edad]
cuts = [0, 45, 60, 75, 200]
labels = ["<45", "45-59", "60-74", "75+"]
missing = "Desconocido"
[variables.Tamano_tumor]
bronze = "BiopsiaMama.bx_tamano_tumor_mm"
source = "tamano_tumor_mm"
cuts = [0, 20.01, 50.01, 10000]
labels = ["<=20 mm", "21-50 mm", ">50 mm"]
missing = "Desconocido"
metabric = { column = "Tumor Size" }
scanb = { column = "TumorSize_mm" }
[variables.Ganglios_positivos]
bronze = "BiopsiaMama.bx_ganglios_positivos"
source = "ganglios_positivos"
cuts = [0, 1, 4, 1000]
labels = ["0", "1-3", "4+"]
missing = "Desconocido"
metabric = { column = "Lymph nodes examined positive" }
scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } }
[variables.Grado_histologico]
bronze = "BiopsiaMama.bx_grado_nottingham"
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "1" },
{ source = "grado_nottingham", codes = ["G2"], then = "2" },
{ source = "grado_nottingham", codes = ["G3"], then = "3" },
]
missing = "Desconocido"
metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } }
scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } }
[variables.Receptor_estrogeno]
bronze = "BiopsiaMama.bx_receptor_estrogeno"
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.Receptor_progesterona]
bronze = "BiopsiaMama.bx_receptor_progesterona"
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.HER2]
bronze = "BiopsiaMama.bx_her2_fish"
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positive" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" },
{ source = "her2", codes = ["H3"], then = "Positive" },
{ source = "her2", codes = ["H0", "H1"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
[variables.Tipo_histologico]
bronze = "BiopsiaMama.bx_tipo_histologico"
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" },
{ source = "tipo_histologico", codes = ["8000/3"], then = "Breast" },
{ source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" },
{ source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" },
]
missing = "Desconocido"
metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } }
[variables.Tipo_histologico.scanb]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" },
{ source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Other" },
]
column = "Histology"
values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" }
[variables.Estado_menopausico]
bronze = "Paciente.pac_estado_menopausico"
rules = [
{ source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" },
{ source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" },
]
missing = "Desconocido"
metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } }
scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } }
[variables.Lateralidad]
bronze = "BiopsiaMama.bx_lateralidad"
rules = [
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" },
{ source = "lateralidad", codes = ["DERECHA"], then = "Right" },
]
missing = "Desconocido"
metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } }
scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } }
# Treatments. The category is the source's own, as the scenarios of each cohort name them.
[variables.Cirugia]
treatment = "cirugia"
rules = [
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" },
{ source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" },
]
missing = "Desconocido"
metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } }
scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } }
[variables.Quimioterapia]
treatment = "quimioterapia"
rules = [
{ source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "quimioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Radioterapia]
treatment = "radioterapia"
rules = [
{ source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "radioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Hormonoterapia]
treatment = "hormonoterapia"
rules = [
{ source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
# ---- METABRIC only ----
[variables.Carga_mutacional]
bronze = "Paciente.pac_carga_mutacional"
source = "carga_mutacional"
terciles = true # the cohort's own terciles of the mutation count
labels = ["baja", "media", "alta"]
missing = "Desconocido"
metabric = { column = "Mutation Count" }
[variables.Subtipo_PAM50]
bronze = "Paciente.pac_pam50"
rules = [
{ source = "pam50", codes = ["LUMA"], then = "LumA" },
{ source = "pam50", codes = ["LUMB"], then = "LumB" },
{ source = "pam50", codes = ["HER2"], then = "Her2" },
{ source = "pam50", codes = ["BASAL"], then = "Basal" },
{ source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" },
{ source = "pam50", codes = ["NORMAL"], then = "Normal" },
{ source = "pam50", codes = ["NC"], then = "NC" },
]
missing = "Desconocido"
metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } }
[variables.Celularidad]
bronze = "Paciente.pac_celularidad"
rules = [
{ source = "celularidad", codes = ["ALTA"], then = "High" },
{ source = "celularidad", codes = ["MODERADA"], then = "Moderate" },
{ source = "celularidad", codes = ["BAJA"], then = "Low" },
]
missing = "Desconocido"
metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } }
[variables.Cluster_integrativo]
bronze = "Paciente.pac_cluster_integrativo"
rules = [
{ source = "cluster_integrativo", codes = ["IC1"], then = "1" },
{ source = "cluster_integrativo", codes = ["IC2"], then = "2" },
{ source = "cluster_integrativo", codes = ["IC3"], then = "3" },
{ source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" },
{ source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" },
{ source = "cluster_integrativo", codes = ["IC5"], then = "5" },
{ source = "cluster_integrativo", codes = ["IC6"], then = "6" },
{ source = "cluster_integrativo", codes = ["IC7"], then = "7" },
{ source = "cluster_integrativo", codes = ["IC8"], then = "8" },
{ source = "cluster_integrativo", codes = ["IC9"], then = "9" },
{ source = "cluster_integrativo", codes = ["IC10"], then = "10" },
]
missing = "Desconocido"
metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } }
# ---- SCAN-B only ----
[variables.Ki67]
bronze = "Paciente.pac_ki67_categoria"
rules = [
{ source = "ki67_categoria", codes = ["BAJO"], then = "Low" },
{ source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" },
{ source = "ki67_categoria", codes = ["ALTO"], then = "High" },
]
missing = "Desconocido"
scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } }
[variables.Subtipo_clinico]
bronze = "Paciente.pac_subtipo_clinico"
rules = [
{ source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" },
{ source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" },
{ source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" },
{ source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" },
{ source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" },
]
missing = "Desconocido"
scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } }
[variables.Estadio_clinico]
bronze = "NotaMedica.nm_estadio_clinico"
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0" },
{ source = "estadio_clinico", codes = ["EI"], then = "1" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" },
]
missing = "Desconocido"
scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } }
[variables.AntiHER2]
treatment = "anti_her2"
rules = [
{ source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" },
{ source = "anti_her2", codes = ["NINGUNA"], then = "No" },
]
missing = "Desconocido"
scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" }
# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ----
[cohorts.metabric]
name = "METABRIC"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico",
"Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
[cohorts.scanb]
name = "SCAN-B"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad",
"Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ----
[[cohorts.metabric.scenarios]]
name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.metabric.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.metabric.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.metabric.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.metabric.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.metabric.scenarios]]
name = "Basal (PAM50)"
when = { Subtipo_PAM50 = ["Basal"] }
[[cohorts.metabric.scenarios]]
name = "HER2 (PAM50)"
when = { Subtipo_PAM50 = ["Her2"] }
[[cohorts.metabric.scenarios]]
name = "Luminal B (PAM50)"
when = { Subtipo_PAM50 = ["LumB"] }
[[cohorts.metabric.scenarios]]
name = "RE+ · 1-3 ganglios · cirugía conservadora"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] }
[[cohorts.metabric.scenarios]]
name = "RE− · grado 3"
when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] }
[[cohorts.scanb.scenarios]]
name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.scanb.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.scanb.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.scanb.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.scanb.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.scanb.scenarios]]
name = "Basal-like"
when = { Subtipo_clinico = ["Basal-like"] }
[[cohorts.scanb.scenarios]]
name = "HER2+ (luminal B HER2+ o no luminal)"
when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] }
[[cohorts.scanb.scenarios]]
name = "Luminal B HER2−"
when = { Subtipo_clinico = ["Luminal B HER2-"] }
[[cohorts.scanb.scenarios]]
name = "Luminal · 1-3 ganglios · lumpectomía"
when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] }
[[cohorts.scanb.scenarios]]
name = "Grado 3"
when = { Grado_histologico = ["3"] }
+135
View File
@@ -0,0 +1,135 @@
"""The risk factors of the recurrence models: a category is a risk factor (or a protector) from four criteria, as in the
survival analysis: the multivariable OR, its stability in the bootstrap, the Markov blanket of the Bayesian network and the
survival difference; treatments are reported apart, never classified. Ported from `04_factores_riesgo.py`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
COLUMNS = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "clasificacion"]
def benjamini_hochberg(p) -> np.ndarray:
p = np.asarray(p, float)
order = np.argsort(p)
adjusted = np.empty_like(p)
m, previous = len(p), 1.0
for rank, i in zip(range(m, 0, -1), order[::-1]):
previous = min(previous, p[i] * m / rank)
adjusted[i] = previous
return adjusted
def _variable_of(term: str, variables: list[str]) -> str:
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
def _km_at(m, e, h):
T = int(m.max()) + 2
d, c = np.bincount(m[e], minlength=T), np.bincount(m[~e], minlength=T)
at_risk = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def _at_horizon(name: str, prepared: Prepared, fitted: CohortModels, H: int, alpha: float, freq_min: float) -> pd.DataFrame:
total, variables, treatment = prepared.cohort, prepared.covariates, prepared.treatment
intrinsic = [v for v in variables if v not in treatment]
recurs = (total["evento"] == 1) & (total["tiempo_meses"] <= H)
free = total["tiempo_meses"] > H
km_data = total.copy()
coh = total[recurs | free].reset_index(drop=True)
data = coh[variables].astype(str)
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
months = np.floor(np.minimum(km_data["tiempo_meses"].values, H + 1)).astype(int)
event = ((km_data["evento"] == 1) & (km_data["tiempo_meses"] <= H)).values
km_data = km_data[variables].astype(str)
def reference(v):
return data[v].value_counts().idxmax()
def fit_or(model_vars):
X = pd.get_dummies(data[model_vars], drop_first=False).astype(float)
refs = {v: f"{v}_{reference(v)}" for v in model_vars}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
model = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = model.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(model.params[X.columns].values),
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
"p": model.pvalues[X.columns].values})
def delta_s(v, cat, ref):
a, b = (km_data[v] == cat).values, (km_data[v] == ref).values
Sa, ea = _km_at(months[a], event[a], H)
Sb, eb = _km_at(months[b], event[b], H)
d, se = Sa - Sb, np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
def complete(t, model_vars):
t = t.copy()
t["variable"] = [_variable_of(x, model_vars) for x in t["termino"]]
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
t["referencia"] = [reference(v) for v in t["variable"]]
t["p_ajustado_BH"] = benjamini_hochberg(t["p"])
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab = complete(fit_or(intrinsic), intrinsic)
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < alpha)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
mh = fitted.models.get(str(H), {})
n_rep, selection = mh.get("n_replicas", 0), mh.get("seleccion_lr", {})
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: selection.get(v, 0) / n_rep if n_rep else np.nan)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= freq_min
tab["en_manta_markov"] = tab["variable"].isin(set(mh.get("padres_hbn", [])))
tab["c3_manta_markov"] = tab["en_manta_markov"]
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
def classify(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(classify, axis=1)
tab["tipo"] = "factor de riesgo"
if treatment:
tr = fit_or(intrinsic + treatment)
tr["_v"] = [_variable_of(t, intrinsic + treatment) for t in tr["termino"]]
tr = tr[tr["_v"].isin(treatment) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
tr = complete(tr, treatment)
tr["tipo"] = "tratamiento"
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = name, H
return tab
def risk_factors(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], alpha: float = 0.05,
freq_min: float = 0.80) -> pd.DataFrame:
"""The classified categories of each horizon, risk factors first, as `factores_riesgo_recurrencia.csv`."""
new = pd.concat([_at_horizon(name, prepared, fitted, H, alpha, freq_min) for H in horizons], ignore_index=True)
new["_t"] = (new["tipo"] != "factor de riesgo").astype(int)
new["_o"] = new["clasificacion"].map(ORDER).fillna(5)
return new.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[COLUMNS].round(4)
+159
View File
@@ -0,0 +1,159 @@
"""CaMa's recurrence analysis as a scenario: the dataflow from the cohort's patients loaded from METABRIC and SCAN-B (the
`fuente` of each, indexed at her first invasive biopsy) to the registered model, its results and its routines. Each node is one
stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery (`models.dags.training.train`)
saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the dashboard shows are in
`population["recurrencia"]`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence import calculator as calc
from models.cama.recurrence import factors as fac
from models.cama.recurrence import modeling
from models.cama.recurrence import cohort as timeline
from models.cama.recurrence.prep import Prepared, finish
COHORTS = ("metabric", "scanb")
def dictionary() -> dict:
"""The variables, cohorts and scenarios of `cohorts.toml`."""
return timeline.load()
def prepared(cohort: pd.DataFrame, dictionary: dict, recurrence: dict) -> dict[str, Prepared]:
"""Each cohort's patients as one table of categories with its covariates (`cohort.recode`, then `prep`)."""
fixed = ["paciente", "tiempo_meses", "evento"]
return {name: finish(timeline.recode(cohort, dictionary, name), fixed, dictionary["cohorts"][name]["treatment"],
recurrence["v_max"]) for name in COHORTS}
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
"""The LR and the HBN at each horizon of each cohort, with their AUC (`modeling`)."""
base = {k: recurrence[k] for k in ("seed", "bdeu_ess", "max_parents", "alpha_in", "alpha_out", "alpha_prefilter")}
return {name: modeling.fit_cohort(name, prepared[name], list(recurrence["horizons"]),
modeling.FitSettings(n_bootstrap=recurrence[f"n_bootstrap_{name}"], **base)) for name in COHORTS}
def factors_table(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> pd.DataFrame:
"""The classified risk factors of both cohorts at each horizon (`factors`)."""
return pd.concat([fac.risk_factors(n, prepared[n], fits[n], list(recurrence["horizons"]), recurrence["alpha"], recurrence["freq_min"])
for n in COHORTS], ignore_index=True)
def calculators(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict[str, tuple[list[dict], pd.DataFrame]]:
"""The figure of each scenario of each cohort and the table of their points (`calculator`)."""
s = calc.CalculatorSettings(seed=recurrence["seed"], n_boot=recurrence["n_boot_calc"], min_events=recurrence["min_events"],
cap_months=recurrence["cap_months"], bdeu_ess=recurrence["bdeu_ess"], ks_seconds=recurrence["ks_seconds"])
return {n: calc.calculator(n, prepared[n], fits[n], list(recurrence["horizons"]), s) for n in COHORTS}
def scenario_factors(prepared: dict[str, Prepared], factors_table: pd.DataFrame, recurrence: dict) -> dict[str, pd.DataFrame]:
"""The risk factors that make up each scenario (`calculator.scenario_risk_factors`): the summary of both cohorts."""
summaries = [calc.scenario_risk_factors(n, prepared[n], factors_table, list(recurrence["horizons"]))[1] for n in COHORTS]
return {"resumen": pd.concat(summaries, ignore_index=True)}
class RecurrenceModel:
"""The recurrence models of one cohort fitted on all of it: at each horizon the logistic regression on the terms the
stepwise chose and the Bayesian network's table over the parents it chose. `predict_proba(X)` is the recurrence probability
at each horizon, the mean of the two models; `X` has the cohort's covariates as categories (the unknown, "Desconocido")."""
def __init__(self, cohort: str, horizons: list[int], covariates: list[str], tables: dict):
self.cohort, self.horizons, self.covariates, self.tables_ = cohort, horizons, covariates, tables
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
out = np.zeros((len(X), len(self.horizons)))
for j, H in enumerate(self.horizons):
t = self.tables_[str(H)]
p_lr = np.full(len(X), t["lr_prior"])
if t["lr_terms"]:
dummies = pd.get_dummies(X[self.covariates].astype(str)).astype(float).reindex(columns=t["lr_terms"], fill_value=0.0)
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + dummies.values @ np.asarray(t["lr_coefficients"]))))
parents, cpt = t["hbn_parents"], t["hbn_cpt"]
p_hbn = np.full(len(X), t["hbn_prior"]) if not parents else np.array(
[cpt.get(tuple(row), t["hbn_prior"]) for row in X[parents].astype(str).values])
out[:, j] = (p_lr + p_hbn) / 2
return out
def _tables(prepared: Prepared, fitted: modeling.CohortModels, horizons: list[int], bdeu_ess: int) -> dict:
"""What `RecurrenceModel` keeps from the fit on the whole cohort, per horizon."""
f = modeling._Fitter(prepared, modeling.FitSettings(bdeu_ess=bdeu_ess))
tables = {}
for H in horizons:
coh = f.at_horizon(H)
mh = fitted.models[str(H)]
terms, parents = mh["terminos_lr"], mh["padres_hbn"]
entry = {"lr_prior": float(coh["y"].mean()), "lr_terms": terms, "lr_constant": 0.0, "lr_coefficients": [],
"hbn_parents": parents, "hbn_prior": float(coh["y"].mean()), "hbn_cpt": {}}
if terms:
X = f.encode(coh)[terms]
model = f.logit(coh["y"], X)
if model is not None:
entry["lr_constant"], entry["lr_coefficients"] = float(model.params["const"]), [float(model.params[t]) for t in terms]
if parents:
table = f.bn_table(coh)
alpha = bdeu_ess / (2 * int(np.prod([table[p].nunique() for p in parents])))
g = table.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
entry["hbn_cpt"] = {(k if isinstance(k, tuple) else (k,)): float((r.n1 + alpha) / (r.n + 2 * alpha)) for k, r in g.iterrows()}
tables[str(H)] = entry
return tables
def fitted_model(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> RecurrenceModel:
"""The model that is saved: METABRIC's, the larger of the two cohorts' external references for the covariates both share."""
return RecurrenceModel("metabric", list(recurrence["horizons"]), prepared["metabric"].covariates,
_tables(prepared["metabric"], fits["metabric"], list(recurrence["horizons"]), recurrence["bdeu_ess"]))
def metrics(fits: dict[str, modeling.CohortModels]) -> dict:
"""Numbers only: each cohort's AUC by internal validation and by bootstrap, per horizon and model, and its Cox C-index."""
found = {}
for name, fit in fits.items():
for _, r in fit.auc.iterrows():
if r["horizonte_meses"] == "completo":
found[f"{name}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{name}.auc_{r['modelo']}_{int(r['horizonte_meses'])}m"
found[tag] = float(r["AUC_validacion_interna"])
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict:
"""The five routine records the registry's promotion reads (ML-01a)."""
return {
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "pacientes cargadas de METABRIC y SCAN-B (`fuente`)"},
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
"horizontes_meses": recurrence["horizons"], "alfa_entrada": recurrence["alpha_in"], "alfa_salida": recurrence["alpha_out"],
"ess_bdeu": recurrence["bdeu_ess"], "maximo_de_padres": recurrence["max_parents"], "cox_penalizado": 0.05,
"combinacion": "promedio de la LR y la HBN"},
"BALANCE_CLASES": {"aplica": False, "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea"},
"CONFIANZA_SALIDA": {"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap",
"replicas": {"metabric": recurrence["n_bootstrap_metabric"], "scanb": recurrence["n_bootstrap_scanb"], "calculadora": recurrence["n_boot_calc"]},
"eventos_minimos_por_escenario": recurrence["min_events"]},
}
def population(calculators: dict, fits: dict[str, modeling.CohortModels], factors_table: pd.DataFrame, scenario_factors: dict,
recurrence: dict) -> dict:
"""What the version publishes under `analisis/`: `recurrencia`, the figure of each scenario of each cohort the dashboard
draws, and `recurrencia_desarrollo`, the tables behind them."""
figures = [r for n in COHORTS for r in calculators[n][0]]
points = pd.concat([calculators[n][1] for n in COHORTS], ignore_index=True)
auc = pd.concat([fits[n].auc for n in COHORTS], ignore_index=True)
def table(df: pd.DataFrame) -> dict:
df = df.replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in df.columns], "filas": df.where(df.notna(), None).to_dict("records")}
return {"recurrencia": {"version": 1, "horizons_months": list(recurrence["horizons"]), "escenarios": figures},
"recurrencia_desarrollo": {"version": 1, "tablas": {"auc": table(auc), "factores_riesgo": table(factors_table),
"calculadora": table(points), "escenarios_resumen": table(scenario_factors["resumen"])}}}
+38
View File
@@ -0,0 +1,38 @@
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, trained on the patients loaded from METABRIC and
# SCAN-B (`cohort_import`, through the platform's import) and read from the database by the dictionary of `cohorts.toml`.
# The scenarios' figures are what the dashboard shows; the hospital's patient is placed in the scenarios her covariates meet.
domain = "cama"
scenario = "recurrence"
cohort = "cama/cohorte_total"
outcome = "recurrencia"
modules = ["models.cama.recurrence.model", "models.steps.indexing"]
description = """\
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
regresión logística y una red bayesiana por horizonte, entrenadas con las pacientes cargadas de dos cohortes externas (METABRIC y SCAN-B). Pendiente \
de validación clínica."""
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
# Its figures are answered per clinical scenario (`/cama/modelo/recurrencia`); the cycle does not score each member.
batch_estimates = false
[config.recurrence]
horizons = [12, 36, 60] # months
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
seed = 42
bdeu_ess = 10
max_parents = 6
alpha_in = 0.10
alpha_out = 0.15
alpha_prefilter = 0.10
alpha = 0.05 # the risk factors' significance
freq_min = 0.80 # the bootstrap's stability criterion
n_bootstrap_metabric = 100
n_bootstrap_scanb = 40
n_boot_calc = 200 # replicas of each scenario's interval
min_events = 15 # recurrences a scenario needs to be drawn
cap_months = 72 # the figure's time axis
ks_seconds = 60 # time budget of each fractional Weibull fit
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA_INVASOR"]
observacion_previa_minima_dias = 0
+194
View File
@@ -0,0 +1,194 @@
"""The recurrence models of one cohort: at each horizon the logistic regression (stepwise) and the Bayesian network (the
BDeu-greedy parents of the outcome), their AUC by internal validation and by bootstrap, how often each covariate enters the
bootstrap's regressions and the parents, and the penalised Cox model's concordance. Ported from `03_modelado.py` without its
figures. The selected terms and parents of each horizon are what the risk factors and the calculator read.
"""
import warnings
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.estimators import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.prep import Prepared
@dataclass(frozen=True)
class FitSettings:
seed: int = 42
n_bootstrap: int = 100
bdeu_ess: int = 10
max_parents: int = 6
alpha_in: float = 0.10
alpha_out: float = 0.15
alpha_prefilter: float = 0.10
@dataclass(frozen=True, eq=False)
class CohortModels:
models: dict[str, dict] # by horizon: the LR terms, the HBN parents and how often each entered the bootstrap
auc: pd.DataFrame
c_index: float
class _Fitter:
def __init__(self, prepared: Prepared, settings: FitSettings):
self.covariates, self.s, self.total = prepared.covariates, settings, prepared.cohort
def encode(self, df: pd.DataFrame) -> pd.DataFrame:
X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
@staticmethod
def logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prefilter(self, X, y) -> list[str]:
keep = []
for c in X.columns:
m = self.logit(y, X[[c]])
if m is not None and m.pvalues[c] < self.s.alpha_prefilter:
keep.append(c)
return keep
def stepwise(self, X, y) -> list[str]:
included = []
for _ in range(200):
changed, best, best_p = False, None, self.s.alpha_in
for c in [c for c in X.columns if c not in included]:
m = self.logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p:
best, best_p = c, m.pvalues[c]
if best is not None:
included.append(best)
changed = True
if included:
m = self.logit(y, X[included])
if m is not None:
p = m.pvalues.drop("const")
if p.max() > self.s.alpha_out:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(self, train: pd.DataFrame, test: pd.DataFrame):
X_all = self.encode(pd.concat([train, test]))
X_tr, X_te = X_all.loc[train.index], X_all.loc[test.index]
X_tr = X_tr.loc[:, X_tr.nunique() > 1]
X_te = X_te[X_tr.columns]
candidates = self.prefilter(X_tr, train["y"])
selected = self.stepwise(X_tr[candidates], train["y"]) if candidates else []
if not selected:
return None, [], np.full(len(test), train["y"].mean())
model = self.logit(train["y"], X_tr[selected])
return model, selected, model.predict(sm.add_constant(X_te[selected], has_constant="add")).values
def variable_of(self, term: str) -> str:
return next((c for c in sorted(self.covariates, key=len, reverse=True) if term.startswith(c + "_")), term)
def parents(self, train: pd.DataFrame) -> list[str]:
score = BDeu(train, equivalent_sample_size=self.s.bdeu_ess)
parents, current = [], score.local_score("outcome", [])
while len(parents) < self.s.max_parents:
best, gain = None, 0
for c in self.covariates:
if c in parents:
continue
g = score.local_score("outcome", parents + [c]) - current
if g > gain:
best, gain = c, g
if best is None:
break
parents.append(best)
current += gain
return parents
def hbn(self, train: pd.DataFrame, test: pd.DataFrame, parents: list[str]) -> np.ndarray:
if not parents:
return np.full(len(test), (train["outcome"] == "1").mean())
q = int(np.prod([train[p].nunique() for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
g = train.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
overall = (train["outcome"] == "1").mean()
table = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
return np.array([table.get(k, overall) for k in map(tuple, test[parents].values)])
def bn_table(self, df: pd.DataFrame) -> pd.DataFrame:
t = df[self.covariates].astype(str).copy()
t["outcome"] = df["y"].astype(int).astype(str)
return t
def at_horizon(self, H: int) -> pd.DataFrame:
recurs = (self.total["evento"] == 1) & (self.total["tiempo_meses"] <= H)
free = self.total["tiempo_meses"] > H
d = self.total[recurs | free].reset_index(drop=True)
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
return d
def fit_cohort(name: str, prepared: Prepared, horizons: list[int], settings: FitSettings) -> CohortModels:
"""The LR and the HBN at each horizon, their AUC and the bootstrap's, and the Cox model's concordance."""
warnings.filterwarnings("ignore")
f, s = _Fitter(prepared, settings), settings
total = prepared.cohort
cox_df = pd.get_dummies(total[["tiempo_meses", "evento"] + f.covariates], columns=f.covariates, drop_first=True).astype(float)
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
tr, te = train_test_split(cox_df, test_size=0.3, random_state=s.seed, stratify=cox_df["evento"])
ok = [c for c in tr.columns if c in ("tiempo_meses", "evento") or 10 <= tr[c].sum() <= len(tr) - 10]
tr, te = tr[ok], te[ok]
cox = CoxPHFitter(penalizer=0.05).fit(tr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
c_index = float(concordance_index(te["tiempo_meses"], -cox.predict_partial_hazard(te), te["evento"]))
rows, models = [], {}
for H in horizons:
coh = f.at_horizon(H)
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=s.seed, stratify=coh["y"])
train, test = coh.loc[tr_idx], coh.loc[te_idx]
_, selected, p_lr = f.lr(train, test)
auc_lr = roc_auc_score(test["y"], p_lr)
bn_train, bn_test = f.bn_table(train), f.bn_table(test)
parents = f.parents(bn_train)
auc_hbn = roc_auc_score(test["y"], f.hbn(bn_train, bn_test, parents))
rng = np.random.default_rng(s.seed)
aucs, count_lr, count_hbn, n_rep = [], {}, {}, 0
for b in range(s.n_bootstrap):
boot = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
try:
b_train, b_test = train_test_split(boot, test_size=0.3, random_state=s.seed + b, stratify=boot["y"])
m, _, p = f.lr(b_train, b_test)
a_lr = roc_auc_score(b_test["y"], p)
bt, be = f.bn_table(b_train), f.bn_table(b_test)
pa = f.parents(bt)
a_h = roc_auc_score(b_test["y"], f.hbn(bt, be, pa))
except Exception:
continue
aucs.append((a_lr, a_h))
n_rep += 1
if m is not None:
for v in {f.variable_of(t) for t in m.params.drop("const").index}:
count_lr[v] = count_lr.get(v, 0) + 1
for v in pa:
count_hbn[v] = count_hbn.get(v, 0) + 1
aucs = np.array(aucs) if aucs else np.full((1, 2), np.nan)
for j, (label, auc) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
rows.append({"cohorte": name, "horizonte_meses": H, "modelo": label, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
"AUC_validacion_interna": auc, "AUC_bootstrap_medio": np.nanmean(aucs[:, j]),
"AUC_bootstrap_IC95_inf": np.nanpercentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.nanpercentile(aucs[:, j], 97.5),
"replicas_bootstrap": n_rep})
models[str(H)] = {"terminos_lr": list(selected), "padres_hbn": parents, "n_replicas": n_rep,
"seleccion_lr": count_lr, "seleccion_hbn": count_hbn,
"arcos_hbn": [[p, "outcome"] for p in parents]}
rows.append({"cohorte": name, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(total),
"recurrencias": int(total["evento"].sum()), "AUC_validacion_interna": c_index})
return CohortModels(models, pd.DataFrame(rows).round(4), c_index)
+36
View File
@@ -0,0 +1,36 @@
"""A hospital patient in the recurrence analysis' terms: her covariates as the external cohorts name them, and the scenarios
(subgroups defined by covariates) she belongs to. What the hospital does not report (nodes, subtype, surgery...) is not given, so
a scenario that needs it does not include her."""
import numpy as np
import pandas as pd
from models.cama.recurrence import prep
POSITIVE = {"POSITIVO": "Positive", "NEGATIVO": "Negative"}
HER2 = {"H3": "Positive", "H0": "Negative", "H1": "Negative"} # 2+ is equivocal: not given
def _bin(value, cuts: list, labels: list) -> str | None:
if value is None or pd.isna(value):
return None
return str(pd.cut([float(value)], cuts, labels=labels, right=False)[0])
def covariates_of(row: pd.Series) -> dict[str, str]:
"""The covariates of one labelled member (`models.cama.survival.live.members`) that the cohorts also have."""
found = {
"Edad": _bin(row.get("age_years"), prep.AGE_CUTS, prep.AGE_LABELS),
"Tamano_tumor": _bin(row.get("size_mm"), prep.SIZE_CUTS, prep.SIZE_LABELS),
"Grado_histologico": {"G1": "1", "G2": "2", "G3": "3"}.get(row.get("grade")),
"Receptor_estrogeno": POSITIVE.get(row.get("er")),
"Receptor_progesterona": POSITIVE.get(row.get("pr")),
"HER2": HER2.get(row.get("her2")),
}
return {k: v for k, v in found.items() if v is not None}
def matching(scenarios: list[dict], covariates: dict[str, str]) -> list[dict]:
"""The scenarios whose every condition her covariates meet, the larger first within each cohort."""
met = [s for s in scenarios if all(var in covariates and covariates[var] in values for var, values in s["condiciones"].items())]
return sorted(met, key=lambda s: (s["cohorte"], -s["n"]))
+51
View File
@@ -0,0 +1,51 @@
"""The recurrence analysis' data: each cohort's patients (`cohort.recode`) as one table, the covariates as categories with
the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped, as in
`01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
@dataclass(frozen=True, eq=False)
class Prepared:
cohort: pd.DataFrame # paciente, tiempo_meses, evento and the covariates
covariates: list[str]
treatment: list[str]
eliminated: list[str]
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
k = min(table.shape) - 1
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[str], v_max: float) -> tuple[list[str], list[str]]:
"""Of each pair of non-treatment covariates with V at or above `v_max`, the one with more unknowns goes."""
covariates, eliminated = list(covariates), []
candidates = [c for c in covariates if c not in treatment]
pairs = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]), reverse=True)
for v, a, b in pairs:
if v < v_max:
break
if a in eliminated or b in eliminated:
continue
drop = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
eliminated.append(drop)
covariates.remove(drop)
return covariates, eliminated
def finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
covariates = [c for c in out.columns if c not in fixed]
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
+3
View File
@@ -0,0 +1,3 @@
from models.cama.seer_survival.pipeline import main
main()
+104
View File
@@ -0,0 +1,104 @@
"""Stage 02a, balancing: the 18-month outcome and an informed undersampling of the majority class.
The patients with a complete record and a known outcome are placed in MCA space (the multiple correspondence analysis
of their categorical columns); every patient of the minority class (death) is kept, with the same number of survivors
closest to them. Each public function is a Hamilton node and each parameter is the node of that name; the inputs are
`depurated_csv`, `labels_json` and `balancing` (its settings). The heavy routines live in `balancing_stats.py`; the
age and tumor categorization of the balanced cohort is `categorization.py`.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.seer_survival import balancing_stats as stats
from models.cama.seer_survival.columns import find_col
from models.cama.seer_survival.settings import BalancingSettings
MINORITY, MAJORITY = 0, 1
def depurated(depurated_csv: str) -> pd.DataFrame:
return pd.read_csv(depurated_csv, dtype=str)
def labels(labels_json: str, depurated: pd.DataFrame) -> dict:
"""Column -> its description; when there is no labels file, the column's own name."""
path = Path(labels_json)
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))
return {c: c.replace("_", " ") for c in depurated.columns}
def age_column(labels: dict, depurated: pd.DataFrame, balancing: BalancingSettings) -> str:
col = find_col(labels, balancing.age_keywords)
if col is None or col not in depurated.columns:
raise ValueError(f"No se encontró la columna de edad (palabras clave {list(balancing.age_keywords)}).")
return col
def age_order(depurated: pd.DataFrame, age_column: str) -> pd.DataFrame:
"""The age levels with a number in them, youngest first: `nivel` and `mid` (its middle)."""
return (pd.Series(depurated[age_column].dropna().unique())
.to_frame("nivel")
.assign(mid=lambda d: d["nivel"].map(stats.age_midpoint))
.dropna(subset=["mid"])
.sort_values("mid"))
def age_levels(age_order: pd.DataFrame) -> list[str]:
return age_order["nivel"].tolist()
def age_midpoints(age_order: pd.DataFrame) -> list[float]:
return age_order["mid"].tolist()
def full_frame(depurated: pd.DataFrame, age_column: str, age_levels: list[str], labels: dict,
balancing: BalancingSettings) -> pd.DataFrame:
"""The patients with an ordered age level, and their `Outcome_cat`: Sobrevive, Muerte or Desconocido."""
df = depurated[depurated[age_column].isin(age_levels)].copy()
values = stats.outcome_values(df, labels, balancing)
df["Outcome_cat"] = np.where(pd.isna(values), "Desconocido", np.where(values == 1, "Sobrevive", "Muerte"))
return df
def categorical_columns(full_frame: pd.DataFrame) -> list[str]:
return [c for c in full_frame.columns if c.endswith("_cat") and c != "Outcome_cat"]
def valid_members(full_frame: pd.DataFrame, categorical_columns: list[str], age_column: str) -> pd.Series:
"""Patients with every categorical column and the age filled in, and a known outcome: the same subset for both
MCA variants."""
complete = full_frame[categorical_columns + [age_column]].notna().all(axis=1)
return complete & (full_frame["Outcome_cat"] != "Desconocido")
def valid_frame(full_frame: pd.DataFrame, valid_members: pd.Series) -> pd.DataFrame:
return full_frame[valid_members].reset_index(drop=True)
def survives(valid_frame: pd.DataFrame) -> np.ndarray:
"""1 survives, 0 dies, per valid patient."""
return (valid_frame["Outcome_cat"] == "Sobrevive").astype(int).values
def mca(valid_frame: pd.DataFrame, categorical_columns: list[str], age_column: str,
balancing: BalancingSettings) -> stats.Mca:
"""The MCA of the chosen variant: `con_edad` also takes the age level as a column, `sin_edad` does not."""
columns = categorical_columns + ([age_column] if balancing.mca_variant == "con_edad" else [])
return stats.fit_mca(valid_frame[columns], n_components=balancing.n_components)
def keep_mask(mca: stats.Mca, survives: np.ndarray, balancing: BalancingSettings) -> np.ndarray:
"""Per valid patient: kept by the undersampling (every death, and the survivors nearest to them)."""
mask, _ = stats.select_informed_undersample(
mca.F, survives, minority_label=MINORITY, majority_label=MAJORITY, target_ratio=balancing.target_ratio,
dims=balancing.distance_dims or None)
return mask
def balanced_frame(valid_frame: pd.DataFrame, keep_mask: np.ndarray) -> pd.DataFrame:
return valid_frame[keep_mask].reset_index(drop=True)
@@ -0,0 +1,109 @@
"""The heavy routines of the balancing stage, apart from its Hamilton nodes (`balancing.py`): the outcome definition,
multiple correspondence analysis (MCA) and the informed undersampling of the majority class around the minority one.
Plain functions with no I/O. Ported from `02_balanceo_categorizacion.py`."""
import re
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.spatial import cKDTree
from models.cama.seer_survival.columns import find_col
from models.cama.seer_survival.settings import BalancingSettings
@dataclass(frozen=True, eq=False)
class Mca:
F: np.ndarray # row coordinates, one row per patient
G: np.ndarray # category coordinates
eigenvalues: np.ndarray
inertia_explained: np.ndarray
contributions: pd.DataFrame
def age_midpoint(v) -> float:
"""The middle of an age level: "40-44" -> 42, "85+" -> 90, "05" -> 5; NaN when it has no number."""
if not isinstance(v, str):
return np.nan
s = v.strip()
m = re.match(r"^(\d+)\s*-\s*(\d+)", s)
if m:
return (int(m.group(1)) + int(m.group(2))) / 2
m = re.match(r"^(\d+)\s*\+", s)
if m:
return int(m.group(1)) + 5
m = re.match(r"^(\d+)", s)
return float(m.group(1)) if m else np.nan
def outcome_values(df: pd.DataFrame, labels: dict, s: BalancingSettings) -> np.ndarray:
"""1.0 survives the horizon, 0.0 dies before it, NaN unknown. With `censura_excluida`, a patient alive with less
follow-up than the horizon is unknown, and so is every patient of a diagnosis year with too much censoring."""
if "outcome" in df.columns:
return df["outcome"].astype(float).values
surv_col = find_col(labels, ["survival months"], exclude=["flag"])
assert surv_col is not None, "No se encontró la columna de meses de supervivencia."
vital_col = find_col(labels, ["vital status"])
year_col = find_col(labels, ["year of diagnosis", "year of dx"])
surv = pd.to_numeric(df[surv_col], errors="coerce")
ge = surv >= s.horizon_months
dead = df[vital_col].astype(str).str.lower().str.contains("dead") if vital_col is not None and vital_col in df.columns else None
original = np.where(surv.notna(), ge.astype(float), np.nan)
if not (s.outcome_mode == "censura_excluida" and dead is not None):
return original
values = np.where(surv.isna(), np.nan, np.where(ge, 1.0, np.where(dead, 0.0, np.nan)))
if s.exclude_censored_years and year_col is not None and year_col in df.columns:
censored = surv.notna() & (~ge) & (~dead)
pct = censored.groupby(df[year_col]).mean() * 100
years = sorted(pct[pct > s.censoring_max_pct].index.tolist())
if years:
values = np.where(df[year_col].isin(years), np.nan, values)
return values
def fit_mca(df_cat: pd.DataFrame, n_components: int = 10) -> Mca:
"""MCA of a frame of categorical columns, by the SVD of the standardized residuals of its indicator matrix."""
Z = pd.get_dummies(df_cat, prefix_sep="__").astype(float)
n, J = Z.shape
Q = df_cat.shape[1]
P = Z.values / (n * Q)
r = P.sum(axis=1)
c = P.sum(axis=0)
Dr_inv_sqrt = 1.0 / np.sqrt(r)
Dc_inv_sqrt = 1.0 / np.sqrt(c)
S = Dr_inv_sqrt[:, None] * (P - np.outer(r, c)) * Dc_inv_sqrt[None, :]
U, sigma, Vt = np.linalg.svd(S, full_matrices=False)
V = Vt.T
K = min(n_components, len(sigma))
U, sigma, V = U[:, :K], sigma[:K], V[:, :K]
F = Dr_inv_sqrt[:, None] * U * sigma[None, :]
G = Dc_inv_sqrt[:, None] * V * sigma[None, :]
eigenvalues = sigma ** 2
inertia_total = ((P - np.outer(r, c)) ** 2 / np.outer(r, c)).sum()
contrib = (c[:, None] * G ** 2) / eigenvalues[None, :]
return Mca(F, G, eigenvalues, eigenvalues / inertia_total,
pd.DataFrame(contrib, index=Z.columns, columns=[f"Dim{k + 1}" for k in range(K)]))
def select_informed_undersample(F: np.ndarray, outcome: np.ndarray, minority_label: int, majority_label: int,
target_ratio: float = 1.0, dims: int | None = None) -> tuple[np.ndarray, np.ndarray]:
"""(keep mask, distance to the nearest minority patient): every minority patient and the `target_ratio` x minority
majority patients closest to the minority in MCA space."""
if dims is not None:
F = F[:, :dims]
mask_min = outcome == minority_label
dist, _ = cKDTree(F[mask_min]).query(F, k=1)
mask_maj = outcome == majority_label
n_keep_maj = int(round(mask_min.sum() * target_ratio))
maj_idx = np.where(mask_maj)[0]
order = np.argsort(dist[maj_idx])
keep_mask = mask_min.copy()
keep_mask[maj_idx[order[:n_keep_maj]]] = True
return keep_mask, dist
+26
View File
@@ -0,0 +1,26 @@
"""Stage 03, bootstrapping: the row indices of each resample of the balanced frame, fixed once so every model stage
resamples the same rows. Hamilton nodes; the inputs are `balanced_csv` and `bootstrap` (its settings)."""
import numpy as np
import pandas as pd
from models.cama.seer_survival.settings import BootstrapSettings
def balanced_rows(balanced_csv: str) -> int:
"""The balanced frame's number of rows (only the first column is read)."""
return len(pd.read_csv(balanced_csv, dtype=str, usecols=[0]))
def bootstrap_indices(balanced_rows: int, bootstrap: BootstrapSettings) -> np.ndarray:
"""`(n_bootstrap, rows)` indices drawn with replacement, reproducible from `random_state`."""
rng = np.random.default_rng(bootstrap.random_state)
out = np.empty((bootstrap.n_bootstrap, balanced_rows), dtype=np.int64)
for b in range(bootstrap.n_bootstrap):
out[b] = rng.integers(0, balanced_rows, size=balanced_rows)
return out
def bootstrap_metadata(balanced_csv: str, balanced_rows: int, bootstrap: BootstrapSettings) -> dict:
return {"source_csv": balanced_csv, "n_filas": int(balanced_rows), "n_bootstrap": int(bootstrap.n_bootstrap),
"random_state": int(bootstrap.random_state)}
+216
View File
@@ -0,0 +1,216 @@
"""Stage 02b, categorization: groups the balanced cohort's age and tumor size into ordinal groups where the patients'
composition changes, and proposes alternatives (other covariate blocks, fixed clinical cuts, quantiles).
Each public function is a Hamilton node and each parameter is the node of that name; it continues `balancing.py`
(`balanced_frame`, `valid_frame`, `keep_mask`, `labels`, `age_column`, `age_levels`, `age_midpoints`) and takes
`categorization` (its settings) as an input. The segmentation itself is in `categorization_stats.py`.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from matplotlib.figure import Figure
from models.cama.seer_survival import categorization_stats as stats
from models.cama.seer_survival.columns import find_col
from models.cama.seer_survival.settings import CategorizationSettings
AGE_GROUP, TUMOR_GROUP, TUMOR_BIN = "Age_group", "Tumor_group", "Tumor_bin"
@dataclass(frozen=True, eq=False)
class CutDiagnostics:
"""What the final cuts of an axis do: sensitivity/specificity per cut, the overlap of deaths and survivors, and
their distribution along the axis."""
table: pd.DataFrame
overlap: float
figure: Figure
@dataclass(frozen=True, eq=False)
class Proposals:
table: pd.DataFrame # row_id and one `<Age|Tumor>_group__<proposal>` column per proposal and axis
summary: pd.DataFrame
def min_segment_size(balanced_frame: pd.DataFrame, categorization: CategorizationSettings) -> int:
"""The smallest segment, as a share of the balanced cohort."""
return max(categorization.min_n_floor, round(categorization.min_n_pct * len(balanced_frame)))
# ---------------------------------------------------------------- age
def age_axis(balanced_frame: pd.DataFrame, age_column: str, age_levels: list[str],
age_midpoints: list[float]) -> stats.Axis:
return stats.Axis.of(balanced_frame, age_column, age_levels, age_midpoints, "corte_edad")
def age_configurations(balanced_frame: pd.DataFrame, age_axis: stats.Axis, labels: dict,
categorization: CategorizationSettings,
min_segment_size: int) -> dict[str, stats.Segmentation]:
"""The segmentation of age under every combination of covariate blocks."""
s = categorization
blocks = {"outcome": ["Outcome"], "biología": list(s.biology), "tratamiento": list(s.treatment),
"demográfico": list(s.demographic)}
return stats.segment_configurations(balanced_frame, age_axis, blocks, labels, s, min_segment_size)
def age_comparison(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis) -> pd.DataFrame:
return stats.comparison_table(age_configurations, age_axis)
def age_group_map(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis,
categorization: CategorizationSettings) -> dict[str, str]:
"""Each age level -> its group, by the final configuration's segments."""
return stats.level_to_group(age_configurations[categorization.age_final].segments, list(age_axis.levels))
def age_grouped(balanced_frame: pd.DataFrame, age_column: str, age_group_map: dict[str, str]) -> pd.DataFrame:
df = balanced_frame.copy()
df[AGE_GROUP] = df[age_column].map(age_group_map)
return df
# ---------------------------------------------------------------- tumor size
def tumor_raw_column(labels: dict, balanced_frame: pd.DataFrame) -> str:
col = find_col(labels, ["tumor size"])
if col is None or col not in balanced_frame.columns:
raise ValueError("No se encontró la columna cruda del tamaño tumoral.")
return col
def tumor_binned(age_grouped: pd.DataFrame, tumor_raw_column: str,
categorization: CategorizationSettings) -> pd.DataFrame:
"""The frame with the tumor size in mm (`tumor_mm`) and its ordinal level (`Tumor_bin`)."""
s = categorization
df = age_grouped.copy()
df["tumor_mm"] = df[tumor_raw_column].map(stats.tumor_size_mm)
df[TUMOR_BIN] = df["tumor_mm"].map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
return df
def tumor_axis(tumor_binned: pd.DataFrame, categorization: CategorizationSettings) -> stats.Axis:
levels, mids = stats.tumor_levels(categorization.bin_width_mm, categorization.tumor_cap_mm)
return stats.Axis.of(tumor_binned, TUMOR_BIN, levels, mids, "corte_mm")
def tumor_configurations(tumor_binned: pd.DataFrame, tumor_axis: stats.Axis, labels: dict,
categorization: CategorizationSettings,
min_segment_size: int) -> dict[str, stats.Segmentation]:
"""The segmentation of tumor size under every combination of blocks; age (`Age_group`) is one more block."""
s = categorization
blocks = {"outcome": ["Outcome"], "biología": [b for b in s.biology if b != "Tamano_tumor"],
"tratamiento": list(s.treatment), "demográfico": list(s.demographic), "edad": [AGE_GROUP]}
return stats.segment_configurations(tumor_binned, tumor_axis, blocks, labels, s, min_segment_size,
direct=(AGE_GROUP,))
def tumor_comparison(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis) -> pd.DataFrame:
return stats.comparison_table(tumor_configurations, tumor_axis)
def tumor_group_map(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis,
categorization: CategorizationSettings) -> dict[str, str]:
return stats.level_to_group(tumor_configurations[categorization.tumor_final].segments, list(tumor_axis.levels))
def categorized(tumor_binned: pd.DataFrame, tumor_group_map: dict[str, str]) -> pd.DataFrame:
"""The balanced cohort with `Age_group` and `Tumor_group`."""
df = tumor_binned.copy()
df[TUMOR_GROUP] = df[TUMOR_BIN].map(tumor_group_map)
return df
def balanced_final(categorized: pd.DataFrame, categorization: CategorizationSettings) -> pd.DataFrame:
"""The preprocessing's final file, read by bootstrapping and modelling: the recoded tumor size is dropped, since
`Tumor_group` carries it."""
assert TUMOR_GROUP in categorized.columns, "Falta Tumor_group"
return categorized.drop(columns=[c for c in categorization.drop_after if c in categorized.columns])
# ---------------------------------------------------------------- diagnostics of the final cuts
def _distribution_figure(df: pd.DataFrame, axis: stats.Axis, known: pd.Series, bounds: list[int], overlap: float,
xlabel: str, title: str) -> Figure:
fig = Figure(figsize=(11, 3.5))
ax = fig.subplots()
for label, color in [("Sobrevive", "steelblue"), ("Muerte", "indianred")]:
sub = df.loc[known & (df["Outcome_cat"] == label), axis.column]
counts = np.array([(sub == l).sum() for l in axis.levels], dtype=float)
ax.plot(axis.mids, counts / max(counts.sum(), 1), marker="o", ms=3, label=label, color=color)
for b in bounds:
ax.axvline((axis.mids[b - 1] + axis.mids[b]) / 2, color="black", lw=1.5, ls="--")
ax.set_xlabel(xlabel)
ax.set_ylabel("proporción dentro del grupo")
ax.set_title(f"{title} (OVL={overlap:.3f}, líneas = cortes finales)", fontsize=10)
ax.legend()
fig.tight_layout()
return fig
def age_diagnostics(categorized: pd.DataFrame, age_axis: stats.Axis, age_configurations: dict,
categorization: CategorizationSettings) -> CutDiagnostics:
bounds = age_configurations[categorization.age_final].bounds
table, overlap, known = stats.sens_spec_table(categorized, age_axis, bounds)
return CutDiagnostics(table, overlap, _distribution_figure(
categorized, age_axis, known, bounds, overlap, "Edad (punto medio del nivel)", "Distribución de edad por desenlace"))
def tumor_diagnostics(categorized: pd.DataFrame, tumor_axis: stats.Axis, tumor_configurations: dict,
categorization: CategorizationSettings) -> CutDiagnostics:
bounds = tumor_configurations[categorization.tumor_final].bounds
table, overlap, known = stats.sens_spec_table(categorized, tumor_axis, bounds)
return CutDiagnostics(table, overlap, _distribution_figure(
categorized, tumor_axis, known, bounds, overlap, "Tamaño tumoral en mm (punto medio del nivel)",
"Distribución de tamaño tumoral por desenlace"))
# ---------------------------------------------------------------- proposals and the natural population
def proposals(categorized: pd.DataFrame, age_column: str, age_axis: stats.Axis, tumor_axis: stats.Axis,
age_configurations: dict, tumor_configurations: dict, categorization: CategorizationSettings) -> Proposals:
"""Each proposal fixes how age and tumor size are grouped; the modelling stage runs every one and compares them."""
s = categorization
table = pd.DataFrame({"row_id": np.arange(len(categorized))})
rows = []
axes = [("edad", "age", "Age_group", age_column, age_axis, age_configurations, list(s.clinical_age), 0.0),
("tumor", "tumor", "Tumor_group", TUMOR_BIN, tumor_axis, tumor_configurations, list(s.clinical_tumor), 0.5)]
for pid, spec in s.proposals.items():
for eje, key, col_base, col_level, axis, configs, clinical, shift in axes:
try:
segs = stats.resolve_segments(spec[key], axis, configs, clinical, shift, s.k_quantiles)
except KeyError:
continue
levels = list(axis.levels)
mapping = stats.level_to_group(segs, levels)
col = f"{col_base}__{pid}"
table[col] = categorized[col_level].map(mapping).values
# mutually exclusive (each level in one group) and exhaustive (every level covered)
assert sorted(t for a, b in segs for t in range(a, b)) == list(range(len(levels))), \
f"{pid}/{eje}: segmentos no particionan el eje"
order = list(dict.fromkeys(mapping.values()))
rows.append({"propuesta": pid, "eje": eje, "especificación": spec[key], "K": table[col].nunique(),
"grupos": " | ".join(order),
"n_por_grupo": table[col].value_counts().reindex(order).dropna().astype(int).tolist(),
"filas_sin_grupo": int(table[col].isna().sum())})
return Proposals(table, pd.DataFrame(rows))
def natural_population(valid_frame: pd.DataFrame, keep_mask: np.ndarray, age_column: str, age_group_map: dict,
tumor_raw_column: str, tumor_group_map: dict, balanced_final: pd.DataFrame,
categorization: CategorizationSettings) -> pd.DataFrame:
"""Every patient with a known outcome (before the undersampling), grouped like the final file, with `en_balanceado`
= 1 where the undersampling kept them. For the AUC diagnosis; no stage consumes it."""
s = categorization
df = valid_frame.copy()
df["en_balanceado"] = np.asarray(keep_mask).astype(int)
df[AGE_GROUP] = df[age_column].map(age_group_map)
df[TUMOR_GROUP] = (df[tumor_raw_column].map(stats.tumor_size_mm)
.map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
.map(tumor_group_map))
df = df.drop(columns=[c for c in s.drop_after if c in df.columns])
assert int(df["en_balanceado"].sum()) == len(balanced_final), "El balanceado y la población natural no coinciden"
return df
@@ -0,0 +1,361 @@
"""The heavy routines of the categorization stage, apart from its Hamilton nodes (`categorization.py`): the Bayesian
change-point segmentation of an ordinal axis (age, tumor size), the choice of segments, the effect sizes across
boundaries, the overlap and sensitivity/specificity of a cut, and the fixed and quantile cuts. Plain functions with no
I/O. Ported from `02_balanceo_categorizacion.py`.
An ordinal axis is cut into contiguous segments where the composition of the covariates changes. The marginal
likelihood of each segment is a Dirichlet-multinomial per covariate; the best segmentation for K segments is a dynamic
programme over those segment scores; K is the largest whose smallest boundary effect (mean total variation between
neighbouring segments) reaches `threshold`; segments under `min_n` patients are merged into a neighbour.
"""
import itertools
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.special import gammaln
from models.cama.seer_survival.columns import resolve_column
from models.cama.seer_survival.settings import CategorizationSettings
@dataclass(frozen=True, eq=False)
class Axis:
"""An ordinal axis: the column holding the level, the levels (low to high), their middles and the patients per level."""
column: str
levels: tuple[str, ...]
mids: tuple[float, ...]
n_per_level: np.ndarray
cut_name: str # name of the cut's column in the tables: "corte_edad", "corte_mm"
@property
def m(self) -> int:
return len(self.levels)
@classmethod
def of(cls, df: pd.DataFrame, column: str, levels, mids, cut_name: str) -> "Axis":
return cls(column, tuple(levels), tuple(mids), np.array([int((df[column] == l).sum()) for l in levels]),
cut_name)
@dataclass(frozen=True, eq=False)
class Segmentation:
covariate_cols: dict
counts: dict
segments: list[tuple[int, int]]
bounds: list[int]
merge_log: list[str]
effect_sizes: pd.DataFrame
# ---------------------------------------------------------------- segmentation
def build_counts(df, axis_col, levels, covariate_cols, min_count=0) -> dict:
"""Per covariate, the level x category table of counts; categories under `min_count` are dropped when two remain."""
counts = {}
for name, col in covariate_cols.items():
tab = pd.crosstab(df[axis_col], df[col]).reindex(index=levels).fillna(0)
if min_count > 0:
keep = tab.sum(axis=0) >= min_count
if keep.sum() >= 2:
tab = tab.loc[:, keep]
if tab.shape[1] >= 2:
counts[name] = tab
return counts
def cumulative_counts(counts: dict) -> dict:
return {c: np.vstack([np.zeros((1, t.shape[1])), np.cumsum(t.values.astype(float), axis=0)])
for c, t in counts.items()}
def segment_logml(cum, u, v, alpha=1.0) -> float:
"""Log marginal likelihood of levels [u, v) forming one segment, summed over the covariates."""
total = 0.0
for c, cm in cum.items():
cj = cm[v] - cm[u]
J = len(cj)
N = cj.sum()
total += (gammaln(J * alpha) - gammaln(N + J * alpha) + (gammaln(cj + alpha) - gammaln(alpha)).sum())
return total
def precompute_segments(cum, m, alpha=1.0) -> np.ndarray:
S = np.full((m + 1, m + 1), -np.inf)
for u in range(m):
for v in range(u + 1, m + 1):
S[u, v] = segment_logml(cum, u, v, alpha)
return S
def best_segmentation(S, m, K):
"""(boundaries, log score) of the best segmentation into K segments."""
V = np.full((K + 1, m + 1), -np.inf)
back = np.zeros((K + 1, m + 1), dtype=int)
V[1, 1:] = S[0, 1:]
for k in range(2, K + 1):
for v in range(k, m + 1):
cand = V[k - 1, k - 1:v] + S[k - 1:v, v]
j = int(np.argmax(cand))
V[k, v] = cand[j]
back[k, v] = k - 1 + j
bounds, v = [], m
for k in range(K, 1, -1):
u = back[k, v]
bounds.append(int(u))
v = u
return sorted(bounds), V[K, m]
def compute_effect(counts, seg_a, seg_b) -> float:
"""Mean over covariates of the total variation between the category mix of two segments."""
tvs = []
for c, tab in counts.items():
mat = tab.values.astype(float)
p = mat[seg_a[0]:seg_a[1]].sum(axis=0)
p = p / max(p.sum(), 1)
q = mat[seg_b[0]:seg_b[1]].sum(axis=0)
q = q / max(q.sum(), 1)
tvs.append(0.5 * np.abs(p - q).sum())
return float(np.mean(tvs))
def choose_K_by_magnitude(S, counts, m, threshold, kmax):
"""(K, boundaries) of the largest K up to `kmax` whose smallest boundary effect is >= `threshold`; (1, []) if none."""
best_K, best_bounds = 1, []
for K in range(2, kmax + 1):
bounds, _ = best_segmentation(S, m, K)
segs = list(zip([0] + bounds, bounds + [m]))
effects = [compute_effect(counts, segs[i], segs[i + 1]) for i in range(len(segs) - 1)]
if min(effects) >= threshold:
best_K, best_bounds = K, bounds
return best_K, best_bounds
def fix_small_segments(counts, n_per_level, bounds, m, min_n):
"""Merges each segment under `min_n` patients into the neighbour whose mix differs least; (segments, log)."""
segments = list(zip([0] + bounds, bounds + [m]))
log = []
while len(segments) > 1:
sizes = [n_per_level[a:b].sum() for a, b in segments]
below = [i for i, s in enumerate(sizes) if s < min_n]
if not below:
break
i = below[0]
effects = [compute_effect(counts, segments[k], segments[k + 1]) for k in range(len(segments) - 1)]
if i == 0:
j = 0
elif i == len(segments) - 1:
j = i - 1
else:
j = i - 1 if effects[i - 1] <= effects[i] else i
log.append(f" Fusionando por tamaño insuficiente: segmentos {j} y {j + 1} (n={sizes[i]:.0f} < {min_n})")
segments = segments[:j] + [(segments[j][0], segments[j + 1][1])] + segments[j + 2:]
return segments, log
def boundary_effect_sizes(counts, bounds, m, levels) -> pd.DataFrame:
"""One row per boundary: between which levels, the mean and max change, and the covariate that changes most."""
segs = list(zip([0] + list(bounds), list(bounds) + [m]))
rows = []
for i in range(len(segs) - 1):
(u1, v1), (u2, v2) = segs[i], segs[i + 1]
tvs = {}
for c, tab in counts.items():
mat = tab.values.astype(float)
p = mat[u1:v1].sum(axis=0)
p = p / max(p.sum(), 1)
q = mat[u2:v2].sum(axis=0)
q = q / max(q.sum(), 1)
tvs[c] = 0.5 * np.abs(p - q).sum()
rows.append({"entre": f"{levels[v1 - 1]} | {levels[v1]}",
"cambio_medio": float(np.mean(list(tvs.values()))),
"cambio_max": float(np.max(list(tvs.values()))),
"covariable_que_mas_cambia": max(tvs, key=tvs.get)})
return pd.DataFrame(rows)
def segment(df: pd.DataFrame, axis: Axis, use_list, labels: dict, s: CategorizationSettings, min_n: int,
direct=()) -> Segmentation:
"""Segments `axis` by the composition of the covariates in `use_list` over the frame's patients."""
cols = {}
for name in use_list:
col = resolve_column(df, name, labels, s.candidate_keywords, direct)
if col is not None and col in df.columns:
cols[name] = col
counts = build_counts(df, axis.column, list(axis.levels), cols, min_count=s.min_count)
S = precompute_segments(cumulative_counts(counts), axis.m, alpha=s.alpha)
_, b1 = choose_K_by_magnitude(S, counts, axis.m, threshold=s.threshold, kmax=s.kmax)
segments, log = fix_small_segments(counts, axis.n_per_level, b1, axis.m, min_n=min_n)
bounds = [seg[1] for seg in segments[:-1]]
return Segmentation(cols, counts, segments, bounds, log,
boundary_effect_sizes(counts, bounds, axis.m, list(axis.levels)))
def configurations(blocks: dict) -> dict[str, list[str]]:
"""Every non-empty combination of the blocks: "Solo outcome", "Outcome + biología", ... -> its covariates."""
out = {}
for r in range(1, len(blocks) + 1):
for combo in itertools.combinations(blocks, r):
label = f"Solo {combo[0]}" if r == 1 else " + ".join(combo)
out[label[0].upper() + label[1:]] = sum((blocks[b] for b in combo), [])
return out
def segment_configurations(df, axis, blocks, labels, s, min_n, direct=()) -> dict[str, Segmentation]:
return {label: segment(df, axis, use, labels, s, min_n, direct) for label, use in configurations(blocks).items()}
# ---------------------------------------------------------------- tables and cuts
def _cut(axis: Axis, b: int) -> float:
return round((axis.mids[b - 1] + axis.mids[b]) / 2, 1)
def boundary_table(result: Segmentation, label: str, axis: Axis) -> pd.DataFrame:
cols = ["configuración", axis.cut_name, "entre_niveles", "n_izquierda", "n_derecha", "cambio_medio"]
if not result.bounds:
return pd.DataFrame(columns=cols)
effect = result.effect_sizes.reset_index(drop=True)
rows = []
for i, b in enumerate(result.bounds):
segs = result.segments
rows.append({"configuración": label, axis.cut_name: _cut(axis, b),
"entre_niveles": f"{axis.levels[b - 1]} | {axis.levels[b]}",
"n_izquierda": int(axis.n_per_level[segs[i][0]:segs[i][1]].sum()),
"n_derecha": int(axis.n_per_level[segs[i + 1][0]:segs[i + 1][1]].sum()),
"cambio_medio": round(float(effect.loc[i, "cambio_medio"]), 3)})
return pd.DataFrame(rows, columns=cols)
def segmentation_summary(result: Segmentation, label: str, axis: Axis) -> dict:
groups = [f"{axis.levels[a]} a {axis.levels[b - 1]}" if b - a > 1 else axis.levels[a] for a, b in result.segments]
sizes = [int(axis.n_per_level[a:b].sum()) for a, b in result.segments]
effects = result.effect_sizes["cambio_medio"].tolist() if len(result.bounds) else []
return {"configuración": label, "n_covariables": len(result.covariate_cols),
"K (nº de grupos)": len(result.segments), axis.cut_name.replace("corte_", "cortes_"):
boundary_table(result, label, axis)[axis.cut_name].tolist(),
"grupos": " | ".join(groups), "n por grupo": sizes,
"efecto mín.": round(min(effects), 3) if effects else None,
"efecto máx.": round(max(effects), 3) if effects else None}
def comparison_table(results: dict[str, Segmentation], axis: Axis) -> pd.DataFrame:
return pd.DataFrame([segmentation_summary(r, label, axis) for label, r in results.items()])
def level_to_group(segments, levels) -> dict[str, str]:
"""Each level -> the label of its segment: the level itself, or "first a last"."""
out = {}
for a, b in segments:
label = levels[a] if b - a == 1 else f"{levels[a]} a {levels[b - 1]}"
for t in range(a, b):
out[levels[t]] = label
return out
def overlap_coefficient(values_a: pd.Series, values_b: pd.Series, levels) -> float:
"""Overlap of the level distributions of two groups (1 = identical, 0 = disjoint)."""
pa = np.array([(values_a == l).sum() for l in levels], dtype=float)
pb = np.array([(values_b == l).sum() for l in levels], dtype=float)
pa = pa / max(pa.sum(), 1)
pb = pb / max(pb.sum(), 1)
return float(np.minimum(pa, pb).sum())
def sens_spec_at_cut(level_index: np.ndarray, is_death: np.ndarray, b: int) -> dict:
"""Sensitivity and specificity of calling "high risk" the side of boundary `b` with the higher death rate."""
high = level_index >= b
rate_high = is_death[high].mean() if high.any() else np.nan
rate_low = is_death[~high].mean() if (~high).any() else np.nan
high_is_positive = rate_high >= rate_low
positive = high if high_is_positive else ~high
tp = int((positive & is_death).sum())
fn = int((~positive & is_death).sum())
tn = int((~positive & ~is_death).sum())
fp = int((positive & ~is_death).sum())
sens = tp / (tp + fn) if (tp + fn) else np.nan
spec = tn / (tn + fp) if (tn + fp) else np.nan
return {"lado_alto_riesgo": "arriba del corte" if high_is_positive else "abajo del corte",
"tasa_muerte_abajo": round(float(rate_low), 3) if pd.notna(rate_low) else np.nan,
"tasa_muerte_arriba": round(float(rate_high), 3) if pd.notna(rate_high) else np.nan,
"sensibilidad": round(sens, 3) if pd.notna(sens) else np.nan,
"especificidad": round(spec, 3) if pd.notna(spec) else np.nan}
def sens_spec_table(df: pd.DataFrame, axis: Axis, bounds: list[int]) -> tuple[pd.DataFrame, float, pd.Series]:
"""(table by final cut, overlap coefficient of deaths vs survivors, mask of the patients used): the patients with a
known outcome and a level on the axis."""
known = (df["Outcome_cat"] != "Desconocido") & df[axis.column].notna()
is_death = (df.loc[known, "Outcome_cat"] == "Muerte").to_numpy()
pos = {l: i for i, l in enumerate(axis.levels)}
idx = df.loc[known, axis.column].map(pos).to_numpy()
ovl = overlap_coefficient(df.loc[known & (df["Outcome_cat"] == "Muerte"), axis.column],
df.loc[known & (df["Outcome_cat"] == "Sobrevive"), axis.column], axis.levels)
cols = [axis.cut_name, "entre_niveles", "tasa_muerte_abajo", "tasa_muerte_arriba", "lado_alto_riesgo",
"sensibilidad", "especificidad"]
rows = []
for b in bounds:
r = sens_spec_at_cut(idx, is_death, b)
r[axis.cut_name] = _cut(axis, b)
r["entre_niveles"] = f"{axis.levels[b - 1]} | {axis.levels[b]}"
rows.append(r)
return (pd.DataFrame(rows)[cols] if rows else pd.DataFrame(columns=cols)), ovl, known
def tumor_size_mm(v) -> float:
"""A tumor size in mm from SEER's code: 1..899 is the size; 0, 9xx and anything else is unknown."""
import re
if not isinstance(v, str):
return np.nan
s = v.strip()
if not re.match(r"^\d{1,3}$", s):
return np.nan
mm = int(s)
if mm == 0 or mm >= 900:
return np.nan
return float(mm)
def tumor_bin_label(mm: float, width: int, cap: int):
if pd.isna(mm):
return np.nan
if mm > cap:
return f">{cap} mm"
lo = int((mm - 1) // width) * width + 1
return f"{lo:03d}-{lo + width - 1:03d} mm"
def tumor_levels(width: int, cap: int) -> tuple[list[str], list[float]]:
"""The ordinal levels of tumor size ("001-005 mm", ..., ">100 mm") and their middles."""
n_bins = cap // width
levels = [f"{1 + i * width:03d}-{(i + 1) * width:03d} mm" for i in range(n_bins)] + [f">{cap} mm"]
mids = [1 + i * width + (width - 1) / 2 for i in range(n_bins)] + [cap + width / 2]
return levels, mids
# ---------------------------------------------------------------- proposals
def segments_from_bounds(bounds, n_levels) -> list[tuple[int, int]]:
cuts = [0] + sorted(set(int(b) for b in bounds if 0 < b < n_levels)) + [n_levels]
return list(zip(cuts[:-1], cuts[1:]))
def quantile_bounds(n_per_level, K) -> list[int]:
cum = np.cumsum(n_per_level)
tot = cum[-1]
return sorted({int(np.searchsorted(cum, tot * q)) + 1 for q in np.linspace(0, 1, K + 1)[1:-1]})
def resolve_segments(spec: str, axis: Axis, configs: dict[str, Segmentation], clinical: list, shift: float,
k_quantiles: int) -> list[tuple[int, int]]:
"""The segments a proposal's spec means on an axis: fixed clinical cuts, quantiles, or a configuration's own."""
if spec == "clinico":
return segments_from_bounds([int(np.searchsorted(axis.mids, thr + shift)) for thr in clinical], axis.m)
if spec == "cuantiles":
return segments_from_bounds(quantile_bounds(axis.n_per_level, k_quantiles), axis.m)
if spec not in configs:
raise KeyError(f"configuración '{spec}' no existe")
return configs[spec].segments
+26
View File
@@ -0,0 +1,26 @@
"""Finding a covariate's column: by its recoded `<name>_cat` column or, failing that, by keywords in the column's label.
Plain functions shared by the balancing and categorization stages (not Hamilton nodes)."""
import pandas as pd
def find_col(labels: dict, keywords, exclude=()) -> str | None:
"""The first column whose lower-cased label has any of `keywords` and none of `exclude`."""
for col, desc in labels.items():
d = str(desc).lower()
if any(k in d for k in keywords) and not any(e in d for e in exclude):
return col
return None
def resolve_column(df: pd.DataFrame, name: str, labels: dict, candidate_keywords: dict, direct=()) -> str | None:
"""`<name>_cat` if the frame has it, a `direct` name that is itself a column (e.g. `Age_group`), else the column
found by the covariate's keywords; None when there is none."""
if name in direct:
return name if name in df.columns else None
cat_col = f"{name}_cat"
if cat_col in df.columns:
return cat_col
kw = candidate_keywords.get(name, {"include": [], "exclude": []})
col = find_col(labels, kw["include"], kw["exclude"])
return col if col in df.columns else None
+89
View File
@@ -0,0 +1,89 @@
"""Stage 01, depuration: drops the redundant categorical variables of the recoded SEER frame.
A removes duplicates (Theil's U both ways), B derived variables (U one way) and C nested ones (GVIF); the thresholds
are calibrated from the data and reported. Each public function is a Hamilton node and each parameter is the node of
that name; the inputs are `recoded_csv`, `mapping_json`, `depuration` (its settings) and `generated_at`. The heavy
statistics live in `depuration_stats.py`; `run.py` holds the driver and writes the files.
"""
import json
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.cama.seer_survival import depuration_stats as stats
from models.cama.seer_survival.settings import DepurationSettings
@dataclass(frozen=True)
class Elimination:
dropped: pd.DataFrame # variable, paso, motivo, a_favor_de
kept: tuple[str, ...]
raw_sources: tuple[str, ...] # raw SEER columns of the dropped variables, dropped with them
def recoded(recoded_csv: str) -> pd.DataFrame:
return pd.read_csv(recoded_csv, dtype=str)
def column_map(mapping_json: str) -> dict:
"""Recoded variable -> its raw SEER column; empty when the file isn't there."""
path = Path(mapping_json)
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
def analysis_frame(recoded: pd.DataFrame, depuration: DepurationSettings) -> pd.DataFrame:
"""The `_cat` columns (and the project's groupings) with unknowns labelled, minus those with a single value."""
s = depuration
cols = [c for c in recoded.columns if c.endswith("_cat") and c not in s.exclude]
for c in (*s.auto_extra, *s.extra_cols):
if c in recoded.columns and c not in cols and c not in s.exclude:
cols.append(c)
frame = recoded[cols].fillna(s.unknown_label)
return frame[[c for c in cols if frame[c].nunique() >= 2]]
def analysis_columns(analysis_frame: pd.DataFrame) -> list[str]:
return list(analysis_frame.columns)
def calibration(analysis_frame: pd.DataFrame, analysis_columns: list[str], depuration: DepurationSettings,
generated_at: str) -> stats.Calibration:
"""Suggested thresholds and how stable the elimination is to them. Reports only: it changes nothing."""
return stats.calibrate(analysis_frame, analysis_columns, depuration, generated_at)
def thresholds(calibration: stats.Calibration, depuration: DepurationSettings) -> stats.Thresholds:
return stats.thresholds_in_use(calibration, depuration)
def calibration_report(calibration: stats.Calibration, thresholds: stats.Thresholds) -> dict:
"""The calibration's JSON report, with the thresholds the elimination used."""
return {**calibration.report, "umbrales_en_uso": {
"DUP_U": thresholds.dup_u, "U_REDUND": thresholds.u_redund, "GVIF_DROP": thresholds.gvif_drop,
"CLUSTER_METODO": thresholds.cluster_method, "CLUSTER_CORTE": thresholds.cluster_cut,
"PAR_R_MIN": thresholds.pair_r_min, "AUTO": bool(thresholds.auto)}}
def elimination(analysis_frame: pd.DataFrame, analysis_columns: list[str], thresholds: stats.Thresholds,
depuration: DepurationSettings, recoded: pd.DataFrame, column_map: dict) -> Elimination:
dropped = stats.eliminate(analysis_frame, analysis_columns, thresholds, depuration)
names = list(dropped["variable"])
kept = tuple(c for c in analysis_columns if c not in names)
raw = ()
if depuration.drop_raw_sources:
raw = tuple(column_map[v] for v in names if v in column_map and column_map[v] in recoded.columns)
return Elimination(dropped, kept, raw)
def depurated(recoded: pd.DataFrame, elimination: Elimination) -> pd.DataFrame:
"""The recoded frame without the dropped variables and their raw columns."""
return recoded.drop(columns=[*elimination.dropped["variable"], *elimination.raw_sources])
def kept_variables(elimination: Elimination, thresholds: stats.Thresholds, recoded_csv: str) -> dict:
return {"entrada": recoded_csv, "conservadas": list(elimination.kept),
"eliminadas": list(elimination.dropped["variable"]), "crudas_eliminadas": list(elimination.raw_sources),
"umbrales": {"DUP_U": thresholds.dup_u, "U_REDUND": thresholds.u_redund,
"GVIF_DROP": thresholds.gvif_drop}}
@@ -0,0 +1,469 @@
"""The heavy routines of the depuration stage, apart from its Hamilton nodes (`depuration.py`): Theil's U, GVIF, the
calibration of the thresholds (chance floor, natural gap, sensitivity sweeps, clustering) and the A/B/C elimination.
Plain functions with no I/O and no module state, so they run alone and on a Dask worker. Ported from
`01_depuracion.py`; the report keys keep the script's Spanish names because downstream files read them.
"""
import itertools
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import squareform
from sklearn.metrics import silhouette_score
from models.cama.seer_survival.settings import DepurationSettings
@dataclass(frozen=True)
class Thresholds:
"""The thresholds in use by the elimination (the configured ones, or the calibration's when `thresholds_auto`)."""
dup_u: float
u_redund: float
gvif_drop: float
cluster_method: str
cluster_cut: float
pair_r_min: float
auto: bool
@dataclass
class Calibration:
"""What the calibration found: its tables and report, and the suggestions the thresholds may adopt."""
pairs_u: pd.DataFrame
cluster_cut_table: pd.DataFrame # empty when the clustering could not be calibrated
report: dict
summary: list[dict]
u_suggestion: dict
dup_u_suggested: float
gvif_drop_suggested: float
cluster_method_suggested: str
config_eliminations: dict
warnings: list[str] = field(default_factory=list)
# ---------------------------------------------------------------- Theil's U and GVIF
def theil_u_matrix(d: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
"""U(row | column): the share of the row variable's entropy that the column variable explains."""
U = pd.DataFrame(np.nan, index=columns, columns=columns)
H = {}
for c in columns:
p = d[c].value_counts(normalize=True).values
H[c] = float(-(p * np.log(p)).sum())
for a, b in itertools.combinations(columns, 2):
pxy = pd.crosstab(d[a], d[b]).values.astype(float)
pxy /= pxy.sum()
nz = pxy[pxy > 0]
hxy = float(-(nz * np.log(nz)).sum())
mi = H[a] + H[b] - hxy
U.loc[a, b] = mi / H[a] if H[a] > 0 else np.nan
U.loc[b, a] = mi / H[b] if H[b] > 0 else np.nan
return U
def design(d: pd.DataFrame, columns: list[str]):
"""Indicator blocks, one per variable, dropping each one's most frequent category and constant columns."""
blocks = {}
for c in columns:
ind = pd.get_dummies(d[c], prefix=c, prefix_sep="=").astype(float)
ind = ind.drop(columns=ind.sum().idxmax())
ind = ind.loc[:, ind.std() > 0]
if ind.shape[1] > 0:
blocks[c] = ind
X = pd.concat(blocks.values(), axis=1)
return X, blocks
def gvif_table(d: pd.DataFrame, columns: list[str]):
"""(table, []) with each variable's GVIF and `GVIF^(1/2df)`; or (None, candidates) when the design is singular,
the candidates being the variables that are an exact combination of the others, fewest categories first."""
X, blocks = design(d, columns)
R = np.corrcoef(X.values, rowvar=False)
pos = {n: i for i, n in enumerate(X.columns)}
s, ld = np.linalg.slogdet(R)
if not (s > 0 and np.isfinite(ld) and ld > -30):
cand = []
for c, b in blocks.items():
others = [x for x in X.columns if x not in b.columns]
A = np.column_stack([X[others].values, np.ones(len(X))])
for x in b.columns:
y = X[x].values
coef, *_ = np.linalg.lstsq(A, y, rcond=None)
r2 = 1 - ((y - A @ coef) ** 2).sum() / ((y - y.mean()) ** 2).sum()
if r2 >= 0.9999:
cand.append((b.shape[1], c))
break
return None, sorted(cand)
rows = []
for c, b in blocks.items():
idx = [pos[n] for n in b.columns]
rest = [i for i in range(len(pos)) if i not in set(idx)]
s1, l1 = np.linalg.slogdet(R[np.ix_(idx, idx)])
s2, l2 = np.linalg.slogdet(R[np.ix_(rest, rest)]) if rest else (1, 0.0)
gv = float(np.exp(l1 + l2 - ld))
rows.append({"variable": c, "gl": len(idx), "GVIF": gv, "GVIF_ajustado": gv ** (1 / (2 * len(idx)))})
return pd.DataFrame(rows).sort_values("GVIF_ajustado", ascending=False).reset_index(drop=True), []
def _entropy(p: np.ndarray) -> float:
p = p[p > 0]
return float(-(p * np.log(p)).sum())
def info_pair(cx: np.ndarray, cy: np.ndarray, kx: int, ky: int) -> dict:
"""Entropies, mutual information and the accuracy of predicting each variable from the other, from factor codes."""
j = np.bincount(cx * ky + cy, minlength=kx * ky).reshape(kx, ky).astype(float)
n = j.sum()
px = j.sum(1) / n
py = j.sum(0) / n
hxy = _entropy((j / n).ravel())
hx, hy = _entropy(px), _entropy(py)
return dict(hx=hx, hy=hy, mi=hx + hy - hxy, acc_x_dado_y=j.max(0).sum() / n, acc_y_dado_x=j.max(1).sum() / n,
base_x=px.max(), base_y=py.max())
def loser(a: str, b: str, protected, prefer, key) -> tuple[str, str] | None:
"""(dropped, kept) of two redundant variables: a protected one is kept, then a preferred one, then the one with
more unknowns, more categories, later position (`key`). None when both are protected."""
if a in protected and b in protected:
return None
if a in protected:
return b, a
if b in protected:
return a, b
if a in prefer and b not in prefer:
return b, a
if b in prefer and a not in prefer:
return a, b
return (a, b) if key(a) > key(b) else (b, a)
# ---------------------------------------------------------------- calibration
def suggest_u(pairs_u: pd.DataFrame, chance_ceiling: float, s: DepurationSettings,
gap_from: float | None = None, gap_min: float | None = None) -> dict:
"""The U_REDUND suggestion: the natural gap among the pairs' U, floored by chance, else the conventional value."""
gap_from = s.u_gap_from if gap_from is None else gap_from
gap_min = s.u_gap_min if gap_min is None else gap_min
v = np.sort(pairs_u["U(X|Y)"].dropna().round(4).unique())[::-1]
out = {"metodo": "convencional", "brecha": None, "borde_sup": None, "borde_inf": None, "confianza": "revisar"}
best = None
for i in range(len(v) - 1):
if v[i] >= gap_from and (best is None or v[i] - v[i + 1] > best[0]):
best = (v[i] - v[i + 1], v[i], v[i + 1])
if best is not None and best[0] >= gap_min:
mid = float(np.clip((best[1] + best[2]) / 2, *s.u_plausible))
out.update(metodo="brecha natural", U=mid, brecha=round(float(best[0]), 3), borde_sup=round(float(best[1]), 3),
borde_inf=round(float(best[2]), 3), confianza="alta")
else:
out["U"] = s.u_conventional
out["motivo"] = (("no hay pares con U >= %.2f" % gap_from) if best is None
else ("la mayor brecha (%.3f) < %.2f" % (best[0], gap_min)))
floor = s.k_azar * chance_ceiling
if out["U"] < floor:
out["U"] = float(min(floor, 0.99))
out["metodo"] += " + piso por azar"
out["confianza"] = "revisar"
out["U"] = round(float(out["U"]), 2)
return out
class RedundancyScreen:
"""Steps A, B and C on one frame at any thresholds, caching U matrices and GVIF tables by the active columns.
The calibration replays the elimination many times, so it uses the fast factor-code U."""
def __init__(self, frame: pd.DataFrame, columns: list[str], codes: dict, kcat: dict, s: DepurationSettings):
self.frame, self.columns, self.codes, self.kcat, self.s = frame, columns, codes, kcat, s
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
ncat = {c: int(frame[c].nunique()) for c in columns}
order = {c: i for i, c in enumerate(columns)}
self._key = lambda c: (pct_unknown[c], ncat[c], order[c])
self._u, self._g = {}, {}
def u_matrix(self, cols_t: tuple) -> pd.DataFrame:
if cols_t not in self._u:
M = pd.DataFrame(np.nan, index=list(cols_t), columns=list(cols_t))
for a, b in itertools.combinations(cols_t, 2):
ip = info_pair(self.codes[a], self.codes[b], self.kcat[a], self.kcat[b])
M.loc[a, b] = ip["mi"] / ip["hx"] if ip["hx"] > 0 else np.nan
M.loc[b, a] = ip["mi"] / ip["hy"] if ip["hy"] > 0 else np.nan
self._u[cols_t] = M
return self._u[cols_t]
def gvif(self, cols_t: tuple):
if cols_t not in self._g:
self._g[cols_t] = gvif_table(self.frame, list(cols_t))
return self._g[cols_t]
def run(self, dup_u: float, u_redund: float, gvif_drop: float) -> tuple[dict, list[str]]:
"""({dropped variable: step}, active variables)."""
s = self.s
active, out = list(self.columns), {}
U = self.u_matrix(tuple(active)) # A
for a, b in itertools.combinations(list(active), 2):
if a not in active or b not in active:
continue
if U.loc[a, b] >= dup_u and U.loc[b, a] >= dup_u:
r = loser(a, b, s.protected, s.prefer, self._key)
if r:
active.remove(r[0])
out[r[0]] = "A"
U = self.u_matrix(tuple(active)) # B
cand = []
for x in active:
for y in active:
if x != y and U.loc[x, y] >= u_redund and U.loc[y, x] < u_redund:
cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in active and y in active and x not in s.protected and x not in s.prefer:
active.remove(x)
out[x] = "B"
for _ in range(s.max_iter_gvif): # C
if len(active) < 3:
break
table, exact = self.gvif(tuple(active))
if table is None:
ex = [c for _, c in exact if c not in s.protected]
if not ex:
break
active.remove(ex[0])
out[ex[0]] = "C"
continue
cd = table[(table["GVIF_ajustado"] >= gvif_drop) & (~table["variable"].isin(s.protected))]
if cd.empty:
break
v = cd.iloc[0]["variable"]
active.remove(v)
out[v] = "C"
return out, active
def _labels(d: dict) -> str:
return ", ".join(f"{k} [{p}]" for k, p in sorted(d.items())) or "(nada)"
def _category_matrix(d, columns, min_n, max_cat, warnings):
X = pd.get_dummies(d[columns], prefix_sep="=", dtype=np.float32)
total = X.sum()
X = X.loc[:, (total >= min_n) & (total <= len(X) - min_n)]
if X.shape[1] > max_cat:
X = X[X.sum().sort_values(ascending=False).index[:max_cat]]
warnings.append(f"demasiadas categorías para el clustering: se usan las {max_cat} más frecuentes.")
return X
def calibrate(frame: pd.DataFrame, columns: list[str], s: DepurationSettings, generated_at: str) -> Calibration:
"""Suggests the thresholds from the data (chance floor and natural gap of U, GVIF margin, clustering linkage and
cut) and reports how stable the elimination is to them. It never changes the frame."""
rng = np.random.default_rng(s.seed)
warnings: list[str] = []
report = {"fecha": generated_at, "advertencias": warnings, "parametros": {
"NULL_PERM": s.null_perm, "K_AZAR": s.k_azar, "U_CONVENCIONAL": s.u_conventional, "U_GAP_DESDE": s.u_gap_from,
"U_GAP_MIN_BRECHA": s.u_gap_min, "U_RANGO_PLAUSIBLE": list(s.u_plausible), "VIF_CORTE": s.vif_cut,
"R_GRANDE": s.r_large, "MIN_N_CAT": s.min_n_cat, "SEMILLA": s.seed}}
if len(columns) < 2:
raise ValueError("La calibración necesita al menos 2 variables categóricas.")
df_cal = frame if len(frame) <= s.n_max_cal else frame.sample(s.n_max_cal, random_state=s.seed)
codes = {c: pd.factorize(df_cal[c])[0] for c in columns}
kcat = {c: int(df_cal[c].nunique()) for c in columns}
n_cal = len(df_cal)
median_cells = float(np.median([n_cal / (kcat[a] * kcat[b]) for a, b in itertools.combinations(columns, 2)]))
if n_cal < 1000:
warnings.append(f"n pequeño ({n_cal}): U está sesgado hacia arriba; el piso por azar lo compensa, pero interpreta con cautela.")
if median_cells < 5:
warnings.append(f"tablas de contingencia dispersas (mediana {median_cells:.1f} pacientes/celda < 5): U se infla; confía más en el piso por azar que en el valor absoluto.")
if len(columns) < 4:
warnings.append("pocas variables (< 4): el GVIF y la brecha natural son poco informativos.")
if max(kcat.values()) > 30:
warnings.append(f"variable con {max(kcat.values())} categorías: considera agruparlas antes de depurar.")
report["datos"] = {"n": int(len(frame)), "n_calibracion": int(n_cal), "n_variables": len(columns),
"categorias_por_variable": kcat, "pacientes_por_celda_mediana": median_cells}
# 1. U of Theil: pairs, accuracy and chance floor
rows, ceiling = [], []
for a, b in itertools.combinations(columns, 2):
ip = info_pair(codes[a], codes[b], kcat[a], kcat[b])
mi_null = np.array([info_pair(codes[a], rng.permutation(codes[b]), kcat[a], kcat[b])["mi"]
for _ in range(s.null_perm)])
for x, y, hx, acc, base in [(a, b, ip["hx"], ip["acc_x_dado_y"], ip["base_x"]),
(b, a, ip["hy"], ip["acc_y_dado_x"], ip["base_y"])]:
u = ip["mi"] / hx if hx > 0 else np.nan
u_null = mi_null.max() / hx if hx > 0 else np.nan
rows.append({"X": x, "dado_Y": y, "U(X|Y)": u, "U_azar_max": u_null,
"exactitud_X_desde_Y": acc, "exactitud_base_X": base})
ceiling.append(u_null)
pairs_u = pd.DataFrame(rows).sort_values("U(X|Y)", ascending=False).reset_index(drop=True)
pairs_u["brecha_al_siguiente"] = pairs_u["U(X|Y)"] - pairs_u["U(X|Y)"].shift(-1)
chance_ceiling = float(np.nanmax(ceiling))
u_sug = suggest_u(pairs_u, chance_ceiling, s)
# 2. Sensitivity: which variables go when each threshold moves
screen = RedundancyScreen(df_cal, columns, codes, kcat, s)
check = theil_u_matrix(df_cal, columns)
fast = screen.u_matrix(tuple(columns))
assert np.allclose(check.values.astype(float), fast.loc[columns, columns].values.astype(float),
equal_nan=True, atol=1e-9), "U rápida != theil_u_matrix"
base_out, base_act = screen.run(s.dup_u, s.u_redund, s.gvif_drop)
dup_sug = round(min(max(0.90, u_sug["U"] + 0.05), 0.99), 2)
out_sug, _ = screen.run(dup_sug, u_sug["U"], s.gvif_drop)
same = set(out_sug) == set(base_out)
u_sug["misma_decision_que_config"] = bool(same)
if not same and u_sug["confianza"] == "alta":
u_sug["confianza"] = "revisar"
if not same:
warnings.append("los umbrales sugeridos producen un conjunto distinto de variables eliminadas: revisa los barridos A-C antes de aplicarlos.")
# D) the gap rule's parameters are conventions: does changing them change the suggestion or what is dropped?
gap_rows = []
for gd in s.gap_from_grid:
for gm in s.gap_min_grid:
sg = suggest_u(pairs_u, chance_ceiling, s, gd, gm)
dup_s = round(min(max(0.90, sg["U"] + 0.05), 0.99), 2)
o, _ = screen.run(dup_s, sg["U"], s.gvif_drop)
gap_rows.append({"U_GAP_DESDE": gd, "U_GAP_MIN_BRECHA": gm, "U_REDUND sugerido": sg["U"],
"método": sg["metodo"], "misma decisión": set(o) == set(base_out),
"elimina [regla]": _labels(o)})
sens_gap = pd.DataFrame(gap_rows)
different = sens_gap[~sens_gap["misma decisión"]]
if len(different):
warnings.append(f"la decisión depende de U_GAP_DESDE / U_GAP_MIN_BRECHA en {len(different)} de {len(sens_gap)} combinaciones: son convenciones; revisa el barrido D antes de fijar el umbral.")
report["sensibilidad_regla_brecha"] = {
"grilla_U_GAP_DESDE": list(s.gap_from_grid), "grilla_U_GAP_MIN_BRECHA": list(s.gap_min_grid),
"proporcion_misma_decision": float(sens_gap["misma decisión"].mean()),
"U_sugerido_min": float(sens_gap["U_REDUND sugerido"].min()),
"U_sugerido_max": float(sens_gap["U_REDUND sugerido"].max())}
# 3. GVIF: margin to the threshold
gvif_drop_sug = round(float(np.sqrt(s.vif_cut)), 2)
tab_k, _ = screen.gvif(tuple(base_act))
margin = None
if tab_k is not None and len(tab_k):
tab_k = tab_k.copy()
tab_k["margen_al_umbral"] = s.gvif_drop - tab_k["GVIF_ajustado"]
margin = float(tab_k["margen_al_umbral"].min())
if margin < 0.15:
warnings.append("alguna variable conservada está muy cerca del umbral de GVIF: la decisión es sensible al corte.")
# 4. Clustering: linkage (cophenetic) and cut (Cohen)
min_n_eff = s.min_n_cat
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
if X.shape[1] < 6:
min_n_eff = max(5, int(0.005 * n_cal))
X = _category_matrix(df_cal, columns, min_n_eff, s.max_cat_cluster, warnings)
warnings.append(f"muy pocas categorías con >= {s.min_n_cat} pacientes: se baja el mínimo a {min_n_eff} para el clustering.")
cluster_ok = X.shape[1] >= 4
method_sug, coph, cut_table = s.cluster_method, {}, pd.DataFrame()
if not cluster_ok:
warnings.append("no hay suficientes categorías para calibrar el clustering; se mantienen los valores por convención.")
else:
names = list(X.columns)
var = np.array([c.split("=", 1)[0] for c in names])
V = X.values.astype(np.float32)
V -= V.mean(0)
cov = V.T @ V
sd = np.sqrt(np.diag(cov))
R = (cov / np.outer(sd, sd)).astype(float)
D = 1 - R if s.cluster_dist == "signed" else 1 - np.abs(R)
D = np.clip((D + D.T) / 2, 0, None)
np.fill_diagonal(D, 0)
cond = squareform(D, checks=False)
for m in ["single", "complete", "average", "weighted"]:
coph[m] = float(cophenet(linkage(cond, method=m), cond)[0])
method_sug = max(coph, key=coph.get)
Zc = linkage(cond, method=method_sug)
rows = []
for t in np.round(np.arange(0.30, 1.01, 0.05), 2):
lab = fcluster(Zc, t=float(t), criterion="distance")
ng = len(set(lab))
multi = sum(1 for g in set(lab) if len(set(var[lab == g])) >= 2)
sil = float(silhouette_score(D, lab, metric="precomputed")) if 2 <= ng <= len(lab) - 1 else np.nan
rows.append({"corte (dist.)": t, "r medio exigido": round(1 - t, 2), "n_grupos": ng,
"grupos_multivariable": multi, "silueta": round(sil, 3) if sil == sil else np.nan})
cut_table = pd.DataFrame(rows)
summary = [
{"parámetro": "U_REDUND", "configurado": s.u_redund, "sugerido": u_sug["U"], "criterio": u_sug["metodo"],
"confianza": u_sug["confianza"]},
{"parámetro": "DUP_U", "configurado": s.dup_u, "sugerido": dup_sug, "criterio": "max(0.90, U_REDUND+0.05)",
"confianza": u_sug["confianza"]},
{"parámetro": "GVIF_DROP", "configurado": s.gvif_drop, "sugerido": gvif_drop_sug,
"criterio": f"sqrt(VIF {s.vif_cut}) (R2={1 - 1 / s.vif_cut:.2f})",
"confianza": "alta" if (margin is None or margin >= 0.15) else "revisar"},
{"parámetro": "CLUSTER_METODO", "configurado": s.cluster_method, "sugerido": method_sug,
"criterio": "máx. correlación cofenética", "confianza": "alta" if cluster_ok else "revisar"},
{"parámetro": "CLUSTER_CORTE", "configurado": round(1 - s.r_large, 2), "sugerido": round(1 - s.r_large, 2),
"criterio": f"Cohen: r medio >= {s.r_large}", "confianza": "alta"},
{"parámetro": "PAR_R_MIN", "configurado": s.r_large, "sugerido": s.r_large, "criterio": "Cohen: efecto grande",
"confianza": "alta"}]
report.update({"piso_azar_U": chance_ceiling, "sugerencia_U": u_sug, "resumen": summary,
"eliminadas_con_config": base_out, "correlacion_cofenetica": coph})
return Calibration(pairs_u, cut_table, report, summary, u_sug, dup_sug, gvif_drop_sug, method_sug, base_out,
warnings)
def thresholds_in_use(c: Calibration, s: DepurationSettings) -> Thresholds:
"""The configured thresholds, or the calibration's suggestions when `thresholds_auto`."""
cut, r_min = round(1 - s.r_large, 2), s.r_large
if s.thresholds_auto:
return Thresholds(c.dup_u_suggested, c.u_suggestion["U"], c.gvif_drop_suggested, c.cluster_method_suggested,
cut, r_min, True)
return Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, cut, r_min, False)
# ---------------------------------------------------------------- elimination (steps A, B, C on the full frame)
def eliminate(frame: pd.DataFrame, columns: list[str], t: Thresholds, s: DepurationSettings) -> pd.DataFrame:
"""The dropped variables, one row each: `variable`, `paso`, `motivo`, `a_favor_de`. A removes duplicates (U both
ways >= dup_u), B derived variables (U one way only >= u_redund), C the nested ones by GVIF."""
active = list(columns)
dropped: list[dict] = []
pct_unknown = {c: float((frame[c] == s.unknown_label).mean()) for c in columns}
ncat = {c: int(frame[c].nunique()) for c in columns}
order = {c: i for i, c in enumerate(columns)}
key = lambda c: (pct_unknown[c], ncat[c], order[c]) # noqa: E731
def drop(var, step, reason, favor):
active.remove(var)
dropped.append({"variable": var, "paso": step, "motivo": reason, "a_favor_de": favor})
U = theil_u_matrix(frame, active) # A
for a, b in itertools.combinations(list(active), 2):
if a not in active or b not in active:
continue
if U.loc[a, b] >= t.dup_u and U.loc[b, a] >= t.dup_u:
r = loser(a, b, s.protected, s.prefer, key)
if r:
drop(r[0], "A duplicada", f"U({a}|{b})={U.loc[a, b]:.2f}, U({b}|{a})={U.loc[b, a]:.2f}", r[1])
U = theil_u_matrix(frame, active) # B
cand = []
for x in active:
for y in active:
if x != y and U.loc[x, y] >= t.u_redund and U.loc[y, x] < t.u_redund:
cand.append((U.loc[x, y], x, y))
for u, x, y in sorted(cand, reverse=True):
if x in active and y in active and x not in s.protected and x not in s.prefer:
drop(x, "B derivada", f"U({x}|{y})={u:.2f} vs U({y}|{x})={U.loc[y, x]:.2f}", y)
for _ in range(s.max_iter_gvif): # C
if len(active) < 3:
break
table, exact = gvif_table(frame, active)
if table is None:
exact = [c for _, c in exact if c not in s.protected]
if not exact:
break
drop(exact[0], "C anidada exacta", "combinación exacta de otras variables", "(el resto)")
continue
cd = table[(table["GVIF_ajustado"] >= t.gvif_drop) & (~table["variable"].isin(s.protected))]
if cd.empty:
break
v = cd.iloc[0]
drop(v["variable"], "C GVIF", f"GVIF ajustado={v['GVIF_ajustado']:.2f} >= {t.gvif_drop}", "(el resto)")
return pd.DataFrame(dropped, columns=["variable", "paso", "motivo", "a_favor_de"])
@@ -0,0 +1,202 @@
"""Survival curves by the classic and the fractional (Kilbas-Saigo) Weibull, and Kaplan-Meier, apart from the stage's
nodes (`survival_curves.py`). Plain functions with no I/O. Ported from `05_curvas_supervivencia.py`.
The fractional Weibull's survival function is a Kilbas-Saigo (Mittag-Leffler type) series, summed in floating point
where that is safe and with arbitrary-precision `mpmath` where the terms get large. Both models are fitted by maximum
likelihood on monthly counts of events and censorings (`tabla_eventos`), by Nelder-Mead from several starting points.
"""
import time
from functools import lru_cache
import numpy as np
from scipy.optimize import minimize
from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
for i in range(N - 1):
c.append(c[-1] * mp.exp(mp.loggamma(rho * (m * i + l) + 1) - mp.loggamma(rho * (m * i + l + 1) + 1)))
return tuple(c)
def _log_terms(az, rho, m, l, N):
i = np.arange(N - 1)
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * i + l) + 1) - gammaln(rho * (m * i + l + 1) + 1))])
n = np.arange(N)
with np.errstate(divide="ignore"):
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
return lt
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
"""The Kilbas-Saigo function E_{rho,m,l}(z) at each `z`: the plain series when its terms stay small, else a polynomial
in `mpmath` with as many digits as the largest term needs; NaN where even that is out of reach."""
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
z = np.atleast_1d(np.asarray(z, float))
rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
az = np.abs(z)
N = 400
lt = _log_terms(az, rho, m, l, N)
lmax, llast = lt.max(axis=1), lt[:, -1]
zero = az == 0
out[zero] = 1.0
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
if okf.any():
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
terms[:, 0] = 1.0
out[okf] = terms.sum(axis=1)
rest = np.where(~zero & ~okf)[0]
if rest.size:
with np.errstate(over="ignore"):
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
est = np.maximum(est, lmax[rest])
use = rest[est <= logmax_cap]
if use.size:
est_u = est[est <= logmax_cap]
dps = 30 + int(est_u.max() / 2.3) + 10
zmax = float(az[use].max())
with np.errstate(over="ignore"):
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
N2 = max(N2, 60)
while True:
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
mp.mp.dps = dps
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
if last < tol or N2 >= nmax:
break
N2 *= 2
if last < tol:
cr = list(c)[::-1]
for j in use:
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
return out
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
"""The fractional Weibull's survival function at `t`; NaN outside its parameter region."""
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full_like(t, np.nan)
m = s / beta + 1
l = s / beta
pref = float(mp.exp(mp.loggamma(k + 1) - mp.loggamma(k + alpha - 1)))
with np.errstate(divide="ignore", invalid="ignore"):
z = -pref * (t / lam) ** k * (t / tau1) ** (alpha - 1) * (t / tau2) ** (beta - 1)
z = np.where(t > 0, z, 0.0)
res = np.ones_like(t)
pos = t > 0
if pos.any():
res[pos] = kilbas_saigo(z[pos], beta, m, l)
return np.clip(res, 0.0, 1.0)
def S_weibull(t, k, lam):
t = np.asarray(t, float)
return np.exp(-(t / lam) ** k)
def tabla_eventos(meses, evento):
"""Per month: the events and the censorings."""
meses = np.asarray(meses, int)
evento = np.asarray(evento, bool)
T = int(meses.max()) + 2
return np.bincount(meses[evento], minlength=T), np.bincount(meses[~evento], minlength=T)
def _nll_from_S(Sfun, d, c):
T = len(d)
Sg = Sfun(np.arange(0, T + 1, dtype=float))
mid = Sfun(np.arange(T) + 0.5)
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
return 1e12 # invalid region / not computable
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def ajustar_weibull(d, c) -> dict:
"""The classic Weibull's maximum likelihood: `k`, `lam`, its negative log-likelihood and its survival function `S`."""
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c) # noqa: E731
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50., 200., 1000.):
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
if best is None or r.fun < best.fun:
best = r
k, lam = np.exp(best.x)
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
S=lambda t: S_weibull(t, k, lam))
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120) -> dict:
"""The fractional Weibull's maximum likelihood with `k` fixed. It starts from the point that reproduces the classic
Weibull, so the fractional one is never worse; `max_seg` caps the seconds spent."""
amin = max(0.0, 1.0 - k_fijo) + 1e-6
def unpack(p):
return amin + np.exp(p[0]), 1 / (1 + np.exp(-p[1])), np.exp(p[2])
T_max = float(len(d))
t_fin = time.time() + max_seg
def f(p):
if time.time() > t_fin:
return 1e12
a, b, lam = unpack(p)
# penalizes degenerate regions (|z| huge in the last month -> costly, unstable series)
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
return 1e12
try:
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
except Exception:
return 1e12
lams = [lam_ref] if lam_ref else []
lams += [100., 500.]
best = None
starts = []
if lam_ref:
starts.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
for l0 in lams:
for a0 in (0.3, 1.0):
for b0 in (0.5, 0.9):
starts.append([np.log(a0), np.log(b0 / (1 - b0)), np.log(l0)])
for p0 in starts:
if time.time() > t_fin and best is not None:
break
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
if best is None or r.fun < best.fun:
best = r
a, b, lam = unpack(best.x)
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
S=lambda t: S_ks(t, k_fijo, a, b, lam))
def km_curva(meses_int, evento, T):
"""(S, lower, upper) of Kaplan-Meier for months 0..T, with the Greenwood 95 % interval on the log-log scale."""
d, c = tabla_eventos(meses_int, evento)
L = max(len(d), T + 1)
d = np.pad(d, (0, L - len(d)))
c = np.pad(c, (0, L - len(c)))
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
with np.errstate(divide="ignore", invalid="ignore"):
se = np.sqrt(V) / np.abs(np.log(S))
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
return S, lo, hi
+130
View File
@@ -0,0 +1,130 @@
"""The hybrid Bayesian network (HBN) of the modeling stage, apart from its nodes (`modeling.py`): structure learning by
hill climbing with bootstrap restarts, a BDeu score and temporal tiers as forbidden arcs; a greedy expansion of the
outcome's parents; the fit and the survival probability of each test row. Plain functions with no I/O. Ported from
`04_modelado.py` (phase 5).
Reproducibility: pgmpy's hill climbing breaks score ties by the iteration order of sets of column names, which depends on
Python's per-process string hashing. Two runs of the same data can learn slightly different networks (the script
behaves the same way) unless `PYTHONHASHSEED` is fixed; with it fixed, the port and the script agree exactly.
Only the categorical path is ported: the script's discretization of continuous variables (L_DVBN) never runs while
`AGE_IS_NUMERIC` and `TUMORSIZE_IS_NUMERIC` are false, which is how the pipeline uses SEER's grouped age and tumor size.
"""
import numpy as np
import pandas as pd
from pgmpy.causal_discovery import ExpertKnowledge
from pgmpy.estimators import BDeu, HillClimbSearch
from pgmpy.inference import VariableElimination
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.parameter_estimator import DiscreteBayesianEstimator
from models.cama.seer_survival.settings import ModelingSettings
OUTCOME = "outcome"
def temporal_order(available: list[str], s: ModelingSettings) -> list[list[str]]:
"""Tiers, earliest first: demography, tumor, treatment, outcome. An arc may not point to an earlier tier. Columns
in no tier go first, unrestricted."""
tiers = []
for tier in [s.tier_demography, s.tier_tumor, s.tier_treatment, [OUTCOME]]:
present = [c for c in tier if c in available]
if present:
tiers.append(present)
classified = {c for t in tiers for c in t}
unclassified = [c for c in available if c not in classified]
if unclassified:
tiers.insert(0, unclassified)
return tiers
def hill_climb_with_restarts(data: pd.DataFrame, tiers: list[list[str]], ess: int, n_restarts: int,
max_indegree: int = 4, random_state: int = 0):
"""(edges, score): hill climbing on `n_restarts` bootstrap resamples (shuffling the column order adds no variability
in this pgmpy), each candidate structure scored on the WHOLE data, keeping the best."""
best_score, best_edges = -np.inf, None
scorer = BDeu(data, equivalent_sample_size=ess)
expert = ExpertKnowledge(temporal_order=tiers)
for i in range(n_restarts):
boot = data.sample(n=len(data), replace=True, random_state=random_state + i)
structure = HillClimbSearch(boot).estimate(
scoring_method=BDeu(boot, equivalent_sample_size=ess), max_indegree=max_indegree,
expert_knowledge=expert, show_progress=False)
score = scorer.score(structure)
if score > best_score:
best_score, best_edges = score, list(structure.edges())
return best_edges, best_score
def expand_outcome_parents(edges: list[tuple], bn_train: pd.DataFrame, bn_cols: list[str], ess: int,
max_parents: int) -> list[tuple]:
"""The outcome becomes a terminal node (diagnosis and treatment precede it), then gains parents greedily by the gain
of its local BDeu score: with all the evidence observed its prediction depends only on its parents, and the global
score may not add them even when they would help THAT prediction."""
edges = [(u, v) for (u, v) in edges if u != OUTCOME]
parents = [u for (u, v) in edges if v == OUTCOME]
others = [(u, v) for (u, v) in edges if v != OUTCOME]
score = BDeu(bn_train, equivalent_sample_size=ess).local_score(OUTCOME, parents)
candidates = [c for c in bn_cols if c != OUTCOME and c not in parents]
improved = True
while improved and len(parents) < max_parents and candidates:
improved = False
best_gain, best = 0, None
for cand in candidates:
# the score object caches the data it is built on: one new frame and scorer per evaluation
trial = bn_train[parents + [OUTCOME]].copy()
trial[cand] = bn_train[cand].values
gain = BDeu(trial, equivalent_sample_size=ess).local_score(OUTCOME, parents + [cand]) - score
if gain > best_gain:
best_gain, best = gain, cand
if best is not None:
parents.append(best)
candidates.remove(best)
score += best_gain
improved = True
return others + [(p, OUTCOME) for p in parents]
def fit_network(edges: list[tuple], bn_train: pd.DataFrame) -> DiscreteBayesianNetwork:
model = DiscreteBayesianNetwork(edges)
model.fit(bn_train, estimator=DiscreteBayesianEstimator(prior_type="BDeu"))
return model
def predict_survival(model: DiscreteBayesianNetwork, bn_test: pd.DataFrame) -> list[float]:
"""P(outcome = 1 | the row's other columns) by variable elimination; NaN where the query fails."""
infer = VariableElimination(model)
evidence_cols = [c for c in bn_test.columns if c != OUTCOME]
preds = []
for _, row in bn_test.iterrows():
evidence = {k: v for k, v in row[evidence_cols].to_dict().items() if k in model.nodes()}
try:
q = infer.query(variables=[OUTCOME], evidence=evidence, show_progress=False)
preds.append(q.values[list(q.state_names[OUTCOME]).index("1")])
except Exception:
preds.append(np.nan)
return preds
def learn_structure(bn_train: pd.DataFrame, bn_cols: list[str], s: ModelingSettings, n_restarts: int,
random_state: int) -> list[tuple]:
"""The arcs: hill climbing with restarts, then the outcome's expanded parents."""
tiers = temporal_order(list(bn_cols), s)
edges, _ = hill_climb_with_restarts(bn_train, tiers, s.bdeu_ess, n_restarts, s.max_indegree, random_state)
return expand_outcome_parents(edges, bn_train, bn_cols, s.bdeu_ess, s.max_outcome_parents)
def arc_strength(model: DiscreteBayesianNetwork, bn_train: pd.DataFrame, ess: int) -> pd.DataFrame:
"""The change of the network's score when an arc is REMOVED, the rest fixed (bnlearn's `arc.strength`): very negative
= strong arc, near 0 = adds little, positive = removing it would even improve the score."""
scorer = BDeu(bn_train, equivalent_sample_size=ess)
rows = []
for (u, v) in model.edges():
parents = [p for (p, c) in model.edges() if c == v]
with_arc = scorer.local_score(v, parents)
without = scorer.local_score(v, [p for p in parents if p != u])
rows.append({"desde": u, "hacia": v, "delta_al_quitar": without - with_arc})
out = pd.DataFrame(rows).sort_values("delta_al_quitar").reset_index(drop=True)
out["delta_al_quitar"] = out["delta_al_quitar"].round(1)
return out
+95
View File
@@ -0,0 +1,95 @@
"""Logistic regression with stepwise selection, apart from the modeling nodes (`modeling.py`): a univariate chi-square
pre-filter, the stepwise search on a stratified subsample and the safe fit. Plain functions with no I/O. Ported from
`04_modelado.py` (phases 3-4)."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import chi2_contingency
from sklearn.model_selection import train_test_split
def univariate_prefilter(X: pd.DataFrame, y: pd.Series, alpha: float = 0.10) -> list[tuple]:
"""(column, p, chi2) of the columns whose chi-square against the outcome has p < alpha."""
kept = []
for col in X.columns:
table = pd.crosstab(X[col], y)
if table.shape[0] < 2 or table.shape[1] < 2:
continue # no variation: nothing to add
try:
chi2_stat, p, _, _ = chi2_contingency(table)
except ValueError:
continue
if p < alpha:
kept.append((col, p, chi2_stat))
return kept
def prefiltered_columns(X: pd.DataFrame, y: pd.Series, alpha: float, max_candidates: int,
always_sort: bool = True) -> list[str]:
"""The pre-filter's columns, at most `max_candidates` and strongest first (by chi-square: with big samples many
p-values are exactly 0.0 and can't order them). The main fit only sorts when it must cut; the others always do."""
kept = univariate_prefilter(X, y, alpha=alpha)
if always_sort or len(kept) > max_candidates:
kept = sorted(kept, key=lambda t: t[2], reverse=True)
return [c for c, _, _ in kept[:max_candidates]]
def safe_fit_logit(y, X_sub, maxiter: int = 200):
"""A BFGS logit; a lightly L2-regularized one if that fails; None if both do."""
try:
return sm.Logit(y, X_sub).fit(disp=0, method="bfgs", maxiter=maxiter)
except Exception:
try:
return sm.Logit(y, X_sub).fit_regularized(disp=0, alpha=0.01, maxiter=maxiter)
except Exception:
return None
def stepwise_selection(X: pd.DataFrame, y: pd.Series, alpha_in: float = 0.10, alpha_out: float = 0.15) -> list[str]:
"""Forward step (the candidate with the lowest p below `alpha_in`), then a backward step (the worst above `alpha_out`),
until nothing changes."""
included, excluded = [], list(X.columns)
while True:
changed = False
best_pval, best_feature = np.inf, None
for col in excluded:
model = safe_fit_logit(y, sm.add_constant(X[included + [col]]))
if model is None or col not in model.pvalues:
continue
pval = model.pvalues[col]
if pval < best_pval:
best_pval, best_feature = pval, col
if best_feature is not None and best_pval < alpha_in:
included.append(best_feature)
excluded.remove(best_feature)
changed = True
if included:
model = safe_fit_logit(y, sm.add_constant(X[included]))
if model is not None:
pvals = model.pvalues.drop("const", errors="ignore")
if len(pvals) > 0 and pvals.max() > alpha_out:
worst = pvals.idxmax()
included.remove(worst)
excluded.append(worst)
changed = True
if not changed:
break
return included
def search_sample(X_train: pd.DataFrame, y_train: pd.Series, columns: list[str], max_rows: int, random_state: int):
"""The stepwise searches on a subsample stratified by outcome (more than enough to decide which variables matter);
the final model is refitted on the whole train."""
if X_train.shape[0] > max_rows:
idx, _ = train_test_split(X_train.index, train_size=max_rows, random_state=random_state, stratify=y_train)
return X_train.loc[idx, columns], y_train.loc[idx]
return X_train[columns], y_train
def encode(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
"""Dummies without the first category; the unknowns are one more category."""
enc = df.copy()
for c in columns:
enc[c] = enc[c].fillna("Desconocido").astype(str)
return enc
+624
View File
@@ -0,0 +1,624 @@
# CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs.
[depuration]
exclude = ["Outcome_cat"] # never analysed or touched
auto_extra = ["Age_group", "Tumor_group"] # included when present
extra_cols = []
protected = ["Estadio_cat", "Subtipo_molecular_cat", "Tratamiento_quirurgico_cat"] # the axes of the clinical scenarios: never dropped
prefer = ["Tumor_group", "Age_group"] # on a tie or duplicate, the one listed here wins (the project's own groupings)
drop_raw_sources = true # also drop the raw SEER column of a dropped variable
unknown_label = "Desconocido"
dup_u = 0.90 # step A
u_redund = 0.80 # step B
gvif_drop = 2.24 # step C: GVIF^(1/2df) (equals VIF 5)
max_iter_gvif = 20
# Calibration: independent of the data, only reports (thresholds_auto = true applies its suggestions)
thresholds_auto = false
n_max_cal = 300000 # more rows are calibrated on a reproducible subsample
null_perm = 100 # permutations for the chance floor of U
k_azar = 5 # U_REDUND must be >= k_azar x (max U by chance)
u_conventional = 0.80 # fallback when the data can't calibrate
u_gap_from = 0.70 # gaps whose upper edge is >= this U are searched
u_gap_min = 0.10 # minimum gap to count as "natural"
u_plausible = [0.60, 0.95] # limits of the suggested threshold
vif_cut = 5 # 5 (R2=0.80) or 10 (R2=0.90)
r_large = 0.5 # Cohen (1988): |phi| 0.1 small, 0.3 medium, 0.5 large
min_n_cat = 30 # categories with fewer patients are left out of the clustering
max_cat_cluster = 400 # cap of columns (categories) in the clustering matrix
cluster_dist = "signed" # "signed": d = 1-r | "abs": d = 1-|r|
cluster_method = "average"
seed = 0
gap_from_grid = [0.50, 0.60, 0.70, 0.80, 0.90]
gap_min_grid = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30]
[balancing]
# The outcome is 18-month survival: "Sobrevive" (alive at the horizon), "Muerte" (dead before it), unknown otherwise.
outcome_mode = "censura_excluida" # "censura_excluida" (recommended: censored patients are unknown) | "original"
horizon_months = 18
# Diagnosis years with INCOMPLETE follow-up: when more than this % of a year's patients are censored (alive with
# < horizon), the whole year leaves the outcome. Avoids only early deaths "entering" in the cut-off years.
exclude_censored_years = true
censoring_max_pct = 10.0
age_keywords = ["age recode", "age at diagnosis", "age"]
n_components = 10
target_ratio = 1.0 # 1.0 = exact 50/50
distance_dims = 0 # 0 = all the fitted MCA dimensions
mca_variant = "con_edad" # "con_edad" | "sin_edad": the MCA that picks the majority patients kept
[categorization]
alpha = 1.0 # Dirichlet prior per category
kmax = 8 # most segments considered
threshold = 0.08 # least composition change for a boundary to count as real
min_count = 50 # categories with fewer patients are dropped from the counts
# Smallest segment, as a share of the BALANCED cohort (a fixed number would mean different things as the cohort shrinks)
min_n_pct = 0.05
min_n_floor = 50
bin_width_mm = 5 # tumor size: width of each ordinal level, analogous to the 5-year age bands
tumor_cap_mm = 100 # from here on, a single ">100 mm" level
k_quantiles = 4
clinical_age = [40, 50, 70] # years
clinical_tumor = [20, 50] # mm (T1 | T2 | T3+)
age_final = "Biología + tratamiento" # the configuration whose cuts become Age_group
tumor_final = "Outcome + biología" # the configuration whose cuts become Tumor_group
drop_after = ["Tamano_tumor_cat"] # replaced by Tumor_group in the final file: the same datum twice is collinear
biology = ["Estadio", "Grado_histologico", "Subtipo_molecular", "Receptor_estrogeno", "Receptor_progesterona",
"Metastasis", "Tamano_tumor", "Localizacion_mama", "Lateralidad", "Tipo_histologico"]
treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
demographic = ["Estado_civil", "Race"]
# Keywords (in the lower-cased column label) that find the raw column of a covariate with no recoded `_cat` column.
[categorization.candidate_keywords]
Estadio = { include = ["stage"], exclude = [] }
Grado_histologico = { include = ["grade"], exclude = [] }
Subtipo_molecular = { include = ["subtype"], exclude = [] }
Receptor_estrogeno = { include = ["er status", "estrogen"], exclude = [] }
Receptor_progesterona = { include = ["pr status", "progesterone"], exclude = [] }
Tamano_tumor = { include = ["tumor size"], exclude = [] }
Metastasis = { include = ["eod mets", "mets recode"], exclude = [] }
Localizacion_mama = { include = ["primary site"], exclude = [] }
Lateralidad = { include = ["laterality"], exclude = [] }
Tipo_histologico = { include = ["histologic"], exclude = [] }
Tratamiento_quirurgico = { include = ["surg"], exclude = [] }
Radioterapia = { include = ["radiation"], exclude = [] }
Quimioterapia = { include = ["chemo"], exclude = [] }
Estado_civil = { include = ["marital"], exclude = [] }
Race = { include = ["race"], exclude = [] }
# Categorization proposals: how age and tumor size are grouped. A value is a configuration's name (the blocks joined
# by " + ": outcome, biología, tratamiento, demográfico, and edad for the tumor axis), "clinico" (fixed cuts) or
# "cuantiles" (K groups of equal frequency, without the outcome). The modelling stage runs every proposal.
[categorization.proposals.P1_actual]
age = "Biología + tratamiento"
tumor = "Outcome + biología"
[categorization.proposals.P2_solo_outcome]
age = "Solo outcome"
tumor = "Solo outcome"
[categorization.proposals.P3_outcome_biologia]
age = "Outcome + biología"
tumor = "Outcome + biología"
[categorization.proposals.P4_outcome_bio_trat]
age = "Outcome + biología + tratamiento"
tumor = "Outcome + biología + tratamiento"
[categorization.proposals.P5_todos_los_bloques]
age = "Outcome + biología + tratamiento + demográfico"
tumor = "Outcome + biología + tratamiento + demográfico + edad"
[categorization.proposals.P6_clinico_fijo]
age = "clinico"
tumor = "clinico"
[categorization.proposals.P7_cuantiles]
age = "cuantiles"
tumor = "cuantiles"
[bootstrap]
n_bootstrap = 200
random_state = 42
[survival]
# Survival curves of the whole cohort and of subgroups: Kaplan-Meier, the classic and the fractional Weibull, and the
# 6/12/18-month survival by LR, HBN and their stacked combination, with bootstrap intervals.
age_mode = "categorizada" # how age enters the LR: "categorizada" | "continua" | "continua_cuadratica"
include_age = true # adds the grouped age (Edad_cat) when no categorical age column exists
age_cuts = [45, 60, 75]
hbn_fixed_parents = ["Estadio", "Tipo_histologico", "Tratamiento_quirurgico", "Quimioterapia", "Radioterapia"] # found by keyword; empty = learn them (BDeu)
hbn_age_parent = true # adds the grouped age as a parent of the outcome (expert knowledge; stage 04 didn't choose it)
hbn_parents = "fijos" # "fijos": learned once and kept in the bootstrap | "reaprender": searched again per replica
covariates = [] # empty = every column ending in "_cat" but the outcome
horizons = [6, 12, 18] # months where the LR and HBN points are shown
censoring = "riesgo" # "riesgo": a model per interval using all the follow-up | "ipcw" | "excluir"
combine = true # one LR + HBN indicator (per-interval stacking weights); only with censoring = "riesgo"
show_individual = false # also draws LR and HBN apart from the combination
stack_folds = 5 # cross-validation folds that decide the weights
stack_shrink = 20 # shrink toward 50/50 with few deaths: lambda = shrink / (shrink + the interval's deaths)
n_boot = 100 # bootstrap replicas for the intervals
n_boot_sub = 100 # and in the subgroups
seed = 42
hbn_ess = 1000 # equivalent sample size of the BDeu prior
hbn_max_parents = 5
k_ident = "clasico" # the fractional Weibull's fixed k: "clasico" = the classic Weibull's | or a number
curves = "ajustada" # "ajustada": KM and Weibull standardized by the same covariates | "cruda": unadjusted
adjust_step = 3 # months per interval of the adjusted curve
show_raw_km = true
ylim_main = [] # e.g. [0.94, 1.0]; empty = automatic
inset_zoom = false
inset_months = 18
cap_months = 24 # follow-up is truncated here (later deaths and follow-up count as alive / censored); 0 = no cap
min_events_sub = 5 # least deaths to fit a subgroup
ks_max_seconds = 120 # time caps of the fractional fits (the whole cohort / a subgroup)
ks_sub_max_seconds = 180
xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty = (0, extrapolation months)
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
# The clinical scenarios, in the doctors' terms: every condition must hold. A condition names a variable of the
# dictionary (`Edad`: the age in years, the start of its band) and tests `contains` (the category has this text), `in` (it
# is one of these) or, for the age, `ge` / `lt`.
[[survival.subgroups]]
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Edad", ge = 60 },
{ variable = "Estadio", in = ["III", "IV"] }
]
[[survival.subgroups]]
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Edad", lt = 60 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "Estadio IV"
conditions = [
{ variable = "Estadio", in = ["IV"] }
]
[[survival.subgroups]]
name = "Estadio I"
conditions = [
{ variable = "Estadio", in = ["I"] }
]
[[survival.subgroups]]
name = "≥ 75 años"
conditions = [
{ variable = "Edad", ge = 75 }
]
[[survival.subgroups]]
name = "< 45 años"
conditions = [
{ variable = "Edad", lt = 45 }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", lt = 45 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "HER2+ · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · estadio 0–II"
conditions = [
{ variable = "Edad", lt = 45 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2−"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", lt = 45 }
]
[[survival.subgroups]]
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
conditions = [
{ variable = "Subtipo_molecular", contains = "HR-/HER2-" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", ge = 65 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[risk_factors]
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
# crossing 1 and Benjamini-Hochberg p < alpha), c2 stability: the variable enters the LR stepwise in at least freq_min
# of the bootstrap replicas, c3 it is in the outcome's Markov blanket in the HBN, c4 the absolute survival difference at
# `horizon` months (Kaplan-Meier) against the reference category. Treatment variables are a clinical decision: they are
# not classified and don't enter c1's model; they are reported apart.
alpha = 0.05
freq_min = 0.80
horizon = 18
cap_months = 24
treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
[risk_factors.canonical_map]
Age_group = "Edad"
Tumor_group = "Tamano_tumor"
Tamano_tumor_cat = "Tamano_tumor"
Estadio_cat = "Estadio"
Grado_histologico_cat = "Grado_histologico"
Subtipo_molecular_cat = "Subtipo_molecular"
Receptor_estrogeno_cat = "Receptor_estrogeno"
Receptor_progesterona_cat = "Receptor_progesterona"
Metastasis_cat = "Metastasis"
Localizacion_mama_cat = "Localizacion_mama"
Lateralidad_cat = "Lateralidad"
Tipo_histologico_cat = "Tipo_histologico"
Tratamiento_quirurgico_cat = "Tratamiento_quirurgico"
Radioterapia_cat = "Radioterapia"
Quimioterapia_cat = "Quimioterapia"
Estado_civil_cat = "Estado_civil"
Ganglios_positivos_cat = "Ganglios_positivos"
Invasion_linfovascular_cat = "Invasion_linfovascular"
Margenes_cat = "Margenes"
Densidad_BIRADS_cat = "Densidad_BIRADS"
Masa_espiculada_cat = "Masa_espiculada"
Microcalcificaciones_cat = "Microcalcificaciones"
Multifocalidad_cat = "Multifocalidad"
BRCA_cat = "BRCA"
HER2_IHQ_cat = "HER2_IHQ"
[modeling]
random_state = 42
test_size = 0.3
prefilter_alpha = 0.10 # univariate chi-square pre-filter of the dummy columns
alpha_in = 0.10 # stepwise: enters below this p
alpha_out = 0.15 # stepwise: leaves above this p
max_candidates = 40 # hard cap of columns the stepwise receives (by chi-square, strongest first)
max_search_rows = 8000 # the stepwise searches on a stratified subsample; the final fit uses the whole train
lr_maxiter = 200
# Hybrid Bayesian network (hill climbing with restarts, BDeu score, temporal tiers as forbidden arcs)
bdeu_ess = 1000 # equivalent sample size: pure K2 (= 1) penalized complexity too hard
n_restarts = 10
max_indegree = 4
max_outcome_parents = 10 # the greedy expansion of the outcome's parents
# The covariates that enter the models, by canonical name (Age/Tumor size carry the Age_group/Tumor_group categories)
categorical_order = ["Edad", "Tamano_tumor", "Estadio", "Grado_histologico", "Subtipo_molecular", "Receptor_estrogeno",
"Receptor_progesterona", "Metastasis", "Localizacion_mama", "Lateralidad", "Tipo_histologico",
"Tratamiento_quirurgico", "Radioterapia", "Quimioterapia", "Estado_civil", "Race",
"Ganglios_positivos", "Invasion_linfovascular", "Margenes", "Densidad_BIRADS", "Masa_espiculada",
"Microcalcificaciones", "Multifocalidad", "BRCA", "HER2_IHQ"]
treatment_vars = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia"]
tier_demography = ["Edad", "Race", "Estado_civil", "BRCA", "Densidad_BIRADS"]
tier_tumor = ["Estadio", "Grado_histologico", "Tipo_histologico", "Subtipo_molecular", "Receptor_estrogeno",
"Receptor_progesterona", "Tamano_tumor", "Localizacion_mama", "Lateralidad", "Metastasis",
"CS_Lymph_Nodes", "Ganglios_positivos", "Invasion_linfovascular", "Masa_espiculada",
"Microcalcificaciones", "Multifocalidad", "HER2_IHQ"]
tier_treatment = ["Tratamiento_quirurgico", "Radioterapia", "Quimioterapia", "Margenes"]
# The natural population (every patient with a known outcome, before the undersampling)
run_lr_natural = true
natural_search_rows = 30000
natural_test_size = 0.30
natural_maxiter = 300
# Bootstrap of the whole pipeline (the indices come from stage 03)
n_bootstrap_run = 60 # max 200 (~27 s per replica with the HBN)
bootstrap_max_seconds = 2700 # safety cap: the loop stops by itself and uses what it has
bootstrap_include_hbn = true # false = LR only (much faster)
bootstrap_restarts = 3 # hill-climbing restarts PER REPLICA
# Comparison of the categorization proposals (stage 02b), on the same splits
n_splits_prop = 5
proposals_only = [] # empty = all of the file's proposals
proposals_include_hbn = true
proposals_max_seconds = 3600
# Column of the balanced file -> the canonical name the models use. Selected by the ORIGINAL name before renaming, so a
# raw SEER column that already has a canonical name is never carried along (a duplicate fails much later, inside pgmpy).
[modeling.canonical_map]
Age_group = "Edad"
Tumor_group = "Tamano_tumor"
Estadio_cat = "Estadio"
Grado_histologico_cat = "Grado_histologico"
Subtipo_molecular_cat = "Subtipo_molecular"
Receptor_estrogeno_cat = "Receptor_estrogeno"
Receptor_progesterona_cat = "Receptor_progesterona"
Metastasis_cat = "Metastasis"
Localizacion_mama_cat = "Localizacion_mama"
Lateralidad_cat = "Lateralidad"
Tipo_histologico_cat = "Tipo_histologico"
Tratamiento_quirurgico_cat = "Tratamiento_quirurgico"
Radioterapia_cat = "Radioterapia"
Quimioterapia_cat = "Quimioterapia"
Estado_civil_cat = "Estado_civil"
Outcome_cat = "Outcome_cat"
Ganglios_positivos_cat = "Ganglios_positivos"
Invasion_linfovascular_cat = "Invasion_linfovascular"
Margenes_cat = "Margenes"
Densidad_BIRADS_cat = "Densidad_BIRADS"
Masa_espiculada_cat = "Masa_espiculada"
Microcalcificaciones_cat = "Microcalcificaciones"
Multifocalidad_cat = "Multifocalidad"
BRCA_cat = "BRCA"
HER2_IHQ_cat = "HER2_IHQ"
# ----------------------------------------------------------------------------------------------------------------------
# The variable dictionary. One table per variable of the model: the column it makes, how its category is read from a
# patient's timeline (`rules`, in order, the first that holds; `missing` when none does) and, for the SEER load, where the
# SEER category is stored in CaMa's bronze (`seer`). A rule is one condition or a `when` list that must all hold; a
# condition names a timeline `source` (the `tipo` of the patient's latest event of that kind) or an earlier `variable`,
# and tests `codes` (the value is one of them), `present` (there is such an event), or `ge` / `lt` (the number).
# ----------------------------------------------------------------------------------------------------------------------
[variables]
window_days_after_index = 365 # the events from the index on that still describe the patient at diagnosis and treatment
[variables.index]
id_column = "Patient_ID"
year_column = "Year_of_diagnosis"
age_column = "Age_recode_with_1_year_olds_and_90"
age_band_years = 5
age_open_from = 90
age_label = "{low}-{high} years"
age_open_label = "{low}+ years"
age_unknown = "Otros (agrupado)"
months_column = "Survival_months"
vital_column = "Vital_status_recode_study_cutoff_used"
alive = "Alive"
dead = "Dead"
days_per_month = 30.4375
death_source = "defuncion"
birth_source = "nacimiento"
# SEER's calendar dates are not recorded: the diagnosis is the 1st of July of its year, the birth the middle of the age
# band, the death the diagnosis plus the survival months, the last contact of the living the same.
seer_diagnosis_month_day = "07-01"
seer_age_open_value = 92
[variables.Estadio]
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0 (in situ)" },
{ source = "estadio_clinico", codes = ["EI"], then = "I" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "II" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "III" },
{ source = "estadio_clinico", codes = ["EIV"], then = "IV" },
]
missing = "Desconocido"
seer = { bronze = "NotaMedica.nm_estadio_clinico", values = { "0 (in situ)" = "E0", "I" = "EI", "II" = "EIIA", "III" = "EIIIA", "IV" = "EIV" } }
[variables.Grado_histologico]
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "G1" },
{ source = "grado_nottingham", codes = ["G2"], then = "G2" },
{ source = "grado_nottingham", codes = ["G3"], then = "G3" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_grado_nottingham", values = { "G1" = "G1", "G2" = "G2", "G3" = "G3" } }
[variables.Receptor_estrogeno]
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positivo" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negativo" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_receptor_estrogeno", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
[variables.Receptor_progesterona]
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positivo" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negativo" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_receptor_progesterona", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
# HER2 is positive or negative by the FISH when there is one, else by the immunohistochemistry (3+ positive, 0 and 1+
# negative, 2+ equivocal).
[variables.HER2_estado]
internal = true
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positivo" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negativo" },
{ source = "her2", codes = ["H3"], then = "Positivo" },
{ source = "her2", codes = ["H0", "H1"], then = "Negativo" },
]
missing = "Desconocido"
seer = { from = "Subtipo_molecular", bronze = "BiopsiaMama.bx_her2_fish", values = { "HR+/HER2+" = "POSITIVO", "HR-/HER2+" = "POSITIVO", "HR+/HER2-" = "NEGATIVO", "HR-/HER2-" = "NEGATIVO" } }
[variables.HER2_IHQ]
rules = [
{ source = "her2", codes = ["H0"], then = "0" },
{ source = "her2", codes = ["H1"], then = "1+" },
{ source = "her2", codes = ["H2"], then = "2+" },
{ source = "her2", codes = ["H3"], then = "3+" },
]
missing = "Sin dato"
seer = { bronze = "BiopsiaMama.bx_her2", values = { "0" = "H0", "1+" = "H1", "2+" = "H2", "3+" = "H3" } }
[variables.HR_estado]
internal = true
rules = [
{ when = [{ variable = "Receptor_estrogeno", codes = ["Positivo"] }], then = "HR+" },
{ when = [{ variable = "Receptor_progesterona", codes = ["Positivo"] }], then = "HR+" },
{ when = [{ variable = "Receptor_estrogeno", codes = ["Negativo"] }, { variable = "Receptor_progesterona", codes = ["Negativo"] }], then = "HR-" },
]
missing = "Desconocido"
[variables.Subtipo_molecular]
rules = [
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR+/HER2-" },
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR+/HER2+" },
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR-/HER2+" },
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR-/HER2-" },
]
missing = "Desconocido"
[variables.Tipo_histologico]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal (NST)" },
{ source = "tipo_histologico", codes = ["8520/3", "8521/3"], then = "Lobulillar" },
{ source = "tipo_histologico", codes = ["8522/3", "8523/3"], then = "Ductal-lobulillar mixto" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Mucinoso" },
{ source = "tipo_histologico", codes = ["8211/3", "8201/3"], then = "Tubular / cribiforme" },
{ source = "tipo_histologico", codes = ["8050/3", "8503/3", "8504/3"], then = "Papilar" },
{ source = "tipo_histologico", codes = ["8507/3"], then = "Micropapilar" },
{ source = "tipo_histologico", codes = ["8540/3", "8541/3", "8543/3"], then = "Paget" },
{ source = "tipo_histologico", codes = ["8510/3"], then = "Medular" },
{ source = "tipo_histologico", codes = ["8530/3"], then = "Inflamatorio" },
{ source = "tipo_histologico", present = true, then = "Otros" },
]
missing = "SIN MAPEAR"
seer = { bronze = "BiopsiaMama.bx_tipo_histologico", values = { "Ductal (NST)" = "8500/3", "Lobulillar" = "8520/3", "Ductal-lobulillar mixto" = "8522/3", "Mucinoso" = "8480/3", "Tubular / cribiforme" = "8211/3", "Papilar" = "8503/3", "Micropapilar" = "8507/3", "Paget" = "8541/3", "Medular" = "8510/3", "Inflamatorio" = "8530/3", "Otros" = "8575/3" } }
[variables.Localizacion_mama]
rules = [
{ source = "localizacion", codes = ["C500"], then = "Pezón" },
{ source = "localizacion", codes = ["C501"], then = "Porción central" },
{ source = "localizacion", codes = ["C502", "C503"], then = "Cuadrantes internos" },
{ source = "localizacion", codes = ["C504", "C505"], then = "Cuadrantes externos" },
{ source = "localizacion", codes = ["C506"], then = "Cola axilar" },
{ source = "localizacion", codes = ["C508"], then = "Lesión solapada" },
{ source = "localizacion", codes = ["C509"], then = "Mama NOS" },
]
missing = "Mama NOS"
seer = { bronze = "BiopsiaMama.bx_localizacion", values = { "Pezón" = "C500", "Porción central" = "C501", "Cuadrantes internos" = "C502", "Cuadrantes externos" = "C504", "Cola axilar" = "C506", "Lesión solapada" = "C508", "Mama NOS" = "C509" } }
[variables.Lateralidad]
rules = [
{ source = "lateralidad", codes = ["DERECHA"], then = "Derecha" },
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Izquierda" },
]
missing = "Otra / no especificada"
seer = { bronze = "BiopsiaMama.bx_lateralidad", values = { "Derecha" = "DERECHA", "Izquierda" = "IZQUIERDA" } }
[variables.Metastasis]
rules = [
{ source = "metastasis", codes = ["M1"], then = "Con metástasis" },
]
missing = "Sin metástasis"
seer = { bronze = "NotaMedica.nm_metastasis", values = { "Con metástasis" = "M1", "Sin metástasis" = "M0" } }
# The tumour size in millimetres: its category and the raw column the age and tumour groupings of stage 02 read.
[variables.Tamano_tumor]
source = "tamano_tumor_mm"
rules = [
{ source = "tamano_tumor_mm", lt = 21, then = "T1 (<=20 mm)" },
{ source = "tamano_tumor_mm", ge = 21, lt = 51, then = "T2 (21-50 mm)" },
{ source = "tamano_tumor_mm", ge = 51, then = "T3+ (>50 mm)" },
]
missing = "Desconocido"
raw_column = "Tumor_Size_Over_Time_Recode_1988"
raw_format = "{:03.0f}"
raw_missing = "Unknown or size unreasonable (includes any tumor sizes 401-989)"
seer = { bronze = "BiopsiaMama.bx_tamano_tumor_mm", number = "Tumor_Size_Over_Time_Recode_1988", unknown = ["Unknown or size unreasonable (includes any tumor sizes 401-989)", "Otros (agrupado)"], microscopic = ["990 (microscopic focus)"], microscopic_mm = 1 }
[variables.Ganglios_positivos]
rules = [
{ source = "ganglios_positivos", lt = 1, then = "0" },
{ source = "ganglios_positivos", ge = 1, lt = 4, then = "1-3" },
{ source = "ganglios_positivos", ge = 4, lt = 10, then = "4-9" },
{ source = "ganglios_positivos", ge = 10, then = "10+" },
]
missing = "0"
seer = { bronze = "BiopsiaMama.bx_ganglios_positivos", number_values = { "0" = 0, "1-3" = 2, "4-9" = 6, "10+" = 12 } }
[variables.Invasion_linfovascular]
rules = [{ source = "invasion_linfovascular", codes = ["PRESENTE"], then = "Si" }]
missing = "No"
seer = { bronze = "BiopsiaMama.bx_invasion_linfovascular", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
[variables.Multifocalidad]
rules = [{ source = "multifocalidad", codes = ["PRESENTE"], then = "Si" }]
missing = "No"
seer = { bronze = "BiopsiaMama.bx_multifocalidad", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
[variables.Margenes]
rules = [
{ source = "margenes", codes = ["LIBRES"], then = "Negativos" },
{ source = "margenes", codes = ["CERCANOS", "AFECTADOS"], then = "Positivos" },
{ source = "margenes", codes = ["SIN_CIRUGIA"], then = "Sin cirugia" },
]
missing = "Sin dato"
seer = { bronze = "BiopsiaMama.bx_margenes", values = { "Negativos" = "LIBRES", "Positivos" = "AFECTADOS", "Sin cirugia" = "SIN_CIRUGIA" } }
[variables.Densidad_BIRADS]
rules = [
{ source = "densidad_mamaria", codes = ["A"], then = "A" },
{ source = "densidad_mamaria", codes = ["B"], then = "B" },
{ source = "densidad_mamaria", codes = ["C"], then = "C" },
{ source = "densidad_mamaria", codes = ["D"], then = "D" },
]
missing = "B"
seer = { bronze = "Mastografia.mast_densidad", values = { "A" = "A", "B" = "B", "C" = "C", "D" = "D" } }
[variables.Masa_espiculada]
rules = [{ source = "margen_masa", codes = ["ESPICULADO"], then = "Si" }]
missing = "No"
seer = { bronze = "Mastografia.mast_margen_masa", values = { "Si" = "ESPICULADO" } }
[variables.Microcalcificaciones]
rules = [{ source = "tipo_hallazgo", codes = ["CALCIFICACIONES"], then = "Si" }]
missing = "No"
seer = { bronze = "Mastografia.mast_tipo_hallazgo", values = { "Si" = "CALCIFICACIONES" } }
[variables.BRCA]
rules = [
{ source = "brca1", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA1" },
{ source = "brca2", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA2" },
]
missing = "Negativo"
seer = { bronze = "Paciente.pac_brca1", values = { "BRCA1" = "PATOGENICA", "Negativo" = "NEGATIVO" }, also = { bronze = "Paciente.pac_brca2", values = { "BRCA2" = "PATOGENICA", "Negativo" = "NEGATIVO" } } }
[variables.Estado_civil]
rules = [
{ source = "estado_civil", codes = ["SOLTERA", "CASADA", "UNION_LIBRE"], then = "Con pareja" },
{ source = "estado_civil", codes = ["SEPARADA", "DIVORCIADA", "VIUDA"], then = "Sin pareja" },
]
missing = "Desconocido"
seer = { bronze = "Paciente.pac_estado_civil", values = { "Con pareja" = "CASADA", "Sin pareja" = "DIVORCIADA" } }
[variables.Race]
column = "Race_recode_White_Black_Other"
rules = [
{ source = "raza", codes = ["BLANCA"], then = "White" },
{ source = "raza", codes = ["NEGRA"], then = "Black" },
{ source = "raza", codes = ["OTRA"], then = "Other (American Indian/AK Native, Asian/Pacific Islander)" },
]
missing = "Unknown"
seer = { bronze = "Paciente.pac_raza", values = { "White" = "BLANCA", "Black" = "NEGRA", "Other (American Indian/AK Native, Asian/Pacific Islander)" = "OTRA" } }
[variables.Tratamiento_quirurgico]
rules = [
{ source = "cirugia", codes = ["ESCISIONAL", "SEGMENTECTOMIA"], then = "Conservadora" },
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"], then = "Mastectomía" },
{ source = "cirugia", codes = ["SIN_CIRUGIA"], then = "Ninguna" },
{ source = "cirugia", codes = ["DESTRUCCION_LOCAL"], then = "Destrucción local" },
{ source = "cirugia", codes = ["CIRUGIA_NO_ESPECIFICADA"], then = "Cirugía NOS" },
]
missing = "Desconocido"
seer = { treatment = "cirugia", values = { "Conservadora" = "SEGMENTECTOMIA", "Mastectomía" = "MASTECTOMIA_TOTAL", "Ninguna" = "SIN_CIRUGIA", "Destrucción local" = "DESTRUCCION_LOCAL", "Cirugía NOS" = "CIRUGIA_NO_ESPECIFICADA" } }
[variables.Radioterapia]
rules = [{ source = "radioterapia", present = true, then = "Sí" }]
missing = "No o desconocido"
seer = { treatment = "radioterapia", values = { "Sí" = "ADYUVANTE" } }
[variables.Quimioterapia]
rules = [{ source = "quimioterapia", present = true, then = "Sí" }]
missing = "No o desconocido"
seer = { treatment = "quimioterapia", values = { "Sí" = "ADYUVANTE" } }
+285
View File
@@ -0,0 +1,285 @@
"""Stage 04, modeling: the stepwise logistic regression (LR) and the hybrid Bayesian network (HBN) on the balanced
cohort, their comparison on the internal test, and the LR on the natural population.
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `balanced_csv`,
`natural_csv` and `modeling` (its settings). The heavy routines live apart: `lr_selection.py`, `hbn.py` and
`natural.py`; the bootstrap and the proposal comparison, which repeat this pipeline, are `resampling.py`.
"""
import os
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from matplotlib import rc_context
from matplotlib.figure import Figure
from sklearn.calibration import calibration_curve
from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve
from sklearn.model_selection import train_test_split
from models.cama.seer_survival import hbn, lr_selection
from models.cama.seer_survival.natural import NaturalResults, fit_natural
from models.cama.seer_survival.settings import ModelingSettings
# seaborn's "whitegrid", which the script set globally for its figures
WHITEGRID = {"axes.facecolor": "white", "axes.edgecolor": ".8", "axes.grid": True, "grid.color": ".8",
"grid.linestyle": "-", "axes.axisbelow": True}
@dataclass(frozen=True, eq=False)
class Design:
X: pd.DataFrame
y: pd.Series
@dataclass(frozen=True, eq=False)
class Split:
X_train: pd.DataFrame
X_test: pd.DataFrame
y_train: pd.Series
y_test: pd.Series
@dataclass(frozen=True, eq=False)
class HbnFit:
model: object # the fitted DiscreteBayesianNetwork
edges: list
bn_train: pd.DataFrame
bn_test: pd.DataFrame
# ---------------------------------------------------------------- the data
def balanced_raw(balanced_csv: str) -> pd.DataFrame:
return pd.read_csv(balanced_csv, dtype=str)
def fit_race_column(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> str | None:
"""SEER's race column as it comes (the recoding never recodes it), found by keyword; None when it is already one of
the canonical map's columns."""
race = next((c for c in balanced_raw.columns if "race" in c.lower().replace("_", " ")), None)
return None if race in modeling.canonical_map else race
def fit_rename_map(balanced_raw: pd.DataFrame, modeling: ModelingSettings) -> dict:
"""The columns that exist -> canonical names; the depuration may have kept `Tamano_tumor_cat` instead of
`Tumor_group`, and then that one is the tumor size."""
mapping = dict(modeling.canonical_map)
if "Tumor_group" not in balanced_raw.columns and "Tamano_tumor_cat" in balanced_raw.columns:
mapping["Tamano_tumor_cat"] = "Tamano_tumor"
return {k: v for k, v in mapping.items() if k in balanced_raw.columns}
def fit_frame(balanced_raw: pd.DataFrame, fit_rename_map: dict, fit_race_column: str | None) -> pd.DataFrame:
"""The balanced cohort under the canonical names, with `outcome` (1 = survives). It SELECTS by the original names
and only then renames, so a raw SEER column that already has a canonical name is never carried along."""
df = balanced_raw[list(fit_rename_map.keys())].rename(columns=fit_rename_map).copy()
if fit_race_column:
df["Race"] = balanced_raw[fit_race_column]
dup = df.columns[df.columns.duplicated()].tolist()
assert not dup, f"Columnas duplicadas tras construir df: {dup}. Revisar canonical_map / la columna de raza."
assert (df["Outcome_cat"] == "Desconocido").sum() == 0, \
"Se esperaba que la cohorte balanceada ya excluyera el desenlace desconocido."
df["outcome"] = (df["Outcome_cat"] == "Sobrevive").astype(int)
return df
def fit_features(fit_frame: pd.DataFrame, modeling: ModelingSettings) -> list[str]:
"""The categorical covariates present, in the settings' order."""
return [c for c in modeling.categorical_order if c in fit_frame.columns]
def fit_design(fit_frame: pd.DataFrame, fit_features: list[str]) -> Design:
enc = lr_selection.encode(fit_frame, fit_features)
X = pd.get_dummies(enc[fit_features], drop_first=True).astype(float)
constant = [c for c in X.columns if X[c].nunique() <= 1]
return Design(X.drop(columns=constant) if constant else X, enc["outcome"])
def fit_split(fit_design: Design, modeling: ModelingSettings) -> Split:
X_train, X_test, y_train, y_test = train_test_split(
fit_design.X, fit_design.y, test_size=modeling.test_size, random_state=modeling.random_state,
stratify=fit_design.y)
constant = [c for c in X_train.columns if X_train[c].nunique() <= 1]
if constant:
X_train, X_test = X_train.drop(columns=constant), X_test.drop(columns=constant)
return Split(X_train, X_test, y_train, y_test)
# ---------------------------------------------------------------- stepwise logistic regression
def lr_selected(fit_split: Split, modeling: ModelingSettings) -> list[str]:
"""The stepwise selection over the pre-filtered columns, on a stratified subsample of the train."""
s = modeling
prefiltered = lr_selection.prefiltered_columns(fit_split.X_train, fit_split.y_train, s.prefilter_alpha,
s.max_candidates, always_sort=False)
X_search, y_search = lr_selection.search_sample(fit_split.X_train, fit_split.y_train, prefiltered,
s.max_search_rows, s.random_state)
return lr_selection.stepwise_selection(X_search, y_search, s.alpha_in, s.alpha_out)
def lr_model(fit_split: Split, lr_selected: list[str], modeling: ModelingSettings) -> object:
"""The final LR, refitted on the WHOLE train with the selected variables."""
return sm.Logit(fit_split.y_train, sm.add_constant(fit_split.X_train[lr_selected])).fit(
disp=0, method="bfgs", maxiter=modeling.lr_maxiter)
def lr_odds_ratios(lr_model: object) -> pd.DataFrame:
conf = lr_model.conf_int()
conf["OR"] = lr_model.params
conf.columns = ["2.5%", "97.5%", "OR"]
table = np.exp(conf)
table["p_value"] = lr_model.pvalues
return table.round(3)
def lr_test_prediction(fit_split: Split, lr_model: object, lr_selected: list[str]) -> pd.Series:
return lr_model.predict(sm.add_constant(fit_split.X_test[lr_selected], has_constant="add"))
# ---------------------------------------------------------------- hybrid Bayesian network
def hbn_fit(fit_frame: pd.DataFrame, fit_features: list[str], modeling: ModelingSettings) -> HbnFit:
s = modeling
enc = lr_selection.encode(fit_frame, fit_features)
bn_cols = [c for c in fit_features if c in enc.columns] + ["outcome"]
small = enc[bn_cols].astype(str)
bn_train, bn_test = train_test_split(small, test_size=s.test_size, random_state=s.random_state,
stratify=small["outcome"])
edges = hbn.learn_structure(bn_train, bn_cols, s, s.n_restarts, s.random_state)
return HbnFit(hbn.fit_network(edges, bn_train), edges, bn_train, bn_test)
def hbn_test_prediction(hbn_fit: HbnFit) -> pd.DataFrame:
"""The HBN's test rows with `pred`, the survival probability; rows whose query failed are dropped."""
preds = hbn.predict_survival(hbn_fit.model, hbn_fit.bn_test)
return hbn_fit.bn_test.assign(pred=preds).dropna(subset=["pred"])
def hbn_arcs(hbn_fit: HbnFit) -> pd.DataFrame:
return pd.DataFrame(list(hbn_fit.model.edges()), columns=["origen", "destino"])
def hbn_arc_strength(hbn_fit: HbnFit, modeling: ModelingSettings) -> pd.DataFrame:
return hbn.arc_strength(hbn_fit.model, hbn_fit.bn_train, modeling.bdeu_ess)
def hbn_graph_figure(hbn_fit: HbnFit, modeling: ModelingSettings) -> Figure:
import networkx as nx
with rc_context(WHITEGRID):
fig = Figure(figsize=(10, 8))
ax = fig.subplots()
G = nx.DiGraph(hbn_fit.model.edges())
pos = nx.spring_layout(G, seed=modeling.random_state, k=0.8)
nx.draw(G, pos, ax=ax, with_labels=True, node_color="lightblue", node_size=2500, font_size=8, arrowsize=15)
ax.set_title("Estructura de la Red Bayesiana Híbrida (aproximación)")
return fig
# ---------------------------------------------------------------- the internal test: LR vs HBN
def auc_internal(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame:
return pd.DataFrame([
{"modelo": "LR", "AUC": roc_auc_score(fit_split.y_test, lr_test_prediction)},
{"modelo": "HBN", "AUC": roc_auc_score(hbn_test_prediction["outcome"].astype(int), hbn_test_prediction["pred"])},
]).round(4)
def roc_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame,
auc_internal: pd.DataFrame) -> Figure:
hb = hbn_test_prediction
fpr_lr, tpr_lr, _ = roc_curve(fit_split.y_test, lr_test_prediction)
fpr_hbn, tpr_hbn, _ = roc_curve(hb["outcome"].astype(int), hb["pred"])
auc_lr, auc_hbn = auc_internal["AUC"].tolist()
with rc_context(WHITEGRID):
fig = Figure(figsize=(7, 6))
ax = fig.subplots()
ax.plot(fpr_lr, tpr_lr, label=f"LR (AUC={auc_lr:.3f})", color="black")
ax.plot(fpr_hbn, tpr_hbn, label=f"HBN (AUC={auc_hbn:.3f})", color="crimson")
ax.plot([0, 1], [0, 1], linestyle="--", color="gray")
ax.set_xlabel("1 - Especificidad")
ax.set_ylabel("Sensibilidad")
ax.set_title("Curvas ROC -- comparacion LR vs. HBN")
ax.legend()
return fig
def calibration_figure(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure:
hb = hbn_test_prediction
true_lr, pred_lr = calibration_curve(fit_split.y_test, lr_test_prediction, n_bins=10)
true_hbn, pred_hbn = calibration_curve(hb["outcome"].astype(int), hb["pred"], n_bins=10)
with rc_context(WHITEGRID):
fig = Figure(figsize=(7, 6))
ax = fig.subplots()
ax.plot(pred_lr, true_lr, marker="o", label="LR", color="black")
ax.plot(pred_hbn, true_hbn, marker="o", label="HBN", color="crimson")
ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Calibracion perfecta")
ax.set_xlabel("Probabilidad predicha")
ax.set_ylabel("Probabilidad observada")
ax.set_title("Curvas de calibracion")
ax.legend()
return fig
def dca_figure(lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> Figure | None:
"""The decision-curve (net benefit) figure, or None when `dcurves` isn't installed."""
try:
import matplotlib.pyplot as plt
from dcurves import dca, plot_graphs
except ImportError:
return None
plt.switch_backend("Agg") # `plot_graphs` draws with pyplot and shows: never open a window from a pipeline
hb = hbn_test_prediction
data = pd.DataFrame({"outcome": hb["outcome"].astype(int).values,
"lr_pred": lr_test_prediction.reindex(hb.index).values, "hbn_pred": hb["pred"].values})
result = dca(data=data, outcome="outcome", modelnames=["lr_pred", "hbn_pred"])
plt.close("all")
with rc_context(WHITEGRID):
plot_graphs(plot_df=result, graph_type="net_benefit", y_limits=[-0.05, 0.5])
fig = plt.gcf()
plt.close("all")
return fig
def _differentiation(y_true, y_prob, threshold: float) -> dict:
tn, fp, fn, tp = confusion_matrix(y_true, (y_prob >= threshold).astype(int)).ravel()
return {"ACC": (tp + tn) / (tp + tn + fp + fn), "TPR": tp / (tp + fn), "TNR": tn / (tn + fp),
"PPV": tp / (tp + fp) if (tp + fp) > 0 else np.nan, "NPV": tn / (tn + fn) if (tn + fn) > 0 else np.nan}
def _youden(y_true, y_prob) -> float:
fpr, tpr, thresholds = roc_curve(y_true, y_prob)
return thresholds[np.argmax(tpr - fpr)]
def differentiation_table(fit_split: Split, lr_test_prediction: pd.Series, hbn_test_prediction: pd.DataFrame) -> pd.DataFrame:
"""Accuracy, sensitivity, specificity and predictive values of each model at the 0.5 threshold and at its own
Youden-optimal one."""
y_lr, p_lr = fit_split.y_test.values, lr_test_prediction.values
y_hbn, p_hbn = hbn_test_prediction["outcome"].astype(int).values, hbn_test_prediction["pred"].values
thr_lr, thr_hbn = _youden(y_lr, p_lr), _youden(y_hbn, p_hbn)
rows = [{"Model": "LR", "Umbral": 0.50, **_differentiation(y_lr, p_lr, 0.5)},
{"Model": "HBN tabular", "Umbral": 0.50, **_differentiation(y_hbn, p_hbn, 0.5)},
{"Model": "LR", "Umbral": round(thr_lr, 3), **_differentiation(y_lr, p_lr, thr_lr)},
{"Model": "HBN tabular", "Umbral": round(thr_hbn, 3), **_differentiation(y_hbn, p_hbn, thr_hbn)}]
return pd.DataFrame(rows).set_index(["Model", "Umbral"]).round(2)
# ---------------------------------------------------------------- the natural population
def natural_raw(natural_csv: str, modeling: ModelingSettings) -> pd.DataFrame | None:
"""The natural population's file; None when the phase is off or the file isn't there."""
if not modeling.run_lr_natural or not os.path.exists(natural_csv):
return None
return pd.read_csv(natural_csv, dtype=str)
def natural_results(natural_raw: pd.DataFrame | None, fit_frame: pd.DataFrame, fit_rename_map: dict,
fit_race_column: str | None, fit_features: list[str], fit_split: Split, lr_model: object,
lr_selected: list[str], modeling: ModelingSettings) -> NaturalResults | None:
if natural_raw is None:
return None
return fit_natural(natural_raw, fit_frame, fit_rename_map, fit_race_column, fit_features, fit_split.X_train,
fit_split.y_train, lr_model, lr_selected, modeling)
+154
View File
@@ -0,0 +1,154 @@
"""The logistic regression on the NATURAL population (every patient with a known outcome, before the undersampling),
compared with the balanced model on the same common test set; apart from the modeling nodes (`modeling.py`). Plain
functions with no I/O. Ported from `04_modelado.py` (phase 6B).
The balanced model is compared both with its raw probabilities and with an intercept correction for the prevalence shift;
the natural model is fitted with and without the treatment variables. The common test set is the natural test patients
that the balanced model did not train on.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.seer_survival import lr_selection
from models.cama.seer_survival.settings import ModelingSettings
@dataclass(frozen=True, eq=False)
class NaturalResults:
odds_ratios: pd.DataFrame # LR on the natural population
odds_ratios_no_treatment: pd.DataFrame
comparison: pd.DataFrame # balanced raw / corrected / natural / natural without treatment
auc_by_stage: pd.DataFrame # balanced vs natural
auc_by_stage_no_treatment: pd.DataFrame
calibration_deciles: pd.DataFrame
def _odds_table(model) -> pd.DataFrame:
ci = np.exp(model.conf_int())
ci["OR_supervivencia"] = np.exp(model.params)
ci.columns = ["2.5%", "97.5%", "OR_supervivencia"]
ci["p"] = model.pvalues
return ci.round(3)
def _logit(p):
p = np.clip(p, 1e-9, 1 - 1e-9)
return np.log(p / (1 - p))
def _sigmoid(z):
return 1 / (1 + np.exp(-z))
def _stage_aucs(stage, y, preds: dict[str, np.ndarray], min_n: int = 50) -> pd.DataFrame:
"""Per stage with at least `min_n` patients and both outcomes: n, deaths and the AUC of each prediction."""
rows = []
for s in sorted(set(stage)):
m = stage == s
if m.sum() >= min_n and len(set(y[m])) == 2:
rows.append({"Estadio": s, "n": int(m.sum()), "muertes": int((1 - y[m]).sum()),
**{name: round(roc_auc_score(y[m], p[m]), 3) for name, p in preds.items()}})
return pd.DataFrame(rows).set_index("Estadio")
def _deciles(p_survival, y, name: str) -> pd.DataFrame:
risk, death = 1 - p_survival, 1 - y
d = pd.DataFrame({"riesgo": risk, "muerte": death})
d["decil"] = pd.qcut(d["riesgo"].rank(method="first"), 10, labels=False) + 1
t = d.groupby("decil").agg(n=("muerte", "size"), muertes=("muerte", "sum"), riesgo_predicho=("riesgo", "mean"),
riesgo_observado=("muerte", "mean")).round(4)
t["modelo"] = name
return t
def fit_natural(natural_raw: pd.DataFrame, df: pd.DataFrame, rename_map: dict, race_column: str | None,
cat_cols: list[str], X_train: pd.DataFrame, y_train: pd.Series, final_lr_model, selected: list[str],
s: ModelingSettings) -> NaturalResults:
dn_raw = natural_raw[natural_raw["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
in_balanced = dn_raw["en_balanceado"].astype(int).values == 1
dn = dn_raw[list(rename_map.keys())].rename(columns=rename_map).copy()
if race_column and race_column in dn_raw.columns:
dn["Race"] = dn_raw[race_column]
for c in cat_cols:
dn[c] = dn[c].fillna("Desconocido").astype(str)
y_nat = (dn["Outcome_cat"] == "Sobrevive").astype(int)
# the balanced rows of the natural file must be EXACTLY the balanced file's, in the same order
idx_b = np.where(in_balanced)[0]
assert len(idx_b) == len(df), f"El archivo natural trae {len(idx_b)} filas balanceadas y df tiene {len(df)}"
for c in ["Estadio", "Tratamiento_quirurgico", "Outcome_cat"]:
assert (dn.loc[idx_b, c].values == df[c].values).all(), \
f"Las filas balanceadas no coinciden en {c}: regenera el archivo natural con el balanceo actual"
position = pd.Series(idx_b, index=df.index) # row of df -> row of dn
train_balanced = set(position.loc[X_train.index]) # natural rows the balanced model trained on
# encoding (reference = the most frequent category) and the natural split
Xn_full = pd.get_dummies(dn[cat_cols], drop_first=False).astype(float)
ref_cols = {}
for c in cat_cols:
cols_c = [k for k in Xn_full.columns if k.startswith(c + "_") and k[len(c) + 1:] in set(dn[c])]
ref_cols[c] = Xn_full[cols_c].sum().idxmax()
Xn = Xn_full.drop(columns=list(ref_cols.values()))
tr_n, te_n = train_test_split(np.arange(len(dn)), test_size=s.natural_test_size, random_state=s.random_state,
stratify=y_nat)
Xn_train, yn_train = Xn.iloc[tr_n], y_nat.iloc[tr_n]
common = np.array([i for i in te_n if i not in train_balanced]) # the COMMON test set
varying = [c for c in Xn_train.columns if Xn_train[c].nunique() > 1]
Xn_train = Xn_train[varying]
pre_cols = lr_selection.prefiltered_columns(Xn_train, yn_train, s.prefilter_alpha, s.max_candidates)
# stepwise and final fit on the natural population
search_idx = None
if len(Xn_train) > s.natural_search_rows:
search_idx, _ = train_test_split(Xn_train.index, train_size=s.natural_search_rows,
random_state=s.random_state, stratify=yn_train)
Xs, ys = Xn_train.loc[search_idx, pre_cols], yn_train.loc[search_idx]
else:
Xs, ys = Xn_train[pre_cols], yn_train
sel_nat = lr_selection.stepwise_selection(Xs, ys, s.alpha_in, s.alpha_out)
lr_nat = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nat])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
# comparison on the common natural test set, with an intercept correction of the balanced model
prev_nat, prev_bal = float(y_nat.mean()), float(y_train.mean())
shift = np.log(prev_nat / (1 - prev_nat)) - np.log(prev_bal / (1 - prev_bal))
Xc, yc, stage_c = Xn.iloc[common], y_nat.iloc[common].values, dn["Estadio"].iloc[common].values
p_nat = lr_nat.predict(sm.add_constant(Xc[sel_nat], has_constant="add")).values
Xb_c = Xn_full.iloc[common].reindex(columns=X_train.columns, fill_value=0.0)
p_bal_raw = final_lr_model.predict(sm.add_constant(Xb_c[selected], has_constant="add")).values
p_bal_cor = _sigmoid(_logit(p_bal_raw) + shift)
def row(name, p):
m3 = np.isin(stage_c, ["I", "II", "III"])
auc3 = roc_auc_score(yc[m3], p[m3]) if len(set(yc[m3])) == 2 else np.nan
return {"modelo": name, "AUC": roc_auc_score(yc, p), "AUC estadios I-III": auc3,
"PR-AUC (muerte)": average_precision_score(1 - yc, 1 - p), "Brier": brier_score_loss(yc, p),
"prob. media predicha": p.mean(), "prob. media real": yc.mean()}
comp = pd.DataFrame([row("LR balanceada (probabilidades crudas)", p_bal_raw),
row("LR balanceada + corrección de intercepto", p_bal_cor),
row("LR población natural", p_nat)]).set_index("modelo").round(3)
auc_stage = _stage_aucs(stage_c, yc, {"AUC LR balanceada": p_bal_raw, "AUC LR natural": p_nat})
# the natural LR WITHOUT treatment
cols_nt = [c for c in Xn_train.columns if not any(c.startswith(t + "_") for t in s.treatment_vars)]
pre_cols_nt = lr_selection.prefiltered_columns(Xn_train[cols_nt], yn_train, s.prefilter_alpha, s.max_candidates)
if len(Xn_train) > s.natural_search_rows:
Xs2, ys2 = Xn_train.loc[search_idx, pre_cols_nt], yn_train.loc[search_idx]
else:
Xs2, ys2 = Xn_train[pre_cols_nt], yn_train
sel_nt = lr_selection.stepwise_selection(Xs2, ys2, s.alpha_in, s.alpha_out)
lr_nt = sm.Logit(yn_train, sm.add_constant(Xn_train[sel_nt])).fit(disp=0, method="bfgs", maxiter=s.natural_maxiter)
p_nt = lr_nt.predict(sm.add_constant(Xc[sel_nt], has_constant="add")).values
comp2 = pd.concat([comp, pd.DataFrame([row("LR población natural SIN tratamiento", p_nt)]).set_index("modelo").round(3)])
auc_stage_nt = _stage_aucs(stage_c, yc, {"AUC natural": p_nat, "AUC natural SIN tratamiento": p_nt})
deciles = pd.concat([_deciles(p_nat, yc, "natural"), _deciles(p_nt, yc, "natural sin tratamiento")]).reset_index()
return NaturalResults(_odds_table(lr_nat), _odds_table(lr_nt), comp2, auc_stage, auc_stage_nt, deciles)
+130
View File
@@ -0,0 +1,130 @@
"""Runs the stages of the SEER survival pipeline in order, in a data folder that holds their inputs and outputs. Replaces
`ejecutar_pipeline.py`: the stages are Hamilton DAGs (`run.py`) run in this process, not scripts run one per process.
python -m models.cama.seer_survival --data DIR # every stage, skipping the ones that are current
python -m models.cama.seer_survival --data DIR --solo 05 # only that stage
python -m models.cama.seer_survival --data DIR --desde 02 # from that stage on
python -m models.cama.seer_survival --data DIR --forzar 02 04 # run those even when current
python -m models.cama.seer_survival --data DIR --todo # run all, skipping none
A stage is skipped only when its outputs exist, are not empty and are newer than its code and its inputs. Writes
`bitacora_pipeline.csv` (stage, state, seconds) to the data folder.
"""
import argparse
import csv
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
from models.cama.seer_survival import run
from models.cama.seer_survival.settings import TOML, Settings, load
PACKAGE = Path(__file__).parent
RECODED = "dataframe_recodificado.csv"
COLUMN_MAP = "mapeo_columnas_recodificadas.json"
LOG = "bitacora_pipeline.csv"
@dataclass(frozen=True)
class Stage:
id: str
run: Callable[[Path, Settings], object]
requires: tuple[str, ...]
produces: tuple[str, ...] # empty: no single output to check, so the stage always runs
code: tuple[str, ...] # the package files whose change makes the outputs stale
STAGES = [
Stage("01", lambda d, s: run.run_depuration(d / RECODED, d / COLUMN_MAP, d, s), (RECODED, COLUMN_MAP),
(run.DEPURATED,), ("depuration.py", "depuration_stats.py", "settings.py", "run.py")),
Stage("02", lambda d, s: run.run_balancing(d / run.DEPURATED, d, settings=s), (run.DEPURATED,),
(run.BALANCED, run.PROPOSALS, run.NATURAL),
("balancing.py", "balancing_stats.py", "categorization.py", "categorization_stats.py", "columns.py",
"settings.py", "run.py")),
Stage("03", lambda d, s: run.run_bootstrap(d / run.BALANCED, d, s), (run.BALANCED,),
(run.BOOTSTRAP_INDICES, run.BOOTSTRAP_METADATA), ("bootstrap.py", "settings.py", "run.py")),
Stage("04", lambda d, s: run.run_modeling(d / run.BALANCED, d, settings=s),
(run.BALANCED, run.PROPOSALS, run.BOOTSTRAP_INDICES, run.BOOTSTRAP_METADATA, run.NATURAL), (),
("modeling.py", "resampling.py", "replica.py", "lr_selection.py", "hbn.py", "natural.py", "settings.py",
"run.py")),
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "scenarios.py", "settings.py", "run.py")),
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
"escenarios_factores_riesgo.csv", "escenarios_resumen.csv"),
("risk_factors.py", "risk_factor_stats.py", "scenarios.py", "settings.py", "run.py")),
]
def _mtime(p: Path) -> float:
return p.stat().st_mtime
def is_current(stage: Stage, data: Path) -> bool:
"""The outputs exist, are not empty and are newer than the stage's code, the settings and its inputs."""
outputs = [data / p for p in stage.produces]
if not outputs or not all(p.exists() and p.stat().st_size > 0 for p in outputs):
return False
reference = max([_mtime(TOML)] + [_mtime(PACKAGE / f) for f in stage.code]
+ [_mtime(data / p) for p in stage.requires if (data / p).exists()])
return min(_mtime(p) for p in outputs) >= reference
def save_log(data: Path, log: list[tuple]) -> None:
with open(data / LOG, "w", newline="", encoding="utf8") as f:
w = csv.writer(f)
w.writerow(["etapa", "estado", "segundos"])
w.writerows(log)
def run_pipeline(data: Path, only=None, since=None, force=(), everything: bool = False,
settings: Settings | None = None) -> list[tuple]:
"""Runs the selected stages; returns the log rows (stage, `ok` | `saltada`, seconds). A stage that wrote outputs
makes every later one run again."""
settings = settings or load()
data = Path(data)
selected = [e for e in STAGES if (not only or e.id in only) and (not since or e.id >= since)]
log, redo = [], False
for stage in selected:
missing = [p for p in stage.requires if not (data / p).exists()]
if missing:
raise FileNotFoundError(f"Etapa {stage.id}: faltan entradas {missing}")
if not (everything or stage.id in force or redo) and is_current(stage, data):
log.append((stage.id, "saltada", 0))
continue
t0 = time.time()
try:
stage.run(data, settings)
except Exception:
log.append((stage.id, "error", round(time.time() - t0)))
save_log(data, log)
raise
log.append((stage.id, "ok", round(time.time() - t0)))
save_log(data, log)
redo = redo or bool(stage.produces)
save_log(data, log)
return log
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--data", default=".", help="folder with the stages' inputs and outputs (default: the current one)")
ap.add_argument("--solo", nargs="+")
ap.add_argument("--desde")
ap.add_argument("--forzar", nargs="+", default=[])
ap.add_argument("--todo", action="store_true")
a = ap.parse_args(argv)
try:
run_pipeline(Path(a.data), a.solo, a.desde, a.forzar, a.todo)
except FileNotFoundError as e:
sys.exit(str(e))
if __name__ == "__main__":
main()
+68
View File
@@ -0,0 +1,68 @@
"""One replica of the modeling pipeline (outcome, encoding, split, stepwise LR, HBN) on a frame, with the seed that
fixes its split: what the bootstrap and the comparison of categorization proposals repeat. Plain functions with no I/O.
Ported from `04_modelado.py` (`ejecutar_replica_pipeline`)."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.seer_survival import hbn, lr_selection
from models.cama.seer_survival.settings import ModelingSettings
def run_replica(df_b: pd.DataFrame, seed: int, cat_cols: list[str], s: ModelingSettings, include_hbn: bool,
n_restarts: int) -> dict:
"""AUC of the stepwise LR and of the HBN on the replica's 30 % test, how many variables each kept, the LR's
coefficients and the HBN's outcome parents. Anything that can't be computed stays NaN / None."""
out = {"auc_lr": np.nan, "auc_hbn": np.nan, "n_selected_lr": np.nan, "n_parents_hbn": np.nan,
"coefs": None, "padres": None}
df_b = df_b.copy()
df_b["outcome"] = (df_b["Outcome_cat"] == "Sobrevive").astype(int)
df_enc_b = lr_selection.encode(df_b, cat_cols)
X_b = pd.get_dummies(df_enc_b[cat_cols], drop_first=True).astype(float)
y_b = df_enc_b["outcome"]
constant = [c for c in X_b.columns if X_b[c].nunique() <= 1]
if constant:
X_b = X_b.drop(columns=constant)
if y_b.nunique() < 2:
return out
X_train_b, X_test_b, y_train_b, y_test_b = train_test_split(
X_b, y_b, test_size=s.test_size, random_state=seed, stratify=y_b)
constant_train = [c for c in X_train_b.columns if X_train_b[c].nunique() <= 1]
if constant_train:
X_train_b = X_train_b.drop(columns=constant_train)
X_test_b = X_test_b.drop(columns=constant_train)
prefiltered = lr_selection.prefiltered_columns(X_train_b, y_train_b, s.prefilter_alpha, s.max_candidates)
if not prefiltered:
return out
X_search, y_search = lr_selection.search_sample(X_train_b, y_train_b, prefiltered, s.max_search_rows, seed)
selected = lr_selection.stepwise_selection(X_search, y_search, s.alpha_in, s.alpha_out)
out["n_selected_lr"] = len(selected)
if selected:
model = lr_selection.safe_fit_logit(y_train_b, sm.add_constant(X_train_b[selected]))
if model is not None:
out["coefs"] = model.params.drop("const", errors="ignore").to_dict()
out["auc_lr"] = roc_auc_score(y_test_b, model.predict(sm.add_constant(X_test_b[selected], has_constant="add")))
if include_hbn:
try:
bn_cols = [c for c in cat_cols if c in df_enc_b.columns] + ["outcome"]
small = df_enc_b[bn_cols].astype(str)
bn_train, bn_test = train_test_split(small, test_size=s.test_size, random_state=seed,
stratify=small["outcome"])
edges = hbn.learn_structure(bn_train, bn_cols, s, n_restarts, seed)
parents = [u for (u, v) in edges if v == "outcome"]
out["n_parents_hbn"] = len(parents)
out["padres"] = parents
model_hbn = hbn.fit_network(edges, bn_train)
bn_test = bn_test.assign(pred=hbn.predict_survival(model_hbn, bn_test)).dropna(subset=["pred"])
out["auc_hbn"] = roc_auc_score(bn_test["outcome"].astype(int), bn_test["pred"])
except Exception:
pass
return out
+141
View File
@@ -0,0 +1,141 @@
"""Stage 04, resampling: the pipeline repeated on bootstrap resamples (the indices of stage 03) and on each
categorization proposal of stage 02b, to put intervals on the AUCs and compare the proposals on the same splits.
Each public function is a Hamilton node; it continues `modeling.py` (`fit_frame`, `fit_features`) and takes
`bootstrap_indices` (stage 03's array), `proposals_csv` and `modeling` (its settings) as inputs. One replica is
`replica.py`. Both loops stop by themselves when their time cap is reached and use what they have.
"""
import time
import numpy as np
import pandas as pd
from models.cama.seer_survival.replica import run_replica
from models.cama.seer_survival.settings import ModelingSettings
# ---------------------------------------------------------------- bootstrap
def bootstrap_runs(fit_frame: pd.DataFrame, bootstrap_indices: np.ndarray, fit_features: list[str],
modeling: ModelingSettings) -> list[dict]:
"""The replica pipeline on each resample, in order, until `n_bootstrap_run` or the time cap."""
assert bootstrap_indices.shape[1] == len(fit_frame), (
f"bootstrap_indices tiene {bootstrap_indices.shape[1]} filas por réplica, pero el balanceado tiene "
f"{len(fit_frame)}: la etapa de bootstrapping debe correr sobre el mismo CSV balanceado.")
s = modeling
runs, t0 = [], time.time()
for b in range(s.n_bootstrap_run):
if time.time() - t0 > s.bootstrap_max_seconds:
break
df_b = fit_frame.iloc[bootstrap_indices[b]].reset_index(drop=True)
runs.append(run_replica(df_b, s.random_state + b, fit_features, s, s.bootstrap_include_hbn,
s.bootstrap_restarts))
return runs
def bootstrap_selection(bootstrap_runs: list[dict], fit_features: list[str]) -> pd.DataFrame:
"""The terms each replica's LR kept, and the outcome's parents in each replica's HBN: how stable the selection is."""
longest_first = sorted(fit_features, key=len, reverse=True)
def variable_of(term):
return next((c for c in longest_first if term.startswith(c + "_")), term)
rows = []
for b, res in enumerate(bootstrap_runs):
if res["coefs"] is not None:
rows.append({"replica": b, "modelo": "LR", "variable": "", "termino": "(replica)", "coef": np.nan})
rows += [{"replica": b, "modelo": "LR", "variable": variable_of(t), "termino": t, "coef": v}
for t, v in res["coefs"].items()]
if res["padres"] is not None:
rows.append({"replica": b, "modelo": "HBN", "variable": "", "termino": "(replica)", "coef": np.nan})
rows += [{"replica": b, "modelo": "HBN", "variable": p, "termino": p, "coef": np.nan} for p in res["padres"]]
return pd.DataFrame(rows)
def _interval(values) -> tuple[float, float, int]:
arr = np.array([a for a in values if not np.isnan(a)])
if len(arr) == 0:
return (np.nan, np.nan, 0)
lo, hi = np.percentile(arr, [2.5, 97.5])
return (lo, hi, len(arr))
def bootstrap_auc(bootstrap_runs: list[dict]) -> pd.DataFrame:
"""Mean AUC and its 95 % percentile interval over the replicas with a valid AUC, per model."""
rows = []
for name, key in [("LR (stepwise)", "auc_lr"), ("HBN (CPT tabular)", "auc_hbn")]:
values = [r[key] for r in bootstrap_runs]
lo, hi, n_valid = _interval(values)
rows.append({"modelo": name, "AUC medio": np.nanmean(values) if n_valid else np.nan,
"IC 95% lo": lo, "IC 95% hi": hi, "replicas validas": n_valid})
return pd.DataFrame(rows).round(3)
def bootstrap_auc_difference(bootstrap_runs: list[dict]) -> pd.DataFrame | None:
"""The paired difference LR - HBN over the replicas where both exist; None when there is none."""
d = np.array([r["auc_lr"] for r in bootstrap_runs]) - np.array([r["auc_hbn"] for r in bootstrap_runs])
d = d[~np.isnan(d)]
if not len(d):
return None
return pd.DataFrame([{"dif_AUC_LR_menos_HBN": d.mean(), "IC95_inf": np.percentile(d, 2.5),
"IC95_sup": np.percentile(d, 97.5), "pct_replicas_LR_gana": (d > 0).mean() * 100}]).round(4)
# ---------------------------------------------------------------- categorization proposals
def proposal_runs(fit_frame: pd.DataFrame, proposals_csv: str, fit_features: list[str],
modeling: ModelingSettings) -> pd.DataFrame:
"""The replica pipeline for each proposal on `n_splits_prop` splits (the same seeds for all: a paired comparison)."""
s = modeling
prop = pd.read_csv(proposals_csv, dtype=str)
assert len(prop) == len(fit_frame), (f"propuestas_categorizacion.csv tiene {len(prop)} filas y el balanceado "
f"{len(fit_frame)}: deben salir del MISMO balanceo (mismo orden de filas)")
ids = sorted({c.split("__", 1)[1] for c in prop.columns if "__" in c})
if s.proposals_only:
ids = [i for i in ids if i in s.proposals_only]
results, t0, stop = [], time.time(), False
for pid in ids:
df_p = fit_frame.copy()
k_age = k_tumor = None
if f"Age_group__{pid}" in prop.columns:
df_p["Edad"] = prop[f"Age_group__{pid}"].values
k_age = df_p["Edad"].nunique()
if f"Tumor_group__{pid}" in prop.columns and "Tamano_tumor" in df_p.columns:
df_p["Tamano_tumor"] = prop[f"Tumor_group__{pid}"].values
k_tumor = df_p["Tamano_tumor"].nunique(dropna=False)
for split in range(s.n_splits_prop):
if time.time() - t0 > s.proposals_max_seconds:
stop = True
break
res = run_replica(df_p, s.random_state + split, fit_features, s, s.proposals_include_hbn,
s.bootstrap_restarts)
results.append({"propuesta": pid, "split": split, "K_edad": k_age, "K_tumor": k_tumor, **res})
if stop:
break
return pd.DataFrame(results)
def proposal_summary(proposal_runs: pd.DataFrame) -> pd.DataFrame:
summary = (proposal_runs.groupby("propuesta")
.agg(K_edad=("K_edad", "first"), K_tumor=("K_tumor", "first"),
AUC_LR=("auc_lr", "mean"), sd_LR=("auc_lr", "std"),
AUC_HBN=("auc_hbn", "mean"), sd_HBN=("auc_hbn", "std"),
vars_LR=("n_selected_lr", "mean"), padres_HBN=("n_parents_hbn", "mean"),
n_splits=("split", "count")).round(3))
return summary.sort_values("AUC_LR", ascending=False)
def proposal_deltas(proposal_runs: pd.DataFrame) -> pd.DataFrame:
"""Each proposal's AUC minus the base proposal's (`P1_actual`, else the first), on the same splits."""
runs = proposal_runs
base = "P1_actual" if "P1_actual" in runs["propuesta"].values else runs["propuesta"].iloc[0]
b = runs[runs["propuesta"] == base].set_index("split")
rows = []
for pid in runs["propuesta"].unique():
if pid == base:
continue
j = b.join(runs[runs["propuesta"] == pid].set_index("split"), lsuffix="_b", rsuffix="_x", how="inner")
rows.append({"propuesta": pid, f"ΔAUC_LR vs {base}": (j["auc_lr_x"] - j["auc_lr_b"]).mean(),
f"ΔAUC_HBN vs {base}": (j["auc_hbn_x"] - j["auc_hbn_b"]).mean(), "splits_comparados": len(j)})
return pd.DataFrame(rows).round(4)
@@ -0,0 +1,74 @@
"""The statistics of the risk-factor stage, apart from its nodes (`risk_factors.py`): the multivariable odds ratios,
Benjamini-Hochberg, and the Kaplan-Meier survival difference against a reference category. Plain functions with no
I/O. Ported from `06_factores_riesgo.py`."""
import numpy as np
import pandas as pd
import statsmodels.api as sm
def reference(data: pd.DataFrame, v: str) -> str:
"""The reference category of a variable: its most frequent one."""
return data[v].value_counts().idxmax()
def fit_odds(data: pd.DataFrame, death: np.ndarray, variables: list[str]) -> pd.DataFrame:
"""The multivariable OR of death for each category of `variables` against the reference, by a binomial GLM."""
X = pd.get_dummies(data[variables], drop_first=False).astype(float)
refs = {v: f"{v}_{reference(data, v)}" for v in variables}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
model = sm.GLM(death, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = model.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_muerte": np.exp(model.params[X.columns].values),
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
"p": model.pvalues[X.columns].values})
def variable_of(term: str, variables: list[str]) -> str:
"""The variable a dummy's name belongs to (the longest name that prefixes it)."""
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
def benjamini_hochberg(p) -> np.ndarray:
p = np.asarray(p, float)
order = np.argsort(p)
adjusted = np.empty_like(p)
m = len(p)
prev = 1.0
for rank, i in zip(range(m, 0, -1), order[::-1]):
prev = min(prev, p[i] * m / rank)
adjusted[i] = prev
return adjusted
def km_at(months: np.ndarray, event: np.ndarray, horizon: int) -> tuple[float, float]:
"""(S(horizon), its Greenwood standard error) from monthly follow-up."""
T = int(months.max()) + 2
d = np.bincount(months[event], minlength=T)
c = np.bincount(months[~event], minlength=T)
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
h = min(horizon, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def survival_difference(data: pd.DataFrame, months: np.ndarray, event: np.ndarray, v: str, cat: str, ref: str,
horizon: int) -> pd.Series:
"""S(horizon) of the category minus the reference's, with its 95 % interval."""
a = (data[v] == cat).values
b = (data[v] == ref).values
Sa, ea = km_at(months[a], event[a], horizon)
Sb, eb = km_at(months[b], event[b], horizon)
d = Sa - Sb
se = np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S18_categoria": Sa, "S18_referencia": Sb, "delta_S18": d,
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
def survival_differences(data, months, event, rows, horizon) -> pd.DataFrame:
"""`survival_difference` for each (variable, category, reference) of `rows`."""
return pd.DataFrame([survival_difference(data, months, event, v, c, r, horizon) for v, c, r in rows])
+306
View File
@@ -0,0 +1,306 @@
"""Stage 06, risk factors: classifies each category of the intrinsic variables as a robust or suggestive risk or
protective factor from four criteria (see `model.toml`, `[risk_factors]`): c1 the multivariable OR, c2 stability in the
bootstrap, c3 the outcome's Markov blanket in the HBN, c4 the 18-month survival difference. Treatment variables are a
clinical decision: they are reported apart, not classified.
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `natural_csv`,
`bootstrap_selection_csv`, `hbn_arcs_csv` (stage 04's outputs) and `risk_factors` (its settings). The statistics are in
`risk_factor_stats.py`.
"""
import os
from dataclasses import dataclass
import numpy as np
import pandas as pd
from models.cama.seer_survival import risk_factor_stats as stats
from models.cama.seer_survival import scenarios
from models.cama.seer_survival.settings import RiskFactorSettings
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
UNKNOWN_CATEGORY = "no aplica (categoria desconocida)"
COLUMNS = ["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p", "p_ajustado_BH",
"freq_seleccion_bootstrap", "en_manta_markov", "S18_categoria", "S18_referencia", "delta_S18",
"delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "criterios_evaluados", "clasificacion"]
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3,
"no concluyente": 4}
@dataclass(frozen=True, eq=False)
class FollowUp:
death: np.ndarray # 1 = Muerte (the outcome at the horizon)
months: np.ndarray # follow-up, capped at `cap_months`
event: np.ndarray # died before the cap
@dataclass(frozen=True, eq=False)
class BootstrapFrequency:
frequency: pd.Series # per variable: the share of valid replicas whose LR kept it (NaN when there are none)
n_replicas: int
@dataclass(frozen=True, eq=False)
class Classification:
table: pd.DataFrame
criteria: list[str] # the criteria that could be evaluated
def _find_col(df: pd.DataFrame, keywords) -> str | None:
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
# ---------------------------------------------------------------- the data
def risk_natural(natural_csv: str) -> pd.DataFrame:
nat = pd.read_csv(natural_csv, dtype=str)
return nat[nat["Outcome_cat"].isin(["Sobrevive", "Muerte"])].reset_index(drop=True)
def risk_data(risk_natural: pd.DataFrame, risk_factors: RiskFactorSettings) -> pd.DataFrame:
"""The covariates under canonical names, the unknowns as one more category; race as it comes from SEER."""
nat = risk_natural
data = pd.DataFrame({v: nat[k].fillna("Desconocido").astype(str)
for k, v in risk_factors.canonical_map.items() if k in nat.columns})
race = _find_col(nat, ["race"])
if race is not None and race not in risk_factors.canonical_map:
data["Race"] = nat[race].fillna("Desconocido").astype(str)
return data
def risk_intrinsic(risk_data: pd.DataFrame, risk_factors: RiskFactorSettings) -> list[str]:
return [v for v in risk_data.columns if v not in risk_factors.treatment]
def risk_treatment(risk_data: pd.DataFrame, risk_factors: RiskFactorSettings) -> list[str]:
return [v for v in risk_data.columns if v in risk_factors.treatment]
def risk_follow_up(risk_natural: pd.DataFrame, risk_factors: RiskFactorSettings) -> FollowUp:
nat, cap = risk_natural, risk_factors.cap_months
months_col, vital_col = _find_col(nat, ["survival months"]), _find_col(nat, ["vital status"])
raw = pd.to_numeric(nat[months_col], errors="coerce").fillna(0)
return FollowUp(death=(nat["Outcome_cat"] == "Muerte").astype(int).values,
months=np.minimum(raw.astype(int).values, cap),
event=nat[vital_col].astype(str).str.lower().str.contains("dead").values & (raw.values < cap))
# ---------------------------------------------------------------- the criteria
def risk_odds(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
risk_factors: RiskFactorSettings) -> pd.DataFrame:
"""c1: the multivariable OR of death of each category (reference = the most frequent), significant when its 95 % CI
doesn't cross 1 and its Benjamini-Hochberg p is below alpha."""
tab = stats.fit_odds(risk_data, risk_follow_up.death, risk_intrinsic)
tab["variable"] = [stats.variable_of(t, risk_intrinsic) for t in tab["termino"]]
tab["categoria"] = [t[len(v) + 1:] for t, v in zip(tab["termino"], tab["variable"])]
tab["referencia"] = [stats.reference(risk_data, v) for v in tab["variable"]]
tab["p_ajustado_BH"] = stats.benjamini_hochberg(tab["p"])
tab["direccion"] = np.where(tab["OR_muerte"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < risk_factors.alpha)
return tab
def risk_survival(risk_odds: pd.DataFrame, risk_data: pd.DataFrame, risk_follow_up: FollowUp,
risk_factors: RiskFactorSettings) -> pd.DataFrame:
"""c4: the survival difference at the horizon against the reference, significant when its interval excludes 0 and it
goes the way the OR says."""
tab = risk_odds
ds = stats.survival_differences(risk_data, risk_follow_up.months, risk_follow_up.event,
zip(tab["variable"], tab["categoria"], tab["referencia"]), risk_factors.horizon)
tab = pd.concat([tab.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab["c4_supervivencia"] = (((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0))
& (np.sign(tab["delta_S18"]) == np.where(tab["direccion"] == "riesgo", -1, 1)))
return tab
def risk_bootstrap_frequency(risk_intrinsic: list[str], bootstrap_selection_csv: str) -> BootstrapFrequency:
"""c2's input: in how many of the bootstrap replicas each variable entered the LR (NaN without the file)."""
freq, n_rep = pd.Series(np.nan, index=risk_intrinsic), 0
if os.path.exists(bootstrap_selection_csv):
sel = pd.read_csv(bootstrap_selection_csv)
lr = sel[sel["modelo"] == "LR"]
n_rep = int((lr["termino"] == "(replica)").sum())
if n_rep > 0:
per_var = lr[lr["termino"] != "(replica)"].groupby("variable")["replica"].nunique()
freq = pd.Series({v: per_var.get(v, 0) / n_rep for v in risk_intrinsic})
return BootstrapFrequency(freq, n_rep)
def risk_stability(risk_survival: pd.DataFrame, risk_bootstrap_frequency: BootstrapFrequency,
risk_factors: RiskFactorSettings) -> pd.DataFrame:
"""c2: the variable's selection frequency is at least `freq_min`."""
tab = risk_survival.copy()
tab["freq_seleccion_bootstrap"] = tab["variable"].map(risk_bootstrap_frequency.frequency)
tab["c2_estabilidad"] = ((tab["freq_seleccion_bootstrap"] >= risk_factors.freq_min).astype(object)
.where(tab["freq_seleccion_bootstrap"].notna(), np.nan))
return tab
def risk_markov_blanket(hbn_arcs_csv: str) -> set | None:
"""The outcome's Markov blanket in the HBN (parents, children and the children's other parents); None without the
file."""
if not os.path.exists(hbn_arcs_csv):
return None
arcs = pd.read_csv(hbn_arcs_csv)
parents = set(arcs.loc[arcs["destino"] == "outcome", "origen"])
children = set(arcs.loc[arcs["origen"] == "outcome", "destino"])
spouses = set(arcs.loc[arcs["destino"].isin(children) & (arcs["origen"] != "outcome"), "origen"])
return parents | children | spouses
def risk_with_blanket(risk_stability: pd.DataFrame, risk_markov_blanket: set | None) -> pd.DataFrame:
"""c3: the variable is in the outcome's Markov blanket."""
tab = risk_stability.copy()
tab["en_manta_markov"] = tab["variable"].map(
lambda v: (v in risk_markov_blanket) if risk_markov_blanket is not None else np.nan)
tab["c3_manta_markov"] = tab["en_manta_markov"].astype(object)
return tab
def risk_classification(risk_with_blanket: pd.DataFrame) -> Classification:
"""Robust: c1 and at least three criteria (or all those evaluated, if fewer); suggestive: at least two; else
inconclusive. A category that is "unknown" doesn't apply."""
tab = risk_with_blanket.copy()
available = [c for c in CRITERIA if tab[c].notna().all()]
tab["criterios_cumplidos"] = tab[available].apply(lambda c: c.map(lambda x: bool(x == True))).sum(axis=1) # noqa: E712
tab["criterios_evaluados"] = len(available)
min_robust = min(3, len(available))
def classify(r):
if r["categoria"] == "Desconocido":
return UNKNOWN_CATEGORY
if r["c1_or"] and r["criterios_cumplidos"] >= min_robust:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(classify, axis=1)
tab["_o"] = tab["clasificacion"].map(ORDER).fillna(5)
tab = tab.sort_values(["_o", "OR_muerte"], ascending=[True, False])[COLUMNS]
return Classification(tab, available)
def risk_factors_table(risk_classification: Classification) -> pd.DataFrame:
return risk_classification.table.round(4)
def risk_variable_summary(risk_classification: Classification) -> pd.DataFrame:
tab = risk_classification.table
summary = tab[tab["clasificacion"] != UNKNOWN_CATEGORY].groupby("variable").agg(
categorias_robustas=("clasificacion", lambda s: int(s.str.contains("robusto").sum())),
categorias_sugerentes=("clasificacion", lambda s: int(s.str.contains("sugerente").sum())),
freq_seleccion_bootstrap=("freq_seleccion_bootstrap", "first"),
en_manta_markov=("en_manta_markov", "first"),
OR_max=("OR_muerte", "max"), OR_min=("OR_muerte", "min"),
).sort_values(["categorias_robustas", "categorias_sugerentes"], ascending=False)
return summary.round(4)
def risk_treatment_associations(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by
indication); None when there are none
or none of them varies."""
if not risk_treatment:
return None
variables = risk_intrinsic + risk_treatment
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
tr = tr[tr["variable"].isin(risk_treatment)].copy()
if tr.empty:
return None
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
tr["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"])
ds = stats.survival_differences(risk_data, risk_follow_up.months, risk_follow_up.event,
zip(tr["variable"], tr["categoria"], tr["referencia"]), risk_factors.horizon)
tr = pd.concat([tr.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tr["nota"] = "asociacion ajustada por las demas variables; no implica efecto causal (confusion por indicacion)"
return tr[["variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf", "IC95_sup", "p",
"p_ajustado_BH", "S18_categoria", "S18_referencia", "delta_S18", "delta_IC95_inf", "delta_IC95_sup",
"nota"]].round(4)
def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency: BootstrapFrequency,
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> dict:
return {"alfa": risk_factors.alpha, "freq_min_bootstrap": risk_factors.freq_min,
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
# ---------------------------------------------------------------- the risk factors of each clinical scenario
PCT_DEFINING = 0.95 # the category is in at least this share of the scenario: it defines it
PCT_MAJORITY = 0.50
PCT_PRESENT = 0.10
@dataclass(frozen=True, eq=False)
class ScenarioFactors:
details: pd.DataFrame # per scenario and classified category: its share of the scenario and of the cohort
summary: pd.DataFrame # per scenario: the risk factors, protectors and treatments that define it or are most of it
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def risk_scenario_masks(risk_natural: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each clinical scenario's mask over the natural population (`scenarios.masks`), on its raw columns."""
return scenarios.masks(risk_natural.drop(columns=[c for c in ("Age_group", "Tumor_group") if c in risk_natural.columns]))
def risk_scenario_factors(risk_classification: Classification, risk_treatment_associations: pd.DataFrame | None,
risk_data: pd.DataFrame, risk_scenario_masks: dict[str, np.ndarray]) -> ScenarioFactors:
"""Which of the classified risk factors, protectors and treatment associations make up each clinical scenario: a
category that is nearly all of a scenario defines it, one that is most of it describes it."""
table = risk_classification.table
classified = table[table["clasificacion"].str.contains("robusto|sugerente")].copy()
classified["tipo"] = classified["clasificacion"].str.split().str[0]
if risk_treatment_associations is not None and len(risk_treatment_associations):
treatment = risk_treatment_associations.copy()
treatment["clasificacion"], treatment["tipo"] = "tratamiento (no se clasifica)", "tratamiento"
classified = pd.concat([classified, treatment], ignore_index=True)
details, summary = [], []
for name, mask in risk_scenario_masks.items():
size = int(mask.sum())
if size == 0:
continue
definition = scenarios.describe(scenarios.SCENARIOS[name]) if name in scenarios.SCENARIOS else ""
rows = []
for _, r in classified.iterrows():
share = float((risk_data[r["variable"]][mask] == r["categoria"]).mean())
rows.append({"escenario": name, "definicion": definition, "n_escenario": size,
"tipo": r["tipo"], "variable": r["variable"], "categoria": r["categoria"], "clasificacion": r["clasificacion"],
"OR_muerte": r["OR_muerte"], "IC95_inf": r["IC95_inf"], "IC95_sup": r["IC95_sup"], "delta_S18": r["delta_S18"],
"pct_en_escenario": share, "pct_en_cohorte": float((risk_data[r["variable"]] == r["categoria"]).mean()),
"presencia": _presence(share)})
found = pd.DataFrame(rows, columns=["escenario", "definicion", "n_escenario", "tipo", "variable", "categoria", "clasificacion",
"OR_muerte", "IC95_inf", "IC95_sup", "delta_S18", "pct_en_escenario", "pct_en_cohorte", "presencia"])
details.append(found[found["pct_en_escenario"] >= PCT_PRESENT])
def listed(kind, levels):
part = found[(found["tipo"] == kind) & (found["presencia"].isin(levels))]
return "; ".join(f"{a}={b} ({c.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for a, b, c, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row = {"escenario": name, "definicion": definition, "n_escenario": size}
for kind in ("riesgo", "protector", "tratamiento"):
row[f"{kind}_definitorios"] = listed(kind, ["definitoria"])
row[f"{kind}_mayoritarios"] = listed(kind, ["mayoritaria"])
row["n_factores_riesgo_incluidos"] = int(((found["tipo"] == "riesgo") & found["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return ScenarioFactors(pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame(), pd.DataFrame(summary))
+217
View File
@@ -0,0 +1,217 @@
"""The pipeline's Hamilton drivers, one per stage, and the files each stage writes. The nodes (`depuration.py`,
`bootstrap.py`, ...) are pure; only this module touches the output folder. `pipeline.py` runs the stages in order:
`python -m models.cama.seer_survival --data DIR`.
"""
import datetime
import json
import re
from pathlib import Path
import numpy as np
from hamilton import driver
from models.cama.seer_survival import (balancing, bootstrap, categorization, depuration, modeling, resampling,
risk_factors, survival_curves)
from models.cama.seer_survival.settings import Settings, load
DEPURATED = "dataframe_depurado.csv"
BOOTSTRAP_INDICES = "bootstrap_indices.npy"
BOOTSTRAP_METADATA = "bootstrap_metadata.json"
DEPURATION_DIR = "depuracion_resultados_1"
FIGURES_DIR = "figuras"
BALANCED_MCA = "dataframe_balanceado_mca.csv"
BALANCED_AGE = "dataframe_balanceado_con_edad_agrupada.csv"
BALANCED = "dataframe_balanceado_con_edad_y_tumor_agrupados.csv"
NATURAL = "dataframe_poblacion_natural.csv"
PROPOSALS = "propuestas_categorizacion.csv"
PROPOSALS_SUMMARY = "propuestas_categorizacion_resumen.csv"
LABELS_JSON = "dataframe_construido_labels.json"
def _jsonable(o):
"""`default` of `json.dump` for the numpy values and sets the reports carry."""
if isinstance(o, np.floating):
return float(o)
if isinstance(o, np.integer):
return int(o)
if isinstance(o, (set, tuple)):
return list(o)
return str(o)
def _dump(path: Path, data: dict, **kwargs) -> None:
path.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=_jsonable, **kwargs), encoding="utf-8")
def run_depuration(recoded_csv: str, mapping_json: str, output_dir: str, settings: Settings | None = None,
generated_at: str | None = None) -> dict:
"""Runs stage 01 and writes `dataframe_depurado.csv` and the reports in `depuracion_resultados_1/`."""
settings = settings or load()
out = Path(output_dir)
reports = out / DEPURATION_DIR
reports.mkdir(parents=True, exist_ok=True)
dr = driver.Builder().with_modules(depuration).build()
inputs = {"recoded_csv": str(recoded_csv), "mapping_json": str(mapping_json), "depuration": settings.depuration,
"generated_at": generated_at or datetime.datetime.now().isoformat(timespec="seconds")}
r = dr.execute(["calibration", "calibration_report", "elimination", "depurated", "kept_variables"], inputs=inputs)
r["calibration"].pairs_u.to_csv(reports / "calibracion_U_pares.csv", index=False)
if len(r["calibration"].cluster_cut_table):
r["calibration"].cluster_cut_table.to_csv(reports / "calibracion_clustering_corte.csv", index=False)
_dump(reports / "calibracion_umbrales.json", r["calibration_report"])
r["depurated"].to_csv(out / DEPURATED, index=False)
r["elimination"].dropped.to_csv(reports / "variables_eliminadas.csv", index=False)
_dump(reports / "variables_conservadas.json", r["kept_variables"])
return r
def save_figures(figures: list, prefix: str, folder: Path, first: int = 1) -> list[Path]:
"""Saves each figure as `<prefix>_<nn>_<slug of its title>.png`, numbered from `first`, as the scripts did."""
folder.mkdir(parents=True, exist_ok=True)
paths = []
for n, fig in enumerate(figures, first):
title = fig._suptitle.get_text() if getattr(fig, "_suptitle", None) is not None else (fig.axes[0].get_title() or "figura")
slug = re.sub(r"[^A-Za-z0-9]+", "_", title).strip("_")[:50] or "figura"
paths.append(folder / f"{prefix}_{n:02d}_{slug}.png")
fig.savefig(paths[-1], dpi=150, bbox_inches="tight")
return paths
def run_balancing(depurated_csv: str, output_dir: str, labels_json: str | None = None,
settings: Settings | None = None) -> dict:
"""Runs stages 02a and 02b: the MCA balancing, then the age and tumor categorization. Writes the balanced files,
the cut comparisons and sensitivity/specificity tables, the proposals, the natural population and two figures."""
settings = settings or load()
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
dr = driver.Builder().with_modules(balancing, categorization).build()
inputs = {"depurated_csv": str(depurated_csv), "labels_json": str(labels_json or out / LABELS_JSON),
"balancing": settings.balancing, "categorization": settings.categorization}
r = dr.execute(["balanced_frame", "age_grouped", "balanced_final", "age_comparison", "tumor_comparison",
"age_diagnostics", "tumor_diagnostics", "proposals", "natural_population"], inputs=inputs)
r["balanced_frame"].to_csv(out / BALANCED_MCA, index=False)
r["age_grouped"].to_csv(out / BALANCED_AGE, index=False)
r["age_comparison"].to_csv(out / "comparacion_cortes_edad.csv", index=False)
r["tumor_comparison"].to_csv(out / "comparacion_cortes_tumor.csv", index=False)
r["balanced_final"].to_csv(out / BALANCED, index=False)
r["age_diagnostics"].table.to_csv(out / "sens_esp_edad.csv")
r["tumor_diagnostics"].table.to_csv(out / "sens_esp_tumor.csv")
save_figures([r["age_diagnostics"].figure, r["tumor_diagnostics"].figure], "02", out / FIGURES_DIR)
r["proposals"].table.to_csv(out / PROPOSALS, index=False)
r["proposals"].summary.to_csv(out / PROPOSALS_SUMMARY, index=False)
r["natural_population"].to_csv(out / NATURAL, index=False)
return r
def run_modeling(balanced_csv: str, output_dir: str, natural_csv: str | None = None,
bootstrap_indices_path: str | None = None, proposals_csv: str | None = None,
settings: Settings | None = None) -> dict:
"""Runs stage 04: the stepwise LR and the HBN on the balanced cohort and their comparison, the natural-population
LR, and the bootstrap and proposal replicas. Writes their tables and four figures."""
import warnings
settings = settings or load()
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
np.random.seed(settings.modeling.random_state)
dr = driver.Builder().with_modules(modeling, resampling).build()
inputs = {"balanced_csv": str(balanced_csv), "natural_csv": str(natural_csv or out / NATURAL),
"bootstrap_indices": np.load(bootstrap_indices_path or out / BOOTSTRAP_INDICES),
"proposals_csv": str(proposals_csv or out / PROPOSALS), "modeling": settings.modeling}
wanted = ["lr_odds_ratios", "hbn_arcs", "hbn_graph_figure", "roc_figure", "calibration_figure", "dca_figure",
"differentiation_table", "auc_internal", "natural_results", "bootstrap_selection", "bootstrap_auc",
"bootstrap_auc_difference", "proposal_runs", "proposal_summary", "proposal_deltas"]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
r = dr.execute(wanted, inputs=inputs)
r["lr_odds_ratios"].to_csv(out / "or_lr_balanceada.csv")
r["hbn_arcs"].to_csv(out / "hbn_arcos.csv", index=False)
figures = [r[k] for k in ("hbn_graph_figure", "roc_figure", "calibration_figure", "dca_figure") if r[k] is not None]
save_figures(figures, "04", out / FIGURES_DIR)
r["differentiation_table"].to_csv(out / "metricas_diferenciacion.csv")
r["auc_internal"].to_csv(out / "auc_validacion_interna.csv", index=False)
nat = r["natural_results"]
if nat is not None:
nat.odds_ratios.to_csv(out / "or_lr_poblacion_natural.csv")
nat.odds_ratios_no_treatment.to_csv(out / "or_lr_poblacion_natural_sin_tratamiento.csv")
nat.comparison.to_csv(out / "comparacion_lr_balanceada_vs_natural.csv")
nat.auc_by_stage.to_csv(out / "auc_por_estadio_lr_natural.csv")
nat.auc_by_stage_no_treatment.to_csv(out / "auc_por_estadio_lr_natural_sin_tratamiento.csv")
nat.calibration_deciles.to_csv(out / "calibracion_deciles_lr_natural.csv", index=False)
r["bootstrap_selection"].to_csv(out / "seleccion_bootstrap.csv", index=False)
r["bootstrap_auc"].to_csv(out / "auc_bootstrap.csv", index=False)
if r["bootstrap_auc_difference"] is not None:
r["bootstrap_auc_difference"].to_csv(out / "auc_bootstrap_diferencia.csv", index=False)
r["proposal_runs"].to_csv(out / "resultados_propuestas_categorizacion.csv", index=False)
r["proposal_summary"].to_csv(out / "resumen_propuestas_categorizacion.csv")
r["proposal_deltas"].to_csv(out / "delta_auc_propuestas_vs_base.csv", index=False)
return r
def _subgroup_file(name: str) -> str:
"""`subgrupo_<name>.png` with the name made ASCII, as the script did."""
for old, new in [("≥", "ge"), ("≤", "le"), ("<", "lt"), (">", "gt"), ("ñ", "n"), ("–", "-")]:
name = name.replace(old, new)
return re.sub(r"[^A-Za-z0-9]+", "_", name).strip("_")
def run_survival(depurated_csv: str, output_dir: str, settings: Settings | None = None) -> dict:
"""Runs stage 05 on the complete cohort: the main curve and its points, the subgroups' curves, fits and points, the
combination's weights and the test of age as a number. Age modes other than `categorizada` write suffixed files."""
settings = settings or load()
s = settings.survival
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
suffix = s.file_suffix
dr = driver.Builder().with_modules(survival_curves).build()
r = dr.execute(["sv_table", "sv_main_figure", "sv_weights_cohort", "sv_sub_figures", "sv_sub_fits_table",
"sv_sub_points_table", "sv_sub_weights_table", "sv_age_test"],
inputs={"depurated_csv": str(depurated_csv), "survival": s})
r["sv_table"].to_csv(out / f"curva_supervivencia_puntos_LR_HBN{suffix}.csv", index=False)
r["sv_main_figure"].savefig(out / f"curva_supervivencia_KM_KS_LR_HBN{suffix}.png", dpi=200)
if r["sv_weights_cohort"] is not None:
r["sv_weights_cohort"].to_csv(out / f"pesos_combinacion_cohorte{suffix}.csv", index=False)
for name, fig in r["sv_sub_figures"].items():
fig.savefig(out / f"subgrupo_{_subgroup_file(name)}{suffix}.png", dpi=170)
r["sv_sub_fits_table"].to_csv(out / f"subgrupos_KM_Weibull_fraccional{suffix}.csv", index=False)
r["sv_sub_points_table"].to_csv(out / f"subgrupos_puntos_LR_HBN{suffix}.csv", index=False)
if r["sv_sub_weights_table"] is not None:
r["sv_sub_weights_table"].to_csv(out / f"subgrupos_pesos_combinacion{suffix}.csv", index=False)
r["sv_age_test"].by_subgroup.to_csv(out / f"prueba_edad_continua_vs_categorizada{suffix}.csv", index=False)
r["sv_age_test"].summary.to_csv(out / f"prueba_edad_resumen{suffix}.csv", index=False)
return r
def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv: str | None = None,
hbn_arcs_csv: str | None = None, settings: Settings | None = None) -> dict:
"""Runs stage 06 and writes the risk factors, their per-variable summary, the treatment associations and the
criteria used."""
settings = settings or load()
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
dr = driver.Builder().with_modules(risk_factors).build()
inputs = {"natural_csv": str(natural_csv),
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
"risk_scenario_factors"], inputs=inputs)
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
if r["risk_treatment_associations"] is not None:
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
r["risk_scenario_factors"].details.to_csv(out / "escenarios_factores_riesgo.csv", index=False)
r["risk_scenario_factors"].summary.to_csv(out / "escenarios_resumen.csv", index=False)
return r
def run_bootstrap(balanced_csv: str, output_dir: str, settings: Settings | None = None) -> dict:
"""Runs stage 03 and writes `bootstrap_indices.npy` and `bootstrap_metadata.json`."""
settings = settings or load()
out = Path(output_dir)
dr = driver.Builder().with_modules(bootstrap).build()
r = dr.execute(["bootstrap_indices", "bootstrap_metadata"],
inputs={"balanced_csv": str(balanced_csv), "bootstrap": settings.bootstrap})
np.save(out / BOOTSTRAP_INDICES, r["bootstrap_indices"])
(out / BOOTSTRAP_METADATA).write_text(json.dumps(r["bootstrap_metadata"], indent=2), encoding="utf-8")
return r
+116
View File
@@ -0,0 +1,116 @@
"""The clinical scenarios of the survival analysis: the subgroups whose curves stage 5 draws and whose risk factors stage 6
lists. Each is a set of conditions over the cohort's raw columns (age, stage, molecular subtype, surgery); the columns are
found by keyword, so a cohort without one of them has no patient in the scenarios that need it. Ported from
`escenarios_clinicos.py`.
"""
import re
import numpy as np
import pandas as pd
def find_col(df: pd.DataFrame, keywords) -> str | None:
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
def _age(v) -> float:
m = re.search(r"\d+", str(v))
return float(m.group()) if m else np.nan
def _stage(v) -> float:
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS":
return 0
for prefix, value in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(prefix):
return value
return np.nan
def _age_column(df: pd.DataFrame) -> str | None:
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
if not candidates:
return None
return sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
def values_by_axis(df: pd.DataFrame) -> dict[str, pd.Series]:
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
col_subtype = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
col_surgery = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
col_age = _age_column(df)
n = len(df)
return {
"edad": df[col_age].map(_age).astype(float) if col_age else pd.Series(np.nan, index=df.index),
"estadio": df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index),
"subtipo": df[col_subtype].astype(str) if col_subtype else pd.Series([""] * n, index=df.index),
"cirugia": df[col_surgery].astype(str).str.lower() if col_surgery else pd.Series([""] * n, index=df.index),
}
AGE_BELOW = lambda x: ("edad", "<", x)
AGE_FROM = lambda x: ("edad", ">=", x)
STAGE_0_II = ("estadio", "en", [0, 1, 2])
STAGE_III_IV = ("estadio", "en", [3, 4])
HER2_POS = ("subtipo", "contiene", "HER2+")
HER2_NEG = ("subtipo", "contiene", "HER2-")
TRIPLE_NEG = ("subtipo", "contiene", "HR-/HER2-")
CONSERVATIVE = ("cirugia", "contiene", "conserv")
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": [HER2_POS, AGE_FROM(60), STAGE_III_IV],
"HER2+ · <60 años · estadio 0–II (Bajo)": [HER2_POS, AGE_BELOW(60), STAGE_0_II],
"Estadio IV": [("estadio", "en", [4])],
"Estadio I": [("estadio", "en", [1])],
"≥ 75 años": [AGE_FROM(75)],
"< 45 años": [AGE_BELOW(45)],
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": [AGE_BELOW(45), HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2− · estadio 0–II · cirugía conservadora": [HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2+ · estadio 0–II · cirugía conservadora": [HER2_POS, STAGE_0_II, CONSERVATIVE],
"Jóvenes (<45) · estadio 0–II": [AGE_BELOW(45), STAGE_0_II],
"Jóvenes (<45) · HER2−": [AGE_BELOW(45), HER2_NEG],
"Triple negativo (HR−/HER2−) · estadio 0–II": [TRIPLE_NEG, STAGE_0_II],
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": [AGE_FROM(65), HER2_NEG, STAGE_0_II, CONSERVATIVE],
}
STAGE_LABEL = {0: "0", 1: "I", 2: "II", 3: "III", 4: "IV"}
def describe(conditions) -> str:
parts = []
for axis, op, value in conditions:
if axis == "edad":
parts.append(f"edad {op} {value:g}")
elif axis == "estadio":
parts.append("estadio " + "/".join(STAGE_LABEL[v] for v in value))
elif axis == "subtipo":
parts.append(f"subtipo {value}")
elif axis == "cirugia":
parts.append("cirugía conservadora")
return "; ".join(parts)
def masks(df: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the cohort: every condition must hold."""
values = values_by_axis(df)
out = {}
for name, conditions in SCENARIOS.items():
mask = pd.Series(True, index=df.index)
for axis, op, value in conditions:
s = values[axis]
if op == "<":
mask &= (s < value).fillna(False)
elif op == ">=":
mask &= (s >= value).fillna(False)
elif op == "en":
mask &= s.isin(value)
else:
mask &= s.str.contains(value, regex=False)
out[name] = mask.values.astype(bool)
return out
+138
View File
@@ -0,0 +1,138 @@
"""SEER's recoded file as CaMa import files: one CSV per bronze entity, named by the fields the import schemas take, to be
uploaded through the platform's import like any other source.
python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR
What goes where is the dictionary's (`[variables.*.seer]` of `model.toml`): each SEER category is stored as the catalog
value the dictionary names, and read back as the same category. SEER records no calendar dates: the diagnosis is a fixed
day of its year, the birth the middle of the age band, the death (or, for the living, the last contact) the diagnosis
plus the survival months; the months stay exact.
"""
import argparse
from datetime import timedelta
from pathlib import Path
import pandas as pd
from models.cama.seer_survival import variables
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "Mastografia": "mastografias",
"NotaMedica": "notas", "TratamientoMama": "tratamientos"}
FEMALE = "Femenino"
def _age_years(label: str, index: dict) -> float | None:
"""The middle of an age band ("60-64 years" -> 62.5); the open band's own value; None without a number."""
head = str(label).split(" ")[0]
if head.endswith("+"):
return float(index["seer_age_open_value"])
low, _, high = head.partition("-")
if not (low.isdigit() and high.isdigit()):
return None
return (int(low) + int(high) + 1) / 2
def _number(text, spec: dict) -> float | None:
text = str(text)
if text in spec["microscopic"]:
return float(spec["microscopic_mm"])
return float(text) if text.replace(".", "", 1).isdigit() else None
def convert(recoded: pd.DataFrame, dictionary: dict) -> dict[str, pd.DataFrame]:
index = dictionary["index"]
ages = recoded[index["age_column"]].map(lambda v: _age_years(v, index))
frame = recoded[ages.notna()].copy()
ages = ages[ages.notna()]
months = pd.to_numeric(frame[index["months_column"]]).astype(int)
dead = frame[index["vital_column"]].eq(index["dead"])
day = pd.to_timedelta(months * index["days_per_month"], unit="D").dt.round("D")
diagnosis = frame[index["year_column"]].astype(int).map(lambda y: pd.Timestamp(variables.diagnosis_date(y, dictionary)))
birth = diagnosis - pd.to_timedelta((ages * 365.25).round(), unit="D")
ident = frame[index["id_column"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d")
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
tables["Paciente"]["pac_sexo"] = FEMALE
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
tables["Paciente"]["pac_fecha_defuncion"] = date(diagnosis + day).where(dead)
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
tables["Mastografia"]["mast_fecha_toma"] = date(diagnosis)
tables["Mastografia"]["mast_fecha_reporte"] = date(diagnosis)
for name in variables.variable_names(dictionary):
spec = dictionary[name]
seer = spec.get("seer")
if not seer or "treatment" in seer:
continue
origin = seer.get("from", name)
category = frame[variables.column_of(origin, dictionary[origin])]
for target in (seer, seer.get("also")):
if not target:
continue
entity, column = target["bronze"].split(".")
if "number" in seer:
tables[entity][column] = frame[seer["number"]].map(lambda v: _number(v, seer))
elif "number_values" in seer:
tables[entity][column] = category.map(seer["number_values"])
else:
tables[entity][column] = category.map(target["values"])
# A biopsy is invasive unless the stage says in situ.
stage = frame[variables.column_of("Estadio", dictionary["Estadio"])]
in_situ = [k for k, v in dictionary["Estadio"]["seer"]["values"].items() if v == "E0"]
tables["BiopsiaMama"]["bx_grado_histologico"] = stage.isin(in_situ).map(
{True: "CARCINOMA_IN_SITU", False: "CARCINOMA_INVASOR"})
# A receptor status the subtype contradicts follows the subtype (the model reads the subtype from the receptors).
subtype = frame[variables.column_of("Subtipo_molecular", dictionary["Subtipo_molecular"])]
positive_hr = subtype.str.startswith("HR+")
negative_hr = subtype.str.startswith("HR-")
bx = tables["BiopsiaMama"]
no_positive = ~((bx["bx_receptor_estrogeno"] == "POSITIVO") | (bx["bx_receptor_progesterona"] == "POSITIVO"))
bx.loc[positive_hr & no_positive, "bx_receptor_estrogeno"] = "POSITIVO"
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
bx.loc[negative_hr & bx[column].isna(), column] = "NEGATIVO"
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
bx.loc[negative_hr & (bx[column] == "POSITIVO"), column] = "NEGATIVO"
notes = tables["NotaMedica"]
notes["nm_id_hospital"] = ident + "-dx"
notes["nm_fecha"] = date(diagnosis)
notes["nm_tipo_nota"] = "CONSULTA"
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(diagnosis + day),
"nm_tipo_nota": "CONSULTA"})[~dead.to_numpy()]
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
treatments = []
for name in variables.variable_names(dictionary):
seer = dictionary[name].get("seer", {})
if "treatment" not in seer:
continue
category = frame[variables.column_of(name, dictionary[name])]
values = category.map(seer["values"])
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": seer["treatment"], "trat_fecha": date(diagnosis),
"trat_detalle": values})[values.notna()]
if seer["treatment"] == "cirugia":
rows["trat_lateralidad"] = bx["bx_lateralidad"].reindex(rows.index)
treatments.append(rows)
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
return tables
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("recoded")
ap.add_argument("out_dir")
args = ap.parse_args(argv)
recoded = pd.read_csv(args.recoded, dtype=str, low_memory=False)
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(recoded, variables.load()).items():
table.to_csv(out / f"{ENTITIES[entity]}.csv", index=False)
if __name__ == "__main__":
main()
+217
View File
@@ -0,0 +1,217 @@
"""The pipeline's settings, read from `model.toml` into typed groups (one per stage)."""
import tomllib
from dataclasses import dataclass, fields
from pathlib import Path
TOML = Path(__file__).parent / "model.toml"
@dataclass(frozen=True)
class DepurationSettings:
exclude: tuple[str, ...]
auto_extra: tuple[str, ...]
extra_cols: tuple[str, ...]
protected: tuple[str, ...]
prefer: tuple[str, ...]
drop_raw_sources: bool
unknown_label: str
dup_u: float
u_redund: float
gvif_drop: float
max_iter_gvif: int
thresholds_auto: bool
n_max_cal: int
null_perm: int
k_azar: int
u_conventional: float
u_gap_from: float
u_gap_min: float
u_plausible: tuple[float, float]
vif_cut: float
r_large: float
min_n_cat: int
max_cat_cluster: int
cluster_dist: str
cluster_method: str
seed: int
gap_from_grid: tuple[float, ...]
gap_min_grid: tuple[float, ...]
@dataclass(frozen=True)
class BalancingSettings:
outcome_mode: str
horizon_months: int
exclude_censored_years: bool
censoring_max_pct: float
age_keywords: tuple[str, ...]
n_components: int
target_ratio: float
distance_dims: int
mca_variant: str
@dataclass(frozen=True)
class CategorizationSettings:
alpha: float
kmax: int
threshold: float
min_count: int
min_n_pct: float
min_n_floor: int
bin_width_mm: int
tumor_cap_mm: int
k_quantiles: int
clinical_age: tuple[int, ...]
clinical_tumor: tuple[int, ...]
age_final: str
tumor_final: str
drop_after: tuple[str, ...]
biology: tuple[str, ...]
treatment: tuple[str, ...]
demographic: tuple[str, ...]
candidate_keywords: dict # covariate -> {"include": [...], "exclude": [...]}
proposals: dict # id -> {"age": spec, "tumor": spec}
@dataclass(frozen=True)
class BootstrapSettings:
n_bootstrap: int
random_state: int
@dataclass(frozen=True)
class ModelingSettings:
random_state: int
test_size: float
prefilter_alpha: float
alpha_in: float
alpha_out: float
max_candidates: int
max_search_rows: int
lr_maxiter: int
bdeu_ess: int
n_restarts: int
max_indegree: int
max_outcome_parents: int
categorical_order: tuple[str, ...]
treatment_vars: tuple[str, ...]
tier_demography: tuple[str, ...]
tier_tumor: tuple[str, ...]
tier_treatment: tuple[str, ...]
run_lr_natural: bool
natural_search_rows: int
natural_test_size: float
natural_maxiter: int
n_bootstrap_run: int
bootstrap_max_seconds: int
bootstrap_include_hbn: bool
bootstrap_restarts: int
n_splits_prop: int
proposals_only: tuple[str, ...]
proposals_include_hbn: bool
proposals_max_seconds: int
canonical_map: dict # column of the balanced file -> canonical name
@dataclass(frozen=True)
class SurvivalSettings:
age_mode: str
include_age: bool
age_cuts: tuple[int, ...]
hbn_fixed_parents: tuple[str, ...]
hbn_age_parent: bool
hbn_parents: str
covariates: tuple[str, ...]
horizons: tuple[int, ...]
censoring: str
combine: bool
show_individual: bool
stack_folds: int
stack_shrink: float
n_boot: int
n_boot_sub: int
seed: int
hbn_ess: int
hbn_max_parents: int
k_ident: str | float
curves: str
adjust_step: int
show_raw_km: bool
ylim_main: tuple[float, ...]
inset_zoom: bool
inset_months: int
cap_months: int
min_events_sub: int
ks_max_seconds: int
ks_sub_max_seconds: int
xlim_sub: tuple[float, ...]
ylim_sub: dict
subgroups: tuple[dict, ...] = ()
@property
def file_suffix(self) -> str:
"""Appended to the output files so the age modes don't overwrite each other."""
return "" if self.age_mode == "categorizada" else f"_edad_{self.age_mode}"
@property
def tag(self) -> str:
"""The title mark that tells the age modes apart."""
return "" if self.age_mode == "categorizada" else f" [edad {self.age_mode.replace('_', ' ')}]"
@property
def combine_active(self) -> bool:
"""The stacked combination only exists with a model per interval."""
return bool(self.combine) and self.censoring == "riesgo"
@property
def months_max(self) -> int:
"""Where the time axis is drawn to."""
return self.cap_months or 60
@property
def months_extrapolated(self) -> int:
"""Where the fits are extrapolated (dotted) past the observed follow-up."""
return self.cap_months or 120
@dataclass(frozen=True)
class RiskFactorSettings:
alpha: float
freq_min: float
horizon: int
cap_months: int
treatment: tuple[str, ...]
canonical_map: dict
@dataclass(frozen=True)
class Settings:
depuration: DepurationSettings
balancing: BalancingSettings
categorization: CategorizationSettings
bootstrap: BootstrapSettings
modeling: ModelingSettings
survival: SurvivalSettings
risk_factors: RiskFactorSettings
def _group(cls, table: dict):
"""A dataclass from a TOML table; lists become tuples so the settings stay hashable and immutable."""
unknown = set(table) - {f.name for f in fields(cls)}
if unknown:
raise ValueError(f"{cls.__name__}: unknown settings {sorted(unknown)}")
return cls(**{k: tuple(v) if isinstance(v, list) else v for k, v in table.items()})
def load(path: Path = TOML) -> Settings:
raw = tomllib.loads(Path(path).read_text(encoding="utf-8"))
return Settings(depuration=_group(DepurationSettings, raw["depuration"]),
balancing=_group(BalancingSettings, raw["balancing"]),
categorization=_group(CategorizationSettings, raw["categorization"]),
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
modeling=_group(ModelingSettings, raw["modeling"]),
survival=_group(SurvivalSettings, {**raw["survival"],
"subgroups": tuple(raw["survival"].get("subgroups", ()))}),
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
@@ -0,0 +1,596 @@
"""Stage 05, survival curves: the complete cohort's Kaplan-Meier, the classic and the fractional Weibull, and the 6/12/18
month survival by LR, HBN and their stacked combination with bootstrap intervals; the same in subgroups; and a test of
age as a continuous variable.
Each public function is a Hamilton node and each parameter is the node of that name; the inputs are `depurated_csv`
(the complete cohort, with follow-up months and vital status) and `survival` (its settings). The numeric core is in
`fractional_weibull.py` and `survival_models.py`; `run.py` holds the driver and writes the files.
"""
import re
from dataclasses import dataclass
import numpy as np
import pandas as pd
from matplotlib.figure import Figure
from sklearn.linear_model import LogisticRegression
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings
STYLE = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
@dataclass(frozen=True, eq=False)
class SurvivalFrame:
df: pd.DataFrame # the cohort with `meses_int` and `evento` (capped), and the derived age columns
covariates: list[str]
age_col: str | None
numeric_cols: list[str] # the continuous age columns the LR takes, if any
@dataclass(frozen=True, eq=False)
class KaplanMeier:
S: np.ndarray
lo: np.ndarray
hi: np.ndarray
T: int
@dataclass(frozen=True, eq=False)
class Oof:
lr: np.ndarray
hb: np.ndarray
@dataclass(frozen=True, eq=False)
class Points:
lr: np.ndarray
hbn: np.ndarray
combined: np.ndarray | None
parents: list
@dataclass(frozen=True, eq=False)
class AgeTest:
by_subgroup: pd.DataFrame # mean predicted survival of each variant against Kaplan-Meier
summary: pd.DataFrame # error against KM and out-of-sample log-likelihood
def _find_col(df, keywords, exclude=()):
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords) and not any(e in d for e in exclude):
return col
return None
def _first_number(v):
m = re.search(r"\d+", str(v))
return float(m.group()) if m else np.nan
def _age_midpoint(v):
n = [float(x) for x in re.findall(r"\d+", str(v))]
if not n:
return np.nan
return n[0] + 2.5 if "+" in str(v) else float(np.mean(n[:2]))
# ---------------------------------------------------------------- the cohort
def sv_frame(depurated_csv: str, survival: SurvivalSettings) -> SurvivalFrame:
return survival_frame(pd.read_csv(depurated_csv, dtype=str), survival)
def survival_frame(df: pd.DataFrame, survival: SurvivalSettings) -> SurvivalFrame:
"""The cohort with follow-up truncated at `cap_months` (later deaths count as alive), its covariates and, when no
categorical age column exists, the grouped age `Edad_cat`."""
s = survival
df = df.copy()
col_months, col_vital = _find_col(df, ["survival months"]), _find_col(df, ["vital status"])
assert col_months and col_vital, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
df["meses"] = pd.to_numeric(df[col_months], errors="coerce")
df["evento"] = df[col_vital].astype(str).str.lower().str.contains("dead")
df = df[df["meses"].notna()].reset_index(drop=True)
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
age_col = (sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
if candidates else None)
df["_edad"] = df[age_col].map(_first_number) if age_col else np.nan
has_age_cat = any(re.search(sm.AGE_PATTERN, c.lower()) for c in df.columns if c.endswith("_cat"))
if s.include_age and not has_age_cat and df["_edad"].notna().mean() > 0.5:
bins = [-np.inf] + list(s.age_cuts) + [np.inf]
labels = [f"<{s.age_cuts[0]}"] + [f"{a}-{b - 1}" for a, b in zip(s.age_cuts[:-1], s.age_cuts[1:])] + [f"≥{s.age_cuts[-1]}"]
df["Edad_cat"] = pd.cut(df["_edad"], bins, right=False, labels=labels).astype(object)
if not s.covariates:
covariates = [c for c in df.columns if c.endswith("_cat") and "outcome" not in c.lower()]
else:
covariates = list(s.covariates)
if s.include_age and "Edad_cat" in df.columns and "Edad_cat" not in covariates:
covariates.append("Edad_cat")
ed = df[age_col].map(_age_midpoint).astype(float) if age_col else pd.Series(np.nan, index=df.index)
df["_edad_z"] = ((ed - ed.mean()) / ed.std()).fillna(0.0)
df["_edad_cuad"] = df["_edad_z"] ** 2
numeric = []
if s.age_mode != "categorizada":
assert ed.notna().mean() > 0.5, "age_mode continua: no se pudo leer la edad numérica de la columna de edad."
covariates = [c for c in covariates if not re.search(sm.AGE_PATTERN, c.lower())]
numeric = ["_edad_z"] + (["_edad_cuad"] if s.age_mode == "continua_cuadratica" else [])
assert covariates, "No hay covariables: define `covariates` con los nombres de columna."
for c in covariates:
df[c] = df[c].fillna("NA").astype(str).str.strip()
return SurvivalFrame(df, covariates, age_col, numeric)
def sv_cohort(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> sm.Cohort:
df, cov = sv_frame.df, sv_frame.covariates
M = pd.get_dummies(df[cov], drop_first=True).values.astype(np.float32) # reference = the first category
X_dum = np.column_stack([M, df[sv_frame.numeric_cols].values.astype(np.float32)]) if sv_frame.numeric_cols else M
X_int = np.column_stack([pd.factorize(df[c])[0] for c in cov]).astype(int)
return sm.Cohort(df["meses_int"].values, df["evento"].values, X_dum, X_int, X_int.max(axis=0) + 1,
[0] + list(survival.horizons), sm.fixed_parent_indices(cov, survival))
# ---------------------------------------------------------------- the curves of the whole cohort
def sv_km(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> KaplanMeier:
T = max(survival.months_max, max(survival.horizons))
return KaplanMeier(*fw.km_curva(sv_frame.df["meses_int"].values, sv_frame.df["evento"].values, T), T)
def sv_adjusted(sv_cohort: sm.Cohort, sv_km: KaplanMeier, survival: SurvivalSettings) -> np.ndarray:
return sm.adjusted_curve(sv_cohort, np.arange(len(sv_cohort.months)), sv_km.T, survival.adjust_step)
def _fixed_k(w: dict, s: SurvivalSettings) -> float:
return w["k"] if s.k_ident == "clasico" else float(s.k_ident)
def _fit_to_curve(S: np.ndarray, n_eq: int, s: SurvivalSettings, max_seg: int):
"""The classic and the fractional Weibull fitted to a survival curve, as if it came from `n_eq` patients."""
d = np.maximum(n_eq * (S[:-1] - S[1:]), 0.0)
T = len(d)
d = np.concatenate([d, [0.0, 0.0]])
c = np.zeros(T + 2)
c[T] = n_eq * S[-1]
w = fw.ajustar_weibull(d, c)
return w, fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=max_seg)
def sv_fractional_fit(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.ndarray,
survival: SurvivalSettings) -> dict:
"""The fractional Weibull drawn on the main figure: fitted to the adjusted curve, or to the raw counts."""
s = survival
if s.curves == "ajustada":
return _fit_to_curve(sv_adjusted, len(sv_frame.df), s, s.ks_max_seconds)[1]
d, c = fw.tabla_eventos(sv_frame.df["meses_int"].values, sv_frame.df["evento"].values)
w = fw.ajustar_weibull(d, c)
return fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=s.ks_max_seconds)
# ---------------------------------------------------------------- LR, HBN and their combination
def sv_oof(sv_cohort: sm.Cohort, survival: SurvivalSettings) -> Oof | None:
"""Out-of-sample interval probabilities, the stacking's input; None without the combination."""
if not survival.combine_active:
return None
return Oof(*sm.out_of_fold(sv_cohort, survival, len(sv_cohort.months)))
def sv_weights_cohort(sv_cohort: sm.Cohort, sv_oof: Oof | None, survival: SurvivalSettings) -> pd.DataFrame | None:
if sv_oof is None:
return None
return sm.stacking_weights(sv_cohort, survival, np.ones(len(sv_cohort.months), bool), sv_oof.lr, sv_oof.hb)
def sv_points(sv_cohort: sm.Cohort, sv_weights_cohort: pd.DataFrame | None, survival: SurvivalSettings) -> Points:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on the whole cohort."""
todas = np.arange(len(sv_cohort.months))
if survival.combine_active:
p_lr, p_hbn, p_cmb, pads = sm.estimate_combined(sv_cohort, survival, todas, None,
sv_weights_cohort["w_LR"].values)
return Points(p_lr, p_hbn, p_cmb, pads)
p_lr, p_hbn, pads = sm.estimate(sv_cohort, survival, todas, survival.censoring)
return Points(p_lr, p_hbn, None, pads)
def _reference_parents(points: Points, s: SurvivalSettings):
"""The HBN's parents learned on the whole cohort, kept in the bootstrap (a steadier interval), or None to learn
them again in each replica."""
return points.parents if s.hbn_parents == "fijos" else None
def sv_bootstrap(sv_cohort: sm.Cohort, sv_weights_cohort: pd.DataFrame | None, sv_points: Points,
survival: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of each model."""
s = survival
N = len(sv_cohort.months)
ref = _reference_parents(sv_points, s)
W = sv_weights_cohort["w_LR"].values if s.combine_active else None
rng = np.random.default_rng(s.seed)
boots = []
for _ in range(s.n_boot):
idx = rng.integers(0, N, N)
if s.combine_active:
r = sm.estimate_combined(sv_cohort, s, idx, ref, W)
boots.append(np.concatenate([r[0], r[1], r[2]]))
else:
r = sm.estimate(sv_cohort, s, idx, s.censoring, ref)
boots.append(np.concatenate([r[0], r[1]]))
n_series = 3 if s.combine_active else 2
return np.array(boots) if s.n_boot > 0 else np.full((1, n_series * len(s.horizons)), np.nan)
def sv_table(sv_points: Points, sv_bootstrap: np.ndarray, sv_km: KaplanMeier, sv_adjusted: np.ndarray,
survival: SurvivalSettings) -> pd.DataFrame:
"""Per model and horizon: S, its bootstrap 95 % interval, and Kaplan-Meier raw and adjusted."""
h = list(survival.horizons)
series = [("LR", sv_points.lr), ("HBN", sv_points.hbn)] + ([("COMB", sv_points.combined)] if survival.combine_active else [])
ic = np.nanpercentile(sv_bootstrap, [2.5, 97.5], axis=0)
rows = [dict(modelo=name, meses=m, S=vals[i], IC_inf=ic[0, j * len(h) + i], IC_sup=ic[1, j * len(h) + i])
for j, (name, vals) in enumerate(series) for i, m in enumerate(h)]
table = pd.DataFrame(rows)
table["KM_crudo"] = [sv_km.S[m] for m in table["meses"]]
table["KM_ajustada"] = [sv_adjusted[m] for m in table["meses"]]
return table
def _plotted_models(s: SurvivalSettings) -> list[str]:
if s.combine_active:
return ["LR", "HBN", "COMB"] if s.show_individual else ["COMB"]
return ["LR", "HBN"]
def _error_bars(ax, table: pd.DataFrame, names, small: bool = False):
for name in names:
color, marker, label = STYLE[name]
s = table[table["modelo"] == name]
yerr = [np.clip(s["S"] - s["IC_inf"], 0, None), np.clip(s["IC_sup"] - s["S"], 0, None)]
if small:
ax.errorbar(s["meses"], s["S"], yerr=yerr, fmt=marker, color=color, ms=6, capsize=3, lw=1.5, mec="white",
mew=.8, zorder=5)
else:
ax.errorbar(s["meses"], s["S"], yerr=yerr, fmt=marker, color=color, ms=9 if name == "COMB" else 8,
capsize=4, lw=1.8, mec="white", mew=1, label=f"{label} (IC 95 % bootstrap)", zorder=5)
def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.ndarray, sv_fractional_fit: dict,
sv_table: pd.DataFrame, survival: SurvivalSettings) -> Figure:
s = survival
n_max = s.months_max
fig = Figure(figsize=(15, 5.6) if s.inset_zoom else (9.5, 5.6))
if s.inset_zoom:
ax, axi = fig.subplots(1, 2, gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
ax = fig.subplots()
xx = np.arange(sv_km.T + 1)
tc = np.linspace(0, n_max, 600)
if s.curves == "ajustada":
S_base = sv_adjusted
if s.show_raw_km:
ax.step(xx, sv_km.S, where="post", color="#9aa5b1", lw=1.0, ls=":", label="Kaplan-Meier crudo (referencia)")
ax.step(xx, sv_adjusted, where="post", color="#3d4852", lw=1.8, label="Kaplan-Meier ajustada por covariables")
label_ks = "Weibull fraccional (ajustado a la curva ajustada)"
else:
S_base = sv_km.S
ax.fill_between(xx, sv_km.lo, sv_km.hi, step="post", color="#9aa5b1", alpha=.35, lw=0,
label="Kaplan-Meier (IC 95 % Greenwood)")
ax.step(xx, sv_km.S, where="post", color="#3d4852", lw=1.6, label="Kaplan-Meier")
label_ks = "Weibull fraccional (Kilbas-Saigo)"
ax.plot(tc, sv_fractional_fit["S"](tc), color="#d1495b", lw=2.4, label=label_ks)
names = _plotted_models(s)
_error_bars(ax, sv_table, names)
plotted = sv_table[sv_table["modelo"].isin(names)]
ax.set_xlim(0, n_max + (0.8 if s.cap_months else 0))
ax.set_xlabel("Meses desde el diagnóstico")
ax.set_ylabel("Supervivencia S(t)")
vals = np.concatenate([S_base[:n_max + 1], plotted["IC_inf"].values,
[sv_fractional_fit["S"](np.array([float(n_max)]))[0]]])
ax.set_ylim(max(0.0, np.nanmin(vals) - 0.03), 1.005)
if s.ylim_main:
ax.set_ylim(*s.ylim_main)
ax.set_xticks(range(0, n_max + 1, 3 if s.cap_months else 6))
ax.grid(alpha=.25)
if s.inset_zoom:
n_in = s.inset_months
xi = np.arange(n_in + 1)
axi.step(xi, S_base[:n_in + 1], where="post", color="#3d4852", lw=1.4)
if s.curves == "ajustada" and s.show_raw_km:
axi.step(xi, sv_km.S[:n_in + 1], where="post", color="#9aa5b1", lw=1.0, ls=":")
tci = np.linspace(0, n_in, 200)
axi.plot(tci, sv_fractional_fit["S"](tci), color="#d1495b", lw=2)
_error_bars(axi, sv_table, names, small=True)
v = np.concatenate([S_base[:n_in + 1], plotted["IC_inf"].values, plotted["IC_sup"].values])
margin = (v.max() - v.min()) * .08
axi.set_xlim(0, n_in + 0.8)
axi.set_ylim(v.min() - margin, min(1.002, v.max() + margin))
axi.set_xticks(range(0, n_in + 1, 6))
axi.grid(alpha=.25)
axi.set_title(f"Zoom: primeros {n_in} meses", fontsize=10)
axi.set_xlabel("Meses desde el diagnóstico")
axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, n_in, color="#888", alpha=.08, lw=0)
ax.set_title(f"Supervivencia de la cohorte completa (n = {len(sv_frame.df):,}){s.tag}")
ax.legend(loc="lower left", frameon=False)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
fig.tight_layout()
return fig
# ---------------------------------------------------------------- subgroups
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict | None = None) -> dict[str, np.ndarray]:
"""Each clinical scenario's mask over the cohort: the `subgroups` of the settings over the variable dictionary when
both are given, else `scenarios.masks`. Every condition of a scenario must hold."""
if not (survival.subgroups and dictionary):
return scenarios.masks(sv_frame.df)
df = sv_frame.df
masks = {}
for spec in survival.subgroups:
mask = np.ones(len(df), bool)
for condition in spec["conditions"]:
name = condition["variable"]
if name == "Edad":
values = df["_edad"].astype(float)
else:
values = df[variables.column_of(name, dictionary[name])].astype(str)
if "contains" in condition:
mask &= values.str.contains(condition["contains"], regex=False).to_numpy()
if "in" in condition:
mask &= values.isin(condition["in"]).to_numpy()
if "ge" in condition:
mask &= (values >= condition["ge"]).to_numpy()
if "lt" in condition:
mask &= (values < condition["lt"]).to_numpy()
masks[spec["name"]] = mask
return masks
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
survival: SurvivalSettings) -> dict[str, pd.DataFrame]:
"""The combination's weights of each subgroup (out-of-sample robustness within the subgroup)."""
if sv_oof is None:
return {}
return {name: sm.stacking_weights(sv_cohort, survival, mk, sv_oof.lr, sv_oof.hb) for name, mk in sv_masks.items()}
def _subgroup_means(c: sm.Cohort, s: SurvivalSettings, idx, parents, masks, weights) -> dict[str, np.ndarray]:
nm, nh = (3 if s.combine_active else 2), len(s.horizons)
out = {}
if s.combine_active:
Pl, Ph, _ = sm.interval_predictions(c, s, idx, parents)
Sl, Sh = np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1)
for name, mk in masks.items():
m = mk[idx]
if not m.any():
out[name] = np.full(nm * nh, np.nan)
continue
W = weights[name]["w_LR"].values[None, :]
Sc = np.cumprod(W * Pl[m] + (1 - W) * Ph[m], axis=1)
out[name] = np.concatenate([Sl[m].mean(0), Sh[m].mean(0), Sc.mean(0)])
else:
Sl, Sh, _ = sm.patient_survival(c, s, idx, s.censoring, parents)
for name, mk in masks.items():
m = mk[idx]
out[name] = np.concatenate([Sl[m].mean(0), Sh[m].mean(0)]) if m.any() else np.full(nm * nh, np.nan)
return out
def sv_sub_points(sv_cohort: sm.Cohort, sv_masks: dict, sv_sub_weights: dict, sv_points: Points,
survival: SurvivalSettings) -> dict[str, pd.DataFrame]:
"""Per subgroup: LR, HBN and combination survival at each horizon with bootstrap intervals; the models are fitted on
the whole cohort and their predictions averaged within the subgroup."""
s = survival
N = len(sv_cohort.months)
names = ["LR", "HBN"] + (["COMB"] if s.combine_active else [])
nm, nh = len(names), len(s.horizons)
point = _subgroup_means(sv_cohort, s, np.arange(N), None, sv_masks, sv_sub_weights)
ref = _reference_parents(sv_points, s)
rng = np.random.default_rng(s.seed + 1)
boots = {n: [] for n in sv_masks}
for _ in range(s.n_boot_sub):
r = _subgroup_means(sv_cohort, s, rng.integers(0, N, N), ref, sv_masks, sv_sub_weights)
for n in sv_masks:
boots[n].append(r[n])
out = {}
for n, mk in sv_masks.items():
B = np.array(boots[n]) if s.n_boot_sub > 0 else np.full((1, nm * nh), np.nan)
ic = np.nanpercentile(B, [2.5, 97.5], axis=0) if mk.any() else np.full((2, nm * nh), np.nan)
pt = point[n]
out[n] = pd.DataFrame([dict(modelo=name, meses=h, S=pt[j * nh + i], IC_inf=ic[0, j * nh + i], IC_sup=ic[1, j * nh + i])
for j, name in enumerate(names) for i, h in enumerate(s.horizons)])
return out
def sv_sub_analyses(sv_frame: SurvivalFrame, sv_masks: dict, sv_sub_points: dict, sv_sub_weights: dict,
survival: SurvivalSettings) -> dict[str, dict | None]:
"""Each subgroup's Kaplan-Meier and classic / fractional Weibull fits; None where it has too few deaths."""
s = survival
df = sv_frame.df
aic = lambda nll, k: 2 * k + 2 * nll # noqa: E731
out = {}
for name, mk in sv_masks.items():
sub = df[mk]
n, deaths = len(sub), int(sub["evento"].sum())
if n == 0 or deaths < s.min_events_sub:
out[name] = None
continue
d, c = fw.tabla_eventos(sub["meses_int"].values, sub["evento"].values)
w = fw.ajustar_weibull(d, c)
ks = fw.ajustar_ks(d, c, k_fijo=_fixed_k(w, s), lam_ref=w["lam"], max_seg=s.ks_sub_max_seconds)
Tm = int(sub["meses_int"].max())
Sk, lok, hik = fw.km_curva(sub["meses_int"].values, sub["evento"].values, Tm)
grid = np.arange(0, Tm + 1, dtype=float)
row = {"subgrupo": name, "n": n, "fallecidos": deaths, "seguim. máx. (m)": Tm, "k Weibull": w["k"],
"k KS / α / β": f"{ks['k']:.2f} / {ks['alpha']:.2f} / {ks['beta']:.2f}",
"AIC Weibull": aic(w["nll"], 2), "AIC fraccional": aic(ks["nll"], 3),
"ΔAIC (W − F)": aic(w["nll"], 2) - aic(ks["nll"], 3),
"máx|KM−Weibull|": np.abs(w["S"](grid) - Sk).max(), "máx|KM−fracc.|": np.abs(ks["S"](grid) - Sk).max()}
out[name] = dict(nombre=name, n=n, ev=deaths, w=w, ks=ks, Sk=Sk, lok=lok, hik=hik, Tm=Tm, fila=row,
modelos=sv_sub_points[name], pesos=sv_sub_weights.get(name))
return out
def _subgroup_figure(a: dict, s: SurvivalSettings) -> Figure:
names = _plotted_models(s)
plotted = a["modelos"][a["modelos"]["modelo"].isin(names)]
Tm, extrapolated = a["Tm"], s.months_extrapolated
tt = np.arange(Tm + 1)
fig = Figure(figsize=(15, 5.2) if s.inset_zoom else (9, 5.2))
if s.inset_zoom:
ax, axi = fig.subplots(1, 2, gridspec_kw=dict(width_ratios=[1.45, 1], wspace=0.18))
else:
ax = fig.subplots()
ax.fill_between(tt, a["lok"], a["hik"], step="post", color="#9aa5b1", alpha=.3, lw=0)
ax.step(tt, a["Sk"], where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
for key, color, ls, label in [("w", "#1f77b4", "-", "Weibull"), ("ks", "#d1495b", "--", "Weibull fraccional")]:
t_in, t_ex = np.linspace(0, Tm, 300), np.linspace(Tm, extrapolated, 200)
ax.plot(t_in, a[key]["S"](t_in), color=color, lw=2.2, ls=ls, label=label)
ax.plot(t_ex, a[key]["S"](t_ex), color=color, lw=1.4, ls=":")
if not s.cap_months:
ax.axvline(Tm, color="#888", lw=.8, ls=":")
_error_bars(ax, plotted, names)
x0, x1 = s.xlim_sub if s.xlim_sub else (0, extrapolated + (0.8 if s.cap_months else 0))
xs = np.linspace(x0, x1, 400)
visible = [a["w"]["S"](xs), a["ks"]["S"](xs), a["Sk"][int(x0):int(min(x1, Tm)) + 1],
a["lok"][int(x0):int(min(x1, Tm)) + 1], plotted["IC_inf"].values, plotted["IC_sup"].values]
v = np.concatenate([np.ravel(u) for u in visible])
v = v[np.isfinite(v)]
margin = (v.max() - v.min()) * .06
ylim = s.ylim_sub.get(a["nombre"], (max(0, v.min() - margin), min(1.005, v.max() + margin)))
ax.set_xlim(x0, x1)
ax.set_ylim(*ylim)
if s.inset_zoom:
n_in = s.inset_months
xi = np.arange(n_in + 1)
axi.fill_between(xi, a["lok"][:n_in + 1], a["hik"][:n_in + 1], step="post", color="#9aa5b1", alpha=.3, lw=0)
axi.step(xi, a["Sk"][:n_in + 1], where="post", color="#222", lw=1.3)
tci = np.linspace(0, n_in, 200)
axi.plot(tci, a["w"]["S"](tci), color="#1f77b4", lw=2)
axi.plot(tci, a["ks"]["S"](tci), color="#d1495b", lw=2, ls="--")
_error_bars(axi, plotted, names, small=True)
vi = np.concatenate([a["Sk"][:n_in + 1], a["lok"][:n_in + 1], plotted["IC_inf"].values, plotted["IC_sup"].values,
a["w"]["S"](tci)])
vi = vi[np.isfinite(vi)]
mi = (vi.max() - vi.min()) * .08
axi.set_xlim(0, n_in + 0.8)
axi.set_ylim(vi.min() - mi, min(1.002, vi.max() + mi))
axi.set_xticks(range(0, n_in + 1, 6))
axi.grid(alpha=.25)
axi.set_title(f"Zoom: primeros {n_in} meses", fontsize=10)
axi.set_xlabel("Meses desde el diagnóstico")
axi.spines[["top", "right"]].set_visible(False)
ax.axvspan(0, n_in, color="#888", alpha=.08, lw=0)
ax.set_xlabel("Meses desde el diagnóstico")
ax.set_ylabel("Supervivencia S(t)")
ax.grid(alpha=.25)
ax.set_title(f"{a['nombre']}{s.tag}\nn={a['n']:,}, fallecidos={a['ev']:,}", fontsize=11)
ax.legend(frameon=False, loc="lower left", fontsize=9)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
fig.tight_layout()
return fig
def sv_sub_figures(sv_sub_analyses: dict, survival: SurvivalSettings) -> dict[str, Figure]:
"""One figure per fitted subgroup, by its name."""
return {name: _subgroup_figure(a, survival) for name, a in sv_sub_analyses.items() if a is not None}
def sv_sub_fits_table(sv_sub_analyses: dict) -> pd.DataFrame:
return pd.DataFrame([a["fila"] for a in sv_sub_analyses.values() if a is not None])
def sv_sub_points_table(sv_sub_analyses: dict) -> pd.DataFrame:
return pd.concat([a["modelos"].assign(subgrupo=a["nombre"]) for a in sv_sub_analyses.values() if a is not None])
def sv_sub_weights_table(sv_sub_analyses: dict, survival: SurvivalSettings) -> pd.DataFrame | None:
if not survival.combine_active:
return None
return pd.concat([a["pesos"].assign(subgrupo=a["nombre"]) for a in sv_sub_analyses.values() if a is not None])
# ---------------------------------------------------------------- age as a continuous variable
def sv_age_test(sv_frame: SurvivalFrame, sv_cohort: sm.Cohort, sv_masks: dict, survival: SurvivalSettings) -> AgeTest:
"""Age as a number (the middle of its 5-year group, standardized, linear or quadratic) in the LR against the
categorized age: how far each variant's mean survival is from Kaplan-Meier, and its out-of-sample log-likelihood."""
s = survival
df, c = sv_frame.df, sv_cohort
N = len(df)
ed = df[sv_frame.age_col].map(_age_midpoint).astype(float) if sv_frame.age_col else pd.Series(np.nan, index=df.index)
assert ed.notna().mean() > 0.5, "No se pudo leer la edad numérica"
z = ((ed - ed.mean()) / ed.std()).fillna(0.0).values
without_age = [v for v in sv_frame.covariates if not re.search(sm.AGE_PATTERN, v.lower())]
Xb = pd.get_dummies(df[without_age], drop_first=True).values.astype(np.float32)
if "Edad_cat" in df.columns:
Xcat = np.column_stack([Xb, pd.get_dummies(df[["Edad_cat"]], drop_first=True).values.astype(np.float32)])
else:
Xcat = c.X_dum if s.age_mode == "categorizada" else None
variants = {"sin edad": Xb, "edad categorizada": Xcat,
"edad continua": np.column_stack([Xb, z]).astype(np.float32),
"edad continua + cuadrática": np.column_stack([Xb, z, z ** 2]).astype(np.float32)}
if Xcat is None:
variants.pop("edad categorizada")
ref_variant = "edad categorizada" if "edad categorizada" in variants else "sin edad"
months, event, borders = c.months, c.event, c.borders
def lr_interval(Xm, idx, test):
P = []
for a, b in zip(borders[:-1], borders[1:]):
sel = np.where(months[idx] >= a)[0]
y = np.where(event[idx][sel] & (months[idx][sel] < b), 0, 1)
w = np.where((~event[idx][sel]) & (months[idx][sel] < b), 0.5, 1.0)
P.append(LogisticRegression(C=1e6, max_iter=500).fit(Xm[idx][sel], y, sample_weight=w).predict_proba(Xm[test])[:, 1])
return np.column_stack(P)
todas = np.arange(N)
fold = np.random.default_rng(s.seed + 11).permutation(N) % s.stack_folds
point, oof = {}, {}
for name, Xm in variants.items():
point[name] = np.cumprod(lr_interval(Xm, todas, todas), axis=1)
O = np.zeros((N, len(s.horizons)))
for k in range(s.stack_folds):
te, tr = np.where(fold == k)[0], np.where(fold != k)[0]
O[te] = lr_interval(Xm, tr, te)
oof[name] = O
def loglik(O, mask):
total = 0.0
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
i = np.where(mask & (months >= a))[0]
y = np.where(event[i] & (months[i] < b), 0, 1)
w = np.where((~event[i]) & (months[i] < b), 0.5, 1.0)
p = np.clip(O[i, j], 1e-9, 1 - 1e-9)
total += np.sum(w * (y * np.log(p) + (1 - y) * np.log1p(-p)))
return total
rows = []
for name, mask in [("Cohorte completa", np.ones(N, bool))] + list(sv_masks.items()):
if mask.sum() == 0:
continue
Sk, _, _ = fw.km_curva(months[mask], event[mask], max(s.horizons))
for i, h in enumerate(s.horizons):
row = {"subgrupo": name, "meses": h, "KM": Sk[h]}
for v in variants:
row[v] = point[v][mask, i].mean()
rows.append(row)
T1 = pd.DataFrame(rows)
res = []
for v in variants:
err = (T1[v] - T1["KM"]).abs()
ll, ll_ref = loglik(oof[v], np.ones(N, bool)), loglik(oof[ref_variant], np.ones(N, bool))
res.append({"variante": v, "error abs. medio vs KM (todos los subgrupos y horizontes)": err.mean(),
"error abs. máx.": err.max(), "log-verosimilitud fuera de muestra (cohorte)": ll,
f"Δ vs {ref_variant}": ll - ll_ref})
return AgeTest(T1, pd.DataFrame(res))
@@ -0,0 +1,320 @@
"""The interval models of the survival-curves stage, apart from its nodes (`survival_curves.py`): the logistic regression
(LR) and the Bayesian network with a tabular CPT (HBN) fitted per time interval, their cumulative survival, the
out-of-sample stacking that combines them, and the covariate-adjusted Kaplan-Meier curve. Plain functions with no I/O.
Ported from `05_curvas_supervivencia.py`.
A patient's survival to a horizon is the product of the survival of each interval up to it. Each interval's models use
the patients alive at its start; a censoring inside the interval counts as half a risk (weight 0.5).
"""
import re
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.optimize import minimize_scalar
from scipy.special import gammaln
from sklearn.linear_model import LogisticRegression
from models.cama.seer_survival.settings import SurvivalSettings
AGE_PATTERN = r"(^|_)age(_|$)|edad"
@dataclass(frozen=True, eq=False)
class Cohort:
"""What the models fit on: the follow-up, the two codings of the covariates (dummies for the LR, integer codes and
their levels for the HBN), and the HBN's fixed parents."""
months: np.ndarray
event: np.ndarray
X_dum: np.ndarray
X_int: np.ndarray
levels: np.ndarray
borders: list[int]
fixed_parents: list[int] | None
def fixed_parent_indices(covariates: list[str], s: SurvivalSettings) -> list[int] | None:
"""The HBN's fixed parents as covariate positions, found by keyword; the grouped age is added when asked (expert
knowledge: the algorithm didn't choose it). None = learn them."""
if not s.hbn_fixed_parents:
return None
keywords = list(s.hbn_fixed_parents)
if s.hbn_age_parent and not any(re.search(AGE_PATTERN, k.lower()) for k in keywords):
keywords.append("Edad")
out = []
for kw in keywords:
hit = [j for j, c in enumerate(covariates) if kw.lower() in c.lower()]
assert hit, f"hbn_fixed_parents: no hay una covariable que contenga '{kw}' en {covariates}"
out.append(hit[0])
return out
def censoring_weights(months, event, h, mode):
"""(known, y, w) for the horizon `h`: who is known at h, who survives to it, and their weights. `ipcw` weights by the
inverse probability of not being censored; `excluir` drops the alive with follow-up under h; `riesgo` is
`interval_predictions`'s."""
m = np.asarray(months, int)
e = np.asarray(event, bool)
known = e | (m >= h)
y = (m >= h).astype(int)
w = np.ones(len(m))
if mode == "ipcw":
T = int(m.max()) + 2
cen = np.bincount(m[~e], minlength=T)
mu = np.bincount(m, minlength=T)
nr = len(m) - np.concatenate([[0], np.cumsum(mu)[:-1]])
G = np.concatenate([[1.0], np.cumprod(1 - cen / np.maximum(nr, 1))]) # G[t] = P(not censored before month t)
G = np.clip(G, 0.05, 1.0)
w = 1.0 / G[np.minimum(m, h)]
return known, y, w
# ---------------------------------------------------------------- the HBN with a tabular CPT
def bdeu(code, y, w, q, ess):
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
nj = n.sum(1)
aj = ess / q
ajk = aj / 2
return float(np.sum(gammaln(aj) - gammaln(aj + nj) + np.sum(gammaln(ajk + n) - gammaln(ajk), axis=1)))
def search_parents(X, levels, y, w, ess, max_parents) -> list[int]:
"""Greedy: the covariate that most improves the BDeu score of the outcome, until none does or `max_parents`."""
parents, code, q = [], np.zeros(len(y), int), 1
best = bdeu(code, y, w, q, ess)
while len(parents) < max_parents:
cand = None
for j in range(X.shape[1]):
if j in parents or q * levels[j] > 200_000:
continue
c2 = code * levels[j] + X[:, j]
s = bdeu(c2, y, w, q * levels[j], ess)
if s > best + 1e-9 and (cand is None or s > cand[0]):
cand = (s, j, c2, q * levels[j])
if cand is None:
break
best, j, code, q = cand
parents.append(j)
return parents
def fit_hbn(X, levels, y, w, s: SurvivalSettings, fixed, parents=None):
"""(parents, P(Y=1 | parents)), smoothed toward the marginal survival so the prior doesn't bias to 0.5."""
if parents is None and fixed is not None:
parents = fixed
parents = search_parents(X, levels, y, w, s.hbn_ess, s.hbn_max_parents) if parents is None else list(parents)
q = int(np.prod([levels[j] for j in parents])) if parents else 1
code = np.zeros(len(y), int)
for j in parents:
code = code * levels[j] + X[:, j]
n = np.bincount(code * 2 + y, weights=w, minlength=q * 2).reshape(q, 2)
aj = s.hbn_ess / q
pbar = (n[:, 1].sum() + 0.5) / (n.sum() + 1)
return parents, (n[:, 1] + aj * pbar) / (n.sum(1) + aj)
def predict_hbn(model, X, levels):
parents, cpt = model
code = np.zeros(len(X), int)
for j in parents:
code = code * levels[j] + X[:, j]
return cpt[code]
# ---------------------------------------------------------------- the models by interval
def predict_horizon(c: Cohort, s: SurvivalSettings, idx, h, mode, parents=None):
"""LR and HBN probabilities of surviving to `h` with a model per horizon (the `ipcw` and `excluir` treatments)."""
m, e = c.months[idx], c.event[idx]
known, y, w = censoring_weights(m, e, h, mode)
sel = np.where(known)[0]
lr = LogisticRegression(C=1e6, max_iter=500)
lr.fit(c.X_dum[idx][sel], y[sel], sample_weight=w[sel])
mod = fit_hbn(c.X_int[idx][sel], c.levels, y[sel], w[sel], s, c.fixed_parents, parents)
return lr.predict_proba(c.X_dum[idx])[:, 1], predict_hbn(mod, c.X_int[idx], c.levels), list(mod[0])
class ConstantProbability:
"""What stands in for a logistic regression in an interval where everyone at risk had the same outcome (nobody
died in it, or everybody did): the same probability for every patient, with `predict_proba`'s two columns."""
def __init__(self, p: float):
self.p = float(p)
def predict_proba(self, X):
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _fit_lr(X, y, w):
"""The unpenalized LR of an interval, or a constant when there is nothing to tell apart."""
if len(y) == 0:
return ConstantProbability(1.0)
if y.min() == y.max():
return ConstantProbability(float(y[0]))
return LogisticRegression(C=1e6, max_iter=500).fit(X, y, sample_weight=w)
def fit_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None):
"""Per interval, `(LR, HBN)` fitted on the patients of `idx` alive at its start: what a model keeps to score
patients it never saw (`predict_intervals`)."""
m, e = c.months[idx], c.event[idx]
fitted = []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0] # alive at the start of the interval
if len(sel) == 0:
fitted.append((ConstantProbability(1.0), ([], np.array([1.0]))))
continue
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
lr = _fit_lr(c.X_dum[idx][sel], y, w)
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
fitted.append((lr, mod))
return fitted
def predict_intervals(fitted, X_dum, X_int, levels):
"""Per interval, the probability of surviving it by the LR and by the HBN, for the rows of `X_dum` and `X_int`, and
the HBN's parents of each interval."""
P_lr = [lr.predict_proba(X_dum)[:, 1] for lr, _ in fitted]
P_hb = [predict_hbn(mod, X_int, levels) for _, mod in fitted]
return np.column_stack(P_lr), np.column_stack(P_hb), [list(mod[0]) for _, mod in fitted]
def interval_predictions(c: Cohort, s: SurvivalSettings, idx, parents=None, test=None):
"""Per interval, the probability of surviving it for the `test` patients (default `idx`) by LR and HBN, fitted on the
patients of `idx` alive at its start; and the HBN's parents of each interval."""
test = idx if test is None else test
return predict_intervals(fit_intervals(c, s, idx, parents), c.X_dum[test], c.X_int[test], c.levels)
def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
"""(LR, HBN, parents): each patient's survival at each horizon."""
if mode == "riesgo":
Pl, Ph, pads = interval_predictions(c, s, idx, parents)
return np.cumprod(Pl, axis=1), np.cumprod(Ph, axis=1), pads
r = [predict_horizon(c, s, idx, h, mode, None if parents is None else parents[i])
for i, h in enumerate(s.horizons)]
return np.column_stack([x[0] for x in r]), np.column_stack([x[1] for x in r]), [x[2] for x in r]
def estimate(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
P_lr, P_hb, pads = patient_survival(c, s, idx, mode, parents)
return P_lr.mean(axis=0), P_hb.mean(axis=0), pads
def out_of_fold(c: Cohort, s: SurvivalSettings, n: int):
"""Each patient's interval probabilities from models that never saw them (`stack_folds` folds)."""
fold = np.random.default_rng(s.seed + 7).permutation(n) % s.stack_folds
oof_lr = np.zeros((n, len(s.horizons)))
oof_hb = np.zeros_like(oof_lr)
for k in range(s.stack_folds):
te, tr = np.where(fold == k)[0], np.where(fold != k)[0]
Pl, Ph, _ = interval_predictions(c, s, tr, None, te)
oof_lr[te], oof_hb[te] = Pl, Ph
return oof_lr, oof_hb
def stacking_weights(c: Cohort, s: SurvivalSettings, mask, oof_lr, oof_hb) -> pd.DataFrame:
"""Per interval, the weight of the LR in the LR + HBN mixture: the one that maximizes the out-of-sample weighted
log-likelihood of the patients in `mask`, shrunk toward 50/50 when there are few deaths
(lambda = shrink / (shrink + deaths))."""
rows = []
for j, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
idx = np.where(mask & (c.months >= a))[0]
e, m = c.event[idx], c.months[idx]
y = np.where(e & (m < b), 0, 1)
wt = np.where((~e) & (m < b), 0.5, 1.0)
p1 = np.clip(oof_lr[idx, j], 1e-9, 1 - 1e-9)
p2 = np.clip(oof_hb[idx, j], 1e-9, 1 - 1e-9)
deaths = int((y == 0).sum())
if len(idx) == 0:
rows.append(dict(intervalo=f"{a}-{b}", n_riesgo=0, muertes=0, w_LR=0.5, w_LR_sin_contraer=0.5,
dLL_LR_menos_HBN=0.0, z=0.0, decision="mezcla"))
continue
def nll(w_):
p = np.clip(w_ * p1 + (1 - w_) * p2, 1e-9, 1 - 1e-9)
return -np.sum(wt * (y * np.log(p) + (1 - y) * np.log1p(-p)))
w_star = float(minimize_scalar(nll, bounds=(0, 1), method="bounded").x)
lam = s.stack_shrink / (s.stack_shrink + deaths)
w_fin = (1 - lam) * w_star + lam * 0.5
d = wt * (y * (np.log(p1) - np.log(p2)) + (1 - y) * (np.log1p(-p1) - np.log1p(-p2))) # LR - HBN log-score
z = d.sum() / (np.sqrt(len(d)) * d.std(ddof=1)) if len(d) > 2 and d.std(ddof=1) > 0 else 0.0
decision = "solo LR" if w_fin >= 0.95 else "solo HBN" if w_fin <= 0.05 else "mezcla"
rows.append(dict(intervalo=f"{a}-{b}", n_riesgo=len(idx), muertes=deaths, w_LR=w_fin, w_LR_sin_contraer=w_star,
dLL_LR_menos_HBN=float(d.sum()), z=float(z), decision=decision))
return pd.DataFrame(rows)
def estimate_combined(c: Cohort, s: SurvivalSettings, idx, parents, W):
"""(LR, HBN, combined, parents): the mean survival at each horizon; the combination mixes each interval's LR and HBN
probabilities with the weights `W` before accumulating."""
Pl, Ph, pads = interval_predictions(c, s, idx, parents)
Sc = np.cumprod(W[None, :] * Pl + (1 - W[None, :]) * Ph, axis=1)
return np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0), Sc.mean(0), pads
def adjusted_curve(c: Cohort, idx, T: int, step: int) -> np.ndarray:
"""The covariate-adjusted Kaplan-Meier: the mean over patients of the product of their interval survivals (a
regularized LR per `step` months), by direct standardization; monotone and interpolated by month."""
m, e = c.months[idx], c.event[idx]
borders = list(range(0, T + 1, step))
if borders[-1] < T:
borders.append(T)
S_i = np.ones(len(idx))
S_b = [1.0]
for a, b in zip(borders[:-1], borders[1:]):
sel = np.where(m >= a)[0]
y = np.where(e[sel] & (m[sel] < b), 0, 1)
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
if y.min() == y.max():
S_i = S_i * y.mean()
else:
lr = LogisticRegression(C=10.0, max_iter=300).fit(c.X_dum[idx][sel], y, sample_weight=w)
S_i = S_i * lr.predict_proba(c.X_dum[idx])[:, 1]
S_b.append(S_i.mean())
S_b = np.minimum.accumulate(np.array(S_b))
return np.exp(np.interp(np.arange(T + 1), borders, np.log(np.maximum(S_b, 1e-12))))
# ---------------------------------------------------------------- fitted models that can be kept and applied later
@dataclass(frozen=True, eq=False)
class IntervalFit:
"""One interval's fitted LR (coefficients, intercept) and HBN (parents and the table of P(survives | parents))."""
coef: np.ndarray
intercept: float
parents: list[int]
cpt: np.ndarray
def fit_kept_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]:
"""The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied."""
m, e = c.months[idx], c.event[idx]
fits = []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0]
y = np.where(e[sel] & (m[sel] < b), 0, 1)
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
chosen, cpt = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
fits.append(IntervalFit(lr.coef_[0].copy(), float(lr.intercept_[0]), list(chosen), cpt))
return fits
def apply_intervals(fits: list[IntervalFit], X_dum: np.ndarray, X_int: np.ndarray, levels) -> tuple[np.ndarray, np.ndarray]:
"""(LR, HBN): each patient's probability of surviving each interval."""
P_lr = np.column_stack([1 / (1 + np.exp(-(X_dum @ f.coef + f.intercept))) for f in fits])
P_hb = np.column_stack([predict_hbn((f.parents, f.cpt), X_int, levels) for f in fits])
return P_lr, P_hb
def mix(P_lr: np.ndarray, P_hb: np.ndarray, weights) -> np.ndarray:
"""The combined survival at each horizon: each interval's LR and HBN probabilities mixed by `weights`, accumulated."""
W = np.asarray(weights)[None, :]
return np.cumprod(W * P_lr + (1 - W) * P_hb, axis=1)
+167
View File
@@ -0,0 +1,167 @@
"""The variable dictionary (`[variables]` of `model.toml`) applied to a cohort's events: one row per patient with the
columns the six stages read (the `_cat` columns, the age band, the tumour size, the diagnosis year, the follow-up and the
vital status). Nothing about a variable is written here: its rules, categories and the columns it makes are the
dictionary's.
A cohort is the long frame of `COHORT_SCHEMA`: one row per member and event, with the member's `fecha_indice`. A
variable reads the latest event of each `source` (`tipo`) up to `window_days_after_index` after the index; its rules
are tried in order and the first that holds gives the category, `missing` when none does.
"""
import tomllib
from datetime import date, timedelta
from pathlib import Path
import numpy as np
import pandas as pd
TOML = Path(__file__).with_name("model.toml")
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))["variables"]
def variable_names(dictionary: dict) -> list[str]:
return [n for n, v in dictionary.items() if isinstance(v, dict) and "rules" in v]
def output_columns(dictionary: dict) -> list[str]:
"""The columns the dictionary makes, in its order: every variable that is not internal, the tumour's raw size, the
age band and the follow-up columns."""
index = dictionary["index"]
columns = [index["id_column"], index["year_column"], index["age_column"]]
for name in variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
columns.append(column_of(name, spec))
if "raw_column" in spec:
columns.append(spec["raw_column"])
return columns + [index["months_column"], index["vital_column"]]
def column_of(name: str, spec: dict) -> str:
return spec.get("column", f"{name}_cat")
def _latest(events: pd.DataFrame, source: str, numeric: bool) -> pd.Series:
"""Each patient's latest event of this kind (by date, then source id): its value, indexed by `pac_id`."""
rows = events[events["tipo"] == source]
if numeric:
rows = rows[rows["valor_numerico"].notna()]
column = "valor_numerico"
else:
rows = rows[rows["valor_codigo"].notna()]
column = "valor_codigo"
rows = rows.sort_values(["fecha", "fuente_id"], kind="stable")
return rows.groupby("pac_id")[column].last()
def _present(events: pd.DataFrame, source: str) -> pd.Series:
return pd.Series(True, index=events.loc[events["tipo"] == source, "pac_id"].unique())
class Reader:
"""Evaluates conditions over the patients' events, caching each source's per-patient value."""
def __init__(self, events: pd.DataFrame, patients: pd.Index, made: dict[str, pd.Series]):
self.events, self.patients, self.made = events, patients, made
self._cache: dict[tuple, pd.Series] = {}
def value(self, source: str, numeric: bool) -> pd.Series:
key = (source, numeric)
if key not in self._cache:
self._cache[key] = _latest(self.events, source, numeric).reindex(self.patients)
return self._cache[key]
def present(self, source: str) -> pd.Series:
key = (source, "present")
if key not in self._cache:
self._cache[key] = _present(self.events, source).reindex(self.patients, fill_value=False).astype(bool)
return self._cache[key]
def holds(self, condition: dict) -> np.ndarray:
if "variable" in condition:
return self.made[condition["variable"]].isin(condition["codes"]).to_numpy()
source = condition["source"]
if condition.get("present"):
return self.present(source).to_numpy()
if "codes" in condition:
return self.value(source, False).isin(condition["codes"]).to_numpy()
number = self.value(source, True)
ok = number.notna()
if "ge" in condition:
ok &= number >= condition["ge"]
if "lt" in condition:
ok &= number < condition["lt"]
return ok.to_numpy()
def category_of(spec: dict, reader: Reader) -> pd.Series:
out = pd.Series(spec["missing"], index=reader.patients, dtype=object)
decided = np.zeros(len(reader.patients), bool)
for rule in spec["rules"]:
conditions = rule["when"] if "when" in rule else [rule]
holds = np.ones(len(reader.patients), bool)
for condition in conditions:
holds &= reader.holds(condition)
take = holds & ~decided
out[take] = rule["then"]
decided |= take
return out
def _band(age: pd.Series, index: dict) -> pd.Series:
width, open_from = index["age_band_years"], index["age_open_from"]
low = (np.floor(age / width) * width).clip(lower=0)
closed = [index["age_label"].format(low=int(a), high=int(a) + width - 1) if pd.notna(a) else None for a in low]
opened = index["age_open_label"].format(low=open_from)
label = pd.Series(closed, index=age.index, dtype=object)
label[age >= open_from] = opened
return label.fillna(index["age_unknown"])
def recode(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
"""One row per patient of the cohort, in the columns of `output_columns`."""
index = dictionary["index"]
window = timedelta(days=int(dictionary["window_days_after_index"]))
frame = cohort.copy()
frame["fecha"] = pd.to_datetime(frame["fecha"])
frame["fecha_indice"] = pd.to_datetime(frame["fecha_indice"])
patients = pd.Index(sorted(frame["pac_id"].unique()), name="pac_id")
start = frame.groupby("pac_id")["fecha_indice"].first().reindex(patients)
visible = frame[frame["fecha"] <= frame["pac_id"].map(start) + window]
reader = Reader(visible, patients, {})
for name in variable_names(dictionary):
reader.made[name] = category_of(dictionary[name], reader)
birth = frame[frame["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
death = frame[frame["tipo"] == index["death_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
last = frame.groupby("pac_id")["fecha"].max().reindex(patients)
end = death.fillna(last)
days = (end - start).dt.days
age = (start - birth).dt.days / 365.25
result = pd.DataFrame(index=patients)
result[index["id_column"]] = patients.to_numpy()
result[index["year_column"]] = start.dt.year.astype(str)
result[index["age_column"]] = _band(age, index)
for name in variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
result[column_of(name, spec)] = reader.made[name]
if "raw_column" in spec:
size = reader.value(spec["source"], True)
result[spec["raw_column"]] = [spec["raw_format"].format(v) if pd.notna(v) else spec["raw_missing"]
for v in size]
result[index["months_column"]] = (days / index["days_per_month"]).round().astype(int).astype(str)
result[index["vital_column"]] = np.where(death.notna(), index["dead"], index["alive"])
return result[output_columns(dictionary)].reset_index(drop=True)
def diagnosis_date(year: int, dictionary: dict) -> date:
month, day = dictionary["index"]["seer_diagnosis_month_day"].split("-")
return date(int(year), int(month), int(day))
View File
+142
View File
@@ -0,0 +1,142 @@
"""The SEER development stages over the cohort a run trains on: what the dashboard shows as the model's development.
The members are written as the pipeline's recoded file (`models.cama.seer_survival`, stages 01 to 06): the depuration of
redundant variables, the balanced cohort and its age and tumor categorization, the stepwise logistic regression and the
Bayesian network with their comparison, the bootstrap, the survival curves of the subgroups and the risk factors. Their
tables and figures are the version's `analisis/desarrollo.json`. Stage and treatment are not in the hospital's data yet, so
they enter as `Desconocido` and the record names them; a stage that cannot run publishes its error and the others go on.
"""
import base64
import dataclasses
import tempfile
import traceback
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.survival.estimator import molecular_subtype
CONTEXT_COLUMNS = {"Estadio_cat": "stage", "Tratamiento_quirurgico_cat": "surgery", "Radioterapia_cat": "radiotherapy",
"Quimioterapia_cat": "chemotherapy"}
# What the dashboard reads: the file written by a stage, under the name it is published with.
TABLES = {
"or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos",
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
"curva_supervivencia_puntos_LR_HBN.csv": "cohorte_puntos",
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
}
MAX_ROWS = 60
# The name the whole cohort's points go by among the subgroups' (`subgroup_points`).
WHOLE_COHORT = "Toda la cohorte"
MAX_FIGURE_BYTES = 400_000
def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
"""The members as the pipeline's recoded file: its raw SEER columns (year, age level, months, vital status, tumor
size) and the categorical ones, each unknown value `Desconocido`."""
lm = labelled_members
age = lm["age_years"].fillna(lm["age_years"].median()).to_numpy()
lower = (np.floor(age / 5) * 5).astype(int)
frame = pd.DataFrame({
"Year of diagnosis": pd.to_datetime(lm["fecha_indice"]).dt.year.astype(str),
"Age recode with <1 year olds": [f"{v}-{v + 4} years" if v < 85 else "85+ years" for v in lower],
"Survival months": lm["months"].astype(float).astype(str),
"Vital status recode (study cutoff used)": np.where(lm["event"], "Dead", "Alive"),
"Tumor size summary (mm)": lm["size_mm"].map(lambda v: "" if pd.isna(v) else str(int(v))),
})
for column, source in (("Tipo_histologico_cat", "histologic_type"), ("Grado_histologico_cat", "grade"),
("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"),
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype
for column, source in CONTEXT_COLUMNS.items():
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy() if source in lm else "Desconocido"
return frame
def _seer_settings(development: dict):
"""The pipeline's own settings with this model's budget (`[config.desarrollo]`) and its Ki-67 column, which the
SEER dictionary does not have."""
from models.cama.seer_survival.settings import load
s = load()
m = s.modeling
modeling = dataclasses.replace(
m, canonical_map={**m.canonical_map, "Ki67_cat": "Ki67"}, categorical_order=(*m.categorical_order, "Ki67"),
tier_tumor=(*m.tier_tumor, "Ki67"), n_bootstrap_run=development["n_bootstrap"],
bootstrap_max_seconds=development["bootstrap_max_seconds"], bootstrap_restarts=development["bootstrap_restarts"],
n_splits_prop=development["n_splits_proposals"], proposals_max_seconds=development["proposals_max_seconds"],
n_restarts=development["restarts"])
return dataclasses.replace(
s, modeling=modeling, depuration=dataclasses.replace(s.depuration, null_perm=development["null_perm"]),
balancing=dataclasses.replace(s.balancing, exclude_censored_years=False))
def _records(path: Path) -> dict:
"""The table as `{"columnas": [...], "filas": [...]}`: the columns in the file's order, which JSON objects do not keep."""
table = pd.read_csv(path)
if table.columns[0].startswith("Unnamed"):
table = table.rename(columns={table.columns[0]: "indice"})
table = table.head(MAX_ROWS).replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in table.columns], "filas": table.where(table.notna(), None).to_dict("records")}
def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict:
"""`{"desarrollo": record}`, or `{}` when `[config.desarrollo]` has `enabled = false`."""
if not desarrollo.get("enabled", True):
return {}
from models.cama.seer_survival import pipeline # the `seer-survival` extra: scoring a member does not need it
errors, log = {}, []
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp)
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
settings = _seer_settings(desarrollo)
for stage in pipeline.STAGES:
try:
log += pipeline.run_pipeline(out, only=[stage.id], everything=True, settings=settings)
except Exception as error:
errors[stage.id] = f"{type(error).__name__}: {error}"
log.append((stage.id, "error", 0))
traceback.print_exc()
tables = {name: _records(out / file) for file, name in TABLES.items() if (out / file).exists()}
figures = {}
for path in sorted(out.rglob("*.png")):
raw = path.read_bytes()
if len(raw) <= MAX_FIGURE_BYTES:
figures[path.stem] = base64.b64encode(raw).decode("ascii")
return {"desarrollo": {
"version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log],
"errores": errors, "variables_no_disponibles": [c for c, s in CONTEXT_COLUMNS.items() if s not in labelled_members], "tablas": tables, "figuras": figures}}
def population(population_curves: dict, development: dict) -> dict:
"""Everything the version publishes about its cohort, by file name under `analisis/`: the curves and the development."""
return {**population_curves, **development}
def subgroup_points(labelled_members: pd.DataFrame, desarrollo: dict) -> list[dict]:
"""The pipeline's stages 01 and 05 over the members as they are now: the depuration, then the LR and HBN fitted on them with
each clinical scenario's survival at the horizons and its bootstrap interval (`subgrupos_puntos`), and the whole cohort's
(`cohorte_puntos`, as subgroup `WHOLE_COHORT`), one row per model, horizon and scenario. What the dashboard draws as a
scenario's points between trainings."""
from models.cama.seer_survival import pipeline
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp)
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
pipeline.run_pipeline(out, only=["01", "05"], everything=True, settings=_seer_settings(desarrollo))
cohort = pd.read_csv(out / "curva_supervivencia_puntos_LR_HBN.csv").assign(subgrupo=WHOLE_COHORT)
table = pd.concat([pd.read_csv(out / "subgrupos_puntos_LR_HBN.csv"), cohort[["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"]]],
ignore_index=True)
table = table.replace([np.inf, -np.inf], np.nan).astype(object)
return table.where(table.notna(), None).to_dict("records")
+218
View File
@@ -0,0 +1,218 @@
"""What the CaMa survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates at the index (age group, the biopsy report's histological type, Nottingham grade,
ER, PR, HER2 and Ki-67 band, read from the report's results within `result_days` of the index) and the index date; the
rest keep their row, empty. `IntervalSurvival` fits, per interval of `survival.horizons`, a logistic regression and a
Bayesian network with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`),
stacks them with out-of-sample weights and scores a patient's survival to each horizon as the product of the intervals'.
The registered model is `Pipeline([MemberFeatures, IntervalSurvival])`, so it takes a build's long frame.
Everything the registered model needs when it scores is in this package, which the registry pickles by value.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
INDEX_COLUMN = "fecha_indice_modelo"
NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding: the SEER development stages band them themselves
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"]
RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er",
"receptor_progesterona": "pr", "her2": "her2"}
# What describes a member's disease and treatment without being a covariate: the clinical scenarios and the development
# stages read them. The stage is the one reported with the diagnosis; a treatment counts in the first year after it.
CONTEXT = ["stage", "surgery", "radiotherapy", "chemotherapy"]
TREATMENT_DAYS = 365
SURGERY_LABELS = {"SEGMENTECTOMIA": "Cirugía conservadora", "ESCISIONAL": "Cirugía conservadora",
"MASTECTOMIA_TOTAL": "Mastectomía", "MASTECTOMIA_RADICAL_MODIFICADA": "Mastectomía",
"SIN_CIRUGIA": "Sin cirugía"}
WINDOW_KEYS = ("recruitment_start", "recruitment_end")
DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
EPOCH = pd.Timestamp("1970-01-01")
def molecular_subtype(labelled: pd.DataFrame) -> pd.Series:
"""The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and
negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario."""
hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO")
hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"])
her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"})
subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido")
return pd.Series(subtype, index=labelled.index)
def survival_settings(table: dict) -> SurvivalSettings:
"""`SurvivalSettings` from a `[config.survival]` table: lists become tuples, an unknown key is an error."""
return SurvivalSettings(**{key: tuple(value) if isinstance(value, list) else value for key, value in table.items()})
def _band(values: pd.Series, cuts: list) -> pd.Series:
"""The values in the bands the cuts make: `<c1`, `c1-(c2-1)`, ..., `≥cn`; empty where the value is."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in zip(cuts[:-1], cuts[1:])], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
def _dated(cohort: pd.DataFrame) -> pd.DataFrame:
return cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_days: int,
size_cuts: list | None = None) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice` and the covariates in `FEATURES`,
empty where the build has no such result near the index."""
frame = _dated(cohort)
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
near = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, result_days)]
near = near.sort_values(["fecha", "fuente_id"])
for tipo, name in RESULTS.items():
members[name] = near[near["tipo"] == tipo].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
ki67 = near[near["tipo"] == "ki67_pct"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["ki67_group"] = _band(ki67, ki67_cuts)
size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS)
members["size_mm"], members["ki67_pct"] = size, ki67
stage = near[near["tipo"] == "estadio_clinico"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
members["stage"] = stage.map(lambda v: v[1:] if isinstance(v, str) and v.startswith("E") else v)
treated = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, TREATMENT_DAYS)].sort_values(["fecha", "fuente_id"])
surgery = treated[treated["tipo"] == "cirugia"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
members["surgery"] = surgery.map(lambda v: SURGERY_LABELS.get(v, "Otra cirugía") if isinstance(v, str) else None)
for kind, name in (("radioterapia", "radiotherapy"), ("quimioterapia", "chemotherapy")):
given = set(treated.loc[treated["tipo"] == kind, "pac_id"])
members[name] = ["Sí" if pac in given else "No" for pac in members.index]
return members[["fecha_indice", *FEATURES, *NUMERIC, *CONTEXT]]
def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: whole months from the index to her death or, if she
has none by the cut-off, to the cut-off (`months`), and whether she died (`event`). Follow-up is cut at
`cap_months`: a later death counts as alive."""
frame = _dated(cohort)
index = frame.groupby("pac_id")["fecha_indice"].first()
death = frame[frame["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(index.index)
cutoff = min(pd.Timestamp(cutoff), pd.Timestamp.today().normalize()) # nobody is followed past today
died = (death.notna() & (death <= cutoff)).to_numpy()
end = death.where(died, cutoff)
months = np.floor((end - index).dt.days.to_numpy() / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""The covariates as the interval models take them: `(X_dum, X_int, categories, dummy_columns)`. With no `categories`
they are learned from `frame` (the first appearance of each value, the first alphabetical level of each covariate
as the dummies' reference); with them, `frame` is coded as the fitted model coded its training rows, and a value it
never saw takes the unknown category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings: SurvivalSettings):
"""The pipeline's `Cohort` of these members, with the categories and dummy columns it was coded by."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(45, 60, 75), ki67_cuts=(14, 20), result_days=30,
size_cuts=DEFAULT_SIZE_CUTS):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.ki67_cuts = ki67_cuts
self.result_days = result_days
self.size_cuts = size_cuts
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), list(self.ki67_cuts), self.result_days, list(self.size_cuts)) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
class IntervalSurvival(BaseEstimator):
"""The stage-5 interval survival of the SEER pipeline as an estimator: per interval, LR and HBN stacked; the survival
to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with `months` and
`event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too."""
def __init__(self, survival=None, horizons_years=(0.5, 1.0, 1.5)):
self.survival = survival
self.horizons_years = horizons_years
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
return self
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def component_survival(self, X: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each member's survival to each horizon by the logistic regression, by the Bayesian network and by their
stacked combination (`survival_proba`)."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return {"LR": np.cumprod(P_lr, axis=1), "HBN": np.cumprod(P_hb, axis=1), "COMB": self.survival_proba(X)}
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
+117
View File
@@ -0,0 +1,117 @@
"""The survival figure of a clinical scenario over the data ingested so far, as the SEER pipeline's survival stage draws a subgroup.
Training and tuning happen in governance; here the production version's results are only shown. The scenarios are the subgroups
of the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
share a figure, and a patient sees the figure of each scenario she belongs to, or the whole cohort's when she is in none. The
record has the Kaplan-Meier curve of what happened to the scenario's members with its Greenwood band, the classic and fractional
Weibull fitted to their deaths, and the pipeline's LR, HBN and combined survival at each horizon with their bootstrap intervals:
the survival stage's points for the scenario (`development.subgroup_points`), never a model of this module's.
"""
from types import SimpleNamespace
import numpy as np
import pandas as pd
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_curves as luis
from models.cama.survival import population
from models.cama.survival.development import WHOLE_COHORT
from models.cama.survival.estimator import IntervalSurvival, molecular_subtype, survival_settings
from models.dags.training import Scenario, dataflow
MIN_MEMBERS = 30
MIN_EVENTS = 5
WHOLE = WHOLE_COHORT
class QueryError(ValueError):
"""The scenario cannot be answered; the message says why, in the reader's language."""
def rehydrate(model) -> IntervalSurvival:
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
is put in the current class and its methods are the code's."""
current = IntervalSurvival.__new__(IntervalSurvival)
current.__dict__.update(model.__dict__)
return current
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
dr = dataflow(*scenario.modules, config=scenario.config)
return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"]
def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the members, by her age, molecular subtype, stage and surgery."""
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy(),
"Estadio_cat": labelled["stage"].to_numpy(), "Tratamiento_quirurgico_cat": labelled["surgery"].to_numpy()},
index=labelled.index)
return scenarios.masks(raw)
def answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool:
return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS
def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
"""The scenarios `pac_id` belongs to and that have enough members to draw; the whole cohort when she is in none."""
row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id)
if len(row) == 0:
raise QueryError("La paciente no está en la cohorte del modelo.")
found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and answerable(labelled, mask)]
return found or [WHOLE]
def published_points(rows: list[dict], name: str | None) -> dict | None:
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`, or `cohorte_puntos` for `WHOLE`:
its model with the stage and the treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
found = [r for r in rows if r.get("subgrupo") == (name or WHOLE)]
if not found:
return None
out = {}
for series in population.SERIES:
mine = sorted((r for r in found if r["modelo"] == series), key=lambda r: r["meses"])
if not mine:
return None
out[series] = {"S": [float(r["S"]) for r in mine], "low": [float(r["IC_inf"]) for r in mine],
"high": [float(r["IC_sup"]) for r in mine]}
return out
def curves(scenario: Scenario, labelled: pd.DataFrame, name: str | None, points: dict | None) -> dict:
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths, with the
stage's `points` for it (`published_points`). `QueryError` for an unknown scenario, one with too few members to say
anything, or one the stage has no points for yet."""
if name in (None, WHOLE):
mask = np.ones(len(labelled), bool)
else:
masks = scenario_masks(labelled)
if name not in masks:
raise QueryError(f"No hay un escenario clínico «{name}».")
mask = masks[name]
if not answerable(labelled, mask):
raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; "
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
if points is None:
raise QueryError("El modelo todavía no tiene la supervivencia de este escenario; se calcula en el siguiente recálculo de indicadores.")
selected = labelled[mask].reset_index(drop=True)
s = survival_settings(scenario.config["survival"])
horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons))
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
months, ended = np.minimum(followed, cap), died & (followed < cap)
S, low, high = luis.fw.km_curva(months, ended, cap)
d, c = luis.fw.tabla_eventos(months, ended)
classic = luis.fw.ajustar_weibull(d, c)
fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_max_seconds)
grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP)
return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)),
"events": int(ended.sum()), "median_follow_up_months": float(np.median(followed)),
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": int(s.n_boot if name in (None, WHOLE) else s.n_boot_sub),
"km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": points, "etiquetas": scenario.config.get("etiquetas", {})}
+221
View File
@@ -0,0 +1,221 @@
"""CaMa survival prototype: the mortality of a woman with an invasive carcinoma at 6, 12 and 18 months from the first
invasive biopsy report.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): the index is the first biopsy report graded invasive. Each member's covariates are the results of
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67, lesion size) and her age at the index; her outcome is the
months from the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts
the follow-up). The fit is the SEER pipeline's interval survival (`models.cama.seer_survival.survival_models`): per
interval a logistic regression and a Bayesian network, stacked. A member without a result has it as a category of its
own, as the pipeline does with its unknowns.
The split, the metrics and the routines (ML-01a) are here; the temporal split is `models.steps.model_fitting`'s.
`fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
`Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through loaders, and
registering is the driver's saver (`models.dags.training`).
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import estimator
from models.cama.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file, and a member without a death is followed to it."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""The pipeline's survival settings; its horizons, in months, must be `horizons_years`."""
settings = estimator.survival_settings(survival)
if [h / 12 for h in settings.horizons] != list(horizons_years):
raise ValueError(f"survival.horizons {list(settings.horizons)} and horizons_years {horizons_years} differ")
return settings
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int,
size_cuts: list[int]) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates."""
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days, size_cuts)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""One row per member, by `pac_id`: months of follow-up and whether she died in them."""
return estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
"""The interval survival fitted on the training members."""
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def _interval_outcomes(frame: pd.DataFrame, borders: list[int], probabilities: np.ndarray) -> pd.DataFrame:
"""One row per member and interval she was at risk in: the model's probability of surviving it, whether she did
(`survived`) and its weight (a censoring inside the interval counts half, as in the fit)."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
rows = []
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
at_risk = months >= a
died = event & (months < b)
rows.append(pd.DataFrame({"interval": f"{a}-{b}", "p": probabilities[at_risk, j],
"survived": (~died[at_risk]).astype(float),
"weight": np.where((~event & (months < b))[at_risk], 0.5, 1.0)}))
return pd.concat(rows, ignore_index=True)
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance: they are what the model was fitted on)."""
return fitted_survival.predict_proba(train_set[FEATURES])
def _known_status_auc(frame: pd.DataFrame, mortality: np.ndarray, horizon_months: int, column: int) -> dict:
"""The AUC of the mortality at one horizon among the members whose status there is known (died before it, or
followed to it), and how many they are; empty without both outcomes in at least 20 members."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
died = event & (months < horizon_months)
known = died | (months >= horizon_months)
if known.sum() < 20 or len(np.unique(died[known])) < 2:
return {}
return {"auc": float(roc_auc_score(died[known], mortality[known, column])), "n": int(known.sum())}
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""Aggregates only: the members and deaths in each part and, over the member-intervals of the test members (every
month they were followed, not only the members whose status at a horizon is known), their number, the observed and
expected survival, the weighted Brier score and, with both outcomes, the AUC. A temporal split leaves the newest
members little follow-up, so a metric at one horizon would be of the few that died. The `auc_train_*` are the
apparent discrimination at each horizon, on the members the model was fitted on: they say the covariates were
used, not how it will do on new patients."""
found = {"n_train": len(train_set), "n_test": len(test_set), "events_train": int(train_set["event"].sum()),
"events_test": int(test_set["event"].sum())}
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
found["n_member_intervals_test"] = len(pairs)
if len(pairs):
w, y, p = pairs["weight"].to_numpy(), pairs["survived"].to_numpy(), pairs["p"].to_numpy()
found.update(observed_survival=float(np.average(y, weights=w)), expected_survival=float(np.average(p, weights=w)),
brier_interval=float(np.average((p - y) ** 2, weights=w)))
if len(np.unique(y)) == 2:
found["auc_interval"] = float(roc_auc_score(y, p, sample_weight=w))
for column, months in enumerate(survival_settings.horizons):
apparent = _known_status_auc(train_set, train_mortality, months, column)
if apparent:
found[f"auc_train_{months}m"], found[f"n_known_train_{months}m"] = apparent["auc"], apparent["n"]
for row, months in zip(fitted_survival.stacking_, survival_settings.horizons):
found[f"stack_w_lr_{months}m"] = float(row["w_LR"])
return found
def _dates(frame: pd.DataFrame) -> dict:
if frame.empty:
return {"n": 0}
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
"last_index_date": str(frame["fecha_indice"].max())}
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"train_fraction": train_fraction, "train": _dates(train_set), "test": _dates(test_set)}
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"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_]}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: deaths and members followed without one in each part; the classes are used as observed."""
def counts(frame: pd.DataFrame) -> dict:
return {"muertes": int(frame["event"].sum()), "sin muerte": int((~frame["event"]).sum())}
return {"method": "ninguno: no se remuestrea ni se pondera por clase; una censura dentro de un intervalo pesa medio "
"riesgo", "train": counts(train_set), "test": counts(test_set)}
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CONFIANZA_SALIDA: over the test members' member-intervals, the predicted survival of the interval against the
observed one, by quantiles."""
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
if len(pairs) == 0 or pairs["p"].nunique() < 2:
return {"method": "calibración en la prueba: sin dispersión suficiente para formar cuantiles", "n": len(pairs)}
bins = pd.qcut(pairs["p"], q=min(calibration_bins, pairs["p"].nunique()), duplicates="drop")
table = pairs.assign(py=pairs["p"] * pairs["weight"], sy=pairs["survived"] * pairs["weight"]).groupby(
bins, observed=True).agg(n=("p", "size"), w=("weight", "sum"), py=("py", "sum"), sy=("sy", "sum"))
return {"method": "calibración en la prueba por intervalo: supervivencia media prevista contra observada, por "
"cuantiles de los miembro-intervalos",
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.py / row.w),
"observed_rate": float(row.sy / row.w)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
ki67_cuts: list[int], result_days: int, size_cuts: list[int]) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days, tuple(size_cuts))),
("survival", fitted_survival)])
+92
View File
@@ -0,0 +1,92 @@
domain = "cama"
scenario = "survival"
cohort = "cama/cohorte_total"
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.cama.survival.model", "models.cama.survival.population", "models.cama.survival.development", "models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a los 6, 12 y 18 meses del primer reporte de biopsia con carcinoma invasor, \
a partir de la edad y de los resultados de ese reporte (tipo histológico, grado de Nottingham, receptores de estrógeno \
y de progesterona, HER2, Ki-67 y tamaño de la lesión). Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana \
combinadas). Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la registra."""
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [0.5, 1.0, 1.5]
# Covariate bands: the age at the index, in years, the Ki-67 percentage and the lesion size in millimetres (T1, T2, T3).
age_cuts = [45, 60, 75]
ki67_cuts = [14, 20]
size_cuts = [20, 50]
# A report's results count for the index when they are dated up to this many days after it (and a week before).
result_days = 30
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). The recruitment window is the
# source cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA_INVASOR"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
[config.desarrollo]
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort,
# with the pipeline's own budgets (`models/cama/seer_survival/model.toml`). The bootstrap and the proposals stop at their
# time caps and use what they have. One adaptation: `exclude_censored_years` is off, because this follow-up is short and
# would leave every year out of the outcome.
enabled = true
null_perm = 100
n_bootstrap = 60
bootstrap_max_seconds = 2700
bootstrap_restarts = 3
n_splits_proposals = 5
proposals_max_seconds = 3600
restarts = 10
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [45, 60, 75]
hbn_fixed_parents = ["histologic_type", "age_group"] # the SEER pipeline's expert parents that this data has (its stage and treatment are not reported yet); empty = learn them by the BDeu score
hbn_age_parent = false # the grouped age is already in `hbn_fixed_parents`
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [6, 12, 18] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 18
cap_months = 24 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
# training run publishes carries these, so changing one is a setting and a new run.
[config.etiquetas]
# The wording of the survival figure, as the SEER pipeline's own chart has it; to be defined with the clinicians.
titulo = "Supervivencia después del primer reporte de biopsia con carcinoma invasor"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
+115
View File
@@ -0,0 +1,115 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon.
Over every member of the indexed cohort (not only the training part), with the SEER pipeline's stage-5 routines
(`models.cama.seer_survival`): the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted curve (the
mean of the members' interval survival), the classic and the fractional (Kilbas-Saigo) Weibull fitted to it, and the
mean survival at each horizon by the logistic regression, the Bayesian network and their stacked combination, each with
a 95 % bootstrap interval. The record is the version's `analisis/curvas.json` (`models.io.tracking.TrainingRun.log_analysis`),
which the WebApi serves from the production version. The labels the chart carries come from `[config.etiquetas]`, so
the clinicians' wording is a setting, not code.
"""
import numpy as np
import pandas as pd
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
from models.cama.survival.estimator import FEATURES, UNKNOWN
SERIES = ("LR", "HBN", "COMB")
GRID_STEP = 0.25 # months between the points of a fitted curve
RECORD_VERSION = 1
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts as
alive) and the covariates as categories."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
"""The members coded as the stage-5 models take them (`survival_curves.sv_cohort`)."""
return luis.sv_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
"""Kaplan-Meier with the Greenwood interval (`survival_curves.sv_km`)."""
return luis.sv_km(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
"""Kaplan-Meier from the index to `months_max`, with its interval, as the record carries it."""
return {"months": list(range(km_raw.T + 1)), "S": km_raw.S.tolist(), "low": km_raw.lo.tolist(), "high": km_raw.hi.tolist()}
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
"""The covariate-adjusted survival curve, month by month (`survival_curves.sv_adjusted`)."""
return luis.sv_adjusted(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR (`sv_weights_cohort`)."""
return luis.sv_weights_cohort(curve_cohort, luis.sv_oof(curve_cohort, survival_settings), survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member (`sv_points`)."""
return luis.sv_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return {"LR": luis_points.lr, "HBN": luis_points.hbn, "COMB": luis_points.combined}
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample, the
HBN's parents kept or learned again as `hbn_parents` says (`sv_bootstrap`)."""
return luis.sv_bootstrap(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
"""The classic and the fractional Weibull fitted to the adjusted curve as if it came from as many members as the
cohort has (`survival_curves._fit_to_curve`), evaluated on a grid of months, with their parameters."""
classic, fractional = luis._fit_to_curve(adjusted_km, len(survival_frame.df), survival_settings, survival_settings.ks_max_seconds)
grid = np.arange(0, len(adjusted_km) - 1 + GRID_STEP, GRID_STEP)
parameters = lambda fit: {key: float(fit[key]) for key in ("k", "alpha", "beta", "lam", "nll") if key in fit}
return {"t": grid.tolist(), "classic": np.asarray(classic["S"](grid), float).tolist(),
"fractional": np.asarray(fractional["S"](grid), float).tolist(),
"parameters": {"classic": parameters(classic), "fractional": parameters(fractional)}}
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""What a version publishes about its cohort, by file name under `analisis/`: `curvas`, the record the dashboard
draws (the figure's curves, its points and their intervals, and the labels)."""
horizons = list(survival_settings.horizons)
low, high = np.nanpercentile(bootstrap_points, [2.5, 97.5], axis=0)
points = {}
for j, name in enumerate(SERIES):
columns = slice(j * len(horizons), (j + 1) * len(horizons))
points[name] = {"S": [float(v) for v in point_estimates[name]], "low": [float(v) for v in low[columns]],
"high": [float(v) for v in high[columns]]}
months, events = labelled_members["months"], labelled_members["event"]
return {"curvas": {
"version": RECORD_VERSION, "n": int(len(labelled_members)), "events": int(events.sum()),
"median_follow_up_months": float(months.median()), "horizons_months": horizons,
"months_max": km_curve["months"][-1], "bootstrap_replicas": int(survival_settings.n_boot),
"km": km_curve, "km_adjusted": {"months": list(range(len(adjusted_km))), "S": adjusted_km.tolist()},
"weibull": {"t": weibull_fits["t"], "S": weibull_fits["classic"]},
"weibull_fractional": {"t": weibull_fits["t"], "S": weibull_fits["fractional"]},
"weibull_parameters": weibull_fits["parameters"], "points": points,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in population_weights.to_dict("records")],
"etiquetas": etiquetas}}
+4 -5
View File
@@ -1,7 +1,6 @@
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
builds its frame from the patients' timeline (dbt's view, through Persistance).
"""Cohorts for the risk models. dbt is their only definition (`Transformation/models/<project>/cohorts/`: population,
index date and exclusions as queries in the manifest); this package stores a build of them for the WebApi cycle.
definition.py a cohort's definition, read from its TOML
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
build.py from dbt's queries to `cohorte_armado` and its rows; the stored frame, wide
cama/ CaMa's screening cohort, a PROPOSAL in the old Python-frame format, not built
"""
+57 -88
View File
@@ -1,111 +1,79 @@
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición.
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
(`TimelineRepository.query`), recortada al corte y,
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
versiones de fila es aproximado, ADR-MD-009). La regla de
la cohorte es la función que nombra su definición (`expression`).
dbt es la única definición de una cohorte (`Transformation/models/<proyecto>/cohorts/`): su población, su fecha
índice y sus exclusiones son consultas del manifest (`models.io.storage.read_queries`), y el armado las corre en la
sesión que le dan, con la misma cadena que la exportación (`models.pipelines.cohort_build.build_cohort`). Las
reglas que no caben en SQL son del modelo, sobre `cacu/cohorte_total` y la línea de tiempo, no de una cohorte.
Rearmar con la misma definición, los mismos parámetros y los mismos datos no
guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están.
Si los datos cambiaron, el `marco_sha` cambia y se guarda un armado nuevo.
`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o
valida con este armado: llaves y huellas, nunca filas ni `pac_id`.
Rearmar con las mismas consultas, los mismos parámetros y los mismos datos no guarda otro armado: la huella del
pedido y la del marco (`marco_sha`) ya están. Si los datos cambiaron, el `marco_sha` cambia y se guarda uno nuevo.
"""
import inspect
import hashlib
import json
from datetime import date, datetime, timezone
from importlib import import_module
from contextlib import nullcontext
from datetime import datetime, timezone
from core.indicadores.cohortes import TablasCohorte
from persistance.edges.dbt import DbtQueryRepository
from sqlmodel import Session, select
from models.cohorts.definition import Definition, json_sha
DECIMALS = 9 # redondeo de los tiempos en la huella del marco
from models.io.contracts import CohortQueries
from models.pipelines.cohort_build import build_cohort
def timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]:
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def frame_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
linea,
pacientes: list[int] | None = None,
conocida_hasta: datetime | None = None,
):
"""El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente)."""
filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta)
return definicion.function()(filas, definicion.reglas, inicio, fin, corte)
def queries_sha(queries: CohortQueries) -> str:
"""Huella de las reglas: el SQL compilado de cada paso, en su orden. Hace el papel de la definición."""
return json_sha({"all_patients": queries.all_patients, "index_date": queries.index_date,
"rules": [[rule.order, rule.name, rule.sql] for rule in queries.rules],
"variables": queries.variables})
def frame_sha(miembros, definicion: Definition) -> str:
def frame_sha(miembros, variables=()) -> str:
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
nombres = [v.nombre for v in definicion.variables]
def redondo(valor):
return round(valor, DECIMALS) if isinstance(valor, float) else valor
return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)]
for m in sorted(miembros, key=lambda m: m.pac_id)])
return json_sha({"miembros": sorted([int(m["pac_id"]), m["fecha_indice"].isoformat()] for m in miembros),
"variables": sorted([v.pac_id, v.variable, v.valor_codigo, v.valor_numerico] for v in variables)})
def code_sha(definicion: Definition) -> str:
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
return json_sha(inspect.getsource(modulo))
def build_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
cohortes: TablasCohorte,
linea,
conocida_hasta: datetime | None = None,
ahora: datetime | None = None,
):
"""El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`).
def build_of(sesion: Session, queries: CohortQueries, *, cohortes: TablasCohorte, ahora: datetime | None = None):
"""El armado sin guardarlo: la fila de `cohorte_armado`, sus exclusiones, sus miembros y sus variables (sin
`armado_id`). Las variables son las de la consulta `variables` de la cohorte, si tiene, solo de sus miembros; las
que no caben en SQL las calcula el modelo de la línea de tiempo.
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
"""
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
conocida_hasta=conocida_hasta)
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
"codigo": code_sha(definicion), "parametros": parametros})
consultas = DbtQueryRepository(lambda: nullcontext(sesion))
built = build_cohort(queries, consultas)
miembros = built.study_population.to_dict("records")
parametros = {**queries.parameters, "corte": queries.cutoff.isoformat()}
reglas_sha = json_sha(queries.parameters)
definicion_sha = queries_sha(queries)
armado = cohortes.CohorteArmado(
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros),
armado_en=ahora or datetime.now(timezone.utc),
url=queries.url, version=queries.version or "0", definicion_sha=definicion_sha, reglas_sha=reglas_sha,
parametros=json.dumps(parametros, sort_keys=True), datos_as_of=queries.cutoff,
huella=json_sha({"definicion": definicion_sha, "reglas": reglas_sha, "parametros": parametros}),
marco_sha="", n_miembros=len(miembros), armado_en=ahora or datetime.now(timezone.utc),
)
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
for orden, (paso, n) in enumerate(atricion, start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
indice_fuente_tabla=m.indice_fuente_tabla,
indice_fuente_id=m.indice_fuente_id) for m in miembros]
tipos = {v.nombre: v.tipo for v in definicion.variables}
variables = [
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
else {"valor_numerico": float(valor)}))
for m in miembros for nombre, valor in m.variables.items() if valor is not None
]
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=fila["step"], n=int(fila["n"]))
for orden, fila in enumerate(built.attrition.to_dict("records"), start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=int(m["pac_id"]), fecha_indice=m["fecha_indice"],
indice_fuente_tabla=m.get("indice_fuente_tabla"),
indice_fuente_id=None if m.get("indice_fuente_id") is None
else str(m["indice_fuente_id"])) for m in miembros]
socias = {int(m["pac_id"]) for m in miembros}
variables = [cohortes.CohorteVariable(pac_id=int(v["pac_id"]), variable=v["variable"],
valor_codigo=None if v.get("valor_codigo") is None else str(v["valor_codigo"]),
valor_numerico=None if v.get("valor_numerico") is None
else float(v["valor_numerico"]))
for v in (consultas.read(queries.variables) if queries.variables else [])
if int(v["pac_id"]) in socias and (v.get("valor_codigo") is not None or v.get("valor_numerico") is not None)]
armado.marco_sha = frame_sha(miembros, variables)
return armado, exclusiones, filas_miembro, variables
@@ -117,15 +85,16 @@ def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int |
).first()
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
nombres = [v.nombre for v in definicion.variables]
def read_frame(sesion: Session, armado_id: int, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro, con las variables que el armado tenga (los de
dbt no tienen: solo `pac_id` y `fecha_indice`)."""
valores: dict[int, dict] = {}
variable = cohortes.CohorteVariable
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
valores.setdefault(fila.pac_id, {})[fila.variable] = (
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
)
nombres = sorted({nombre for porpac in valores.values() for nombre in porpac})
miembro = cohortes.CohorteMiembro
filas = [
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
-1
View File
@@ -1 +0,0 @@
"""CaCu's cohorts: the surveillance cohort."""
-106
View File
@@ -1,106 +0,0 @@
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
Quién entra:
- la índice es la primera citología de toda la historia, si cae en la ventana;
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
- y luego a quien no tiene resultado citológico ni de VPH en la índice.
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
SIN_ESTADO = -999
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # nombre -> valor; un valor nulo no se guarda
def _by_patient(filas):
pacientes = defaultdict(list)
for fila in filas:
pacientes[fila["pac_id"]].append(fila)
return pacientes
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(miembros, atrición). `filas`: la línea de tiempo de CaCu, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_evento"])
ventana = int(reglas["ventana_basal_dias"])
pap_negativo = set(reglas["no_prevalente"]["pap"])
vph_negativo = set(reglas["no_prevalente"]["vph"])
candidatas = evento_previo = sin_resultado = 0
miembros = []
for pac_id, eventos in sorted(_by_patient(filas).items()):
eventos = [e for e in eventos if e["fecha"] <= corte]
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
continue
indice = tomas[0]
llave = (indice["fuente_tabla"], indice["fuente_id"])
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
candidatas += 1
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
evento_previo += 1
continue
if pap_0 is None and hpv_0 is None:
sin_resultado += 1
continue
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
for fecha, positiva in biopsias if fecha >= fecha_indice]
if reglas["negativo_da_l"]:
for toma in tomas[1:]:
clave = (toma["fuente_tabla"], toma["fuente_id"])
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
positivas = [d for d, positiva, _ in verificaciones if positiva]
primera_positiva = min(positivas) if positivas else None
negativas = [d for d, positiva, _ in verificaciones
if not positiva and (primera_positiva is None or d < primera_positiva)]
ultima_negativa = max(negativas) if negativas else None
if primera_positiva is not None and primera_positiva <= ventana:
c = 1
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
c = 0
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
c = 0
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
c = 0
else:
c = SIN_ESTADO
if c == 1:
l = r = SIN_ESTADO
else:
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
miembros.append(Member(pac_id, fecha_indice, *llave,
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
("sin sin_resultado", len(miembros))]
return miembros, atricion
-78
View File
@@ -1,78 +0,0 @@
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
#
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cacu/cohorte_vigilancia"
version = "0.2.0"
status = "draft"
membership = "definitional"
title = "Mujeres en vigilancia por citología"
expression = "cacu.surveillance:frame"
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "evento_previo"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
[[group.characteristic]]
code = "sin_resultado"
exclude = true
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
[group.reglas]
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
ventana_basal_dias = 90
negativo_da_l = true
negativo_confirma_no_prevalente = true
colposcopia_negativa = []
[group.reglas.no_prevalente]
pap = ["NORMAL"]
vph = ["NEGATIVO"]
description = "Tamizaje completamente negativo: confirma que no es prevalente"
[group.reglas_estado]
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
[[evidenceVariable]]
name = "c"
role = "outcome"
tipo = "numero"
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
[[evidenceVariable]]
name = "l"
role = "outcome"
tipo = "numero"
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
[[evidenceVariable]]
name = "r"
role = "outcome"
tipo = "numero"
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Categoría citológica de la citología índice"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "Resultado de VPH de la misma muestra"
-82
View File
@@ -1,82 +0,0 @@
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
"""
import hashlib
import json
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
@dataclass(frozen=True)
class Variable:
nombre: str
rol: str # outcome o covariate
tipo: str # numero o codigo
titulo: str
@dataclass(frozen=True)
class Definition:
url: str
version: str
titulo: str
expression: str
desenlace: str
reglas: dict
variables: tuple[Variable, ...]
definicion_sha: str # sha256 del TOML
@property
def reglas_sha(self) -> str:
return json_sha(self.reglas)
def function(self):
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
return function_of(self.expression)
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
def read_definition(ruta: Path) -> Definition:
texto = ruta.read_text(encoding="utf-8")
doc = tomllib.loads(texto)
g = doc["group"]
reglas = dict(g["reglas"])
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
nombres = [v.nombre for v in variables]
if len(set(nombres)) != len(nombres):
raise ValueError(f"{g['url']}: variables repetidas.")
return Definition(
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
desenlace=g["desenlace"], reglas=reglas, variables=variables,
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
)
def function_of(expresion: str):
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
modulo, nombre = expresion.split(":")
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
if not callable(function):
raise ValueError(f"{modulo} debe definir la función {nombre}.")
return function
+44 -17
View File
@@ -1,9 +1,8 @@
"""Estimating with any scenario's registered version: score a source's build and write the estimate, once.
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order.
A build with no rows, or with nulls where a member, a date or an event goes, is refused first (`storage.model_frame`).
Its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order;
its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
classifier that's the positive class at its one horizon. The output has one row per member and horizon
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
"""
@@ -20,7 +19,10 @@ from models.dags.training import Scenario
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, model_frame, read_metadata, write_once
from models.io.storage import CohortSource, read_metadata, write_once
# The config key, logged with the run, of a model whose risks come with their interval (`estimate_frame`).
INTERVAL_PARAM = "risk_interval_level"
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
@@ -28,16 +30,43 @@ def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon."""
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float],
intervals: bool = False) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon. A model that decides its own index
date (`models.steps.indexing`) gives it as one more first column, in days since 1970-01-01, with the members it
leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index. A member without
a risk (NaN: one the model can't place) has no rows. With `intervals`
the model gives three blocks of one column per horizon, the risk and its interval's lower and upper ends
(`ic_bajo`, `ic_alto`)."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
if probabilities.ndim != 2 or len(probabilities) != len(members):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
risks = probabilities[:, -len(horizons):]
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(members["fecha_indice"].to_numpy(), len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": risks.ravel().astype(float)})
width = len(horizons) * (3 if intervals else 1)
if probabilities.ndim != 2 or len(probabilities) != len(members) or probabilities.shape[1] not in (width, width + 1):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members and {len(horizons)} horizons"
+ (" with intervals" if intervals else ""))
risks, dates = probabilities[:, -width:], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == width + 1:
decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
scored = ~np.isnan(risks[:, :len(horizons)]).any(axis=1) # a member the model can't place (a combination unseen in training)
members, risks, dates = members[scored], risks[scored], dates[scored]
blocks = np.split(risks, 3 if intervals else 1, axis=1)
frame = pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(dates, len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": blocks[0].ravel().astype(float)})
if intervals:
frame["ic_bajo"], frame["ic_alto"] = blocks[1].ravel().astype(float), blocks[2].ravel().astype(float)
return frame
def scored_frame(resolved: ResolvedVersion, cohort_frame: pd.DataFrame) -> pd.DataFrame:
"""The version's estimate of a build's long frame: its model's output at the run's horizons, with the interval
when the run has `INTERVAL_PARAM`."""
params = registry.client.get_run(resolved.run_id).data.params
intervals = params.get(INTERVAL_PARAM) not in (None, "", "None", "null")
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
return estimate_frame(cohort_frame, probabilities, json.loads(params["horizons_years"]), intervals)
def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
@@ -49,10 +78,8 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = model_frame(source)
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
risks = estimate_frame(cohort_frame, probabilities, horizons)
cohort_frame = source.frame()
risks = scored_frame(resolved, cohort_frame)
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
+44 -11
View File
@@ -4,12 +4,11 @@ the adapters.
A scenario is a folder with `model.toml` and its dataflow. `model.toml` names it (`domain`, `scenario`, `cohort`,
`outcome`, `description`), lists the `modules` whose functions are the graph's nodes, and holds `[config]`, the values
the dataflow receives through `with_config`. The dataflow goes from `cohort` and `cohort_lineage` to `fitted_model` (a
scikit-learn estimator that takes the long frame), `metrics` and, for a version that can be promoted, `routines` (what each
routine around training did, by kind, ML-01a), with no I/O.
scikit-learn estimator that takes the long frame) and `metrics`, with no I/O.
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed
it failed if the graph fails. Before running, it stores the graph's drawing as `diagramas/pipeline.svg` (and its `.dot`). `find_trained` answers before anything is built whether this source, the installed
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold
members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
"""
@@ -18,7 +17,7 @@ import hashlib
import json
import logging
import tomllib
from dataclasses import dataclass
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
from types import ModuleType
@@ -33,8 +32,6 @@ from models.io.storage import CohortSource
from models.io.tracking import TrainingRun
REGISTERED_MODEL = "registered_model"
# A scenario without this node registers a version that ML-01a keeps out of production.
ROUTINES = "routines"
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
@@ -50,6 +47,14 @@ class Scenario:
config: dict
folder: Path
requirements: tuple[str, ...] = ()
# Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`).
tables: dict | None = None
# What the model's number is (`[estimand]`): `quantity`, `description`, `outcome`, `index_date`, `horizons_unit`;
# what a screen shows next to each risk. How its interval is computed is the version's report's, not the screen's.
estimand: dict = field(default_factory=dict)
# Whether the cycle scores every member of the cohort with the version in production (`batch_estimates`); off for a
# model whose answers are per clinical scenario, not a risk per member.
batch_estimates: bool = True
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
@@ -58,7 +63,9 @@ class Scenario:
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
folder=path.parent, requirements=tuple(found.get("requirements", ())),
tables={name: found[name] for name in found.get("settings_tables", ())} or None,
estimand=dict(found.get("estimand", {})), batch_estimates=bool(found.get("batch_estimates", True)))
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
@@ -70,7 +77,8 @@ class Scenario:
return cls.from_toml(Path(package.__file__).parent / "model.toml")
def config_sha256(self) -> str:
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
content = self.config if not self.tables else {"config": self.config, **self.tables}
return hashlib.sha256(json.dumps(content, sort_keys=True, default=str).encode()).hexdigest()
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
@@ -81,6 +89,11 @@ 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, 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]]:
"""The graph's inputs that some node requires, and those every node taking them has a default for."""
variables = dr.list_available_variables()
@@ -106,6 +119,23 @@ def find_trained(scenario: Scenario, source: CohortSource, environment: str = "D
return None
def pipeline_drawing(dr: driver.Driver) -> tuple[str, str | None] | None:
"""The scenario's Hamilton graph as Graphviz source and SVG: every node of its modules and the external inputs,
left to right. The SVG is None when Graphviz's `dot` program is missing; the whole drawing is None when the
`graphviz` package is (the `notebooks` extra)."""
try:
graph = dr.display_all_functions(None, orient="LR", show_schema=False)
except ImportError:
return None
if graph is None: # Hamilton logs the missing `graphviz` and gives nothing
return None
try:
svg = graph.pipe(format="svg", encoding="utf-8")
except Exception: # graphviz.ExecutableNotFound or a failed render: the source still goes
svg = None
return graph.source, svg
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows."""
@@ -115,11 +145,14 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
try:
plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain)
if drawing := pipeline_drawing(plain):
run.log_diagram("pipeline", *drawing)
loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("cohort_lineage", from_.cohort_source_lineage))
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
("cohort_lineage", from_.cohort_source_lineage))
if target in required]
produced = ["fitted_model", "metrics", *(v.name for v in plain.list_available_variables() if v.name == ROUTINES)]
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=produced,
produced = {v.name for v in plain.list_available_variables() if not v.is_external_input}
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=sorted(SAVED & produced),
combine=base.DictResult(), run=run, description=scenario.description,
hyperparameters={**expected_params(scenario, source), **scenario.config},
requirements=list(scenario.requirements))
+273
View File
@@ -0,0 +1,273 @@
"""TEA's EEG analysis against the database: which EEGs to analyse, the batch, and its results written to bronze.
An EEG is pending when it has an EDF and was never analysed, or was analysed with another plan or other module
versions, or, being valid, against baselines other than those now in production. One that failed with the current
plan and versions waits for a new one instead of failing again on every run.
Each result replaces the EEG's previous checks, metrics, electrode and zone values in `eeg`, `eeg_criterio`,
`eeg_metrica`, `eeg_metrica_electrodo` and `eeg_metrica_zona`. Row ids derive from the EEG and what each row is, so a row keeps its id
from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with
its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
`cluster` is the `tea` library's: "sync" runs in this process, "local" on a LocalCluster, "auto" on the scheduler in
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
"""
import uuid
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from itertools import batched
from sqlalchemy import case
from sqlmodel import Session, col, delete, select
from core.tea.enums import MetricaEeg
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, EegMetricaZona, Pacientes
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
from models.tea.eeg.baselines import Baselines
from models.tea.eeg.settings import Settings, scenario_of, settings as model_settings
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
def checked_settings() -> Settings:
"""The analysis's settings, checked against the metric catalog the tables use."""
s = model_settings()
codes = sorted(m.code for m in s.metrics)
if codes != sorted(c.value for c in MetricaEeg):
raise ValueError(f"model.toml must map every MetricaEeg code once, not {codes}")
return s
def selected_ids(session: Session, ids: Sequence[int | str]) -> list[str]:
"""Resolve requested IDs and return the ones with stored EDFs."""
requested = {str(eeg_id) for eeg_id in ids}
has_edf = case((Eeg.eeg_estudio.is_not(None), 1), else_=0)
found = {}
for group in batched(requested, 500):
query = select(Eeg.eeg_id, has_edf).where(col(Eeg.eeg_id).in_(group))
found.update(session.exec(query).all())
missing = sorted(requested - found.keys())
if missing:
raise LookupError(f"No se encontraron los EEG: {', '.join(missing)}")
return sorted(eeg_id for eeg_id, stored in found.items() if stored)
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None) -> list[str]:
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
if ids is not None:
return selected_ids(session, ids)
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
out, expected = [], None
for eeg_id, valid, stored_hash, stored_versions, error in session.exec(query):
if everything or stored_hash != plan_hash or stored_versions != versions:
out.append(eeg_id)
elif valid == 1 and error is None:
stored = dict(session.exec(select(EegMetrica.met_codigo, EegMetrica.met_modelo)
.where(EegMetrica.met_eeg_id == eeg_id)).all())
expected = models() if expected is None else expected
if any(stored.get(code) != label for code, label in expected.items()):
out.append(eeg_id)
if limit is not None and len(out) >= limit:
break
return out
def age_months(born, studied, days_per_month: float) -> float | None:
if born is None or studied is None or studied < born:
return None
return round((studied - born).days / days_per_month, 1)
def inputs(session: Session, eeg_id: str, days_per_month: float) -> tuple[bytes, float | None]:
eeg = session.get(Eeg, eeg_id)
if eeg is None or eeg.eeg_estudio is None:
raise LookupError(f"no EDF for EEG {eeg_id!r}")
born = session.exec(select(Pacientes.pac_fecha_nacimiento).where(Pacientes.pac_id == eeg.eeg_pac_id)).first()
return bytes(eeg.eeg_estudio), age_months(born, eeg.eeg_fecha_estudio, days_per_month)
def row_id(*parts: object) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, "tea:eeg/" + "/".join("" if p is None else str(p) for p in parts)))
@dataclass
class Rows:
eeg: dict
criteria: list[EegCriterio]
metrics: list[EegMetrica]
electrodes: list[EegMetricaElectrodo]
zones: list[EegMetricaZona]
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
eeg = {
"eeg_valido": m.valid, "eeg_nivel": m.level, "eeg_fraccion_limpia": m.clean_fraction,
"eeg_canales_malos": m.bad_channels, "eeg_ruido_linea_db": m.line_db, "eeg_con_sueno": m.asleep,
"eeg_edad_meses": m.age_months, "eeg_plan_hash": m.plan_hash, "eeg_versiones": m.versions,
"eeg_analizado_en": at or datetime.now(timezone.utc).replace(tzinfo=None), "eeg_error": m.error,
}
if m.channels is not None:
eeg["eeg_canales"] = m.channels
if m.duration_min is not None:
eeg["eeg_duracion_min"] = m.duration_min
seen: dict[tuple[str, str | None], int] = {}
criteria = []
for c in m.checks:
n = seen[c.code, c.electrode] = seen.get((c.code, c.electrode), 0) + 1
criteria.append(EegCriterio(
cri_id=row_id(m.key, "criterio", c.code, c.electrode, n), cri_eeg_id=m.key, cri_codigo=c.code,
cri_electrodo=c.electrode, cri_valor=c.value, cri_valor_texto=c.text, cri_unidad=c.unit,
cri_bajo=c.low, cri_alto=c.high, cri_decisivo=int(c.decisive), cri_anormal=int(c.abnormal),
))
by_code = {metric.code: metric for metric in s.metrics}
metrics, electrodes, zones = [], [], []
for value in m.metrics:
metric = by_code[value.code]
met_id = row_id(m.key, "metrica", value.code)
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months, value.exposure)
used = [metric.scenario] if deviation is not None else []
for electrode, raw in sorted(value.electrodes.items()):
at_electrode = None
if metric.electrode_scenario:
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
raw, m.age_months, value.exposure)
if at_electrode is not None and metric.electrode_scenario not in used:
used.append(metric.electrode_scenario)
electrodes.append(EegMetricaElectrodo(
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode,
mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
))
for zone, raw in sorted(value.zones.items()):
at_zone = None
if metric.zone_scenario:
at_zone = baselines.deviation(metric.zone_scenario, metric.zone_prefix + zone, raw, m.age_months,
value.exposure)
if at_zone is not None and metric.zone_scenario not in used:
used.append(metric.zone_scenario)
zones.append(EegMetricaZona(
mez_id=row_id(m.key, "metrica", value.code, "zona", zone), mez_met_id=met_id, mez_zona=zone,
mez_valor=raw, mez_z=at_zone.z if at_zone else None,
))
metrics.append(EegMetrica(
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value,
met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
met_p5=deviation.p5 if deviation else None, met_mediana=deviation.median if deviation else None,
met_p95=deviation.p95 if deviation else None,
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
))
return Rows(eeg, criteria, metrics, electrodes, zones)
def save(session: Session, eeg_id: str, new: Rows) -> None:
"""Replaces the EEG's analysis in the caller's session; the caller commits."""
eeg = session.get(Eeg, eeg_id)
if eeg is None:
raise LookupError(f"no EEG {eeg_id!r}")
for column, value in new.eeg.items():
setattr(eeg, column, value)
session.add(eeg)
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id)
session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
session.exec(delete(EegMetricaZona).where(col(EegMetricaZona.mez_met_id).in_(metric_ids)))
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
session.flush()
session.add_all([*new.criteria, *new.metrics, *new.electrodes, *new.zones])
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
if m.error:
quality = f"error: {m.error}"
elif m.valid:
quality = f"valido: {m.level}"
else:
quality = "no valido: " + "; ".join(c.code for c in m.checks if c.abnormal and c.decisive)
return ExtractionRun(
domain=s.domain, entity="eeg", entity_pk=m.key, column_extracted=COLUMNS,
source_description="eeg.eeg_estudio (EDF)", source_started_at=started, source_ended_at=ended,
transform_description=f"tea {s.impl}, plan {s.plan} {m.plan_hash}; {m.versions}",
quality_validation=quality,
estatus=(EstatusExtraccion.FALLIDA if m.error else EstatusExtraccion.COMPLETADA).value,
)
@dataclass
class Summary:
pending: int = 0
valid: int = 0
not_valid: int = 0
failed: int = 0
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
out = {}
for m in s.metrics:
scenarios = [scenario_of(n, m.phase) for n in m.readers]
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
return out
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def analyze_pending(*, everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None,
cluster: str = "auto", batch: int = 16,
settings: Settings | None = None, baselines: Baselines | None = None,
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
from tea.pipeline.dask_runner import run as run_batch
from tea.pipeline.run_monitor import monitor_from_env
from persistance.tea import eeg_repository
with monitor_from_env() as monitor:
s = settings or checked_settings()
b = baselines or Baselines(s.domain)
pipe = pipeline(s)
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
with eeg_repository.open_session() as session:
selected = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
everything=everything, limit=limit, ids=ids)
summary = Summary(pending=len(selected))
monitor.total(summary.pending)
monitor.phase("analizando")
def write(m: Measurement) -> None:
ended = _now()
with eeg_repository.open_session() as session:
save(session, m.key, rows(m, s, b, at=ended))
session.commit()
monitor.advance()
if log_runs:
from persistance.governance import extraction_run_repository
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
if m.error:
summary.failed += 1
elif m.valid:
summary.valid += 1
else:
summary.not_valid += 1
def lost(args, exc) -> Measurement:
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
error=f"{type(exc).__name__}: the batch lost this study")
for start in range(0, len(selected), batch):
argsets = []
with eeg_repository.open_session() as session:
for eeg_id in selected[start:start + batch]:
edf, age = inputs(session, eeg_id, s.days_per_month)
argsets.append((eeg_id, edf, age, s))
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost, track_progress=False)
return summary
+16 -11
View File
@@ -6,11 +6,13 @@ 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).
The frame is checked against `MODEL_COHORT` whatever its source: a build with no rows, or with a member, a date or
an event missing, stops the run before any node reads it.
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics"], ...)`: 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.
- `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`).
The saver pickles the packages of the model's own classes by value, so the registered version loads with
scikit-learn and the model's libraries, without this repository. The saver and the metrics being numbers are what keep members' rows out
@@ -28,13 +30,12 @@ from hamilton import registry as hamilton_registry
from hamilton.io.data_adapters import DataLoader, DataSaver
from models.io.registry import registered_name, registry
from models.io.storage import model_frame
from models.io.tracking import TrainingRun, pinned
@dataclasses.dataclass
class CohortSourceLoader(DataLoader):
"""A build's long frame, from whatever source reads it, if a model may read it (`storage.model_frame`)."""
"""A build's long frame, from whatever source reads it."""
source: Any
@@ -47,7 +48,7 @@ class CohortSourceLoader(DataLoader):
return "cohort_source"
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
frame = model_frame(self.source)
frame = self.source.frame()
return frame, {"source": type(self.source).__name__, "rows": len(frame)}
@@ -94,9 +95,9 @@ def _numbers(metrics: dict) -> dict[str, float]:
@dataclasses.dataclass
class RegisteredModelSaver(DataSaver):
"""Records each of `routines` (ML-01a) in `run`, logs `fitted_model` with `requirements` (pinned to the installed
versions), records `metrics` (numbers only) and `hyperparameters`, closes the run, registers the version and gives
it `description`."""
"""Records `routines`, when the dataflow has them, logs `fitted_model` in `run` with `requirements` (pinned to the
installed versions), records `metrics` (numbers only) and `hyperparameters`, closes the run, registers the version
and gives it `description`."""
run: TrainingRun
description: str = ""
@@ -115,6 +116,10 @@ class RegisteredModelSaver(DataSaver):
model, metrics = data["fitted_model"], _numbers(data["metrics"])
for kind, record in data.get("routines", {}).items():
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)

Some files were not shown because too many files have changed in this diff Show More