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
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
# 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\{-(t/\lambda)^k e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (Weibull, riesgos
|
||||
proporcionales).
|
||||
- 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.
|
||||
@@ -84,17 +84,44 @@ def numerical_hessian(f, x, step=1e-4):
|
||||
return hessian
|
||||
|
||||
|
||||
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):
|
||||
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
|
||||
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")
|
||||
# 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).
|
||||
log_scale = _starting_log_scale(c, l, r)
|
||||
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), log_scale, 0.0],
|
||||
np.r_[np.zeros(n_x), np.zeros(n_z), log_scale, 0.0]]
|
||||
results = [minimize(neg_loglik, s, args=(c, l, r, X, Z), method="BFGS") for s in starts]
|
||||
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
|
||||
theta, beta, log_scale, log_shape = split_params(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
|
||||
@@ -103,9 +130,10 @@ def fit(c, l, r, X, Z):
|
||||
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), 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
|
||||
@@ -116,10 +144,12 @@ def fit(c, l, r, X, Z):
|
||||
"log_shape": log_shape,
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
"""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`.
|
||||
`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
|
||||
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 numpy as np
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
@@ -59,31 +60,45 @@ def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
|
||||
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) -> 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
|
||||
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
|
||||
|
||||
|
||||
@@ -20,5 +20,6 @@ train_fraction = 0.7
|
||||
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"] }
|
||||
|
||||
+84
-28
@@ -1,9 +1,9 @@
|
||||
"""What this module covers: `models.cacu.cin2_pim`: how a member's index results and biopsies become a code and an
|
||||
interval, the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
|
||||
"""What this module covers: `models.cacu.cin2_pim`: how a member's screening visits and biopsies become a code and an
|
||||
interval (one test per worked example of `docs/codificacion_pim.md`), the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
|
||||
driver, with every member scored at every horizon, also outside this repository.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 300 simulated members (a quarter with an abnormal index sample, some with a
|
||||
prevalent or a later CIN2+ biopsy); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
|
||||
prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
|
||||
`predict_without_repository` (conftest).
|
||||
"""
|
||||
|
||||
@@ -35,16 +35,26 @@ def _row(pac_id, index, days, tipo, valor=None):
|
||||
"fuente_id": f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsies=()):
|
||||
rows = [_row(pac_id, index, 0, "citologia"), _row(pac_id, index, 7, "bethesda", bethesda),
|
||||
_row(pac_id, index, 7, "vph", vph)]
|
||||
def _visit(pac_id, index, day, bethesda, vph):
|
||||
return [_row(pac_id, index, day, "bethesda", bethesda), _row(pac_id, index, day, "vph", vph)]
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
|
||||
rows = [_row(pac_id, index, 0, "citologia"), *_visit(pac_id, index, 7, bethesda, vph)]
|
||||
rows += [row for day, b, v in visits for row in _visit(pac_id, index, day, b, v)]
|
||||
return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies]
|
||||
|
||||
|
||||
def _coded(rows):
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
return model.interval_coded_members(frame, CUTOFF, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
|
||||
CONFIG["index_sample_days"], CONFIG["known_negative"]).set_index("pac_id")
|
||||
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
|
||||
CONFIG["index_sample_days"], CONFIG["known_negative"])
|
||||
return tuple(coded.iloc[0][["c", "l", "r"]])
|
||||
|
||||
|
||||
INDEX = date(2025, 1, 1)
|
||||
ASCUS_HPV = ("ASC-US", "POSITIVO")
|
||||
COTEST_NEGATIVE = ("NORMAL", "NEGATIVO")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -59,9 +69,10 @@ def cohort_frame():
|
||||
grade = "LIEAG" if rng.random() < 0.35 else "NEGATIVO"
|
||||
rows += _member(pac_id, index, "LIEBG", "POSITIVO", [(45, grade)])
|
||||
elif rng.random() < 0.1:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")])
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")],
|
||||
[(365, *COTEST_NEGATIVE)])
|
||||
else:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
|
||||
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
|
||||
|
||||
@@ -74,31 +85,76 @@ def cohort_file(cohort_frame, tmp_path):
|
||||
return path
|
||||
|
||||
|
||||
def test_each_member_gets_its_code_and_interval():
|
||||
"""Pins down the coding: a CIN2+ biopsy in the window is prevalent; a known negative baseline with a later CIN2+
|
||||
biopsy is incident in `(0, t]`; a known negative without one is censored at its follow-up; an abnormal sample with
|
||||
no biopsy is unknown in `(0, inf)`; a negative biopsy in the window makes the baseline known. Fails if any case
|
||||
gets another code, which changes what the likelihood counts."""
|
||||
index = date(2025, 1, 1)
|
||||
coded = _coded(_member(1, index, "LIEAG", "POSITIVO", [(30, "LIEAG")])
|
||||
+ _member(2, index, "NORMAL", "NEGATIVO", [(730, "CIS")])
|
||||
+ _member(3, index, "NORMAL", "NEGATIVO")
|
||||
+ _member(4, index, "ASC-US", "POSITIVO")
|
||||
+ _member(5, index, "ASC-US", "POSITIVO", [(60, "NEGATIVO")]))
|
||||
def test_patient_1_a_cin2_biopsy_at_the_referral_colposcopy_is_prevalent():
|
||||
"""Patient 1: ASC-US/HPV+ at T0, colposcopy a month later finds CIN3. Pins down `(1, 0, 0)`: she counts as a case
|
||||
in the prevalence and adds nothing to the incidence. Fails if a CIN2+ within the window stops being prevalent."""
|
||||
assert _coded(_member(1, INDEX, *ASCUS_HPV, [(30, "LIEAG")])) == (1, 0.0, 0.0)
|
||||
|
||||
assert coded["c"].tolist() == [1, 0, 0, -999, 0]
|
||||
assert coded.loc[2, "r"] == pytest.approx(730 / 365.25) and coded.loc[2, "l"] == 0.0
|
||||
assert coded.loc[3, "l"] == pytest.approx((CUTOFF - index).days / 365.25) and np.isinf(coded.loc[3, "r"])
|
||||
assert (coded.loc[4, "l"], coded.loc[4, "r"]) == (0.0, np.inf)
|
||||
|
||||
def test_patient_2_the_interval_opens_at_the_last_negative_not_at_the_index():
|
||||
"""Patient 2: ASC-US/HPV+ at T0, negative biopsies at T1 (a month), negative cotest at T2 (a year), ASC-US/HPV+ at
|
||||
T3 (two years), CIN3 at T4. Pins down `(0, T2, T4]`: the negative colposcopy makes her a control in the prevalence,
|
||||
T2 is the last time she was free, and T3's abnormal result isn't a negative. Fails if `l` goes back to 0 or an
|
||||
abnormal visit is taken for a negative."""
|
||||
c, l, r = _coded(_member(2, INDEX, *ASCUS_HPV, [(30, "NEGATIVO"), (760, "LIEAG")],
|
||||
[(365, *COTEST_NEGATIVE), (730, *ASCUS_HPV)]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), pytest.approx(760 / 365.25))
|
||||
|
||||
|
||||
def test_patient_3_a_case_never_found_free_has_an_unknown_baseline():
|
||||
"""Patient 3: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US/HPV+ again at T1, CIN3 at T2. Pins down
|
||||
`(-999, 0, T2]`: she may have been prevalent or incident, the likelihood weighs both, and onset is anywhere up to
|
||||
T2 (not exactly at T2). Fails if a repeated abnormal result is taken for a known baseline."""
|
||||
c, l, r = _coded(_member(3, INDEX, *ASCUS_HPV, [(395, "LIEAG")], [(365, *ASCUS_HPV)]))
|
||||
|
||||
assert (c, l, r) == (-999, 0.0, pytest.approx(395 / 365.25))
|
||||
|
||||
|
||||
def test_patient_4_a_later_negative_cotest_settles_an_unknown_baseline():
|
||||
"""Patient 4: ASC-US/HPV+ at T0, colposcopy skipped, negative cotest at T1 (a year). Pins down `(0, T1, inf)`: CIN2+
|
||||
being absorbing, free at T1 means free at T0, so she's a control in the prevalence and right-censored at T1. Fails
|
||||
if she's left unknown, which throws her away, or censored at the cut-off."""
|
||||
c, l, r = _coded(_member(4, INDEX, *ASCUS_HPV, visits=[(365, *COTEST_NEGATIVE)]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
||||
|
||||
|
||||
def test_an_hpv_negative_ascus_is_a_negative_visit():
|
||||
"""KPNC's second negative without histology: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US with HPV negative at T1
|
||||
(a year). Pins down `(0, T1, inf)`, as for patient 4's negative cotest. Fails if `known_negative` goes back to NILM
|
||||
only, which leaves her unknown."""
|
||||
c, l, r = _coded(_member(7, INDEX, *ASCUS_HPV, visits=[(365, "ASC-US", "NEGATIVO")]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
||||
|
||||
|
||||
def test_an_hpv_positive_nilm_is_not_a_negative_visit():
|
||||
"""The other side of the criterion: ASC-US/HPV+ at T0, colposcopy skipped, NILM with HPV positive at T1. Pins down
|
||||
`(-999, 0, inf)`: a positive test without histology leaves the status unknown. Fails if a NILM alone counts."""
|
||||
assert _coded(_member(8, INDEX, *ASCUS_HPV, visits=[(365, "NORMAL", "POSITIVO")])) == (-999, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_patient_5_a_negative_colposcopy_without_follow_up_counts_only_for_the_prevalence():
|
||||
"""Patient 5: ASC-US/HPV+ at T0, negative biopsies a month later, no further visit. Pins down `(0, 0, inf)`: a
|
||||
control in the prevalence whose factor holds no survival (S(0) = 1). Fails if she's credited follow-up up to the
|
||||
cut-off that no test checked."""
|
||||
assert _coded(_member(5, INDEX, *ASCUS_HPV, [(30, "NEGATIVO")])) == (0, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_patient_6_referred_and_lost_carries_no_information():
|
||||
"""Patient 6: ASC-US/HPV+ at T0, colposcopy skipped, never seen again. Pins down `(-999, 0, inf)`, whose factor
|
||||
is 1. Fails if she's given a code that adds a term."""
|
||||
assert _coded(_member(6, INDEX, *ASCUS_HPV)) == (-999, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"""Pins down the driver's external inputs: the loaders' `cohort` and `cohort_lineage` and the config's keys, and
|
||||
"""Pins down the driver's external inputs: the loader's `cohort` and the config's keys, and
|
||||
nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
|
||||
or a module added to the driver rewires a parameter."""
|
||||
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "index_sample_days",
|
||||
assert required == {"cohort", "event_grades", "horizons_years", "index_sample_days",
|
||||
"known_negative", "prevalent_window_months", "train_fraction"}
|
||||
assert optional == set()
|
||||
|
||||
@@ -108,7 +164,7 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the
|
||||
fit stops recovering the prevalence."""
|
||||
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
||||
["metrics"], inputs={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["metrics"]
|
||||
["metrics"], inputs={"cohort": cohort_frame})["metrics"]
|
||||
|
||||
assert found["n_train"] == 210 and found["n_test"] == 90
|
||||
assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found)
|
||||
|
||||
@@ -55,3 +55,28 @@ def test_cumulative_risk_starts_at_prevalence():
|
||||
cr = L.cumulative_risk(fitted, X, Z, years=[0, 1, 5])
|
||||
np.testing.assert_allclose(cr[:, 0], L.prevalence(fitted["theta"], X))
|
||||
assert np.all(np.diff(cr, axis=1) >= 0)
|
||||
|
||||
|
||||
def test_fit_finds_a_rare_incidence():
|
||||
"""A rare outcome, like CIN3+ with HPV negative: the Weibull scale is thousands of years and only ~1 % has an
|
||||
incident case in 7 yearly visits. Pins down that the fit reaches the optimum near the truth and not the far worse
|
||||
one where a start at the median detection time used to leave it. Fails if the starting scale goes back to the
|
||||
detection times."""
|
||||
rng = np.random.default_rng(3)
|
||||
n = 20000
|
||||
group = rng.integers(0, 2, n)
|
||||
X = np.column_stack([np.ones(n), group])
|
||||
Z = group[:, None].astype(float)
|
||||
theta, beta, scale, shape = np.array([-5.0, 1.0]), np.array([1.4]), 2500.0, 1.08
|
||||
prevalent = rng.random(n) < L.prevalence(theta, X)
|
||||
time = scale * (rng.exponential(size=n) / np.exp(Z @ beta)) ** (1 / shape)
|
||||
c = np.where(prevalent, 1, 0)
|
||||
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 7.0))
|
||||
r = np.where(prevalent, 0.0, np.where(time < 7, np.floor(time) + 1, np.inf))
|
||||
|
||||
fitted = L.fit(c, l, r, X, Z)
|
||||
truth = L.neg_loglik(np.r_[theta, beta, np.log(scale), np.log(shape)], c, l, r, X, Z)
|
||||
|
||||
assert fitted["converged"] and fitted["neg_loglik"] <= truth + 1e-6
|
||||
np.testing.assert_allclose(fitted["beta"], beta, atol=0.4)
|
||||
assert np.all(np.isfinite(fitted["se"]))
|
||||
|
||||
Reference in New Issue
Block a user