Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67ee8eb526 | |||
| 29586515cc | |||
| 2bc2ab9e97 | |||
| 5624e1f361 | |||
| c12ea569cf | |||
| 3908ddf74d |
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "tea"]
|
||||
path = libs/tea
|
||||
url = ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
url = ../../alberto/tea.git
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
# CaCu scenario instances, follow-up, and model interfaces
|
||||
|
||||
This proposal gives `seguimiento` and all six CaCu model scenarios a shared unit of work. A **scenario instance** represents one patient, one model scenario, and one candidate procedure. The follow-up list reads the instance and its eligibility. A separate episode endpoint returns the clinical studies. Hamilton uses the same procedure references to assemble the features and outcomes required by each model.
|
||||
|
||||
The current WebApi `GET /cacu/seguimiento` delegates to `webapi.follow_up.listing.seguimiento_de`, which builds one item per patient and slices the list for pagination. The new list changes the unit of pagination to the scenario instance. The names and IDs in the examples are illustrative. See [Experiment and measurements](#experiment-and-measurements) for the implemented slice.
|
||||
|
||||
## Scenario instance schema
|
||||
|
||||
Proposed table name `cacu_instancia_escenario`. Reuse `persona`, `procedimiento`, and `observacion_clinica` in Persistance. The existing `procedimiento` table distinguishes `orden`, `encuentro`, `toma`, `reporte`, and `parte`, and can link a child procedure through `padre_id`. `observacion_clinica.procedimiento_id` identifies the procedure or report that owns each result.
|
||||
|
||||
| Column | Type | Meaning |
|
||||
|---|---|---|
|
||||
| `instancia_id` | Stable ID, primary key | Identifies the instance across refreshes. The API can expose an opaque ID. |
|
||||
| `pac_id` | Integer, FK to `persona.pac_id` | Patient the instance belongs to. |
|
||||
| `escenario` | Scenario code | For example, `cin2_pim`, `cin2_pim_post_colposcopy`, or `cin2_pim_post_treatment`. |
|
||||
| `candidato_procedimiento_id` | Integer, FK to `procedimiento.procedimiento_id` | The procedure under consideration. This can be a cytology `toma` or the qualifying biopsy `reporte` for survival. |
|
||||
| `ancla_procedimiento_id` | Nullable integer, FK to `procedimiento.procedimiento_id` | The earlier colposcopy or treatment that starts the visit sequence. Surveillance can leave it empty. |
|
||||
| `episodio_id` | Nullable episode reference | Groups related studies. Resolve through `episodioclinico.episodio_id` where the source episode actually matches the care period being shown. |
|
||||
| `fecha_indice` | Date | Time zero for the scenario. For a sample-indexed model, this is the collection date. |
|
||||
| `resultados_disponibles_en` | Nullable timestamp | Earliest cutoff at which all results required by this scenario were available. |
|
||||
| `elegibilidad` | `elegible`, `pendiente`, or `excluida` | Decision for this candidate at the published cutoff. |
|
||||
| `version_reglas` | Immutable version or hash | Identifies the visit, inclusion, and exclusion rules used to derive the row. |
|
||||
|
||||
The business key is `(pac_id, escenario, candidato_procedimiento_id)`. Both procedure references must belong to `pac_id`. Each scenario in this proposal resolves at most one anchor for a candidate. If a future scenario permits multiple valid anchors for the same candidate, extend its identity before publishing those rows. A second observation or an earlier visit used as a covariate remains a reference in the timeline, while the instance still has one candidate.
|
||||
|
||||
The CaCu baseline migration already defines `episodioclinico`. Confirm that an existing episode represents the grouping needed by this endpoint before publishing it as a care episode. Where an episode is unresolved, return an empty episode reference and omit the studies link. The episode period, the index date, and the cutoff are separate values.
|
||||
|
||||
## Eligibility and shared inputs
|
||||
|
||||
dbt enumerates candidates and emits **one result per applicable rule and instance**. Store or publish the rule code, its result (`cumple`, `incumple`, `pendiente`), and an evidence procedure or observation ID when one exists. The instance carries the overall decision. The list can expose the relevant reason codes without returning the underlying clinical values.
|
||||
|
||||
| Scenario | Candidate and anchor | Example inclusion and exclusion checks |
|
||||
|---|---|---|
|
||||
| Surveillance | Cytology sample with an empty anchor | Required results belong to the same sample. A prior-event rule checks for qualifying history relative to the sample date. |
|
||||
| Post-colposcopy | Follow-up cytology and its colposcopy | Check the anchor workup and whether the follow-up cotest is complete. Apply the scenario's prior cancer, hysterectomy, and treatment rules as of the candidate date. |
|
||||
| Post-treatment | Follow-up cytology and its treatment | Require the treatment relationship and the results specified for the follow-up visit. Evaluate any historical exclusion declared for this scenario. |
|
||||
|
||||
For example, a configured `histerectomia_previa` rule is an `EXISTS` check for qualifying evidence for the same patient with a clinical date before the candidate's index and a known date at or before the evaluation cutoff. `vph_disponible` checks the HPV result linked to the selected sample. Model and clinical owners approve the exact rules, date bounds, and visit policy for each scenario. The table above describes how to express them. [Current Python index rules](../models/steps/indexing.py)
|
||||
|
||||
## CaCu scenarios and their inputs
|
||||
|
||||
Use the same instance schema for all CaCu models. The scenario configuration determines the candidate, index policy, required features, outcome, and training target. This table records the current model definitions as the starting point for migration. Any change to cohort membership, index timing, or scoreability should be reviewed as a separate model change.
|
||||
|
||||
| Current scenario | Candidate procedure and index | Features and training target |
|
||||
|---|---|---|
|
||||
| `cin2_logistic` | Surveillance cytology sample. Current index policy uses the first cytology. The configured outcome horizon is one year. | Bethesda, HPV, and HPV 16/18. Binary CIN2+ outcome for the configured window, with ascertainment handled by the scenario. [Configuration](../models/cacu/cin2_logistic/model.toml) |
|
||||
| `cin2_pim` | Surveillance cytology sample. Current training uses the first cytology. Current scoring selects the latest complete sample when the patient has neither a recorded colposcopy nor a biopsy in the scoring frame. | Cytology category and HPV status. CIN2+ coded intervals `(c, l, r)`. [Configuration](../models/cacu/cin2_pim/model.toml) |
|
||||
| `cancer_pim` | Surveillance cytology sample with the same current first-versus-latest index policy as `cin2_pim`. It has its own instance even when both models use the same sample. | Cytology category and HPV status. Coded intervals for carcinoma as the endpoint. [Configuration](../models/cacu/cancer_pim/model.toml) |
|
||||
| `cin2_pim_post_colposcopy` | Follow-up cytology sample after the colposcopy workup, with that colposcopy as the anchor. The configured visit is `1`. | Index cytology and HPV, plus referral grade from the pre-colposcopy lookback. CIN2+ coded intervals. [Configuration](../models/cacu/cin2_pim_post_colposcopy/model.toml) |
|
||||
| `cin2_pim_post_treatment` | First cytology after treatment, with the treatment as the anchor. The current build supplies the index. | Index cytology and HPV. CIN2+ coded intervals. [Configuration](../models/cacu/cin2_pim_post_treatment/model.toml) |
|
||||
| `survival` | First biopsy report with a qualifying carcinoma grade (`CIS` or `CARCINOMA`). The report supplies the index date. | Age group and the latest cytology and HPV through diagnosis. Time to all-cause death or censoring. The estimator returns mortality and the current presentation can show its survival complement. [Configuration](../models/cacu/survival/model.toml) |
|
||||
|
||||
## Model interface
|
||||
|
||||
Hamilton gets a batch of instance rows keyed by `instancia_id`, plus a reference to the source publication. It loads candidate and anchor procedures by ID and retrieves the linked observations and permitted history in batches. For sample-indexed scoring, it reads cytology and HPV from the exact sample in the instance. A nearby result from another sample does not replace a result for that candidate. When a rule uses a historical covariate, such as referral grade, the scenario declares the anchor and lookback for that feature.
|
||||
|
||||
### Input and output contracts
|
||||
|
||||
| Dataset | Key | Contents |
|
||||
|---|---|---|
|
||||
| `instances` | `instancia_id` | Patient, scenario, candidate and anchor procedure IDs, date of index, episode reference, result availability, eligibility, and rule version. The batch carries `publicacion_id` and its clinical and data-availability cutoffs. |
|
||||
| `features` | `instancia_id` | One row of prepared covariates per scorable instance and a versioned feature schema. The model signature declares the predictor columns and their types. |
|
||||
| `targets` | `instancia_id` | Training only. PIM uses `(c, l, r)`, logistic uses its ascertainable binary target, and survival uses its time-to-event and censoring input. |
|
||||
| `risks` | `(scoring_run_id, instancia_id, horizonte_anios)` | Scenario and index date, outcome, probability, and interval bounds when the model gives them. The scoring run pins the concrete model version and source publication. |
|
||||
| `scoring_decisions` | `(scoring_run_id, instancia_id)` | Scored, pending, excluded, or unable to score, with a reason such as missing required results or an unsupported feature level. |
|
||||
|
||||
The estimator receives its predictor columns. Hamilton retains `instancia_id` as the join key for results and reads the model's registered horizons and outcome. A score for November and a score for August can therefore coexist for one patient in the same scenario. If a registry alias selects a production model, resolve it once at the start of the run and record the concrete version.
|
||||
|
||||
For example, post-treatment instance `ins-82fc` in the follow-up response below produces a `pendiente` scoring decision while HPV is missing. Once a later publication includes that result, Hamilton can prepare the cytology and HPV predictors from `pr-526`. If the selected model version supports that visit, it gives one risk row per configured horizon, all keyed by `ins-82fc` and the new scoring run. The model receives the feature values through its signature. The procedure references stay with the instance and its evidence.
|
||||
|
||||
### Training and scoring paths
|
||||
|
||||
```text
|
||||
Training: publication + training visit policy
|
||||
→ selected instances → linked evidence → features + targets
|
||||
→ split → fit → held-out metrics → registered model version
|
||||
|
||||
Scoring: publication + requested visit or validated scoring visit policy
|
||||
→ selected instances → linked evidence → features
|
||||
→ registered model → risks and scoring decisions
|
||||
```
|
||||
|
||||
Select the training index before coding outcomes. Join features and targets by `instancia_id`. Keep the existing temporal split for the first migration and ensure that repeated instances of a patient cannot cross from training to holdout if a model later includes multiple visits. Score a single patient by passing a batch of one instance through the same preparation and prediction steps. A visit number or new index policy requires a model validated for that use.
|
||||
|
||||
Enforce time bounds in feature preparation. Historical features use events from their specified window and evidence available by the feature cutoff. Results linked to the candidate sample can arrive after collection when the scenario allows it. Follow-up used to construct or evaluate the outcome is read separately from feature evidence. For retrospective scoring, use the source version available at the requested scoring cutoff.
|
||||
|
||||
The current `CohortSource` and registered MLflow pipelines accept the long cohort frame. The current estimate contract identifies output by patient and horizon within each estimate. Add an instance-based source and versioned scoring contract alongside that interface. Keep existing registered versions callable with the input shape they were registered with. A compatibility adapter can use an old model only where it can verify that the model uses the intended candidate. Existing risk batches that store patient and horizon need a new instance-aware representation before multiple visits can be published in one batch. [Current cohort source](../models/io/storage.py) · [Current training graph](../models/dags/training.py) · [Current scoring path](../models/dags/estimation.py)
|
||||
|
||||
### Rollout and verification
|
||||
|
||||
1. Publish the dbt instance and rule projections from `procedimiento` and `observacion_clinica`. Compare selected patients, index dates, and attrition with the existing paths for all six scenarios. Record differences that come from changing the index policy.
|
||||
2. Add Hamilton batch loaders and a shared sample lookup keyed by procedure ID. Verify the same features and scores in a single-instance run and a batch. Use a fixture with two samples in the same time window and keep each sample's results together.
|
||||
3. Enable the instance-based follow-up list and episode detail on a retained publication. Check pagination and measure both derivation and publication times. Verify repeat publication is idempotent and a late result only updates affected instances.
|
||||
4. Register the first model versions with explicit feature and visit policies. Compare old and new estimates for matching instances and capture score coverage by scenario before exposing instance-level risks.
|
||||
|
||||
## Endpoint 1 · Follow-up list
|
||||
|
||||
```http
|
||||
GET /cacu/seguimiento/instancias?corte=2026-10-20&escenario=cin2_pim_post_treatment&page=1&page_size=50
|
||||
```
|
||||
|
||||
Expose the new granularity through a separate route so current one-item-per-patient consumers can migrate deliberately. An item can include an index date and a compact status for a visit still awaiting results. Filters can include scenario, eligibility, and patient reference where authorized. The response carries a stable `publicacion_id`. Pass it on later pages to retain the same cutoff and data version, with rows ordered by index date and instance ID. `total_items` counts instances.
|
||||
|
||||
```json
|
||||
{
|
||||
"corte": "2026-10-20",
|
||||
"publicacion_id": "seg-20261020-01",
|
||||
"paginacion": {"page": 1, "page_size": 50, "total_items": 1},
|
||||
"items": [
|
||||
{
|
||||
"instancia_id": "ins-82fc",
|
||||
"paciente_ref": "P-EXAMPLE",
|
||||
"escenario": "cin2_pim_post_treatment",
|
||||
"candidato_procedimiento_ref": "pr-526",
|
||||
"ancla_procedimiento_ref": "pr-301",
|
||||
"episodio_ref": "eoc-07",
|
||||
"fecha_indice": "2026-10-15",
|
||||
"resultados_disponibles_en": null,
|
||||
"elegibilidad": "pendiente",
|
||||
"motivos": ["vph_pendiente"],
|
||||
"version_reglas": "cacu-pim-v1",
|
||||
"estudios_url": "/cacu/episodios/eoc-07/estudios?publicacion_id=seg-20261020-01"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Publish a slim projection for this route and apply filters and pagination in the database. Batch changes for patients affected by new procedures, results, corrections, or rule changes. Upsert changed instance rows by the business key. Readers should see a consistent publication across a refresh. Historical reads require retained revisions or a reproducible source snapshot. Measure derivation time and publication time separately to see which part of the current upload benefits.
|
||||
|
||||
## Endpoint 2 · Clinical studies and results for the episode
|
||||
|
||||
```http
|
||||
GET /cacu/episodios/{episodio_ref}/estudios?publicacion_id=seg-20261020-01
|
||||
```
|
||||
|
||||
Resolve the episode and patient, then return the study records linked to that episode and available at the publication cutoff. A patient may have more than one episode. When the source lacks explicit episode membership, publish the links derived from the episode rules as `(episodio_id, procedimiento_id)` pairs in dbt. Use the existing silver join rules for study details. `cacu_citologias` connects the sample and separate reports through their source keys. `cacu_biopsias` follows `padre_id` from the report through the biopsy order to the source sample. For each study return its reference, status, dates, and actual coded or typed results. Preserve multiple findings and represent pending results explicitly. The client can fetch this detail when someone opens an episode.
|
||||
|
||||
```json
|
||||
{
|
||||
"episodio_ref": "eoc-07",
|
||||
"paciente_ref": "P-EXAMPLE",
|
||||
"publicacion_id": "seg-20261020-01",
|
||||
"estudios": [
|
||||
{"tipo": "referencia_colposcopia", "orden_ref": "ord-179", "fecha": "2025-05-02", "estado": "atendida", "motivo": "citologia_anormal"},
|
||||
{"tipo": "colposcopia", "procedimiento_ref": "pr-204", "orden_ref": "ord-179", "fecha": "2025-05-10", "estado": "realizada"},
|
||||
{"tipo": "biopsia", "procedimiento_ref": "pr-240", "fecha_reporte": "2025-09-25", "estado": "informada", "resultados": [{"codigo": "biopsia.grado", "valor": "LIEAG"}]},
|
||||
{"tipo": "tratamiento", "procedimiento_ref": "pr-301", "fecha": "2025-10-01", "estado": "realizado", "codigo": "LEEP"},
|
||||
{"tipo": "citologia", "toma_ref": "pr-526", "reporte_ref": "pr-527", "fecha_toma": "2026-10-15", "fecha_reporte": "2026-10-19", "estado": "informada", "resultados": [{"codigo": "citologia.bethesda", "valor": "NORMAL"}]},
|
||||
{"tipo": "vph", "toma_ref": "pr-526", "estado": "pendiente", "resultados": []}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Only publish a referral when there is a source order or referral record. Record the performed colposcopy separately and link it to the referral when that relationship is known. Cytology and HPV can share a sample reference while retaining separate report dates and result values. Check access to the patient and episode on the detail request as well as the list request.
|
||||
|
||||
## How this fits a FHIR API
|
||||
|
||||
Use the CaCu routes as application JSON. A FHIR R5 facade can publish the linked clinical records as FHIR resources under `/fhir`. The scenario instance stays in the application schema because it expresses eligibility for a particular model. The list can include FHIR references for the patient, episode, and study records that have been mapped. [FHIR R5 EpisodeOfCare](https://hl7.org/fhir/R5/episodeofcare.html)
|
||||
|
||||
| CaCu record | FHIR R5 representation |
|
||||
|---|---|
|
||||
| Care episode | `EpisodeOfCare` for the period of responsibility. Link an actual `Encounter` to the episode through `Encounter.episodeOfCare`. [Episode reference](https://hl7.org/fhir/R5/encounter-definitions.html#Encounter.episodeOfCare) |
|
||||
| Cytology or HPV | `Specimen` for the collected sample when represented in the source, `DiagnosticReport` for the report, and `Observation` for each coded or quantitative result. Share the specimen reference when it is the same sample. [Specimen](https://hl7.org/fhir/R5/specimen.html) · [DiagnosticReport](https://hl7.org/fhir/R5/diagnosticreport.html) · [Observation](https://hl7.org/fhir/R5/observation.html) |
|
||||
| Colposcopy referral | `ServiceRequest`. A performed colposcopy can be a `Procedure` linked back through `Procedure.basedOn`. [ServiceRequest](https://hl7.org/fhir/R5/servicerequest.html) · [Procedure](https://hl7.org/fhir/R5/procedure.html) |
|
||||
| Biopsy | `Procedure` for a documented biopsy collection and `DiagnosticReport` with result `Observation` records for the histology. An order can be a separate `ServiceRequest`. [Procedure](https://hl7.org/fhir/R5/procedure.html) · [DiagnosticReport](https://hl7.org/fhir/R5/diagnosticreport.html) |
|
||||
| Treatment | `Procedure` for a documented intervention such as LEEP. [Procedure](https://hl7.org/fhir/R5/procedure.html) |
|
||||
| Computed risk | `RiskAssessment` when a score exists. Use `basis` for the evidence and `prediction` for the outcome, probability, and time horizon. [RiskAssessment](https://hl7.org/fhir/R5/riskassessment.html) |
|
||||
|
||||
For a single FHIR response containing all studies, a server could declare an instance operation such as `GET /fhir/EpisodeOfCare/{id}/$estudios` in its `OperationDefinition` and `CapabilityStatement` and return a `Bundle` of type `collection`. This would be a CaCu operation. Its published definition should specify the cutoff parameter, included resource types, and authorization behavior. The application JSON endpoint above is sufficient for the initial follow-up UI. [FHIR operations](https://hl7.org/fhir/R5/operations.html) · [FHIR Bundle](https://hl7.org/fhir/R5/bundle.html)
|
||||
|
||||
## Experiment and measurements
|
||||
|
||||
The first implementation adds [PIM instance nodes](../models/cacu/instance_pim.py) and a [SQLite publication reader](../models/cacu/instance_publication.py). The PIM experiment fits the existing mixture with explicit outcome intervals joined by instance ID. It reuses the fitted mixture for inference and writes probabilities by instance and horizon. A regression test scores two visits for the same patient independently, checks single-versus-batch parity, and checks the effect of a result posted after the cutoff. Unscored instances still have a decision. The feature input expects the owning sample ID for each result, while referral history can be supplied as a feature keyed by instance.
|
||||
|
||||
The WebApi branch `feature/cacu-seguimiento-instances` adds the two application JSON routes when `CACU_SIMULATED_INSTANCE_PUBLICATION` points to a prepared SQLite publication. The publisher stores immutable snapshots in one transaction. SQL applies filters and pagination before the response is built. The episode route resolves the linked studies from the same snapshot. The existing `/cacu/seguimiento` route also filters the cytology date window in SQL before pulling study rows into Python, while retaining its original response.
|
||||
|
||||
This experiment uses synthetic instance rows and preassembled episode studies. The live dbt eligibility producer, migration of registered models and risk storage, and incremental refresh of live data remain design work. The FHIR section specifies a possible mapping. The current WebApi validates its FHIR routes against R4B, so the project would need to choose and test that version's profiles for an implementation.
|
||||
|
||||
### Measured request times
|
||||
|
||||
Both comparisons used local SQLite and Flask's HTTP test client. Response equality was checked before timing. The two rows below have different workloads and baselines.
|
||||
|
||||
| Request and workload | Requests per path | Baseline median / p95 | Prototype median / p95 |
|
||||
|---|---:|---:|---:|
|
||||
| Existing `/cacu/seguimiento` with 25,000 extra cytology samples outside its requested window. Compared to WebApi `4840bd3`. | 15 | 203.69 ms / 379.72 ms | 97.02 ms / 141.29 ms |
|
||||
| New `/cacu/seguimiento/instancias`, one filtered 50-row page from 120,000 instances. Compared to reading the same full publication and filtering and paging it in Python. | 20 | 934.36 ms / 1,091.52 ms | 3.20 ms / 5.11 ms |
|
||||
|
||||
The existing endpoint's median fell by about 52% on this fixture. The new endpoint handled the filtered page in about 3 ms after a 4.71-second full local publication. These measurements describe request latency and synthetic publication cost. Production latency, live publication throughput, and clinical model performance still need separate measurements.
|
||||
|
||||
### Reproduce the prototype
|
||||
|
||||
In the Models checkout, generate a synthetic publication.
|
||||
|
||||
```bash
|
||||
python -m models.cacu.experiments.instance_follow_up /tmp/cacu-follow-up.sqlite --patients 1000
|
||||
```
|
||||
|
||||
Run the WebApi branch with the Models branch importable and `CACU_SIMULATED_INSTANCE_PUBLICATION=/tmp/cacu-follow-up.sqlite`. A request to `/cacu/seguimiento/instancias?escenario=cin2_pim` returns a page. The sample episode is available at `/cacu/episodios/eoc-demo-1/estudios?publicacion_id=demo-v1`.
|
||||
|
||||
See `docs/cacu-follow-up-benchmarks.md` on the matching WebApi branch for the measurement method and endpoint regression checks.
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Build a reproducible, entirely synthetic publication for the CaCu prototype."""
|
||||
|
||||
import argparse
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
from models.cacu.instance_publication import EpisodeStudies, FollowUpInstance, publish
|
||||
|
||||
CUTOFF = date(2026, 10, 20)
|
||||
SCENARIOS = (
|
||||
"cin2_pim", "cancer_pim", "cin2_logistic",
|
||||
"cin2_pim_post_colposcopy", "cin2_pim_post_treatment", "survival",
|
||||
)
|
||||
|
||||
|
||||
def demo_instances(patients: int) -> Iterator[FollowUpInstance]:
|
||||
for patient in range(1, patients + 1):
|
||||
anchors = {"cin2_pim_post_colposcopy": patient * 100 + 97, "cin2_pim_post_treatment": patient * 100 + 98}
|
||||
for visit, scenario in enumerate(SCENARIOS):
|
||||
index = CUTOFF - timedelta(days=10 + (patient % 180) + (len(SCENARIOS) - visit) * 7)
|
||||
pending = patient % 10 == 0 and scenario == "cin2_pim"
|
||||
yield FollowUpInstance(
|
||||
instancia_id=f"ins-{patient:06}-{visit}",
|
||||
paciente_ref=f"P-DEMO-{patient:06}",
|
||||
escenario=scenario,
|
||||
candidato_procedimiento_id=patient * 100 + visit,
|
||||
ancla_procedimiento_id=anchors.get(scenario),
|
||||
episodio_ref="eoc-demo-1" if patient == 1 else None,
|
||||
fecha_indice=index,
|
||||
resultados_disponibles_en=None if pending else f"{index + timedelta(days=5)}T12:00:00Z",
|
||||
elegibilidad="pendiente" if pending else "elegible",
|
||||
motivos=("vph_pendiente",) if pending else (),
|
||||
version_reglas="synthetic-v1",
|
||||
)
|
||||
|
||||
|
||||
def demo_episodes() -> list[EpisodeStudies]:
|
||||
studies = [
|
||||
{"tipo": kind, "toma_ref": f"pr-{visit.candidato_procedimiento_id}", "fecha_toma": visit.fecha_indice.isoformat(),
|
||||
"resultados": [{"codigo": code, "valor": value}]}
|
||||
for visit in demo_instances(1) if visit.escenario != "survival"
|
||||
for kind, code, value in (("citologia", "bethesda", "NORMAL"), ("vph", "vph", "NEGATIVO"))
|
||||
]
|
||||
studies.extend([
|
||||
{"tipo": "referencia_colposcopia", "orden_ref": "ord-1", "estado": "atendida"},
|
||||
{"tipo": "colposcopia", "procedimiento_ref": "pr-197", "orden_ref": "ord-1", "estado": "realizada"},
|
||||
{"tipo": "biopsia", "procedimiento_ref": "pr-105", "resultados": [{"codigo": "grado", "valor": "CIS"}]},
|
||||
{"tipo": "tratamiento", "procedimiento_ref": "pr-198", "estado": "realizado"},
|
||||
])
|
||||
return [EpisodeStudies("eoc-demo-1", "P-DEMO-000001", studies)]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("--patients", type=int, default=1000)
|
||||
parser.add_argument("--publication-id", default="demo-v1")
|
||||
args = parser.parse_args()
|
||||
if args.patients < 1:
|
||||
parser.error("--patients must be positive")
|
||||
publish(args.output, args.publication_id, CUTOFF, demo_instances(args.patients), demo_episodes())
|
||||
print(f"Published {args.patients * len(SCENARIOS)} synthetic instances in {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""PIM nodes for a batch of CaCu scenario instances with resolved sample references."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture, _features, _most_severe
|
||||
|
||||
RESULT_TYPES = ["bethesda", "glandular", "vph"]
|
||||
INSTANCE_ID = "instancia_id"
|
||||
SAMPLE_KEY = ["pac_id", "candidato_procedimiento_id"]
|
||||
|
||||
|
||||
def pim_instance_features(
|
||||
instances: pd.DataFrame,
|
||||
sample_results: pd.DataFrame,
|
||||
feature_cutoff: datetime,
|
||||
cytology: dict,
|
||||
history: dict,
|
||||
instance_history: pd.DataFrame | None = None,
|
||||
) -> pd.DataFrame:
|
||||
"""Build features by instance. Results carry the owning sample's ID, even when stored on a report."""
|
||||
if not instances[INSTANCE_ID].is_unique or instances[INSTANCE_ID].isna().any():
|
||||
raise ValueError("instance IDs must be unique and present")
|
||||
if instances["escenario"].nunique() > 1:
|
||||
raise ValueError("a model batch must use one scenario")
|
||||
cutoff = pd.Timestamp(feature_cutoff)
|
||||
if cutoff.tzinfo is None:
|
||||
raise ValueError("the feature cutoff must have a time zone")
|
||||
|
||||
eligible = instances.loc[instances["elegibilidad"].eq("elegible"), [INSTANCE_ID, *SAMPLE_KEY]]
|
||||
visible = sample_results.loc[
|
||||
sample_results["tipo"].isin(RESULT_TYPES)
|
||||
& sample_results["valor_codigo"].notna()
|
||||
& pd.to_datetime(sample_results["conocida_en"], utc=True).le(cutoff)
|
||||
]
|
||||
results = eligible.merge(visible, on=SAMPLE_KEY, how="inner")
|
||||
# A corrected result supersedes the previous known value. Ties with conflicting codes have no safe ordering.
|
||||
results["conocida_en"] = pd.to_datetime(results["conocida_en"], utc=True)
|
||||
result_keys = [INSTANCE_ID, "tipo"]
|
||||
latest = results.groupby(result_keys)["conocida_en"].transform("max")
|
||||
results = results.loc[results["conocida_en"].eq(latest), [*result_keys, "valor_codigo"]].drop_duplicates()
|
||||
if results.duplicated(result_keys).any():
|
||||
raise ValueError("conflicting results for the same candidate, type, and known time")
|
||||
wide = results.pivot(index=INSTANCE_ID, columns="tipo", values="valor_codigo").reindex(columns=RESULT_TYPES)
|
||||
category = _most_severe(wide[["bethesda", "glandular"]].stack(), cytology).reindex(wide.index)
|
||||
usable = category.notna() & wide["vph"].isin(["POSITIVO", "NEGATIVO"])
|
||||
features = pd.DataFrame({
|
||||
"cytology": category[usable],
|
||||
"hpv_positive": wide.loc[usable, "vph"].eq("POSITIVO").astype(float),
|
||||
})
|
||||
if history:
|
||||
if instance_history is None:
|
||||
raise ValueError("the scenario requires instance history features")
|
||||
name = history["feature"]
|
||||
values = instance_history.set_index(INSTANCE_ID)[name]
|
||||
if not values.index.is_unique:
|
||||
raise ValueError("history features must have unique instance IDs")
|
||||
features[name] = values.reindex(features.index)
|
||||
features = features.dropna(subset=[name])
|
||||
return features[_features(history)]
|
||||
|
||||
|
||||
def fit_instance_mixture(
|
||||
estimator: PrevalenceIncidenceMixture,
|
||||
training_features: pd.DataFrame,
|
||||
interval_targets: pd.DataFrame,
|
||||
) -> PrevalenceIncidenceMixture:
|
||||
"""Fit selected training instances against their own outcome intervals."""
|
||||
targets = interval_targets.set_index(INSTANCE_ID)
|
||||
if (not targets.index.is_unique or not training_features.index.is_unique
|
||||
or not training_features.index.isin(targets.index).all()):
|
||||
raise ValueError("each training instance must have exactly one coded interval")
|
||||
return estimator.fit(training_features, targets.loc[training_features.index, ["c", "l", "r"]])
|
||||
|
||||
|
||||
def pim_instance_risks(
|
||||
instances: pd.DataFrame,
|
||||
pim_instance_features: pd.DataFrame,
|
||||
fitted_mixture: PrevalenceIncidenceMixture,
|
||||
) -> pd.DataFrame:
|
||||
"""Score the prepared instances in order and return one row per instance and horizon."""
|
||||
features = pim_instance_features
|
||||
horizons = np.asarray(fitted_mixture.horizons_years, dtype=float)
|
||||
keys = [INSTANCE_ID, "pac_id", "escenario", "fecha_indice"]
|
||||
columns = [*keys, "horizonte_anios", "probabilidad"]
|
||||
if fitted_mixture.interval_level:
|
||||
columns.extend(["ic_bajo", "ic_alto"])
|
||||
if features.empty:
|
||||
return pd.DataFrame(columns=columns)
|
||||
members = instances.set_index(INSTANCE_ID)
|
||||
if not members.index.is_unique or not features.index.is_unique:
|
||||
raise ValueError("instance IDs must be unique for scoring")
|
||||
members = members.loc[features.index].reset_index()[keys]
|
||||
matrix = fitted_mixture.predict_proba(features)
|
||||
width = len(horizons) * (3 if fitted_mixture.interval_level else 1)
|
||||
if matrix.shape != (len(features), width):
|
||||
raise ValueError("PIM returned an unexpected prediction shape for its configured horizons")
|
||||
scored = np.isfinite(matrix[:, :len(horizons)]).all(axis=1)
|
||||
rows = members.loc[members.index[scored].repeat(len(horizons))].reset_index(drop=True)
|
||||
rows["horizonte_anios"] = np.tile(horizons, scored.sum())
|
||||
rows["probabilidad"] = matrix[scored, :len(horizons)].ravel()
|
||||
if fitted_mixture.interval_level:
|
||||
rows["ic_bajo"] = matrix[scored, len(horizons):2 * len(horizons)].ravel()
|
||||
rows["ic_alto"] = matrix[scored, 2 * len(horizons):].ravel()
|
||||
return rows
|
||||
|
||||
|
||||
def pim_scoring_decisions(
|
||||
instances: pd.DataFrame,
|
||||
pim_instance_features: pd.DataFrame,
|
||||
pim_instance_risks: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""Keep one decision per requested instance, including instances with no prediction."""
|
||||
found = instances[[INSTANCE_ID, "elegibilidad"]].copy()
|
||||
eligible = found["elegibilidad"].eq("elegible")
|
||||
found["decision"] = found.pop("elegibilidad")
|
||||
found.loc[eligible, "decision"] = "sin_variables"
|
||||
found.loc[found[INSTANCE_ID].isin(pim_instance_features.index), "decision"] = "sin_riesgo"
|
||||
found.loc[found[INSTANCE_ID].isin(pim_instance_risks[INSTANCE_ID]), "decision"] = "estimada"
|
||||
return found
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Read model for the simulated CaCu follow-up experiment.
|
||||
|
||||
A publisher supplies as-of instances and episode studies. Request-time reads never rebuild clinical eligibility.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from collections.abc import Iterable
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
ELIGIBILITIES = ("elegible", "pendiente", "excluida")
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS publication (
|
||||
publicacion_id TEXT PRIMARY KEY,
|
||||
corte TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS publication_by_cutoff ON publication (corte DESC);
|
||||
CREATE TABLE IF NOT EXISTS episode (
|
||||
publicacion_id TEXT NOT NULL REFERENCES publication,
|
||||
episodio_ref TEXT NOT NULL,
|
||||
paciente_ref TEXT NOT NULL,
|
||||
estudios TEXT NOT NULL,
|
||||
PRIMARY KEY (publicacion_id, episodio_ref),
|
||||
UNIQUE (publicacion_id, episodio_ref, paciente_ref)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS instance (
|
||||
publicacion_id TEXT NOT NULL REFERENCES publication,
|
||||
instancia_id TEXT NOT NULL,
|
||||
paciente_ref TEXT NOT NULL,
|
||||
escenario TEXT NOT NULL,
|
||||
candidato_procedimiento_id INTEGER NOT NULL,
|
||||
ancla_procedimiento_id INTEGER,
|
||||
episodio_ref TEXT,
|
||||
fecha_indice TEXT NOT NULL,
|
||||
resultados_disponibles_en TEXT,
|
||||
elegibilidad TEXT NOT NULL CHECK (elegibilidad IN ('elegible', 'pendiente', 'excluida')),
|
||||
motivos TEXT NOT NULL,
|
||||
version_reglas TEXT NOT NULL,
|
||||
PRIMARY KEY (publicacion_id, instancia_id),
|
||||
UNIQUE (publicacion_id, paciente_ref, escenario, candidato_procedimiento_id),
|
||||
FOREIGN KEY (publicacion_id, episodio_ref, paciente_ref)
|
||||
REFERENCES episode (publicacion_id, episodio_ref, paciente_ref)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS instance_by_date
|
||||
ON instance (publicacion_id, fecha_indice DESC, instancia_id);
|
||||
CREATE INDEX IF NOT EXISTS instance_by_scenario
|
||||
ON instance (publicacion_id, escenario, fecha_indice DESC, instancia_id);
|
||||
CREATE INDEX IF NOT EXISTS instance_by_eligibility
|
||||
ON instance (publicacion_id, elegibilidad, fecha_indice DESC, instancia_id);
|
||||
CREATE INDEX IF NOT EXISTS instance_by_scenario_eligibility
|
||||
ON instance (publicacion_id, escenario, elegibilidad, fecha_indice DESC, instancia_id);
|
||||
"""
|
||||
|
||||
|
||||
class PublicationNotFound(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class EpisodeStudies:
|
||||
episodio_ref: str
|
||||
paciente_ref: str
|
||||
estudios: list[dict]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FollowUpInstance:
|
||||
instancia_id: str
|
||||
paciente_ref: str
|
||||
escenario: str
|
||||
candidato_procedimiento_id: int
|
||||
fecha_indice: date
|
||||
elegibilidad: str
|
||||
version_reglas: str
|
||||
ancla_procedimiento_id: int | None = None
|
||||
episodio_ref: str | None = None
|
||||
resultados_disponibles_en: str | None = None
|
||||
motivos: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def publish(
|
||||
path: Path,
|
||||
publicacion_id: str,
|
||||
corte: date,
|
||||
instances: Iterable[FollowUpInstance],
|
||||
episodes: Iterable[EpisodeStudies] = (),
|
||||
) -> None:
|
||||
"""Publish one immutable simulated snapshot in a single transaction."""
|
||||
with closing(sqlite3.connect(path)) as connection:
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.executescript(_SCHEMA)
|
||||
with connection:
|
||||
connection.execute("INSERT INTO publication VALUES (?, ?)", (publicacion_id, corte.isoformat()))
|
||||
connection.executemany(
|
||||
"INSERT INTO episode VALUES (?, ?, ?, ?)",
|
||||
((publicacion_id, e.episodio_ref, e.paciente_ref, json.dumps(e.estudios)) for e in episodes),
|
||||
)
|
||||
connection.executemany(
|
||||
"INSERT INTO instance VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
(publicacion_id, i.instancia_id, i.paciente_ref, i.escenario, i.candidato_procedimiento_id,
|
||||
i.ancla_procedimiento_id, i.episodio_ref, i.fecha_indice.isoformat(), i.resultados_disponibles_en,
|
||||
i.elegibilidad, json.dumps(i.motivos), i.version_reglas)
|
||||
for i in instances
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _published(
|
||||
connection: sqlite3.Connection, publicacion_id: str | None, corte: date | None
|
||||
) -> sqlite3.Row:
|
||||
if publicacion_id is not None:
|
||||
found = connection.execute(
|
||||
"SELECT * FROM publication WHERE publicacion_id = ?", (publicacion_id,)
|
||||
).fetchone()
|
||||
if found is not None and corte is not None and found["corte"] != corte.isoformat():
|
||||
raise ValueError("el corte no corresponde a la publicación")
|
||||
elif corte is not None:
|
||||
found = connection.execute(
|
||||
"SELECT * FROM publication WHERE corte = ? ORDER BY rowid DESC LIMIT 1", (corte.isoformat(),)
|
||||
).fetchone()
|
||||
else:
|
||||
found = connection.execute("SELECT * FROM publication ORDER BY corte DESC, rowid DESC LIMIT 1").fetchone()
|
||||
if found is None:
|
||||
raise PublicationNotFound("publicación de seguimiento no encontrada")
|
||||
return found
|
||||
|
||||
|
||||
def _read(path: Path) -> sqlite3.Connection:
|
||||
if not path.is_file():
|
||||
raise PublicationNotFound("publicación de seguimiento no encontrada")
|
||||
connection = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
|
||||
connection.row_factory = sqlite3.Row
|
||||
return connection
|
||||
|
||||
|
||||
def follow_up_page(
|
||||
path: Path,
|
||||
*,
|
||||
publicacion_id: str | None = None,
|
||||
corte: date | None = None,
|
||||
escenario: str | None = None,
|
||||
elegibilidad: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict:
|
||||
"""Apply filters and pagination before decoding rows for the response."""
|
||||
if page < 1 or not 1 <= page_size <= 200:
|
||||
raise ValueError("page empieza en 1 y page_size va de 1 a 200")
|
||||
if elegibilidad is not None and elegibilidad not in ELIGIBILITIES:
|
||||
raise ValueError("elegibilidad desconocida")
|
||||
with closing(_read(path)) as connection:
|
||||
publication = _published(connection, publicacion_id, corte)
|
||||
conditions = ["publicacion_id = ?"]
|
||||
params = [publication["publicacion_id"]]
|
||||
for field, value in (("escenario", escenario), ("elegibilidad", elegibilidad)):
|
||||
if value is not None:
|
||||
conditions.append(f"{field} = ?")
|
||||
params.append(value)
|
||||
where = " AND ".join(conditions)
|
||||
total, = connection.execute(f"SELECT count(*) FROM instance WHERE {where}", params).fetchone()
|
||||
offset = (page - 1) * page_size
|
||||
if offset and offset >= total:
|
||||
raise PublicationNotFound("página de seguimiento no encontrada")
|
||||
rows = connection.execute(
|
||||
f"""SELECT * FROM instance WHERE {where}
|
||||
ORDER BY fecha_indice DESC, instancia_id LIMIT ? OFFSET ?""",
|
||||
[*params, page_size, offset],
|
||||
).fetchall()
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
item.pop("publicacion_id")
|
||||
item["candidato_procedimiento_ref"] = f"pr-{item.pop('candidato_procedimiento_id')}"
|
||||
anchor = item.pop("ancla_procedimiento_id")
|
||||
item["ancla_procedimiento_ref"] = None if anchor is None else f"pr-{anchor}"
|
||||
item["motivos"] = json.loads(item["motivos"])
|
||||
items.append(item)
|
||||
return {
|
||||
"simulado": True,
|
||||
**dict(publication),
|
||||
"paginacion": {
|
||||
"page": page, "page_size": page_size, "total_items": total,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
def episode_studies(path: Path, episodio_ref: str, publicacion_id: str) -> dict:
|
||||
"""Retrieve one episode's preassembled studies at the same publication as the follow-up page."""
|
||||
with closing(_read(path)) as connection:
|
||||
publication = _published(connection, publicacion_id, None)
|
||||
found = connection.execute(
|
||||
"""SELECT episodio_ref, paciente_ref, estudios FROM episode
|
||||
WHERE publicacion_id = ? AND episodio_ref = ?""",
|
||||
(publicacion_id, episodio_ref),
|
||||
).fetchone()
|
||||
if found is None:
|
||||
raise PublicationNotFound("episodio no encontrado en la publicación")
|
||||
return {"simulado": True, **dict(publication), **dict(found), "estudios": json.loads(found["estudios"])}
|
||||
@@ -0,0 +1,47 @@
|
||||
import sqlite3
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from models.cacu.instance_publication import EpisodeStudies, FollowUpInstance, PublicationNotFound
|
||||
from models.cacu.instance_publication import episode_studies, follow_up_page, publish
|
||||
|
||||
CUTOFF = date(2026, 10, 20)
|
||||
|
||||
|
||||
def test_page_filters_and_episode_reads_remain_on_the_same_publication(tmp_path):
|
||||
path = tmp_path / "follow_up.sqlite"
|
||||
pending = FollowUpInstance(
|
||||
"ins-2", "P-DEMO", "cin2_pim_post_treatment", 526, date(2026, 10, 15),
|
||||
"pendiente", "rules-v1", 301, "eoc-07", motivos=("vph_pendiente",),
|
||||
)
|
||||
eligible = replace(
|
||||
pending, instancia_id="ins-1", candidato_procedimiento_id=410, elegibilidad="elegible",
|
||||
resultados_disponibles_en="2026-04-19T00:00:00Z", motivos=(),
|
||||
)
|
||||
old_episode = EpisodeStudies("eoc-07", "P-DEMO", [{"tipo": "vph", "estado": "pendiente"}])
|
||||
publish(path, "first", CUTOFF, [pending, eligible], [old_episode])
|
||||
first_page = follow_up_page(path, page_size=1)
|
||||
|
||||
assert first_page["paginacion"]["total_items"] == 2
|
||||
assert first_page["items"][0]["candidato_procedimiento_ref"] == "pr-410" # ties sort by instance
|
||||
item = follow_up_page(path, escenario="cin2_pim_post_treatment", elegibilidad="pendiente")["items"][0]
|
||||
assert item["motivos"] == ["vph_pendiente"] and "pac_id" not in item
|
||||
|
||||
now_eligible = replace(pending, elegibilidad="elegible", resultados_disponibles_en="2026-10-20T00:00:00Z")
|
||||
new_episode = replace(old_episode, estudios=[{"tipo": "vph", "estado": "informada"}])
|
||||
publish(path, "second", CUTOFF, [now_eligible, eligible], [new_episode])
|
||||
assert follow_up_page(path, corte=CUTOFF)["publicacion_id"] == "second"
|
||||
assert follow_up_page(path, publicacion_id="first", page=2, page_size=1)["items"][0] == item
|
||||
assert episode_studies(path, item["episodio_ref"], "first")["estudios"] == old_episode.estudios
|
||||
assert episode_studies(path, item["episodio_ref"], "second")["estudios"] == new_episode.estudios
|
||||
|
||||
|
||||
def test_failed_publication_does_not_leave_a_visible_snapshot(tmp_path):
|
||||
path = tmp_path / "follow_up.sqlite"
|
||||
instance = FollowUpInstance("ins-1", "P-DEMO", "cin2_pim", 12, CUTOFF, "elegible", "v1", episodio_ref="eoc-1")
|
||||
with pytest.raises(sqlite3.IntegrityError): # Episode exists but belongs to another patient.
|
||||
publish(path, "broken", CUTOFF, [instance], [EpisodeStudies("eoc-1", "P-OTHER", [])])
|
||||
with pytest.raises(PublicationNotFound):
|
||||
follow_up_page(path, publicacion_id="broken")
|
||||
@@ -0,0 +1,72 @@
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from models.cacu import instance_pim
|
||||
from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture
|
||||
|
||||
CUTOFF = datetime(2026, 4, 30, tzinfo=timezone.utc)
|
||||
CYTOLOGY = {"NILM": ["NORMAL"], "LSIL": ["LIEBG"]}
|
||||
|
||||
|
||||
def test_hamilton_scores_two_visits_of_one_patient_and_keeps_pending_instances():
|
||||
instances = pd.DataFrame(
|
||||
[
|
||||
("second", 42, "cin2_pim", 11, date(2026, 4, 11), "elegible"),
|
||||
("first", 42, "cin2_pim", 10, date(2026, 4, 10), "elegible"),
|
||||
("pending", 42, "cin2_pim", 12, date(2026, 4, 12), "pendiente"),
|
||||
("unavailable", 42, "cin2_pim", 13, date(2026, 4, 13), "elegible"),
|
||||
],
|
||||
columns=["instancia_id", "pac_id", "escenario", "candidato_procedimiento_id", "fecha_indice", "elegibilidad"],
|
||||
)
|
||||
results = pd.DataFrame(
|
||||
[
|
||||
(42, 10, "bethesda", "NORMAL", "2026-04-14"),
|
||||
(42, 10, "vph", "NEGATIVO", "2026-04-15"),
|
||||
(42, 11, "bethesda", "LIEBG", "2026-04-13"),
|
||||
(42, 11, "vph", "POSITIVO", "2026-04-14"),
|
||||
(42, 11, "bethesda", "NORMAL", "2026-05-01"),
|
||||
(42, 12, "bethesda", "NORMAL", "2026-04-14"),
|
||||
(42, 13, "bethesda", "NORMAL", "2026-04-15"),
|
||||
(42, 13, "vph", "POSITIVO", "2026-05-01"),
|
||||
(99, 13, "vph", "POSITIVO", "2026-04-14"),
|
||||
],
|
||||
columns=["pac_id", "candidato_procedimiento_id", "tipo", "valor_codigo", "conocida_en"],
|
||||
)
|
||||
training = pd.DataFrame(
|
||||
[("NILM", 0.0)] * 10 + [("LSIL", 1.0)] * 10,
|
||||
columns=["cytology", "hpv_positive"],
|
||||
index=pd.Index(range(20), name="instancia_id"),
|
||||
)
|
||||
targets = pd.DataFrame(
|
||||
[(i, 1, 0.0, 0.0) if i in {1, 10, 11, 12, 13} else (i, 0, 0.5, np.inf) for i in range(20)],
|
||||
columns=["instancia_id", "c", "l", "r"],
|
||||
).iloc[::-1]
|
||||
fitted = instance_pim.fit_instance_mixture(
|
||||
PrevalenceIncidenceMixture(
|
||||
[0.0, 1.0], incidence_features=(), strata=("hpv_positive",),
|
||||
levels={"cytology": list(CYTOLOGY)},
|
||||
),
|
||||
training, targets,
|
||||
)
|
||||
graph = driver.Builder().with_modules(instance_pim).with_config({"cytology": CYTOLOGY, "history": {}}).build()
|
||||
inputs = {"instances": instances, "sample_results": results, "feature_cutoff": CUTOFF, "fitted_mixture": fitted}
|
||||
output = graph.execute(["pim_instance_features", "pim_instance_risks", "pim_scoring_decisions"], inputs=inputs)
|
||||
|
||||
features = output["pim_instance_features"]
|
||||
assert features.to_dict("index") == {
|
||||
"first": {"cytology": "NILM", "hpv_positive": 0.0},
|
||||
"second": {"cytology": "LSIL", "hpv_positive": 1.0},
|
||||
}
|
||||
assert output["pim_scoring_decisions"].set_index("instancia_id")["decision"].to_dict() == {
|
||||
"first": "estimada", "second": "estimada", "pending": "pendiente", "unavailable": "sin_variables",
|
||||
}
|
||||
risks = output["pim_instance_risks"].pivot(index="instancia_id", columns="horizonte_anios", values="probabilidad")
|
||||
assert risks.shape == (2, 2) and risks.loc["second", 0] > risks.loc["first", 0]
|
||||
single = graph.execute(["pim_instance_risks"], inputs={**inputs, "instances": instances.iloc[[0]]})
|
||||
np.testing.assert_allclose(single["pim_instance_risks"]["probabilidad"], risks.loc["second"])
|
||||
with pytest.raises(ValueError, match="exactly one coded interval"):
|
||||
instance_pim.fit_instance_mixture(fitted, training, targets[targets["instancia_id"] != 10])
|
||||
Reference in New Issue
Block a user