Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67ee8eb526 | |||
| 29586515cc | |||
| 2bc2ab9e97 | |||
| 5624e1f361 | |||
| c12ea569cf | |||
| 3908ddf74d | |||
| 2a04ee8c8e |
+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.
|
||||
+1
-1
Submodule libs/tea updated: fcf8e6ef03...ed31baf70f
+16
-1
@@ -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:
|
||||
@@ -164,10 +166,22 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
|
||||
|
||||
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
|
||||
|
||||
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
|
||||
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
|
||||
|
||||
|
||||
@@ -542,6 +556,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
"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)
|
||||
|
||||
@@ -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"])}
|
||||
+60
-36
@@ -13,10 +13,12 @@ its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrup
|
||||
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
||||
"""
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping
|
||||
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
|
||||
@@ -38,10 +40,26 @@ def checked_settings() -> Settings:
|
||||
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) -> list[str]:
|
||||
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
|
||||
@@ -203,47 +221,53 @@ def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
|
||||
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
|
||||
|
||||
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:
|
||||
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||
everything=everything, limit=limit)
|
||||
summary = Summary(pending=len(ids))
|
||||
|
||||
def write(m: Measurement) -> None:
|
||||
ended = _now()
|
||||
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:
|
||||
save(session, m.key, rows(m, s, b, at=ended))
|
||||
session.commit()
|
||||
if log_runs:
|
||||
from persistance.governance import extraction_run_repository
|
||||
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")
|
||||
|
||||
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 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
|
||||
|
||||
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")
|
||||
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
|
||||
|
||||
for start in range(0, len(ids), batch):
|
||||
argsets = []
|
||||
with eeg_repository.open_session() as session:
|
||||
for eeg_id in ids[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)
|
||||
return summary
|
||||
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
|
||||
|
||||
@@ -6,11 +6,19 @@ then promoting each through the registry's checks. `--reference-dir` trains on a
|
||||
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
SETTINGS = settings()
|
||||
CLUSTERS = ("auto", "local", "remote", "sync")
|
||||
|
||||
|
||||
def _cluster() -> str:
|
||||
"""Where training measures the studies: `EEG_ANALYSIS_CLUSTER` when it names a runner, else `auto`."""
|
||||
chosen = os.environ.get("EEG_ANALYSIS_CLUSTER", "auto")
|
||||
return chosen if chosen in CLUSTERS else "auto"
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
@@ -32,7 +40,7 @@ def run_steps(args: argparse.Namespace) -> int:
|
||||
return 2
|
||||
versions: dict[str, str] = {}
|
||||
if args.train:
|
||||
for scenario, (version, new) in train.train_all(s, environment).items():
|
||||
for scenario, (version, new) in train.train_all(s, environment, cluster=_cluster()).items():
|
||||
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
||||
versions[scenario] = version
|
||||
if not args.promote:
|
||||
|
||||
+24
-14
@@ -19,6 +19,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
from tea.pipeline.run_monitor import active_monitor, monitor_from_env
|
||||
|
||||
from models.io.lineage import (
|
||||
COHORT_BUILD_TAG,
|
||||
@@ -78,7 +79,7 @@ def list_reference(s: Settings) -> list[tuple[str, float]]:
|
||||
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster, track_progress=False)
|
||||
return Listing.of(s.reference.name, found)
|
||||
|
||||
|
||||
@@ -146,9 +147,14 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
data = table(studies, biomarker, phase)
|
||||
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
||||
monitor = active_monitor()
|
||||
if monitor is not None:
|
||||
monitor.phase("ajustando")
|
||||
module.train(data)
|
||||
sha, state = _module_state(module)
|
||||
name = registered_name(DOMAIN, scenario)
|
||||
if monitor is not None:
|
||||
monitor.phase("registrando")
|
||||
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
||||
experiment_id(MlflowClient(), name)
|
||||
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
||||
@@ -210,19 +216,23 @@ def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Li
|
||||
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
||||
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
||||
scenario needs it."""
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
studies = studies if studies is not None else measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
with monitor_from_env() as monitor:
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
if studies is None:
|
||||
monitor.total(len(found.studies))
|
||||
monitor.phase("midiendo")
|
||||
studies = measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
|
||||
|
||||
def latest(scenario: str, environment: str):
|
||||
|
||||
@@ -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])
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Cover cluster probes using clean_environment, loopback_port and monkeypatch.
|
||||
|
||||
Fails if mode resolution, connection handling or independent probe results regress.
|
||||
"""
|
||||
|
||||
import socket
|
||||
from contextlib import nullcontext
|
||||
from time import perf_counter
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import distributed
|
||||
import pytest
|
||||
|
||||
from tea.pipeline import cluster_status
|
||||
from tea.pipeline.cluster_status import ClusterStatus
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_environment(monkeypatch):
|
||||
"""Clear cluster configuration so machine settings cannot change probe targets or results."""
|
||||
for variable in (
|
||||
"DASK_SCHEDULER_ADDRESS",
|
||||
"TEA_DASK_EXPECTED_WORKERS",
|
||||
"TEA_DASK_DASHBOARD_URL",
|
||||
"TEA_DASK_DASHBOARD_PORT",
|
||||
):
|
||||
monkeypatch.delenv(variable, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def loopback_port():
|
||||
"""Reserve a loopback port so live probes cannot connect to another service."""
|
||||
try:
|
||||
port = socket.socket()
|
||||
except PermissionError as exc:
|
||||
pytest.skip(f"TCP sockets are unavailable: {exc}")
|
||||
with port:
|
||||
try:
|
||||
port.bind(("127.0.0.1", 0))
|
||||
except PermissionError as exc:
|
||||
pytest.skip(f"Loopback binding is unavailable: {exc}")
|
||||
yield port.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["auto", "local", "sync"])
|
||||
def test_non_remote_mode_does_not_connect(monkeypatch, mode):
|
||||
"""Pin the full non-remote response. Fail if a client starts or a probe reports a value."""
|
||||
client = Mock()
|
||||
monkeypatch.setattr(distributed, "Client", client)
|
||||
if mode != "auto":
|
||||
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
|
||||
|
||||
assert ClusterStatus().check(mode) == {
|
||||
"mode": "local" if mode == "auto" else mode,
|
||||
"scheduler": None,
|
||||
"reachable": True,
|
||||
"workers": None,
|
||||
"expected_workers": None,
|
||||
"versions_ok": None,
|
||||
"version_error": None,
|
||||
"dashboard_ok": None,
|
||||
"dashboard_url": None,
|
||||
"reference": None,
|
||||
"latency_ms": None,
|
||||
"error": None,
|
||||
}
|
||||
client.assert_not_called()
|
||||
|
||||
|
||||
def test_unreachable_scheduler_is_bounded(monkeypatch, loopback_port):
|
||||
"""Pin failure on a closed TCP port. Fail if it raises or ignores the connection timeout."""
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_PORT", str(loopback_port))
|
||||
start = perf_counter()
|
||||
status = ClusterStatus().check(scheduler=f"tcp://127.0.0.1:{loopback_port}")
|
||||
|
||||
assert perf_counter() - start < 9
|
||||
assert status["mode"] == "remote"
|
||||
assert status["reachable"] is False
|
||||
assert status["error"]
|
||||
assert status["workers"] is None
|
||||
assert status["versions_ok"] is None
|
||||
assert status["dashboard_ok"] is False
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("loopback_port")
|
||||
def test_reachable_scheduler_reports_one_worker(monkeypatch):
|
||||
"""Pin health on a real Dask worker. Fail if the client miscounts it or skips version checks."""
|
||||
with distributed.LocalCluster(
|
||||
n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0"
|
||||
) as cluster:
|
||||
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", cluster.scheduler_address)
|
||||
monkeypatch.setenv("TEA_DASK_EXPECTED_WORKERS", "2")
|
||||
port = cluster.scheduler.services["dashboard"].port
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", f"http://127.0.0.1:{port}/status")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
|
||||
status = ClusterStatus().check()
|
||||
|
||||
assert status["scheduler"] == cluster.scheduler_address
|
||||
assert status["reachable"] is True
|
||||
assert status["workers"] == 1
|
||||
assert status["expected_workers"] == 2
|
||||
assert status["versions_ok"] is True
|
||||
assert status["dashboard_ok"] is True
|
||||
assert status["latency_ms"] >= 0
|
||||
assert status["error"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dashboard_healthy", [True, False])
|
||||
def test_version_mismatch_and_dashboard_are_independent(monkeypatch, dashboard_healthy):
|
||||
"""Pin zero-worker and mismatch responses. Fail if either prevents an independent dashboard probe."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {}}
|
||||
client.get_versions.side_effect = ValueError("version mismatch")
|
||||
connect = Mock(return_value=client)
|
||||
monkeypatch.setattr(distributed, "Client", connect)
|
||||
if dashboard_healthy:
|
||||
dashboard_url = "https://dashboard.example/status?view=all"
|
||||
health_url = "https://dashboard.example/health"
|
||||
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", dashboard_url)
|
||||
open_health = Mock(return_value=nullcontext(SimpleNamespace(status=200)))
|
||||
else:
|
||||
dashboard_url = "http://scheduler:8787/status"
|
||||
health_url = "http://scheduler:8787/health"
|
||||
open_health = Mock(side_effect=TimeoutError)
|
||||
monkeypatch.setattr(cluster_status, "urlopen", open_health)
|
||||
|
||||
status = ClusterStatus().check("remote", "tcp://scheduler:8786", "cohort")
|
||||
|
||||
assert status["reachable"] is True
|
||||
assert status["error"] is None
|
||||
assert status["workers"] == 0
|
||||
assert status["versions_ok"] is False
|
||||
assert status["version_error"] == "version mismatch"
|
||||
assert status["dashboard_ok"] is dashboard_healthy
|
||||
assert status["dashboard_url"] == dashboard_url
|
||||
assert status["reference"] is None
|
||||
connect.assert_called_once_with("tcp://scheduler:8786", timeout=5)
|
||||
client.get_versions.assert_called_once_with(check=True)
|
||||
client.submit.assert_not_called()
|
||||
client.close.assert_called_once_with()
|
||||
open_health.assert_called_once_with(health_url, timeout=3)
|
||||
|
||||
|
||||
def test_warning_only_version_mismatch_is_reported(monkeypatch):
|
||||
"""Pin mismatches returned by Dask without an exception. Fail if they count as compatible."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||
matching = {"packages": {"distributed": "2026.8.0"}}
|
||||
client.get_versions.return_value = {
|
||||
"scheduler": matching,
|
||||
"client": matching,
|
||||
"workers": {"worker": {"packages": {"distributed": "2026.9.0"}}},
|
||||
}
|
||||
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||
|
||||
status = ClusterStatus().check(scheduler="tcp://scheduler:8786")
|
||||
|
||||
assert status["versions_ok"] is False
|
||||
assert "Mismatched versions found" in status["version_error"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["cohort-1", "../escape", ".."])
|
||||
def test_reference_submission_requires_safe_name(monkeypatch, name):
|
||||
"""Pin worker-side reference lookup. Fail if an unsafe name is submitted or a valid count is lost."""
|
||||
client = Mock()
|
||||
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||
client.submit.return_value.result.return_value = 3
|
||||
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||
|
||||
status = ClusterStatus().check(scheduler="tcp://scheduler:8786", reference_name=name)
|
||||
|
||||
if name == "cohort-1":
|
||||
client.submit.assert_called_once_with(cluster_status._count_edfs, name, pure=False)
|
||||
assert status["reference"] == {"name": name, "edfs": 3}
|
||||
else:
|
||||
client.submit.assert_not_called()
|
||||
assert status["reference"] is None
|
||||
|
||||
|
||||
def test_local_workers_can_be_capped_by_the_environment(monkeypatch):
|
||||
"""Pins down: `TEA_LOCAL_WORKERS` fixes the size of a local cluster, an explicit count still wins, and a value
|
||||
below one means one worker.
|
||||
|
||||
Fails if a local run on a shared machine can no longer be limited from the environment.
|
||||
"""
|
||||
from tea.pipeline.dask_runner import local_workers
|
||||
|
||||
monkeypatch.setenv("TEA_LOCAL_WORKERS", "1")
|
||||
assert local_workers() == 1
|
||||
monkeypatch.setenv("TEA_LOCAL_WORKERS", "0")
|
||||
assert local_workers() == 1
|
||||
assert local_workers(n_workers=3) == 3
|
||||
@@ -1,9 +1,10 @@
|
||||
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
|
||||
library.
|
||||
library, plus EEG selection and the CLI summary. Fails if explicit selection skips current studies or the CLI
|
||||
stops reporting its final counts.
|
||||
|
||||
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
|
||||
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
|
||||
posterior channels flat; and bytes that are not an EDF.
|
||||
posterior channels flat; and bytes that are not an EDF. `selection_session` holds three EEG rows in SQLite.
|
||||
"""
|
||||
import pytest
|
||||
from synth_edf import edf_bytes
|
||||
@@ -18,7 +19,7 @@ FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measured():
|
||||
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
|
||||
"""Measure clean, flat, and broken studies to expose changes in triage and metrics."""
|
||||
s = settings()
|
||||
return {
|
||||
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
|
||||
@@ -115,3 +116,77 @@ def test_channel_codes_lose_their_numbers():
|
||||
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
|
||||
"intermittent-bursts"
|
||||
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def selection_session():
|
||||
"""Store current, pending, and EDF-less EEGs to expose scope regressions."""
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from core.tea.models import Eeg
|
||||
|
||||
engine = create_engine("sqlite://")
|
||||
Eeg.__table__.create(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
Eeg(eeg_id="1", eeg_estudio=b"edf", eeg_plan_hash="current", eeg_versiones="current", eeg_valido=0),
|
||||
Eeg(eeg_id="2"),
|
||||
Eeg(eeg_id="3", eeg_estudio=b"edf"),
|
||||
])
|
||||
session.commit()
|
||||
yield session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_explicit_ids_select_current_edfs(selection_session):
|
||||
"""Pin explicit reanalysis. Fail if current EEGs are skipped or EDF-less and unrequested rows are selected."""
|
||||
from models.eeg_analysis import pending_ids
|
||||
|
||||
options = {"plan_hash": "current", "versions": "current", "models": dict}
|
||||
assert pending_ids(selection_session, **options) == ["3"]
|
||||
assert pending_ids(selection_session, ids=[2, 1, 1], **options) == ["1"]
|
||||
with pytest.raises(LookupError, match=r"8, 9"):
|
||||
pending_ids(selection_session, ids=[1, 9, 8], **options)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failed", [0, 1])
|
||||
def test_analyze_cli_emits_summary_and_passes_ids(monkeypatch, capsys, failed):
|
||||
"""Pin the final JSON line and failure status. Fail if explicit IDs or the failed count are ignored."""
|
||||
import json
|
||||
|
||||
from models import eeg_analysis
|
||||
from models.__main__ import main
|
||||
|
||||
def analyze(**options):
|
||||
assert options == {"everything": False, "limit": None, "ids": ["1", "2"], "cluster": "sync"}
|
||||
return eeg_analysis.Summary(pending=2, valid=1, not_valid=1 - failed, failed=failed)
|
||||
|
||||
monkeypatch.setattr(eeg_analysis, "analyze_pending", analyze)
|
||||
assert main(["tea", "analyze", "--ids", "1,2", "--cluster", "sync"]) == failed
|
||||
line = capsys.readouterr().out.splitlines()[-1]
|
||||
assert line.startswith("summary: ")
|
||||
assert json.loads(line.removeprefix("summary: ")) == {
|
||||
"pending": 2, "valid": 1, "not_valid": 1 - failed, "failed": failed,
|
||||
}
|
||||
|
||||
|
||||
def test_explicit_ids_may_be_uuids(selection_session):
|
||||
"""Pin that ids are matched as strings, so the UUID ids real EEGs carry select their rows. Fail if ids go back
|
||||
to being parsed as integers."""
|
||||
from core.tea.models import Eeg
|
||||
from models.eeg_analysis import selected_ids
|
||||
|
||||
uuid = "ed257fbd-61d5-4c9c-bb72-00c4ec550961"
|
||||
selection_session.add(Eeg(eeg_id=uuid, eeg_estudio=b"EDF"))
|
||||
selection_session.commit()
|
||||
assert selected_ids(selection_session, [uuid]) == [uuid]
|
||||
with pytest.raises(LookupError, match="no-such-id"):
|
||||
selected_ids(selection_session, [uuid, "no-such-id"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("other", [["--all"], ["--limit", "2"]])
|
||||
def test_analyze_cli_rejects_conflicting_scope(other):
|
||||
"""Pin exit 2 for ambiguous scopes. Fail if an explicit ID request can start with another scope."""
|
||||
from models.__main__ import main
|
||||
|
||||
assert main(["tea", "analyze", "--ids", "1", *other]) == 2
|
||||
|
||||
@@ -184,3 +184,20 @@ def test_a_reference_study_is_measured_from_its_path(tmp_path):
|
||||
assert (st.valid, st.error) == (1, None)
|
||||
assert set(st.features) == set(settings().scenarios.values())
|
||||
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
|
||||
|
||||
|
||||
def test_training_reads_the_cluster_choice_from_the_environment(monkeypatch):
|
||||
"""Pins down: training measures its studies on the runner `EEG_ANALYSIS_CLUSTER` names, and falls back to `auto`
|
||||
for an unset or unknown value (including `off`, which only the analysis understands).
|
||||
|
||||
Fails if `run_steps` stops passing the choice to `train_all`, or lets an unknown value reach the runner.
|
||||
"""
|
||||
from models.tea.eeg import model
|
||||
|
||||
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
|
||||
assert model._cluster() == "auto"
|
||||
for chosen in ("auto", "local", "remote", "sync"):
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", chosen)
|
||||
assert model._cluster() == chosen
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "off")
|
||||
assert model._cluster() == "auto"
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Cover optional, atomic progress reporting and ETA with temporary files and a fake clock.
|
||||
|
||||
Fails if monitoring changes unconfigured runs, publishes incomplete samples, or miscalculates throughput.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
from tea.pipeline import run_monitor
|
||||
|
||||
|
||||
def test_monitor_without_directory(monkeypatch):
|
||||
"""Pin the no-op monitor. Fail if an unconfigured run activates sampling."""
|
||||
monkeypatch.delenv("RUN_PROGRESS_DIR", raising=False)
|
||||
with run_monitor.monitor_from_env() as monitor:
|
||||
monitor.start()
|
||||
monitor.phase("analizando")
|
||||
monitor.total(12)
|
||||
monitor.advance()
|
||||
assert run_monitor.active_monitor() is None
|
||||
monitor.stop()
|
||||
|
||||
|
||||
def test_local_cluster_progress(tmp_path, monkeypatch):
|
||||
"""Pin live Dask telemetry and atomic snapshots. Fail if progress stalls, grows unbounded, or tears."""
|
||||
path = tmp_path / "progress.json"
|
||||
replace = run_monitor.os.replace
|
||||
replacements = []
|
||||
|
||||
def verify_replace(source, target):
|
||||
if target == path:
|
||||
assert json.loads(source.read_text())["history"]
|
||||
if path.exists():
|
||||
assert json.loads(path.read_text())["history"]
|
||||
replacements.append(source)
|
||||
replace(source, target)
|
||||
|
||||
def read_until(predicate):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
if path.exists():
|
||||
progress = json.loads(path.read_text())
|
||||
if predicate(progress):
|
||||
return progress
|
||||
time.sleep(0.01)
|
||||
pytest.fail("Timed out waiting for progress")
|
||||
|
||||
monkeypatch.setattr(run_monitor.os, "replace", verify_replace)
|
||||
with LocalCluster(n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0") as cluster:
|
||||
with Client(cluster) as client, run_monitor.RunMonitor(tmp_path, interval=0.1, history=4) as monitor:
|
||||
monitor.start(client, ("local", None))
|
||||
monitor.total(10)
|
||||
monitor.phase("midiendo")
|
||||
initial = read_until(lambda p: p["phase"] == "midiendo" and p["tasks"] and p["cluster"]["workers"])
|
||||
assert initial["done"] == 0 and initial["eta_s"] is None
|
||||
assert set(initial["tasks"]) == {"processing", "waiting", "memory", "erred"}
|
||||
assert initial["cluster"]["workers"][0]["threads"] == 1
|
||||
monitor.advance(3)
|
||||
measured = read_until(lambda p: p["done"] == 3 and len(p["history"]) == 4)
|
||||
assert measured["eta_s"] > 0
|
||||
monitor.advance(2)
|
||||
monitor.phase("ajustando")
|
||||
monitor.stop()
|
||||
|
||||
final = json.loads(path.read_text())
|
||||
assert final["done"] == 5 and final["eta_s"] is None
|
||||
assert final["phase"] == "ajustando"
|
||||
assert len(final["history"]) == 4
|
||||
assert final["history"][-1]["done"] == 5
|
||||
assert len(replacements) >= 5
|
||||
assert list(tmp_path.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_eta_smoothed_rate(tmp_path, monkeypatch):
|
||||
"""Pin ETA arithmetic and its threshold. Fail if cumulative or instantaneous rate replaces smoothing."""
|
||||
now = 100.0
|
||||
monkeypatch.setattr(run_monitor, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(run_monitor.Thread, "start", lambda self: None)
|
||||
monkeypatch.setenv("RUN_PROGRESS_DIR", str(tmp_path))
|
||||
path = tmp_path / "progress.json"
|
||||
with run_monitor.monitor_from_env() as monitor:
|
||||
assert run_monitor.active_monitor() is monitor
|
||||
monitor.phase("analizando")
|
||||
monitor.total(20)
|
||||
monitor.advance(2)
|
||||
now += 2
|
||||
monitor._write_sample()
|
||||
first = json.loads(path.read_text())
|
||||
assert first["eta_s"] is None
|
||||
assert first["tasks"] is None and first["cluster"] is None
|
||||
monitor.advance(4)
|
||||
now += 2
|
||||
monitor._write_sample()
|
||||
assert json.loads(path.read_text())["eta_s"] == pytest.approx(14 / (0.3 * 2 + 0.7))
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
"""A stand-in for a Dask client with one busy worker, whose status the test can flip."""
|
||||
|
||||
status = "running"
|
||||
|
||||
def scheduler_info(self):
|
||||
return {"workers": {"tcp://w:1": {"name": "w", "nthreads": 1, "memory_limit": 1000,
|
||||
"metrics": {"cpu": 90.0, "memory": 500, "executing": 1}}}}
|
||||
|
||||
|
||||
def _wait_for(path, condition, seconds=5.0):
|
||||
"""The last snapshot at `path` once `condition(snapshot)` holds, or fail after `seconds`."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if path.exists():
|
||||
snapshot = json.loads(path.read_text())
|
||||
if condition(snapshot):
|
||||
return snapshot
|
||||
time.sleep(0.02)
|
||||
raise AssertionError(f"no snapshot matched: {path.read_text() if path.exists() else 'no file'}")
|
||||
|
||||
|
||||
def test_the_cluster_figures_clear_when_the_client_is_released(tmp_path):
|
||||
"""Pin that `release` drops the cluster and task figures from every later snapshot, including the final one.
|
||||
Fail if a finished run keeps reporting its last CPU, RAM and task counts as if the cluster were still busy."""
|
||||
path = tmp_path / "progress.json"
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
monitor.start(_FakeClient(), ("local", None))
|
||||
busy = _wait_for(path, lambda s: s["cluster"] and s["cluster"]["cpu_pct"] == 90.0)
|
||||
assert busy["cluster"]["workers"][0]["name"] == "w"
|
||||
monitor.release()
|
||||
cleared = _wait_for(path, lambda s: s["cluster"] is None)
|
||||
assert cleared["tasks"] is None
|
||||
monitor.stop()
|
||||
final = json.loads(path.read_text())
|
||||
assert final["cluster"] is None and final["tasks"] is None
|
||||
|
||||
|
||||
def test_the_cluster_figures_clear_when_the_sampler_sees_a_closed_client(tmp_path):
|
||||
"""Pin that a client closed without a `release` call still stops being reported on the next sample.
|
||||
Fail if the sampler goes on writing the last figures of a client whose status is closed."""
|
||||
path = tmp_path / "progress.json"
|
||||
client = _FakeClient()
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
monitor.start(client, ("remote", "tcp://s:1"))
|
||||
_wait_for(path, lambda s: s["cluster"] and s["cluster"]["scheduler"] == "tcp://s:1")
|
||||
client.status = "closed"
|
||||
_wait_for(path, lambda s: s["cluster"] is None and s["tasks"] is None)
|
||||
monitor.stop()
|
||||
|
||||
|
||||
def test_a_client_attached_later_is_reported_again(tmp_path):
|
||||
"""Pin that releasing one client does not stop the next one (a run opens a cluster per phase) from reporting.
|
||||
Fail if `release` leaves the monitor unable to take a new client."""
|
||||
path = tmp_path / "progress.json"
|
||||
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||
first = _FakeClient()
|
||||
monitor.start(first, ("local", None))
|
||||
_wait_for(path, lambda s: s["cluster"] is not None)
|
||||
monitor.release(first)
|
||||
_wait_for(path, lambda s: s["cluster"] is None)
|
||||
monitor.start(_FakeClient(), ("local", None))
|
||||
_wait_for(path, lambda s: s["cluster"] is not None and s["cluster"]["cpu_pct"] == 90.0)
|
||||
monitor.stop()
|
||||
Reference in New Issue
Block a user