Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 675ebffc09 | |||
| 7fc0d8ff31 | |||
| d83940c966 | |||
| f11efe9bb0 | |||
| 3db4f1f8f8 | |||
| 79c7d36756 | |||
| 8615395304 | |||
| d6244ebb6e | |||
| 3bd2ebf505 | |||
| e0c7643dba | |||
| ae3f6c89fa | |||
| a820c7c2bf | |||
| 415873c767 | |||
| a9b8623bc5 | |||
| 50034dd471 | |||
| 22331edfe6 | |||
| 7dfb4df498 | |||
| 541a8114c7 | |||
| 8a7ed7669d | |||
| 52f378a625 | |||
| 26dd5b8a01 | |||
| 35544fc98a | |||
| f9560aee8c | |||
| 74af823764 | |||
| 23708bfff9 | |||
| 7a08c0b335 | |||
| 35df57fcec | |||
| a495fc2852 | |||
| dadd7249fa | |||
| 4a47d5f965 | |||
| 2cfa573204 | |||
| bcff4d495d | |||
| 234c45c10a | |||
| a3b848ef6f | |||
| f84f497cf9 | |||
| 8e30ac5aea |
@@ -0,0 +1,3 @@
|
||||
graphify-out
|
||||
.claude/
|
||||
samples/
|
||||
@@ -104,14 +104,14 @@ ISSSTELEON/ (outer) this WorkingNarrative repo: AGENTS.md, reference PD
|
||||
├── models/ submodule: train/predict interface, cohorts, registry, OCR jobs
|
||||
├── WebApi/ submodule: Flask API (also holds `webapi.orquestacion`, the Hamilton-based ETL graph)
|
||||
├── WebApp/ submodule: Angular 22 + Material
|
||||
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080)
|
||||
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080) + indicadores + notebooks (isolated notebook runner)
|
||||
```
|
||||
|
||||
Commands below are given relative to the inner `ISSSTELEON/` checkout (where
|
||||
actual development happens) unless noted otherwise; `../` reaches this outer
|
||||
repo's own files (`../e2e/`, `../docs_desarrollo-2.pdf`, etc.).
|
||||
|
||||
Dependencies (uv path deps): WebApi → Persistance, models[export], Extraction ·
|
||||
Dependencies (uv path deps): WebApi → Persistance, models[notebooks], Extraction ·
|
||||
models → Persistance, Extraction · Persistance → Core · Extraction → (no
|
||||
internal deps). Each Python package has its own `uv` env: `cd <pkg> && uv run pytest -q`.
|
||||
|
||||
@@ -123,11 +123,22 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
|
||||
## 3. Git state of the local working tree
|
||||
|
||||
- **`dev` is where work happens**, in this repo and in every submodule
|
||||
(`WebApi`, `WebApp`, `models`, `indicadores_kit`), all on the `ISSSTELEON`
|
||||
org Gitea: each piece of work is a branch off `dev`, merged back by a pull
|
||||
request (rule 10). Other branches are not used for new work. In
|
||||
`indicadores_kit`, `origin` is our org copy; `upstream` is the external
|
||||
fork (read-only).
|
||||
(`WebApi`, `WebApp`, `models`), all on the `ISSSTELEON` org Gitea: each
|
||||
piece of work is a branch off `dev`, merged back by a pull request
|
||||
(rule 10). Other branches are not used for new work. `indicadores_kit`
|
||||
is no longer a submodule: its jobs live in `Transformation/`, the WebApi
|
||||
and `models` (kit exit, 2026-11-15); the repo stays on Gitea for its
|
||||
notebooks.
|
||||
- **Changes flow `dev` → `staging` → `main`.** Changes are made on `dev`
|
||||
(through branches off it), then passed on to `staging`, and finally to
|
||||
`main`, which is what is handed off for installation. `staging` and
|
||||
`main` are never worked on directly, so `dev` must always contain both;
|
||||
the pending alignment is in `docs/ledgers/open-items.md`.
|
||||
- When SSH to Gitea is refused, the repos can still be read over HTTP
|
||||
without credentials (read-only):
|
||||
`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`
|
||||
(`<repo>`: `WorkingNarrative`, `ISSSTELEON`, `WebApi`, `WebApp`, `models`).
|
||||
Pushing still needs SSH or a token.
|
||||
- This file lives outside the submodule, in the outer WorkingNarrative repo
|
||||
(`ISSSTELEON/../AGENTS.md`) — versioned there instead of the prior
|
||||
gitignored-local-notes setup, so it has real history and isn't lost on a
|
||||
@@ -143,10 +154,10 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
|
||||
one baseline generated from the models, verified upgrade/downgrade/upgrade
|
||||
on SQLite, MySQL 8, PostgreSQL 16 and SQL Server 2022; older revisions are
|
||||
gone, so a database stamped with them must start fresh):
|
||||
- tea `a3e1c7b90d12`, cacu `b4f2d8c01e23`, cama `c5a3e9d12f34`, governance `d6b4f0e23a45` -> `e7c5a1f34b56`
|
||||
- on `feature/163-source-terminology` (not in `dev` yet): tea `a3e1c7b90d12` -> `f2b6d1e8c934` ->
|
||||
`6d772e9a342f`, cacu -> `f89e1f081998`, cama -> `f82b64f43abd` (`cat_sistema_fuente`, `cat_mapeo`;
|
||||
verified on SQLite only)
|
||||
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join);
|
||||
cacu `b4f2d8c01e23` -> `f89e1f081998`; cama `c5a3e9d12f34` -> `f82b64f43abd` (`cat_sistema_fuente`,
|
||||
`cat_mapeo`); governance `d6b4f0e23a45` -> `e7c5a1f34b56`. The TEA chain and the join verified
|
||||
upgrade/downgrade/upgrade on SQLite only.
|
||||
|
||||
---
|
||||
|
||||
@@ -180,8 +191,9 @@ Read these only when a task points there (its `area/*` label or its **Context**
|
||||
|
||||
| What | Where |
|
||||
|---|---|
|
||||
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (indicator computation), `other.md` |
|
||||
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (the retired kit; measures now live in `Transformation/`, see `webapi.md`), `other.md` |
|
||||
| Live testing against real infrastructure | `docs/operations/`: `local-dashboard.md`, `fork-source.md`, `mysql-tunnel.md`, `docker-engines.md`, `seed-pipeline-verify.md`, `browser.md`, `dev-data-ingest.md` |
|
||||
| Plans and decisions | `plans/` |
|
||||
| What the contract promises against what exists | `docs/scope-status.md` |
|
||||
| How to test and run each package | `docs/testing.md` |
|
||||
| History of past sessions | `docs/history/sessions.md` (the original §6, §7, §8.1, §9 and §10 of this file) |
|
||||
|
||||
+1
-1
Submodule ISSSTELEON updated: e27a5da077...28d80ad7e3
+1
-1
Submodule dev-data updated: 57023b6cfb...3dea0ad641
+108
-14
@@ -7,28 +7,122 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
Package `Extraction/extraction/`:
|
||||
- `readers/` — `DocumentReader` + `@register_reader`; `PdfReader` (text
|
||||
layer, Tesseract on pages without one, embedded image detection),
|
||||
`ImageReader` (PNG/JPG/multi-page TIFF). `combine_pages` builds one PDF
|
||||
from pages of several PDFs.
|
||||
`ImageReader` (PNG/JPG/multi-page TIFF), `TextReader` (fallback: plain
|
||||
text, one line per newline). `combine_pages` builds one PDF from pages of
|
||||
several PDFs.
|
||||
- Text layer: glyphs drawn several times a fraction of a point apart
|
||||
(fake bold) are deduplicated (`dedupe_chars`); every line keeps its
|
||||
words with their horizontal extent (`document.Line.words`).
|
||||
- OCR: a page that is mostly one scanned image is OCRed unless its text
|
||||
layer is substantial (a scanner may stamp a header over the scan); a
|
||||
page read with low confidence is retried at the orientation Tesseract's
|
||||
OSD detects. OCR lines carry word positions too.
|
||||
- `segmentation.py` — `Segmenter` subclasses: `auto`, `document`, `pages`
|
||||
(N per record), `key` (new record when the patient id changes; pages
|
||||
without id continue the previous record).
|
||||
- `nlp/` — `FieldSpec` (kind, labels, choices, pattern, scan_free_text,
|
||||
multiline); extractors `LabeledValueExtractor` (captions, multi-field
|
||||
lines, value under the label, fuzzy OCR-tolerant labels),
|
||||
`PatternExtractor`, `FreeTextMentionExtractor` (catalog terms in
|
||||
narrative, NegEx-style negation). Vocabulary of captions and clinical
|
||||
terms in `nlp/vocabulary.py` (extend there, no code changes).
|
||||
- `records.py` — `DocumentExtractor` and `RecordMerger` (same patient across
|
||||
multiline); extractors `LabeledValueExtractor`, `PatternExtractor`,
|
||||
`FreeTextMentionExtractor` (catalog terms in narrative, NegEx-style
|
||||
negation). Vocabulary of captions and clinical terms in
|
||||
`nlp/vocabulary.py` (extend there, no code changes); schema descriptions
|
||||
also become captions, without a leading item code or what follows a
|
||||
colon.
|
||||
- Layout handling, all general (no form-specific rules): several captions
|
||||
on one line; captions on one row with their values on the next, read
|
||||
per column from word positions; item numbers (`3.-`, `b)`) belong to the
|
||||
caption they precede and end the value before them; a value ends at a
|
||||
wide horizontal gap once it has started; abbreviated captions (`Fech.`)
|
||||
and dropped connectors (`de`, `del`) still match; a caption may run on a
|
||||
few words before its colon; a label right after a connector is the tail
|
||||
of a longer caption naming something else; an integer field never reads
|
||||
a date.
|
||||
- `nlp/discovery.py::discover_captions` — captions no `FieldSpec` claims,
|
||||
found anywhere a known label could be (several per line, numbered,
|
||||
heading a column) and read by the same extractor through temporary
|
||||
specs.
|
||||
- `template.py` — lines in the top or bottom margin that repeat (digits
|
||||
exact, letters OCR-tolerant) on documents of two or more different
|
||||
patients are the issuer's letterhead or footer; `DocumentExtractor`
|
||||
re-extracts the affected records without them. A header repeated only
|
||||
across one patient's documents is kept.
|
||||
- `records.py` — `DocumentExtractor` and `RecordMerger` (same key across
|
||||
pages/files, most confident value wins, confident disagreements become
|
||||
`FieldConflict`).
|
||||
`FieldConflict`). `extract(..., source_fields=, record_keys=)`: values a
|
||||
structured source hands over per document (trusted over the page,
|
||||
including the key) and the record each document joins (documents sharing
|
||||
one merge; others stay apart even for the same patient).
|
||||
`ExtractedRecord.discovered` carries the captions no spec claimed.
|
||||
- WebApi side: `connectors/document.py` + `schemas/field_specs.py` (field
|
||||
specs derived from the target schema). Each row carries `documento` (the
|
||||
record's pages as one PDF), mappable to a file column. Corrections from
|
||||
the UI travel as `overrides`. Results cached per worker for repeated calls.
|
||||
record's pages as one PDF), mappable to a file column, and every
|
||||
discovered caption as a column of its own. Corrections from the UI travel
|
||||
as `overrides`; `include_pattern`/`exclude_pattern` keep or leave out
|
||||
documents by their text; unreadable documents are listed in `skipped`
|
||||
instead of failing the batch. Results cached per worker.
|
||||
- Documents stored in columns of any tabular source (SQL table or query,
|
||||
CSV, Excel, JSON): `connectors/document_columns.py::DocumentColumns`
|
||||
(document columns; `name_by`, `group_by` and `fields` as a column, a
|
||||
list of columns or a derived rule). Cells may hold the file as binary,
|
||||
hex or base64 text (`document_bytes`). Used by a `document` source's
|
||||
`sql` payload and by any import source's `documents` (see webapi.md).
|
||||
- `schemas/catalog_matching.py` + `services/catalog_commit_service.py`:
|
||||
opt-in per source (`catalog_fallback: true`). A discovered caption is
|
||||
fuzzy-matched (`rapidfuzz`) against the project's catalog
|
||||
(`core/catalogos/<proyecto>.toml`); only captions the catalog already
|
||||
knows are written, straight into `procedimiento`/`observacion`, tagged
|
||||
with the sentinel `fuente_tabla` `catalogo_abierto`. The import path never
|
||||
mints catalog entries (the catalog is versioned with the code);
|
||||
unmatched captions are counted, and the import report lists unused
|
||||
captions without their values (webapi.md).
|
||||
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
|
||||
source line and page, conflicts, image thumbnails, editable values).
|
||||
- Limits: NLP is rule-based (no trained model); images are located and
|
||||
shown, not classified, and only stored inside the record's PDF.
|
||||
source line and page, conflicts, image thumbnails, editable values,
|
||||
document filters; each value's assertion when it isn't affirmed, the
|
||||
other candidates as one-click picks, a warning on off-topic records).
|
||||
- Narrative layer (2026-11-13), all in `Extraction/` (`README.md` there has
|
||||
the method and references for VAR-04/VARM-05):
|
||||
- `nlp/context.py`: ConText/NegEx assertions (negated, hypothetical,
|
||||
historical, uncertain, presumed) with form-style answers after a mention
|
||||
(`Término: NO`) and a caption without its answer read as asserting
|
||||
nothing; sections from standalone headings (clinical, description,
|
||||
result, history, reference text), a caption with content qualifying only
|
||||
its line. Labels' values are only qualified by clinical and history
|
||||
sections, so a footer date under an interpretation guide still counts.
|
||||
- `FieldSpec` gained `anchors` (a generic answer like "POSITIVO" needs its
|
||||
concept before it), `severity` (most severe affirmed value wins),
|
||||
`negated_value` ("sin actividad epileptiforme" -> 0) and `unit`
|
||||
(`MeasurementExtractor`, ranges give their midpoint). Vocabulary for all
|
||||
of them, EEG terms (ACNS), narrative BI-RADS, Bethesda/LAST terms and
|
||||
section headings and triggers is in `nlp/vocabulary.py`.
|
||||
- `ocr_fold`: OCR look-alikes collapsed on both sides, as a fallback for
|
||||
labels and choices on OCR lines only.
|
||||
- Subject check: `DocumentExtractor(subject=, foreign=)` from
|
||||
`vocabulary.SUBJECTS` keyed by table name (`__table__.name`, e.g.
|
||||
`citologiacervical`). Only positive evidence gates: a record naming a
|
||||
foreign subject and not its own fills nothing; values held back from an
|
||||
off-topic segment come back if its merged record is on topic.
|
||||
- Every candidate is kept (`ExtractedRecord.candidates`) with features
|
||||
(no document text); `nlp/ranking.py` picks one: `HeuristicRanker`
|
||||
(confidence, with hypothetical and off-topic vetoed) or `LearnedRanker`
|
||||
(online logistic regression, AdaGrad + L2, blended with the heuristic
|
||||
until `TRUST_EXAMPLES`; the rules' vetoes hold until then).
|
||||
- `models/io/extraction_ranker.py` versions each domain's ranker as
|
||||
`<domain>-extraccion` (DEV version per batch, five routines, saved
|
||||
model). WebApi learns in line: `commit_sources` ->
|
||||
`review_learning.learn_from_reviews` (background, one worker) from
|
||||
records with `overrides` (corrected fields plus the rest as accepted).
|
||||
`python -m webapi.nlp evaluate|train` scores against / trains from an
|
||||
answer key (leave-one-document-out estimate first).
|
||||
- The connector fills the entity's `*_nlp_version` column with
|
||||
`extraction <version> + extraccion:<n>`; the review report carries
|
||||
`alternatives`, `on_topic` and `nlp_version`.
|
||||
- Development set: six real CaCu documents (cytology forms, HPV PCR
|
||||
reports, scanned biopsies) kept outside every repository; answer key in
|
||||
the session scratch only. Rules alone went from P 0.65 / R 0.85 to
|
||||
1.00 / 1.00 on them, and the leave-one-out ranker estimate is 1.00; both
|
||||
are fit on the same documents the rules were adjusted to.
|
||||
- Limits: images are located and shown, not classified, and only stored
|
||||
inside the record's PDF; the template rule needs at least two patients'
|
||||
documents in the batch.
|
||||
|
||||
### 5.4 EEG (TEA)
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
# indicadores-kit
|
||||
|
||||
Moved from `AGENTS.md` on 2026-11-03.
|
||||
Moved from `AGENTS.md` on 2026-11-03. **Retired on 2026-11-15:** the kit is no longer a submodule or a
|
||||
dependency. Its measures are dbt semantic models in `Transformation/`, answered on request by the WebApi as FHIR
|
||||
MeasureReports (`webapi/kpis.py`, `webapi/fhir/`); its silver load, reference tables and follow-up list are in
|
||||
`webapi/orchestration/` and `webapi/follow_up/`; its cohorts are in `models/cohorts/`. What follows describes the
|
||||
division of labor that still holds and the kit as it was.
|
||||
|
||||
### 5.6a Indicator computation — division of labor (clarified by the owner, 2026-10-19)
|
||||
|
||||
|
||||
+103
-16
@@ -14,19 +14,106 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
|
||||
### 5.5 Model versioning and cohorts (ML/MLD/EL)
|
||||
|
||||
- Governance DB tables (`Core/core/governance/`): ExtractionRun,
|
||||
CohortVersion, CohortMember, CohortExclusion, CohortExclusionCount,
|
||||
ModelVersion, ModelArtifact, ModelPrediction.
|
||||
- `models/models/registry.py` — `ModelRegistry`: register, attach reports,
|
||||
upload artifacts (checksummed, ONNX validated), status derived
|
||||
(desarrollo/candidata/produccion/retirada), `checks()` gates promotion
|
||||
(ML-02, ML-03, MLD-01, MLD-01b, MLD-03, ML-01b), retire, lineage, compare.
|
||||
- `models/models/cohort.py` — `CohortBuilder`, `ExclusionCriterion`,
|
||||
`@register_cohort_builder`. **No concrete builders exist**: clinical
|
||||
criteria are not defined in the requirements document, so production
|
||||
promotion is impossible until a scenario is registered.
|
||||
- `models/models/prediction.py` — `PredictionService` persists predictions
|
||||
tagged with the active version.
|
||||
- Routes `/governance/model-versions*`, `/governance/artifacts/<id>/download`,
|
||||
`/governance/cohort-scenarios`, `/governance/cohort-versions`. WebApp
|
||||
model-version detail dialog and cohort build menu.
|
||||
Versions, runs and their files live in MLflow; the cohorts a model trains on
|
||||
are the kit's builds (`cohorte_armado`) or dbt's, exported to Parquet files.
|
||||
|
||||
- `models/models/io/tracking.py`: `TrainingRun`, one MLflow run per training.
|
||||
It links the cohort build (ML-03), tags DEV/PROD (ML-02) and the git commit,
|
||||
saves the model (`log_model`, `modelo_sha`; PROD refuses a class defined in a
|
||||
notebook) and records each routine around training while it runs
|
||||
(`log_routine(kind, record)` → `rutinas/<KIND>.json`, counts and settings,
|
||||
never rows). `ROUTINE_KINDS` are the five of §5 of the requirements:
|
||||
MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES,
|
||||
CONFIANZA_SALIDA (`Core/core/governance/enums.py::ArtifactKind`, plus
|
||||
OTRO for any other file the run keeps). `run_files`/`run_file` list and
|
||||
download a run's files; a folder downloads as a zip.
|
||||
- `models/models/io/registry.py`: `registry`. Status is derived
|
||||
(desarrollo/candidata/produccion/retirada); `checks()` gates promotion:
|
||||
ML-02, ML-03, MLD-01 (metrics, technical report), MLD-01b, MLD-03, **ML-01a
|
||||
(all five routine records, written by the run) and ML-01b (the saved
|
||||
model)**. Only what the training run itself wrote counts: nothing can be
|
||||
uploaded to a version. `lineage()` returns every file of the run and the
|
||||
routine records; `artifact()` downloads one (ML-01b).
|
||||
- `models/models/cacu/cin2_logistic/model.py`: Hamilton nodes `sampling`,
|
||||
`missing_data`, `analytic_method`, `class_balance`, `output_confidence`
|
||||
(and `routines`, which gathers them) record what this training did:
|
||||
the temporal split, missing predictors as the `(none)` category,
|
||||
coefficients, class counts (no reweighting) and a calibration table.
|
||||
- Routes: `/governance/model-versions*` (list, register, reports, lineage,
|
||||
checks, promote, retire) and
|
||||
`GET /governance/model-versions/<d>/<s>/<v>/artifacts/<path>` (download).
|
||||
WebApp version dialog: checklist, cohort, the five routines (recorded or
|
||||
missing, each viewable), the run's files as downloads, reports, and
|
||||
"Probar en un notebook".
|
||||
- Removed 2026-11-13: uploading a file of any kind to a version (it let a
|
||||
hand-picked file satisfy ML-01b), and the ONNX checkpoint support with it
|
||||
(`ONNX_CHECKPOINT`, `inspect_onnx_metadata`, the `export` extra). Nothing
|
||||
produced an ONNX file and predictions never used one.
|
||||
|
||||
### 5.6 Notebooks run on the server (ML-01a, ML-04, ML-05)
|
||||
|
||||
A Jupyter notebook uploaded from the WebApp runs against one exported cohort
|
||||
build, isolated from the server, for development experiments.
|
||||
|
||||
- `models/models/pipelines/experiment.py`: `start` creates an MLflow run in
|
||||
`<domain>-<scenario>/experimentos`, tagged with the notebook's name and
|
||||
content hash, the build's file (`cohort_reference`), the chosen version and
|
||||
the code version, and stores the notebook without outputs. `execute` hands
|
||||
the job to an executor, then stores the page (`report/<name>.html`), what
|
||||
was imported (`importado.json`) and, if it failed, `error.txt`; the run is
|
||||
tagged `sandbox: contenedor|local`. Status: en_curso, terminado, fallido,
|
||||
interrumpido (running past `NOTEBOOK_JOB_TIMEOUT` + 30 min).
|
||||
- `models/models/io/notebook_jobs.py`: the job folder
|
||||
(`<NOTEBOOK_JOBS_DIR>/<run_id>/`: `notebook.ipynb`, a copy of the build's
|
||||
file `cohorte.parquet`, the chosen version's saved model `model/`,
|
||||
`job.json`), assembled aside and renamed into place, and handed to
|
||||
`NOTEBOOK_RUNNER_UID`. `run_job` runs it on the `python3` kernel with an
|
||||
environment built from the job alone: the build's file, `MODEL_PATH`, an
|
||||
MLflow store inside the job (`mlflow.db`, `artefactos/`), every
|
||||
`*_DATABASE_URL` set to `sqlite://`, HOME and temp folders inside the job;
|
||||
writes `page.html` and `result.json`. Executors (`EXECUTORS`,
|
||||
`register_executor`): `local` runs it in the API's process (development,
|
||||
unisolated); `contenedor` leaves it for the runner and waits
|
||||
(`NOTEBOOK_JOB_TIMEOUT`, 6 h). `NOTEBOOK_EXECUTOR` picks one; the default is
|
||||
`contenedor` when `NOTEBOOK_JOBS_DIR` is set. `serve` (`python -m models
|
||||
notebooks serve`) is the runner's loop; a job is claimed by creating
|
||||
`en_curso/` in it.
|
||||
- `models/models/io/notebook_import.py`: copies what the notebook trained
|
||||
into the platform's MLflow. Only `<domain>-<scenario>` experiments of the
|
||||
job's domain; each run becomes a new DEV run with the real cohort tags,
|
||||
`notebook.run_id`, the code version and a recomputed `modelo_sha`
|
||||
(`kit.armado_id` and the notebook's own `modelo_sha` are dropped); versions
|
||||
come across as DEV, never with an alias. The store is opened from a copy,
|
||||
files are walked without following links and must sit inside the job
|
||||
(`read_job_file`, `inside`), and `NOTEBOOK_MAX_IMPORT_MB` (500) caps them.
|
||||
All of it exists because the trusted side reads files an untrusted
|
||||
notebook wrote.
|
||||
- `models/models/notebook.py`: the API inside a notebook. `experiment()` →
|
||||
`.cohort()`, `.lineage()`, `.model()` (the job's copy, `MODEL_PATH`),
|
||||
`.training_run()` (a DEV `TrainingRun` linked to the build),
|
||||
`.register(run)`.
|
||||
- `models/models/io/rendering.py`: renderers as classes (`RENDERERS`,
|
||||
`register_renderer`): `quarto`, and `jupyter` (`nbclient` + `nbconvert`,
|
||||
the `notebooks` extra, which WebApi installs). `NOTEBOOK_RENDERER` picks
|
||||
one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT`
|
||||
(1800 s per cell).
|
||||
- `models/models/io/storage.py`: `exported_builds(root, domain)` and
|
||||
`build_file(root, url, source, build)`, read from the files alone.
|
||||
- Deployment: service `notebooks` in `docker-compose.yml` and
|
||||
`dist/docker-compose.yml`, the webapi image with command `notebooks`
|
||||
(`WebApi/docker-entrypoint.sh`): `network_mode: none`, `read_only`, tmpfs
|
||||
`/tmp`, user 10001, `cap_drop: ALL`, `no-new-privileges`, memory/CPU/PID
|
||||
limits, only the jobs volume at `/trabajos`. webapi mounts the same volume
|
||||
at the same path (the import checks paths as the runner wrote them) with
|
||||
`NOTEBOOK_JOBS_DIR=/trabajos` and `NOTEBOOK_RUNNER_UID=10001`.
|
||||
- WebApi (`webapi/blueprints/governance.py`): `GET /governance/cohort-files`,
|
||||
`GET|POST /governance/experiments` (multipart `file`, `domain`, `scenario`,
|
||||
`url`, `source`, `build`, `version?`; 202, executed in a thread pool,
|
||||
`WEBAPI_NOTEBOOK_WORKERS`, default 1),
|
||||
`GET /governance/experiments/<run_id>`, `.../page` (served with
|
||||
`Content-Security-Policy: sandbox`), `.../artifacts/<path>`.
|
||||
- WebApp: Gobernanza tab "Notebooks" (`experiments-panel`, polls while a run
|
||||
is in progress, flags "Sin aislar" runs) and `notebook-run-dialog` (also
|
||||
opened from a version).
|
||||
- Only `.ipynb` (nbformat 4) is accepted. Open items in
|
||||
`docs/ledgers/open-items.md`.
|
||||
|
||||
@@ -23,4 +23,41 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
`merge_duplicates` (opt-in, `merge_duplicates: true` on `/imports/commit`)
|
||||
combines rows of different sources sharing a natural key **before**
|
||||
validation (first source wins, disagreements reported as warnings).
|
||||
- **SQL sources** — `server.host` tolerates pasted forms (`host\instance`,
|
||||
`host,port`, `host:port`, JDBC/URI strings); a named instance without a
|
||||
port is left for the server to resolve. A user query is wrapped as a
|
||||
derived table, so a trailing `ORDER BY` that no TOP/LIMIT/OFFSET needs is
|
||||
dropped (SQL Server refuses it there). Every preview lists, in
|
||||
`document_columns`, the columns whose cells hold files.
|
||||
- **Mapping beyond one-to-one** — an import source may carry, besides
|
||||
`column_mapping` and `defaults`:
|
||||
- `derived`: `{field: rule}` computed from source columns
|
||||
(`imports/mapping/derived.py`; one `Derivation` class per operation plus
|
||||
`@register_derivation`): `column`, `concat`, `template`, `split`,
|
||||
`coalesce`, `extract`, `map`, with an optional `case`. Short forms: a
|
||||
column name or a list of columns. `GET /imports/derivations` describes
|
||||
them, and the WebApp builds its forms from it.
|
||||
- `documents`: columns holding documents (`DocumentColumns`, see
|
||||
extraction.md), with `group_by`, `name_by`, `fields`, `file_field` and
|
||||
the extraction settings. Values the mapping takes from the row's own
|
||||
columns are trusted over the page; then mapping and `derived` run again
|
||||
over each record's namespace (the rows' columns plus every field and
|
||||
caption its documents print), and extracted fields fill what's left.
|
||||
Rows without documents pass through mapped.
|
||||
- `catalog_fallback: true` to opt in to the catalog path (extraction.md).
|
||||
- Order: mapping and `derived` (one field can't be fed by both), document
|
||||
extraction, then `defaults` for anything still empty.
|
||||
- **Previews** — `POST /imports/mapped-preview` (`{source, limit}`: rows as
|
||||
they would be written); `POST /imports/sources/document/columns` (a source
|
||||
with `documents`: its columns plus the documents' fields and captions, as
|
||||
a preview with suggestions); `POST /imports/sources/document/extract`
|
||||
also takes `{source}` to review a mapping's documents.
|
||||
- **Import report (Bitácora de cargas)** — `imports/audit.py`, counts and
|
||||
shapes only, never record values. Per source it also lists the captions
|
||||
its documents print that nothing used (`etiquetas_sin_usar`, captions
|
||||
with how many records print them, from `WEBAPI_REPORT_MIN_COUNT` up;
|
||||
`etiquetas_sin_usar_poco_frecuentes` counts the rest).
|
||||
- Routes in `webapi/blueprints/imports.py`; `GET /api` lists every route.
|
||||
- WebApp: the flow editor's "Reglas" tab (`connect/components/mapping-rules`)
|
||||
sets document columns, derived fields and the catalog fallback, and shows
|
||||
the mapped preview.
|
||||
|
||||
@@ -2892,3 +2892,22 @@ code, given it adds a service to operate/secure? Lean toward only doing
|
||||
this if MLflow's web UI becomes independently useful for the team (e.g.
|
||||
browsing experiments/artifacts outside this app), not for the code
|
||||
reduction alone.
|
||||
|
||||
## 11. Indicator recompute moved from polling to a filesystem watch, 2026-11-13
|
||||
|
||||
`WebApi/webapi/indicadores_vivos.py`'s loop used to just sleep for
|
||||
`INDICADORES_INTERVALO_S` (default 20s) between checks of the
|
||||
`pendiente/<dominio>` marker directory. Replaced the sleep with a
|
||||
`watchdog` observer on that directory: any marker write now wakes the loop
|
||||
immediately (verified in a standalone smoke test: pickup in well under a
|
||||
second against a 100s fallback interval), and `INDICADORES_INTERVALO_S`
|
||||
stays only as a safety net for a missed or coalesced filesystem event, not
|
||||
the normal reaction time. `ColaDeRecalculo`'s marker/state semantics
|
||||
(`solicitar`/`tomar`/`atender`, the coalescing of requests that arrive
|
||||
mid-run) are unchanged; only how the loop wakes up moved. `watchdog` added
|
||||
as a WebApi dependency (`uv add watchdog`, pure Python, inotify on Linux).
|
||||
|
||||
This is the live mechanism G-DBT-3 (`docs/ledgers/grooming.md`) describes
|
||||
as "it drops a marker and the `indicadores` service runs the domain's
|
||||
cycle" — that description still holds; only the wake-up trigger inside it
|
||||
changed, not the cycle itself.
|
||||
|
||||
@@ -62,3 +62,31 @@ Something went wrong or was surprising while doing a task. Format and plan codes
|
||||
- **Decides:** owner.
|
||||
- **Decision:** 2026-11-05, owner: no past-date rebuilds for now, drop it from the export; a dbt snapshot may
|
||||
replace it in the future.
|
||||
|
||||
|
||||
### I-DBT-3. `cin2_logistic.predictors()` crashes the whole training run on a cohort member with a biopsy but no citología — high · open
|
||||
- **What happens:** `predictors()` builds each member's index sample from `citologia` rows only
|
||||
(`model.py`, lines ~61-68): `sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] ==
|
||||
cohort["fecha_indice"])]`, grouped by `pac_id`. For a cohort that includes a member with a `biopsia`
|
||||
row but no `citologia` row at all, `sample` comes back empty; the following
|
||||
`cohort.merge(sample, left_on="pac_id", right_index=True)` degenerates, and the resulting frame's
|
||||
implicit index ends up also named `pac_id` on top of the `pac_id` column already there. The later
|
||||
`pivot_table(index="pac_id", columns="tipo", values="valor_codigo", ...)` then raises
|
||||
`ValueError: 'pac_id' is both an index level and a column label, which is ambiguous`, which is
|
||||
unhandled and kills the whole run — not just that member's row.
|
||||
- **Evidence:** `docker compose ... run --rm entrenar` against a CaCu cohort containing one member with
|
||||
a `BiopsiaCervical` row (imported through the "documents in columns" connector) and no
|
||||
`CitologiaCervical` row for that patient. Full traceback bottoms out at
|
||||
`models/models/cacu/cin2_logistic/model.py:68`, in `predictors`, inside the `pivot_table` call.
|
||||
- **Consequence:** a cohort build with even one biopsy-only member (plausible: direct referral,
|
||||
partial/migrated history, a document-column import that only carries pathology results) blocks
|
||||
`entrenar` entirely for every member, not just that one. The model can't be trained at all until the
|
||||
offending member is removed from the cohort or the code tolerates the empty-sample case.
|
||||
- **Proposal:** make the empty-`sample` case produce `MISSING` predictors for that member instead of a
|
||||
malformed frame, e.g. reset the index after the merge (`results = cohort.merge(sample, left_on="pac_id",
|
||||
right_index=True).reset_index(drop=True)`) before the `pivot_table` call, or build `wide` from an
|
||||
explicit left-join against `members["pac_id"]` so a member with zero sample rows still gets a row of
|
||||
`MISSING` rather than disappearing and corrupting the frame's index naming. Add a unit test with a
|
||||
cohort containing one biopsy-only, no-citología member to pin this down.
|
||||
- **Decides:** owner (models package).
|
||||
- **Decision:**
|
||||
|
||||
+116
-3
@@ -11,7 +11,120 @@ Moved from `AGENTS.md` §5.7 on 2026-11-03. Each item can become an issue.
|
||||
- No authentication/authorization on WebApi; SQL credentials travel from the
|
||||
browser on each call (mitigated by `SqlSourcePolicy`).
|
||||
- Cross-field validation rules not implemented in the import schemas.
|
||||
- No trained NLP model (options discussed: pretrained Spanish clinical
|
||||
model as an extra `FieldExtractor`, plus learning from review corrections;
|
||||
needs real anonymized reports to evaluate).
|
||||
- Document NLP (narrative layer and learned ranker, see
|
||||
`docs/architecture/extraction.md`), still open:
|
||||
- Only measured on six real CaCu documents, the same ones the rules were
|
||||
adjusted on; a held-out set (ideally 30+ per report type, with an answer
|
||||
key written by someone else) is needed for an honest score. EEG,
|
||||
mammography and breast biopsy vocabulary has never seen a real report.
|
||||
- The ranker trained on those six lives only in a scratch MLflow store;
|
||||
on the server it starts empty until `python -m webapi.nlp train` is run
|
||||
with a key, or reviewers correct imports.
|
||||
- `<domain>-extraccion` versions can't pass ML-03 (no cohort: they learn
|
||||
from documents), so they can't be promoted; extraction uses the latest
|
||||
DEV version. Needs a decision on how governance treats this model.
|
||||
- Learning runs in one background thread per WebApi process; with several
|
||||
gunicorn workers two batches can continue the same version and both
|
||||
register, the second not including the first's examples.
|
||||
- A correction teaches only if made in the review dialog before
|
||||
committing (it travels as `overrides`); fixing a value later in the
|
||||
database teaches nothing.
|
||||
- No pretrained Spanish clinical model; it would be one more
|
||||
`FieldExtractor` whose candidates the ranker weighs, once a held-out
|
||||
set exists to show it helps.
|
||||
- Colposcopy (Reid, Swede) has no columns, so it stays as text.
|
||||
- Possible DICOM connector for mammograms (`pydicom`, fits `mast_dicom_blob`).
|
||||
- A source may hold a biopsy and the cytology that led to it as separate
|
||||
orders with nothing linking them (no shared id in the rows or in the
|
||||
documents). The CaCu confirmation indicator only counts the biopsy a
|
||||
cytology originated (`BiopsiaCervical.cit_id`), so such biopsies read as
|
||||
"sin biopsia aún". Option: a general import rule that fills a link with
|
||||
the same patient's latest record of the parent kind dated on or before
|
||||
the child's date; needs a decision on the rule and its time window.
|
||||
- Which printed date counts as a cytology's sampling date is a per-source
|
||||
mapping choice (request or reception date), not code.
|
||||
- `documents.group_by` takes the source's own columns (or rules over
|
||||
them), not values read from the documents.
|
||||
- A user query starting with `WITH` can't be wrapped as a derived table on
|
||||
SQL Server (`connectors/sql.py::_text_subquery`).
|
||||
- Compose ports and the `ng serve` proxy target are fixed in
|
||||
`docker-compose.yml` and `WebApp/proxy.conf.json`; neither reads an env
|
||||
var yet.
|
||||
- The template-line rule (`Extraction/extraction/template.py`) needs at
|
||||
least two patients' documents in one batch; a single document still
|
||||
reads its letterhead.
|
||||
- Branch alignment, as of 2026-11-13: `dev` was pushed in all six repos
|
||||
and contains `staging` and `main` everywhere, except that
|
||||
`WorkingNarrative`'s `main` keeps one merge commit with identical content.
|
||||
`staging` and `main` are behind `dev` until the next promotion. SSH to
|
||||
Gitea refuses the local key; pushes went over HTTP with the API token.
|
||||
- Notebooks run in the `notebooks` container (no network, read-only system,
|
||||
uid 10001, no capabilities, only the jobs volume), and what they train is
|
||||
imported by trusted code (`models.io.notebook_import`). Still open:
|
||||
- The app has no login, so anyone who reaches it can upload a notebook,
|
||||
and its page (which may print cohort rows) is readable by anyone.
|
||||
- The container was validated with `docker compose config` and tested as a
|
||||
separate process, not yet started as a real container.
|
||||
- Local development (`NOTEBOOK_EXECUTOR=local`, the default without
|
||||
`NOTEBOOK_JOBS_DIR`) runs notebooks unisolated in the API's process; runs
|
||||
say so (`sandbox: local`, "Sin aislar" in the WebApp).
|
||||
- A WebApi worker that restarts while waiting leaves its run "en curso"
|
||||
until it shows as "interrumpido" (job timeout + 30 min) and its job
|
||||
folder behind; nothing picks the result up again.
|
||||
- A version registered over `POST /governance/model-versions` has no routine
|
||||
records or saved model, so it fails ML-01a/ML-01b and can't be promoted;
|
||||
production versions come only from training code in `models`.
|
||||
- ML-01b is met by downloading a run's files; there is no portable model
|
||||
export (ONNX support was removed 2026-11-13 as unused).
|
||||
- The notebook tab needs exported cohort builds on the server
|
||||
(`python -m models cohorts export ...`), and the WebApi image must be
|
||||
rebuilt to get the Jupyter libraries (`models[notebooks]`).
|
||||
- `cin2_logistic`'s routine records (`model.py`) are the only real ones;
|
||||
any new model has to add its own five, or it can't be promoted.
|
||||
|
||||
### TEA redesign (#163, branch `feature/163-tea-redesign` off `refactor/kit-exit`), 2026-11-12
|
||||
|
||||
Left open by the implementation of `plans/kit-exit/tea-redesign.md` (all but the WebApp):
|
||||
|
||||
- §12.6 not done: CaCu's risk as `RiskAssessment`, imports as `transaction` Bundles with `AuditEvent` and
|
||||
`Provenance`, OCR jobs as `Task`, and CaCu's follow-up list as `EpisodeOfCare`. The old routes stay; removing
|
||||
them, and `/<domain>/indicadores`, needs the owner (§12.9).
|
||||
- §12.2: suppression (`data-absent-reason: masked`) and confidence intervals wait for #73.
|
||||
- The new Alembic revision (`f2b6d1e8c934`) was checked upgrade/downgrade/upgrade on SQLite only; MySQL,
|
||||
PostgreSQL and SQL Server untested (rule 7). `dbt build --select tea` passed on SQLite only; the SQL Server 2016
|
||||
VM and `e2e/sqlserver2016` (piece 11 of `tea-port.md`) not run. `tea_meses_cumplidos` has a separate `floor` path
|
||||
for the other engines, untested there.
|
||||
- Assumptions to confirm: the metric references live in dbt's var `tea` (an ephemeral model), not a seed, because
|
||||
the cycle doesn't run `dbt seed`; effect texts and electrode positions are in `WebApi/webapi/fhir/tea_eeg.toml`.
|
||||
An EEG without any criterion written is `SIN_ANALIZAR`, a third category of M29 (the §10 question). M25's units are
|
||||
all the period's children, its event the first F84.0 note. M29 counts the cohort's children only. ADOS-2 items are
|
||||
the 28 of the old staging (the plan says 29 but its own total of 76 columns has 28); labels of B13 to B18 and D5
|
||||
wait for the manuals. Codes are the project's: no LOINC or SNOMED until confirmed (§12.9).
|
||||
- `fhir.resources` (8.3, R4B models) added to WebApi's dev group to validate responses in tests: needs the owner's
|
||||
approval as a new dependency (§12.9).
|
||||
- Patient routes (`EpisodeOfCare`, `$resumen-tea`) are registered only in DEV with the `simulado` tag; alterations
|
||||
stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`.
|
||||
|
||||
### Kit exit integrated on `dev` (branch `feature/kit-exit-integration`), 2026-11-15
|
||||
|
||||
Left open by bringing `feature/163-source-terminology`, `feature/163-tea-redesign` and the CaMa dashboard's
|
||||
presentation onto one branch:
|
||||
|
||||
- `cat_mapeo` is seeded by the `catalogs` step but no load reads it yet: the CaMa silver load still takes captions
|
||||
and aliases from the catalog's TOML (`webapi/orchestration/reference/catalogs.py`); the remap step, the mappings
|
||||
screens and the `ConceptMap` endpoint of G-GEN-1 are not built.
|
||||
- The follow-up list exists for CaCu only (`webapi/follow_up/`); the CaMa follow-up tab shows the unavailable state
|
||||
until a CaMa list is served. Angel's CaMa follow-up and Análisis endpoints (`dashboard-test`) read the kit and a
|
||||
synthetic reader, so they were not merged.
|
||||
- The three CaMa measures Angel added to the kit (`deteccion_histopatologica`, `dias_resultado_diagnostico`,
|
||||
`histopatologia_birads`, #161) were not ported; the dbt CaMa measures and the invasive-cancer stratifiers are what
|
||||
the page draws. Re-expressing them in dbt is a separate task.
|
||||
- `feature/cacu-pim-vigilancia` (models as a Hamilton dataflow, the CIN2+ prevalence-incidence scenario) is
|
||||
deferred: it predates the cohort move into `models/cohorts` and needs rebasing on the new `dev`.
|
||||
- The webapi image compiles dbt's manifest for SQLite at build time and, on another engine, at start-up against the
|
||||
configured databases (`webapi.dbt_manifest`); the start-up path was not exercised against a real MySQL,
|
||||
PostgreSQL or SQL Server here, and Docker was unavailable on the machine that built the branch.
|
||||
- TEA's alterations stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`; `fhir.resources` in the WebApi's dev group
|
||||
still needs the owner's word; suppression and intervals are #73's.
|
||||
- A risk batch stays `preliminary` until `python -m webapi.orchestration confirm-risks`; the risk route serves
|
||||
only final batches.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# What is promised, what we have, what is missing
|
||||
|
||||
Checked on 2026-11-13 against `Alcance_proyecto.pdf` (modules and the
|
||||
deliverables list) and `docs_desarrollo-2.pdf` (requirement IDs), reading
|
||||
the code rather than the notes. Hand-off is 2026-11-30. Status: **done**,
|
||||
**partial** or **missing**. Items that depend on the client's data or
|
||||
clinical decisions say so; they need negotiating, not just code.
|
||||
|
||||
## Contract deliverables
|
||||
|
||||
| Deliverable | Status | What exists / what is missing |
|
||||
|---|---|---|
|
||||
| Structured, integrated, cleaned database apart from the source systems | **done** | Four engine-agnostic databases (CaCu, CaMa, TEA, governance), versioned cohort builds. |
|
||||
| Data integration layer through web services (APIs) | **done** | "Conectar datos": SQL, Excel/CSV, PDF tables, clinical documents, EEG, documents stored in columns; validation, merge, import log. |
|
||||
| NLP modules | **partial** | Field extraction from forms and free text: captions and layout, ConText/NegEx assertions, sections, anchors, severity, measurements, OCR tolerance, subject check, review dialog; a learned candidate ranker that learns from review corrections (`<domain>-extraccion`); `python -m webapi.nlp evaluate/train`. Missing: a held-out evaluation set; EEG, mammography and breast biopsy vocabulary tested on real reports; colposcopy (Reid, Swede) has no columns. |
|
||||
| Breast cancer (CaMa) risk model | **missing** | `models/cama` holds only its package docstring. Needs data and outcome definition from the client. |
|
||||
| TEA diagnostic model from EEG alterations | **missing** | EDF files are read and validated (amendment done) and the report's EEG findings can be extracted; no signal features, no model. Needs data. |
|
||||
| CaCu progression risk model | **done (one scenario)** | `cin2_logistic`: routines recorded, estimate, risks stored with model provenance. Risk cut-offs (immediate / priority / scheduled) undefined, so the risk-band indicator is hidden. |
|
||||
| CaCu survival model (OS/DFS, Kaplan-Meier at 1/3/5 years) | **missing** | Only a draft survival chart contract in the indicators kit. Needs follow-up and death data. |
|
||||
| Interactive dashboards with each module's indicators | **partial** | Indicator pages per domain; no PDF/XLS export of indicators (only the import log downloads), no heatmap, no single combined view. |
|
||||
| User manual | **partial** | `dist/MANUAL.md` covers installation, operation and the import flow; not every screen. |
|
||||
| Technical manual | **partial** | Preliminary design specification PDF, package READMEs (`Extraction/README.md` documents the NLP method and references), architecture notes; no final consolidated document. |
|
||||
| Project closure letter | n/a | Administrative. |
|
||||
|
||||
## Modules
|
||||
|
||||
| Module | Status | Notes |
|
||||
|---|---|---|
|
||||
| M00 Configuración: login, 2FA, password change, lockout, access, profiles, users | **missing** | No authentication at all; the biggest security gap (anyone who reaches the app can import data and run notebooks). |
|
||||
| M00 Parametrización, catálogos generales | **partial** | Catalogs and parameters exist as versioned files (`core/catalogos/*.toml`, `parametros.toml`); no screens to edit them. |
|
||||
| M01 CaMa: BI-RADS indicators | **done** | BI-RADS 4/5, confirmation, biopsies, time to diagnosis. |
|
||||
| M01 CaMa: risk calculator, heatmap, PDF/XLS reports, individual profiles, model | **missing** | Risk band only as a proposal. |
|
||||
| M01 CaMa: mammogram images | **partial** | Images embedded in reports are located and stored; no DICOM connector. |
|
||||
| M02 TEA: % with/without EEG, evaluation, confirmation, screening-to-diagnosis | **done** | |
|
||||
| M02 TEA: % normal vs abnormal EEG, correlation with severity | **missing** | The extraction to fill `eeg_anormalidad_presente` and the conclusion category now exists; the indicators don't. |
|
||||
| M02 TEA: EEG model | **missing** | |
|
||||
| M03 CaCu: cytology distribution, histopathology confirmation, screening-to-diagnosis time, risk model | **done** | |
|
||||
| M03 CaCu: diagnosis-to-treatment time, survival, cut-offs, incidence/prevalence against state data, individual profiles | **missing** | |
|
||||
| M04 Integrated dashboard with PDF/XLS | **partial** | Per-domain pages only. |
|
||||
|
||||
## Requirements document
|
||||
|
||||
| IDs | Status | Notes |
|
||||
|---|---|---|
|
||||
| VAR-01..03, VARM-01..04a | **done** | OCR with confidence, status, main and alternative method, review flag. |
|
||||
| VAR-04, VARM-05 (document the extraction method) | **done** | `Extraction/README.md`: method and references; the evaluation command. A held-out score is still missing. |
|
||||
| VAR-07, VAR-08, VAR-09 | **done** | Transformation descriptions, source and dates at load, results persisted. |
|
||||
| IND-01..03 | **done** | |
|
||||
| EL-01..07 | **done** | Versioned builds with hash, per-criterion exclusion counts. |
|
||||
| ML-01a, ML-01b | **done** | Five routine records written by training; run files downloadable. |
|
||||
| ML-02, ML-03 | **done** | DEV/PROD tags; cohort link. The extraction ranker can't meet ML-03 (no cohort), so it can't be promoted: decision pending. |
|
||||
| ML-04, ML-05 | **done, unverified** | Read-only access; notebooks isolated in the `notebooks` container, never started as a real container. |
|
||||
| MLD-01, MLD-01b | **done** | Promotion checks for technical and clinical validation reports. |
|
||||
| MLD-03 (weights and OR/HR shown) | **partial** | Coefficients recorded in the METODO_ANALITICO routine; not shown on screen, the check only asks for a report link. |
|
||||
| MLD-4, MLD-5 | **done** | Estimates carry their version and are stored with it. |
|
||||
| TRIPOD 20b/20c | **partial** | EDA report covers part of it. |
|
||||
|
||||
## What code alone can still close before 2026-11-30
|
||||
|
||||
1. Minimal login, users and profiles (or a documented plan).
|
||||
2. PDF/XLS export of the indicator pages.
|
||||
3. Coefficients and OR on the model version screen (MLD-03).
|
||||
4. A user manual for every screen.
|
||||
5. Run the notebook container for real; rebuild the WebApi image.
|
||||
|
||||
Everything else on the missing list (CaMa and TEA models, survival, risk
|
||||
cut-offs, incidence against state data, a held-out NLP set) needs data or
|
||||
clinical decisions from the client and should be raised as a dependency.
|
||||
+4
-4
@@ -5,10 +5,10 @@ Moved from `AGENTS.md` §4 on 2026-11-03.
|
||||
```bash
|
||||
(cd Core && uv run pytest -q) # 18 (2 skip)
|
||||
(cd Persistance && uv run pytest -q) # 18 (1 skip)
|
||||
(cd Extraction && uv run pytest -q) # 31 (OCR tests need tesseract + spa data)
|
||||
(cd models && uv run pytest -q) # 41
|
||||
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 417 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
|
||||
(cd WebApp && npx ng test --watch=false && npx ng build) # 1235 (a few vendored indicadores specs time out under heavy load; pass alone)
|
||||
(cd Extraction && uv run pytest -q) # 83 (OCR tests need tesseract + spa and osd data)
|
||||
(cd models && uv run pytest -q) # 180 (real Jupyter kernels and a runner process in tests/pipelines/test_experiment.py)
|
||||
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 497 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
|
||||
(cd WebApp && npx ng test --watch=false && npx ng build) # 1248 (a few specs, mostly indicadores, time out under heavy load; pass alone)
|
||||
```
|
||||
|
||||
If a package's `.venv` has stale absolute paths baked into its entry-point
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# TEA FHIR synthetic browser check
|
||||
|
||||
Run from a WorkingNarrative checkout whose ISSSTELEON and WebApp gitlinks include the local TEA changes. The script creates a temporary SQLite database from `WebApi/tests/staging/tea.py`; it never imports production data. `DEV_REVISION` enables the simulated patient routes. It serves the Angular build and the real Flask API on a temporary loopback port and closes them after the check.
|
||||
|
||||
Prerequisites: Python 3.12, uv, Node and npm, a Chromium-compatible browser, and Playwright available to Node. Install the WebApi dev dependencies and build WebApp. Generate the dbt manifest from this exact Transformation tree:
|
||||
|
||||
```sh
|
||||
cd ISSSTELEON/Transformation
|
||||
uv run dbt compile --profiles-dir . --profile tea
|
||||
cd ../WebApi
|
||||
uv sync --locked
|
||||
cd ../WebApp
|
||||
npm ci
|
||||
npm run build
|
||||
cd ../..
|
||||
```
|
||||
|
||||
Set `PLAYWRIGHT_PATH` to the installed Playwright module and `BROWSER_PATH` to the browser executable when the defaults in `verify.cjs` do not exist. Then run:
|
||||
|
||||
```sh
|
||||
ISSSTELEON/WebApi/.venv/bin/python e2e/tea-fhir/serve_and_verify.py
|
||||
```
|
||||
|
||||
On Windows use `ISSSTELEON\WebApi\.venv\Scripts\python.exe`. The harness supplies a Windows-only `fcntl` stub that raises if locking is used; it does not verify lock behaviour. `DBT_MANIFEST` is set to `Transformation/target/manifest.json` in the harness before Flask starts. For the API outside the harness, the file must be available inside the API environment at the path set in `DBT_MANIFEST`, and the cycle must create the definitions and event views in the domain database. Migrations alone do not do this. The WebApi image compiles the manifest from `Transformation` while it builds and sets `DBT_MANIFEST` to it (SQLite's SQL); the `indicadores` service runs the cycle after each import.
|
||||
|
||||
The browser check covers M28, history, filters, paging, the patient's identity, ADOS-2 and EEG, returning with focus, a partial record and a simulated FHIR 404. Patient selection races and absent/masked values are covered by the focused Angular tests. No EEG alteration validation switch is enabled.
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
api = root / 'ISSSTELEON' / 'WebApi'
|
||||
sys.path[:0] = [str(api), str(api / 'tests')]
|
||||
if os.name == 'nt':
|
||||
fcntl = types.ModuleType('fcntl')
|
||||
def unavailable(*args):
|
||||
raise RuntimeError('fcntl locking is unavailable in this Windows test')
|
||||
fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_UN = unavailable, 2, 8
|
||||
sys.modules['fcntl'] = fcntl
|
||||
os.environ['DEV_REVISION'] = 'pruebas'
|
||||
os.environ['DBT_MANIFEST'] = str(root / 'ISSSTELEON' / 'Transformation' / 'target' / 'manifest.json')
|
||||
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
|
||||
|
||||
from conftest import base_de
|
||||
from flask import send_from_directory
|
||||
from werkzeug.serving import make_server
|
||||
from webapi import create_app
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='tea-e2e-') as directory:
|
||||
base = base_de('tea', Path(directory))
|
||||
base.run('catalogs', 'load', 'views', 'registry', 'definitions', 'event_models', allow_undecided=True)
|
||||
app = create_app()
|
||||
static = root / 'ISSSTELEON' / 'WebApp' / 'dist' / 'WebApp' / 'browser'
|
||||
@app.get('/indicadores/tea')
|
||||
def page():
|
||||
return send_from_directory(static, 'index.html')
|
||||
@app.get('/<path:filename>')
|
||||
def assets(filename):
|
||||
return send_from_directory(static, filename)
|
||||
server = make_server('127.0.0.1', 0, app)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
subprocess.run(['node', str(root / 'e2e' / 'tea-fhir' / 'verify.cjs'), str(server.server_port)], check=True, timeout=90)
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
base.motor.dispose()
|
||||
from persistance.db import get_tea_engine
|
||||
get_tea_engine().dispose()
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_PATH || 'C:/Users/angel/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ executablePath: process.env.BROWSER_PATH || 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
const root = `http://127.0.0.1:${process.argv[2]}`;
|
||||
await page.goto(`${root}/indicadores/tea`);
|
||||
const m28 = page.locator('article').filter({ has: page.getByRole('heading', { name: 'Casos por estatus' }) });
|
||||
await m28.getByText('6', { exact: true }).waitFor();
|
||||
for (const [name, count] of [['Solo M-CHAT','2'], ['Hasta evaluación psicológica','1'], ['Hasta evaluación neuropediátrica','1'], ['Con EEG','2']]) {
|
||||
const row = m28.locator('dl div').filter({ hasText: name });
|
||||
if (await row.locator('dd').innerText() !== count) throw new Error(`M28 ${name}`);
|
||||
}
|
||||
console.log('M28: 6 casos y cuatro etapas');
|
||||
await page.getByRole('button', { name: 'Histórico' }).click();
|
||||
await page.getByRole('heading', { name: 'Casos por estatus' }).first().waitFor();
|
||||
if (await page.locator('article').count() !== 3) throw new Error('Histórico no devolvió tres periodos');
|
||||
await page.getByRole('button', { name: 'Seguimiento', exact: true }).click();
|
||||
await page.getByLabel('Fecha de corte').fill('2025-12-31');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('6 episodios', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Siguiente' }).click();
|
||||
await page.getByText('Página 2', { exact: true }).waitFor();
|
||||
if (await page.locator('tbody tr').count() !== 1) throw new Error('Paginación incorrecta');
|
||||
await page.getByRole('button', { name: 'Anterior' }).click();
|
||||
await page.getByText('Página 1', { exact: true }).waitFor();
|
||||
await page.getByLabel('Edad al M-CHAT').selectOption('16_23');
|
||||
await page.locator('select[name=status]').selectOption('finished');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('1 episodios', { exact: true }).waitFor();
|
||||
const button = page.getByRole('button', { name: 'Abrir ficha' });
|
||||
const patient = await button.getAttribute('data-patient');
|
||||
await button.click();
|
||||
await page.getByRole('heading', { name: 'Ficha del paciente' }).waitFor();
|
||||
await page.getByLabel('Ficha del paciente').getByText(patient, { exact: true }).waitFor();
|
||||
await page.getByText('Fecha: 2025-05-20').waitFor();
|
||||
await page.getByText('Calidad: Buena').waitFor();
|
||||
await page.getByText('Puntaje de severidad (CSS)', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
|
||||
if (await page.getByLabel('Edad al M-CHAT').inputValue() !== '16_23') throw new Error('Filtro perdido');
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute('data-patient') !== null);
|
||||
console.log('Histórico, filtros, paginación, ficha correcta y retorno con foco');
|
||||
await page.locator('select[name=status]').selectOption('active');
|
||||
await page.getByLabel('Edad al M-CHAT').selectOption('');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('4 episodios', { exact: true }).waitFor();
|
||||
const ids = await page.locator('button[data-patient]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-patient')));
|
||||
let partial = null;
|
||||
for (const id of ids) {
|
||||
const res = await page.request.get(`${root}/tea/fhir/Patient/${id}/$resumen-tea`);
|
||||
const body = await res.json();
|
||||
if (!body.entry.some(e => e.resource.resourceType === 'DiagnosticReport')) { partial = id; break; }
|
||||
}
|
||||
if (!partial) throw new Error('No se encontró ficha parcial');
|
||||
await page.locator(`button[data-patient="${partial}"]`).click();
|
||||
await page.getByText('Sin información de EEG.').waitFor();
|
||||
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
|
||||
await page.locator('input[name=cssMin]').fill('100');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('No hay episodios para la selección.').waitFor();
|
||||
await page.locator('input[name=cssMin]').fill('');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('4 episodios', { exact: true }).waitFor();
|
||||
await page.route('**/tea/fhir/Patient/*/$resumen-tea', route => route.fulfill({ status: 404, contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'OperationOutcome', issue: [{ code: 'not-found', diagnostics: 'Paciente no encontrado' }] }) }));
|
||||
await page.locator(`button[data-patient="${partial}"]`).click();
|
||||
await page.getByRole('alert').getByText('Paciente no encontrado').waitFor();
|
||||
console.log('Ficha parcial y OperationOutcome 404');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error); process.exit(1); });
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# Settings for the manual deployment (docker-compose.yml in this folder). Docker
|
||||
# Compose reads it for the values below, and the webapi and indicadores
|
||||
# containers receive it as their environment.
|
||||
|
||||
# --- Project ---
|
||||
# Prefix of every container, network, volume and image. Change it (and the
|
||||
# ports) to run a second copy next to this one.
|
||||
COMPOSE_PROJECT_NAME=isssteleon-manual
|
||||
|
||||
# --- Published ports ---
|
||||
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
|
||||
# machine only.
|
||||
BIND_ADDRESS=0.0.0.0
|
||||
# The application (nginx: pages and proxy to the API). Open this one.
|
||||
WEBAPP_PORT=5210
|
||||
# The API, direct.
|
||||
WEBAPI_PORT=5211
|
||||
# The simulated hospital's MySQL (user/password hospital/hospital).
|
||||
HOSPITAL_PORT=5212
|
||||
|
||||
# --- Simulated hospital contents ---
|
||||
# Patients generated per project, the generator's seed and reference date.
|
||||
N=200
|
||||
N_CACU=300
|
||||
N_CAMA=300
|
||||
SEMILLA=7
|
||||
REFERENCIA=2026-01-01
|
||||
TEA_ALTERACIONES_VALIDADAS=1
|
||||
|
||||
# --- Patient-level views ---
|
||||
# Any value turns on the routes that return one patient's data (the follow-up
|
||||
# lists, TEA's patient summary). They exist for simulated data only: leave it
|
||||
# unset on a platform that holds real patients.
|
||||
DEV_REVISION=manual-deploy
|
||||
|
||||
# --- Platform (same variables as ISSSTELEON/.env.example) ---
|
||||
# Target databases. Unset, each is a SQLite file in this project's
|
||||
# webapi_data volume.
|
||||
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
|
||||
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
|
||||
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
|
||||
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
|
||||
# WEBAPI_MAX_UPLOAD_MB=200
|
||||
# WEBAPI_WORKERS=2
|
||||
# WEBAPI_TIMEOUT=600
|
||||
# EXTRACTION_OCR_LANG=spa+eng
|
||||
@@ -0,0 +1 @@
|
||||
documentos/
|
||||
@@ -0,0 +1,134 @@
|
||||
# Manual deployment
|
||||
|
||||
The whole platform plus the simulated hospital in one Compose project, built
|
||||
from the two checkouts next to this folder (`../ISSSTELEON` and `../dev-data`).
|
||||
Everything here is simulated data.
|
||||
|
||||
Run every command from this folder.
|
||||
|
||||
## What it starts
|
||||
|
||||
| Service | What it is | Published on |
|
||||
|---|---|---|
|
||||
| `webapp` | the Angular app behind nginx, which also proxies the API | `WEBAPP_PORT` |
|
||||
| `webapi`, `indicadores` | the Flask API and the indicator recomputation | `WEBAPI_PORT` |
|
||||
| `hospital` | MySQL playing the hospital system (`hospital`, `hospital_cacu`, `hospital_cama`) | `HOSPITAL_PORT` |
|
||||
| `poblar`, `poblar-cacu`, `poblar-cama` | one-shot jobs that generate the hospital's data on `up` | |
|
||||
| `load` | one-shot job that imports the hospital into the platform | |
|
||||
| `documentos` | one-shot job that writes the test PDFs | |
|
||||
|
||||
Ports, bind address and project name come from `.env`. Change
|
||||
`COMPOSE_PROJECT_NAME` and the three ports to run a second copy on the same
|
||||
machine.
|
||||
|
||||
## Bring it up and load it
|
||||
|
||||
```sh
|
||||
docker compose up --build -d # platform and hospital; the hospital is populated
|
||||
docker compose run --rm --build load # import the hospital into the platform
|
||||
```
|
||||
|
||||
`load` prints one line per table (`leídas, nuevas, actualizadas, rechazadas`);
|
||||
every `rechazadas` should be 0. It needs an empty platform: the hospital's ids
|
||||
travel with the rows, so a second load is refused without writing anything.
|
||||
To load again, run `docker compose down -v` first.
|
||||
|
||||
```sh
|
||||
docker compose down # stop, keep the data
|
||||
docker compose down -v # stop and delete this project's data
|
||||
```
|
||||
|
||||
## Indicators
|
||||
|
||||
The measures are defined in dbt (`../ISSSTELEON/Transformation`). The `webapi`
|
||||
image compiles them into a manifest while it builds and sets `DBT_MANIFEST` to
|
||||
it; without that variable the API has no measure routes and the pages answer
|
||||
"No fue posible cargar los indicadores". Check it with:
|
||||
|
||||
```sh
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5210/tea/fhir/Measure # 200
|
||||
```
|
||||
|
||||
After `load`, the `indicadores` service recomputes each project on its own
|
||||
(it polls every 20 seconds, and a project takes from seconds to a few
|
||||
minutes). Until it finishes, the pages have no figures. Its state per project:
|
||||
|
||||
```sh
|
||||
curl -s http://localhost:5210/reportes/indicadores # "estado": "ok" when done
|
||||
docker compose logs -f indicadores
|
||||
```
|
||||
|
||||
A platform that was loaded before the image had the manifest keeps its data
|
||||
but has nothing computed. Rebuild and ask for the recomputation, once per
|
||||
project:
|
||||
|
||||
```sh
|
||||
docker compose up --build -d
|
||||
for p in cacu cama tea; do curl -s -X POST "http://localhost:5210/$p/fhir/Measure/\$recalcular"; done
|
||||
```
|
||||
|
||||
Things to know:
|
||||
|
||||
- **The manifest's SQL is SQLite's**, the default engine here. With
|
||||
`*_DATABASE_URL` on another engine, compile the manifest with that dbt
|
||||
target (`../ISSSTELEON/Transformation/profiles.yml`), mount it in `webapi`
|
||||
and `indicadores`, and set `DBT_MANIFEST` to its path.
|
||||
- **Patient-level pages need `DEV_REVISION`** (set in `.env`): the follow-up
|
||||
lists and TEA's patient summary are served only with it, because they are
|
||||
meant for simulated data.
|
||||
- **A change in `Transformation` needs a rebuild** (`up --build -d`) and a
|
||||
recomputation, as above.
|
||||
|
||||
## Generate the test documents
|
||||
|
||||
```sh
|
||||
docker compose run --rm --build documentos
|
||||
```
|
||||
|
||||
It writes PDFs of the same patients the hospital holds into `./documentos`
|
||||
(ignored by git). It doesn't need the platform or the hospital to be up: the
|
||||
documents come from the same generator, seed (`SEMILLA`) and reference date
|
||||
(`REFERENCIA`) as the hospital's rows, so a patient key in a PDF is a patient
|
||||
key in the hospital.
|
||||
|
||||
| Folder | Documents | How many |
|
||||
|---|---|---|
|
||||
| `documentos/cacu/` | CaCu records, one per cytology (`CACU-0002-C1`), 3 to 7 pages: order, cover, cytology form and, when the history has them, HPV result, colposcopy note, pathology report and the note that resolves the cytology | the first `N_DOCUMENTOS_CACU` patients (20) |
|
||||
| `documentos/tea/` | the ADOS-2 score summary of the psychological evaluation, one page per child with module 1, 2 or 3 (`N-0001-ADOS2`) | all `N` children (200) |
|
||||
|
||||
Each record has its own folder:
|
||||
|
||||
- CaCu: `<key>_limpio.pdf` (text), `<key>_escaneado.pdf` (every page an
|
||||
image, no text layer, to exercise OCR), the page images and field masks,
|
||||
and `ground_truth.json` / `.csv` with each field's value and its box in
|
||||
both PDFs.
|
||||
- TEA: `<key>.pdf` with selectable text, not scanned, and its `ground_truth`.
|
||||
|
||||
`indice.json` in each folder lists the records.
|
||||
|
||||
Things to know:
|
||||
|
||||
- **CaCu is heavy by design.** Every page is rasterised and degraded: 12
|
||||
patients took 28 seconds and 35 MB for 76 pages on the development machine.
|
||||
Twenty patients give around 30 records; all 300 give 442 records and 1,800
|
||||
pages, so expect several minutes and close to 1 GB. Raise it for one run
|
||||
with `N_DOCUMENTOS_CACU=300 docker compose run --rm --build documentos`.
|
||||
- **Module 3 is rare.** With seed 7 the first child with ADOS-2 module 3 is
|
||||
number 247, so a hospital of 200 children has none. To see one, generate
|
||||
with `N=250` or more; those documents have no row in a 200-child hospital.
|
||||
- **What matches the hospital.** Patient key, dates, cytology and HPV results,
|
||||
biopsy grade, ICD-10 codes and each ADOS-2 item score are the hospital's.
|
||||
Names, doctors, vital signs and the wording of notes exist only in the
|
||||
documents. The ADOS-2 totals add only the items of the child's module; the
|
||||
platform adds every item the hospital row has, so its totals can be higher.
|
||||
- **The files belong to root**, because the container writes them. Delete the
|
||||
folder with `sudo rm -rf documentos`.
|
||||
- Nothing here loads these PDFs into the platform; `load` only imports the
|
||||
hospital's tables.
|
||||
|
||||
The same documents without Docker, from `../dev-data`:
|
||||
|
||||
```sh
|
||||
uv run python -m dev_data documentos cacu --referencia 2026-01-01 --salida datos/expedientes
|
||||
uv run python -m dev_data documentos tea --referencia 2026-01-01 --salida datos/ados2
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
# Manual deployment of the whole platform plus the simulated hospital, built
|
||||
# from the two checkouts next to this folder (../ISSSTELEON and ../dev-data).
|
||||
# Ports, bind address and project name come from .env, so several copies can
|
||||
# run on one machine without touching each other or the other deployments.
|
||||
#
|
||||
# docker compose up --build -d # platform + hospital, hospital populated
|
||||
# docker compose run --rm --build load # import the hospital into the platform
|
||||
# docker compose run --rm --build documentos # write the test PDFs to ./documentos
|
||||
# docker compose down # stop, keep the data
|
||||
# docker compose down -v # stop and delete this project's data
|
||||
#
|
||||
# Run from this folder. `load` needs an empty platform: the hospital's ids
|
||||
# travel with the rows, so a second load is refused without writing anything.
|
||||
# To load again, `down -v` first. README.md has the whole walkthrough.
|
||||
include:
|
||||
- path:
|
||||
- ../ISSSTELEON/docker-compose.yml
|
||||
- platform.override.yml
|
||||
project_directory: ../ISSSTELEON
|
||||
env_file: .env
|
||||
- path:
|
||||
- ../dev-data/compose.prueba.yml
|
||||
- hospital.override.yml
|
||||
project_directory: ../dev-data
|
||||
env_file: .env
|
||||
|
||||
services:
|
||||
# One-shot: imports the three projects through the platform's import API.
|
||||
# Inside the project network the API is the webapp proxy and the hospital
|
||||
# is reached by service name, as the webapi container sees it.
|
||||
load:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: dev-data/Dockerfile
|
||||
profiles: [load]
|
||||
depends_on:
|
||||
webapi:
|
||||
condition: service_healthy
|
||||
webapp:
|
||||
condition: service_started
|
||||
poblar:
|
||||
condition: service_completed_successfully
|
||||
poblar-cacu:
|
||||
condition: service_completed_successfully
|
||||
poblar-cama:
|
||||
condition: service_completed_successfully
|
||||
entrypoint: ["sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
for pair in cacu:hospital_cacu cama:hospital_cama tea:hospital; do
|
||||
project="$${pair%%:*}"
|
||||
database="$${pair#*:}"
|
||||
echo "== $$project"
|
||||
uv run --frozen --no-dev python -m dev_data cargar "$$project" \
|
||||
--api http://webapp \
|
||||
--hospital "mysql+pymysql://hospital:hospital@hospital:3306/$$database"
|
||||
done
|
||||
|
||||
# One-shot: writes the test PDFs of the same patients the hospital holds
|
||||
# (same seed and reference date) into ./documentos. It needs neither the
|
||||
# platform nor the hospital. CaCu pages are rasterised and degraded, which
|
||||
# is slow and large, so its count is separate from the hospital's.
|
||||
documentos:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: dev-data/Dockerfile
|
||||
profiles: [documentos]
|
||||
volumes:
|
||||
- ./documentos:/documentos
|
||||
entrypoint: ["sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
uv run --frozen --no-dev python -m dev_data documentos cacu \
|
||||
--n "${N_DOCUMENTOS_CACU:-20}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
|
||||
--salida /documentos/cacu
|
||||
uv run --frozen --no-dev python -m dev_data documentos tea \
|
||||
--n "${N:-200}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
|
||||
--salida /documentos/tea
|
||||
@@ -0,0 +1,16 @@
|
||||
# Applied over ../dev-data/compose.prueba.yml. The platform reaches the
|
||||
# hospital by service name; the published port is only for inspecting it
|
||||
# from outside with a MySQL client.
|
||||
services:
|
||||
hospital:
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${HOSPITAL_PORT:-29505}:3306"
|
||||
|
||||
# Without their profile the populate jobs run on every `up`. They leave a
|
||||
# hospital that already has rows alone.
|
||||
poblar:
|
||||
profiles: !reset []
|
||||
poblar-cacu:
|
||||
profiles: !reset []
|
||||
poblar-cama:
|
||||
profiles: !reset []
|
||||
@@ -0,0 +1,25 @@
|
||||
# Applied over ../ISSSTELEON/docker-compose.yml. Paths here resolve from
|
||||
# ../ISSSTELEON.
|
||||
#
|
||||
# Images are tagged per project so a build here doesn't replace the
|
||||
# isssteleon/*:dev images other deployments run. The containers read
|
||||
# manual-deploy/.env instead of ISSSTELEON/.env, so a .env left in the source
|
||||
# tree never points this stack at another deployment's databases.
|
||||
x-api: &api
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapi:local
|
||||
env_file: !override
|
||||
- ../manual-deploy/.env
|
||||
|
||||
services:
|
||||
webapi:
|
||||
<<: *api
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
|
||||
|
||||
indicadores:
|
||||
<<: *api
|
||||
|
||||
webapp:
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapp:local
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPP_PORT:-28080}:80"
|
||||
@@ -0,0 +1,306 @@
|
||||
# TEA redesign: what was added, and the state machines in the code
|
||||
|
||||
Implementation of `WorkingNarrative/plans/kit-exit/tea-redesign.md` (all but the WebApp), 2026-11-12.
|
||||
|
||||
- **Where:** `/home/admon/alberto/WorkingNarrative/ISSSTELEON`, branch `feature/163-tea-redesign` in ISSSTELEON,
|
||||
WebApi, models and indicadores_kit, cut from `refactor/kit-exit` (the plan builds on its dbt semantic layer and
|
||||
measure engine, which `dev` doesn't have). WebApp untouched.
|
||||
- **State:** nothing committed (AGENTS.md rule 1). Open items are recorded in
|
||||
`WorkingNarrative/docs/ledgers/open-items.md`, which is modified in the outer repo, on `main`.
|
||||
- **Size:** ISSSTELEON 13 files changed (+528 −1385) plus 30 new; WebApi 37 changed (+475 −793) plus 18 new;
|
||||
models 2; indicadores_kit 2.
|
||||
|
||||
---
|
||||
|
||||
## 1. Additions and changes, by layer
|
||||
|
||||
### 1.1 Bronze: TEA staging (Core, Persistance)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `Core/core/tea/models.py` | Rewritten: 8 tables instead of 10, 76 columns instead of 275. `pacientes`, `ordenes_estudio`, `mchat`, `ados2` (28 items, constant `ADOS2_ITEMS`), `evaluacion_neuropediatrica`, `eeg` (EDF, channels, duration, sleep, 5 quality criteria), `eeg_metrica`, `eeg_metrica_electrodo` |
|
||||
| `Core/core/tea/enums.py` | Trimmed to `TipoEstudio` (ADOS2, NEUROPEDIATRIA, EEG) with aliases, `ModuloAdos2`, `ClasificacionAdos2` with aliases, `MetricaEeg`, `ELECTRODOS_10_20` |
|
||||
| `Core/spec/tablas_TEA.md` | Data dictionary rewritten for the 8 tables (Spanish, as before) |
|
||||
| `Core/core/catalogos/tea.toml` | Rewritten: studies `mchat`, `ados2` (module, algorithm, CSS, classification, 28 items with labels), `evaluacion_neuropediatrica` (ICD-10), `eeg` (sleep, channels, duration, 5 criteria, 5 metrics), `orden` |
|
||||
| `Core/tests/test_models.py` | TEA's table set |
|
||||
| `Persistance/persistance/tea/alembic/versions/f2b6d1e8c934_tea_staging_by_study.py` | **New revision** after the baseline: creates the 6 new tables, drops the 8 old ones, drops the unused columns of `pacientes` and `ordenes_estudio` (keeping their rows) and maps the old study codes to the new ones; downgrade restores everything with generic types. Round trip checked on SQLite; `alembic check` clean |
|
||||
| `Persistance/persistance/tea/__init__.py` | Repositories for the 8 tables |
|
||||
| `Persistance/persistance/edges/silver/procedures.py` | An observation whose procedure isn't in silver is skipped and counted (it used to raise `KeyError`) |
|
||||
| `Persistance/persistance/edges/gold/history.py` | `group_counts`: a stored answer's units per group (for M30) |
|
||||
|
||||
### 1.2 Import (WebApi)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/imports/schemas/tea/` | New: `mchat.py`, `ados2.py`, `evaluacion_neuropediatrica.py` (ICD-10 with or without the dot), `eeg.py`, `eeg_metrica.py`, `eeg_metrica_electrodo.py`. `pacientes.py` and `ordenes_estudio.py` rewritten. The 8 old schemas deleted |
|
||||
| `webapi/imports/schemas/coercion.py` | `Bounded(kind, low, high)`: numbers out of range are a validation error (M-CHAT 0–20, CSS 1–10, items 0–3, channels) |
|
||||
| `webapi/imports/schemas/registry.py` | TEA's 8 targets (`tea.Mchat`, `tea.Ados2`, `tea.EvaluacionNeuropediatrica`, `tea.Eeg`, `tea.EegMetrica`, `tea.EegMetricaElectrodo`, …) |
|
||||
| `webapi/imports/connectors/edf.py` | Shaped for `tea.Eeg`: lab id, patient, date, channels, duration and the file |
|
||||
|
||||
### 1.3 Silver (WebApi orchestration)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/orchestration/silver/tea.py` | **New**: TEA's `DESDE_STAGING`: order → `orden` of the study it asks for; M-CHAT → `toma`; ADOS-2 and note → `encuentro`; EEG → `toma`; metric → observation on its EEG's `toma`; electrode value → `parte` of the EEG |
|
||||
| `webapi/orchestration/silver/procedures.py` | Two generic additions to `DeStaging`: `juntas` (columns from another staging row by key, null-filled when missing) and `observa_en` (observations on another row's procedure); result templates can name content columns (`eeg.{metrica}`) |
|
||||
| `webapi/orchestration/tables/tea.py` | **New**: TEA's `TablasKit` and `COHORTES` |
|
||||
| `tables/__init__.py`, `orchestration/__main__.py`, `recomputation.py`, `webapi/__init__.py` | `tea` added to the domain lists; the KPI and FHIR blueprints registered for TEA |
|
||||
| `webapi/orchestration/reference/parametros.toml` | The 18 TEA keys of §7.2 removed; `tea.cohorte.ventanas` set to the page's windows (16–23, 24–29, 30–36) |
|
||||
|
||||
### 1.4 dbt (Transformation)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `dbt_project.yml` | Var `tea`: ages, `dias_por_mes`, `ventanas`, `cie_tea: [F840]`, `alteracion_z`, quality thresholds and the metric reference ranges (placeholders until validated) |
|
||||
| `macros/tea.sql` | **New**: `tea_meses_cumplidos` (per engine), `tea_grupo_edad`, `tea_criterio_bueno`, `tea_despues` (no `GREATEST` on SQL Server 2016) |
|
||||
| `models/tea/silver/tea_linea_de_tiempo.yml` | 29 sources → 5 (mchat, ados2, evaluacion_neuropediatrica, eeg, orden) |
|
||||
| `models/tea/silver/` (ephemeral, new) | `tea_mchat`, `tea_ados2`, `tea_ados2_reactivos`, `tea_neuropediatria`, `tea_eegs`, `tea_eeg_referencias`, `tea_eeg_metricas`, `tea_eeg_electrodos`, `tea_cohorte`, `tea_hitos` (each child's step dates and when they became known) |
|
||||
| `models/tea/gold/eventos/` (views, new) | `tea_pasos` (M28), `tea_diagnosticos` (M23, M24, M21, M22), `tea_casos` (M26, M27, M25), `tea_eegs_periodo` (M29), `tea_alteraciones` (M30), each with its semantic model and metrics |
|
||||
| `models/tea/gold/seguimiento/` (views, new) | `tea_seguimiento`, `tea_paciente_ados2`, `tea_paciente_eegs`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`, marked `lee_la_webapi` so the cycle creates them |
|
||||
|
||||
### 1.5 The ten measures
|
||||
|
||||
| Measure | Event model | Scoring | Construct |
|
||||
|---|---|---|---|
|
||||
| M28 `casos_por_estado` | `tea_pasos` | composition (C2) | status at the period's end |
|
||||
| M23 `pacientes_evaluados` | `tea_diagnosticos` | composition, admits CONFIRMADO and EN_PROCESO | status at the period's end |
|
||||
| M24 `confirmacion_diagnostico` | `tea_diagnosticos` | proportion with `denominator-exclusion` (SIN_TEA) | status + `grupo_edad` column stratum |
|
||||
| M21 / M22 `diagnosticados_con/sin_eeg` | `tea_diagnosticos` | proportion | status + EEG reached (or not) by the period's end + stratum |
|
||||
| M26 / M27 / M25 day counts | `tea_casos` | continuous variable | status; a value only if the interval ended by the period's end |
|
||||
| M29 `calidad_eeg` | `tea_eegs_periodo` | composition by exam | events in the period |
|
||||
| M30 `resultado_eeg` | `tea_alteraciones` | proportion + one group per alteration | several groups |
|
||||
|
||||
### 1.6 Measure engine (WebApi)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `webapi/metrics.py` | `StatusAtEnd` (`meta.poblacion`): each unit that entered by the period's end and hadn't left before its start, with its highest-order row dated by the end and known by the cut-offs; `ReachedByEnd` (`meta.al_fin`); column stratum (`tipo: columna`); `Group` (`meta.grupos`) answered one by one and stored by group; exclusion count (`meta.exclusion`); `meta` kept on the definition |
|
||||
| `webapi/compositions.py`, `webapi/durations.py` | Take `StatusAtEnd`; a duration's value must have ended before the period's end |
|
||||
| `webapi/orchestration/semantic_layer.py` | The publication catalog lists M30's groups and the exclusion population; the cycle creates the `lee_la_webapi` views |
|
||||
|
||||
### 1.7 FHIR R4 (WebApi, new package `webapi/fhir/`)
|
||||
|
||||
| File | What it serves |
|
||||
|---|---|
|
||||
| `common.py` | `application/fhir+json`, `OperationOutcome`, searchset with `self`/`next`/`previous`, `_count` (≤200) and `_offset`, the `simulado` tag, canonical URLs |
|
||||
| `measures.py` | `Measure` from each metric's meta (title, description, scoring, populations with their dbt metric, strata, period types, figures, category labels and colors); `MeasureReport` with an absolute canonical, `group.code`, codings, C2 as `cohort` with categories as a stratifier (`stratum.component` with strata), several groups, exclusion, durations with `measure-population-exclusion`. FHIR ids use `-` instead of `_` |
|
||||
| `terminology.py`, `tea_eeg.toml` | `CodeSystem`s: the domain's catalog, stages, diagnostic results, EEG quality, metrics with their effect texts, 10-20 electrodes, age groups; `ValueSet/tea-alteracion` |
|
||||
| `tea.py` | Seguimiento as `EpisodeOfCare` (+ `CarePlan`, `Patient`, M-CHAT, `Condition`, EEG `Procedure` + `DiagnosticReport` + quality observations); metric and electrode observations; ADOS-2 with components; the `$resumen-tea` collection |
|
||||
| `__init__.py` | `/<domain>/fhir/`: `metadata`, `Measure`, `Measure/<id>`, `$evaluate-measure`, `MeasureReport` search (`periodo`, or `tipo-periodo` + `period=ge/le`), `POST Measure/$recalcular`, `CodeSystem`; for TEA in DEV: `EpisodeOfCare` (filters `status`, `date`, `etapa`, `fecha-etapa`, `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; `_include`), `EpisodeOfCare/$resumen-eeg`, `Patient/<pseudonym>/$resumen-tea`, `ValueSet/tea-alteracion` |
|
||||
|
||||
- **Alterations:** hidden until `TEA_ALTERACIONES_VALIDADAS=1`. That covers M30, the alteration filter, the normal/abnormal split and the metric and electrode observations.
|
||||
- **Old routes:** `/<domain>/indicadores` stays as it is.
|
||||
|
||||
### 1.8 Tests (WebApi)
|
||||
|
||||
| File | What it covers |
|
||||
|---|---|
|
||||
| `tests/staging/tea.py` | **New** fixture: seven children, one per rule of the chain |
|
||||
| `tests/test_tea_measures.py` | **New**, 48 cases: the ten measures by month and semester, event and knowledge cut-offs, M30 read back from the history |
|
||||
| `tests/test_fhir_tea.py` | **New**, 19 cases: every response checked against FHIR models |
|
||||
| `tests/test_fhir_measures.py` | **New**: CaCu's and CaMa's measures in FHIR |
|
||||
| `conftest.py`, `test_orquestacion_*`, `test_imports_*`, `test_new_sources.py`, `test_schemas*.py`, `test_source_ids.py` | TEA added to the cycle tests and moved to the new tables |
|
||||
| `pyproject.toml`, `uv.lock` | `fhir.resources` 8.3 in the dev group (needs the owner's approval) |
|
||||
|
||||
Results:
|
||||
- WebApi: 404 passed, 10 failed (tesseract and the SQL Server driver are missing; the same 10 fail without these changes).
|
||||
- Core: 18 passed. Persistance: 48 passed.
|
||||
- `dbt build --select tea` passes on SQLite.
|
||||
|
||||
### 1.9 Removed
|
||||
|
||||
- `models/models/tea/` (empty stub).
|
||||
- `indicadores_kit/scripts/equivalencia_tea.py` (it imported kit code that no longer exists) and its README mentions.
|
||||
- The sentence in `models/cohorts/cama/screening.py` that cited the retired TEA cohort.
|
||||
- The 8 old TEA import schemas and the §7.2 parameters.
|
||||
|
||||
---
|
||||
|
||||
## 2. State machines, as the code implements them
|
||||
|
||||
Nothing stores a state: each state is derived from dated facts at a date. For the measures that date is the
|
||||
period's end, under the question's event and knowledge cut-offs; for Seguimiento and the summary it's the cut-off
|
||||
(by default, today).
|
||||
|
||||
### 2.1 A child's screening
|
||||
|
||||
**Source:** `models/tea/silver/tea_cohorte.sql`, `tea_hitos.sql`, `gold/eventos/tea_pasos.sql`; `webapi/metrics.py`
|
||||
(`StatusAtEnd`); `webapi/fhir/tea.py` (`Episode`).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16–36 months
|
||||
[*] --> SOLO_MCHAT: first M-CHAT at 16–36 months, or no birth date
|
||||
SOLO_MCHAT --> PSICOLOGIA: first ADOS-2
|
||||
PSICOLOGIA --> NEUROPEDIATRIA: first neuropediatrics note (any diagnosis)
|
||||
NEUROPEDIATRIA --> EEG: first good-quality EEG
|
||||
EEG --> COMPLETADO: end of the period of that EEG
|
||||
FUERA_DE_COHORTE --> [*]
|
||||
COMPLETADO --> [*]
|
||||
```
|
||||
|
||||
| Rule | In the code |
|
||||
|---|---|
|
||||
| Who enters | `tea_cohorte.en_cohorte = 1`: completed months at the first M-CHAT (days / 30.4375, rounded to one decimal, truncated) between 16 and 36, or unknown age (`grupo_edad = 'sin_dato'`) |
|
||||
| Steps go in order | `tea_despues(previous, own)`: a step is dated by the later of its first fact and the previous step, and is null without the previous one. An EEG before the note counts from the note's date |
|
||||
| What was known at a date | `tea_versiones`: one version of the child per load that brought one of its facts. `tea_cohorte` and `tea_hitos` have one row per child and version, built from the facts known by it, so the first M-CHAT, ADOS-2, note and good EEG are the first known then. The engine takes each child's latest version by the knowledge cut-off (`meta.version_conocida`) |
|
||||
| Entry and exit | `ingreso` = first M-CHAT; `salida` = the EEG step (null if never reached) |
|
||||
| Who a period counts | `ingreso < period end` and not (`salida` before the period's start, dated by the event cut-off and known by the knowledge cut-off) |
|
||||
| A period's category | The highest-order step (`paso_orden` 1–4) dated before the period's end and known by the cut-offs |
|
||||
| No exit | Without a good EEG in the chain (no ADOS-2, no note, only bad EEGs) the child stays in every period |
|
||||
| Seguimiento | `Episode`: stage = furthest step dated by the cut-off, `fecha_etapa` its date, `pendientes` the rest. `EpisodeOfCare.status` is `finished` once the EEG step is reached by the cut-off, `active` before. The `date=ge…` window leaves out episodes finished before it |
|
||||
|
||||
Stage codes in the code: `SOLO_MCHAT`, `PSICOLOGIA`, `NEUROPEDIATRIA`, `EEG` (the page's codes). `COMPLETADO` and
|
||||
`FUERA_DE_COHORTE` are never stored: the first is "not counted after the period of the exit", the second
|
||||
"filtered out by `en_cohorte`".
|
||||
|
||||
### 2.2 The diagnostic result
|
||||
|
||||
**Source:** `tea_neuropediatria.sql` (`es_tea`: ICD-10 without the dot, exactly in `cie_tea`), `tea_hitos.sql`
|
||||
(`fecha_tea`, `fecha_sin_tea`), `gold/eventos/tea_diagnosticos.sql`; `Episode.diagnosis`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> EN_PROCESO: first M-CHAT
|
||||
EN_PROCESO --> SIN_TEA: first note without F84.0
|
||||
EN_PROCESO --> CONFIRMADO: first note with F84.0
|
||||
SIN_TEA --> CONFIRMADO: a later note with F84.0
|
||||
```
|
||||
|
||||
| State | Order | Counted in |
|
||||
|---|---|---|
|
||||
| `EN_PROCESO` | 1 | M23 (in process), M24 denominator |
|
||||
| `SIN_TEA` | 2 | M24 `denominator-exclusion`; out of M23; still in the screening |
|
||||
| `CONFIRMADO` | 3 | M23, M24 numerator and denominator, base of M21/M22, event of M25 |
|
||||
|
||||
- **Highest order wins:** at each date the state is the one of highest order, so `CONFIRMADO` is final. A note without F84.0 after it changes nothing.
|
||||
- **Within the chain:** a note counts from the psychology step on, so a F84.0 note without the ADOS-2 leaves the child in process (child 5 in the fixture). F84 without its subcode is `SIN_TEA`.
|
||||
- **Seguimiento:** `diagnostico_tea` is `true` with a F84.0 note by the cut-off, `false` with notes but none with F84.0, and `null` without a note.
|
||||
|
||||
### 2.3 One EEG's quality
|
||||
|
||||
**Source:** `tea_eegs.sql`, `tea_paciente_eegs.sql` (`<criterion>_bueno` per criterion), thresholds in var
|
||||
`tea.calidad`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_ANALIZAR: loaded, no criterion written
|
||||
SIN_ANALIZAR --> BUENO: every criterion within its threshold
|
||||
SIN_ANALIZAR --> MALO: some criterion missing or over its threshold
|
||||
BUENO --> MALO: re-analysis or new thresholds
|
||||
MALO --> BUENO: re-analysis or new thresholds
|
||||
```
|
||||
|
||||
| State | `valido` | Feeds |
|
||||
|---|---|---|
|
||||
| `SIN_ANALIZAR` | 0 | M29 (third category); moves nothing else |
|
||||
| `BUENO` | 1 | M29; may become the study EEG and complete the chain |
|
||||
| `MALO` | 0 | M29; no result, its alterations don't count |
|
||||
|
||||
- **Recomputed, never stored:** the quality is recomputed from the criteria on every answer, so new thresholds in var `tea` move EEGs between `BUENO` and `MALO`.
|
||||
- **A missing criterion counts as bad** once any criterion has been written.
|
||||
|
||||
### 2.4 A child's study EEG
|
||||
|
||||
**Source:** `tea_hitos.primer_bueno` (for the measures), `Episode.study_eeg` (for Seguimiento and the summary, at the
|
||||
cut-off).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_EEG
|
||||
SIN_EEG --> SOLO_MALOS: a bad or unanalysed EEG
|
||||
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
|
||||
```
|
||||
|
||||
| State | Shown | Alterations |
|
||||
|---|---|---|
|
||||
| `SIN_EEG` | No EEG | None |
|
||||
| `SOLO_MALOS` | The latest EEG, `conclusionCode` MALO and «no es válido para el estudio» | None |
|
||||
| `CON_EEG_DEL_ESTUDIO` | The first good EEG (two on the same day: the first written) | That EEG's, once each; M30 counts it in its period |
|
||||
|
||||
- **Not tied to the chain:** the study EEG is the first good EEG whether or not the chain reached it. Child 5 has a study EEG and M30 counts it, but its chain never reaches the EEG step.
|
||||
- **Same event as the chain's end only when the note is there:** entering `CON_EEG_DEL_ESTUDIO` moves the screening (§2.1) to `EEG` only if the neuropediatrics note already exists; otherwise the EEG step is dated by the note when it arrives.
|
||||
|
||||
### 2.5 A metric of the EEG
|
||||
|
||||
**Source:** `tea_eeg_metricas.sql`: age group at the EEG, reference range from `tea_eeg_referencias` (var
|
||||
`tea.referencias`), mean = middle of the range, SD = a quarter of its width.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> no_evaluable: null value, or no reference for the age
|
||||
[*] --> normal: |z| < alteracion_z
|
||||
[*] --> aumentado: z ≥ alteracion_z
|
||||
[*] --> disminuido: z ≤ −alteracion_z
|
||||
```
|
||||
|
||||
- **Used in:** `tea_alteraciones` (M30 and its groups), `Episode.alterations`, and the metric observations (`interpretation` H, L or N, or `dataAbsentReason` for `no_evaluable`).
|
||||
- **Only a good EEG counts:** a bad EEG's metrics are stored but never read as alterations.
|
||||
|
||||
### 2.6 Showing the alterations
|
||||
|
||||
**Source:** `webapi/fhir/tea.py` (`alterations_validated`); the M30 metric's `meta.requiere_validacion`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PROVISIONAL
|
||||
PROVISIONAL --> VALIDADO: TEA_ALTERACIONES_VALIDADAS=1
|
||||
VALIDADO --> PROVISIONAL: variable removed
|
||||
```
|
||||
|
||||
| State | FHIR answers |
|
||||
|---|---|
|
||||
| `PROVISIONAL` | No M30 (`Measure` 404); `alteracion` filter refused (403); `$resumen-eeg` gives only `con_eeg_valido` / `sin_eeg_valido`; `resultado-eeg` only `valido` / `sin-eeg-valido`; no metric or electrode observations |
|
||||
| `VALIDADO` | Everything: M30, the filter, `normales`/`anormales`/`por_alteracion`, metrics and electrodes |
|
||||
|
||||
In the code it's an environment variable, so it can go back to `PROVISIONAL`. The plan wants that to need the domain
|
||||
expert, which is a process rule, not a code one.
|
||||
|
||||
### 2.7 A measure's answer for a period
|
||||
|
||||
**Source:** `webapi/metrics.py` (`key_of`, `answer`), `persistance/edges/gold/history.py` (`find`, `record`,
|
||||
`counts`, `group_counts`).
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_RESPUESTA
|
||||
SIN_RESPUESTA --> RESPONDIDA: first question (computed and recorded)
|
||||
RESPONDIDA --> RESPONDIDA: same key again (read from the history)
|
||||
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off) or a new definition
|
||||
```
|
||||
|
||||
- **The key:** measure, version, metric, period, both cut-offs, rule values and strata, hashed with SHA-256.
|
||||
- **An old cut-off keeps its answer:** asked as of an earlier load, a child is read in the version known then, so a
|
||||
later load with earlier-dated facts doesn't change it.
|
||||
- **Why a new load means a new answer:** by default the knowledge cut-off is the start of the last load, so a new load is a new key. A change to dbt's models or to var `tea` changes the model's checksum or version, and so the answer.
|
||||
- **The old answer stays** in the history.
|
||||
|
||||
### 2.8 One staging row through the silver load
|
||||
|
||||
**Source:** `webapi/orchestration/silver/procedures.py`, `persistance/edges/silver/procedures.py`.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> DESCARTADA: study code outside the catalog
|
||||
[*] --> NUEVO: logical key not in silver
|
||||
[*] --> HUERFANO: no patient and no parent (e.g. electrode without its metric)
|
||||
NUEVO --> SIN_CAMBIO: same row loaded again
|
||||
SIN_CAMBIO --> CAMBIADO: a column or observation changed
|
||||
CAMBIADO --> SIN_CAMBIO: loaded again without changes
|
||||
```
|
||||
|
||||
- **Counted in `carga`:** new, changed and unchanged procedures; discards and orphans by reason.
|
||||
- **`observa_en` rows** (EEG metrics) give no procedure of their own: their observations go on the EEG's `toma`, and are skipped and logged when that EEG isn't in silver.
|
||||
|
||||
### 2.9 Where the code differs from the plan's §13
|
||||
|
||||
- **The first good EEG.** In §13.4 the study EEG and the one that completes the chain are the same event. In the
|
||||
code the study EEG is the first good one overall, while the chain's EEG step is dated by the later of it and the
|
||||
note. A child with a good EEG but no ADOS-2 has a study EEG (M30, the summary) but never leaves the screening,
|
||||
and its note doesn't confirm it either: it stays in process.
|
||||
- **`SIN_ANALIZAR` in M29.** It shows as its own category; this was the open question in §10.
|
||||
- **The alteration switch.** It is an environment variable and can go back to `PROVISIONAL`.
|
||||
- **Without a birth date.** The child is in the cohort with `sin_dato`, as §5 says, whereas the §13.1 diagram only
|
||||
draws «16 to 36 months».
|
||||
@@ -0,0 +1,671 @@
|
||||
# TEA redesign: a trimmed schema, the new definitions and the unused indicators removed
|
||||
|
||||
Proposal, 2026-11-10, for the owner. It replaces the parts of [`tea-port.md`](tea-port.md) that port the kit's TEA
|
||||
as it is: the ten staging tables, the five measures M21 to M25 with their October definitions, and R01. Nothing here
|
||||
is implemented yet.
|
||||
|
||||
The target is what the TEA page shows today in the WebApp and the mock API: indicators M21 to M30, the period
|
||||
summary, Histórico, Seguimiento and the patient summary. Their definitions are the team's (#indicadores-tea,
|
||||
10 Nov 2026). Everything the page doesn't need is dropped, from staging to gold.
|
||||
|
||||
---
|
||||
|
||||
## 1. The definitions this design serves
|
||||
|
||||
- **The cohort** is the children whose first M-CHAT was at 16 to 36 completed months (owner, 2026-11-11).
|
||||
- **A period counts every cohort child who is in the screening during it**: entered by the period's end (first M-CHAT
|
||||
on or before it) and not finished before the period's start, whether or not anything of theirs happened in the
|
||||
period.
|
||||
- **A child leaves after completing the chain** (owner, 2026-11-11). The period of their good-quality EEG is the last
|
||||
one that counts them, with stage EEG; from the next period on they're no longer pending and don't appear.
|
||||
- **A child who never gets a good EEG stays in the screening** (owner, 2026-11-11): one with a neuropediatrics note
|
||||
without F84.0, one who stops coming back, one who ages past 36 months. They're counted in every period from their
|
||||
entry on, so M22 and the in-process counts of M23 and M28 grow with them.
|
||||
- **Each child's stage in a period is the furthest step reached by the period's end**: the steps dated on or before
|
||||
it and known at the report's cut-off. Steps go in order (M-CHAT, psychology note (ADOS-2), neuropediatrics note,
|
||||
good-quality EEG) and each needs the previous one. A child can be in process in one period and further on in a
|
||||
later one.
|
||||
- Example, by month: ADOS-2 in September, nothing in October, good EEG in December. September and October count the
|
||||
child at the psychology stage (a neuropediatrics note in November would make November's stage neuropediatrics);
|
||||
December counts them at EEG; from January on they no longer appear.
|
||||
- These rules hold for M28, M23, M24, M21 and M22. M29 and M30 count the EEG of the period instead (table below).
|
||||
- **The day counts (M26, M27, M25) take the period's children whose interval ended on or before the period's end**
|
||||
(owner, 2026-11-11). A child's days repeat in every period that counts them; the others count as without event.
|
||||
- **Only a good-quality EEG counts as an EEG**, everywhere except M29. An EEG is bad when any of its quality criteria
|
||||
is; a bad EEG has no result and its alterations don't count.
|
||||
- **A patient's alterations are those of their first good-quality EEG** (owner, 2026-11-11). Later EEGs, good or
|
||||
bad, don't change them. Each alteration counts once per patient; a patient can have several, so the alterations
|
||||
don't add up. The first good EEG is also the one that completes the chain.
|
||||
- **The age group is the age at the patient's first M-CHAT** (owner, 2026-11-10): from `pac_fecha_nacimiento` to
|
||||
that date, in completed months (days / 30.4375, rounded to one decimal, then truncated, as the kit does), placed in
|
||||
the page's windows: 16 to 23, 24 to 29 and 30 to 36 months. It is one value per patient, the same in every period
|
||||
they are counted in, and it also decides who is in the cohort. The EEG reference ranges are the exception: they take the age at the EEG date.
|
||||
|
||||
| Measure | Contract | Unit | What it counts | EEG analysis |
|
||||
|---|---|---|---|---|
|
||||
| M28 `casos_por_estado` | C2 | patient | The cohort children entered by the period's end, by their stage at that end | Yes: the EEG stage counts only a graded, good EEG |
|
||||
| M21 `diagnosticados_con_eeg` | C1 | patient | Of the confirmed (F84.0 by neuropediatrics), those with a good EEG; stratified by age group | Yes: a good EEG is the numerator |
|
||||
| M22 `diagnosticados_sin_eeg` | C1 | patient | The complement of M21 | Yes: the complement of M21 |
|
||||
| M23 `pacientes_evaluados` | C2 | patient | Confirmed, and in process (no neuropediatrics note yet); a note without F84.0 doesn't count | Indirectly: who is counted (a child leaves after their first good EEG) |
|
||||
| M24 `confirmacion_diagnostico` | C1 | patient | Confirmed out of confirmed plus in process; stratified by age group | Indirectly: who is counted |
|
||||
| M26 `dias_mchat_ados2` | C3r | patient | Days from the M-CHAT to the psychology note | Indirectly: who is counted |
|
||||
| M27 `dias_ados2_diagnostico` | C3r | patient | Days from the psychology note to the neuropediatrics note | Indirectly: who is counted |
|
||||
| M25 `dias_mchat_diagnostico` | C3r | patient | Days from the M-CHAT to the F84.0 note | Indirectly: who is counted |
|
||||
| M29 `calidad_eeg` | C2 | exam | The period's EEG, good or bad | Yes: the quality rating |
|
||||
| M30 `resultado_eeg` | C1 | patient | Of the patients whose first good EEG falls in the period, those with any alteration in it; one group per alteration | Yes: the quality and the alterations |
|
||||
|
||||
The out-of-protocol rule (M-CHAT of 2 or less, or ADOS-2 «no espectro») and the 30 days between ADOS-2 and EEG are
|
||||
gone.
|
||||
|
||||
These definitions hold over the earlier ones of #128 to #131 (owner, 2026-11-10). A confirmation is F84.0 exactly:
|
||||
F84 without the subcode doesn't count, so `cie_tea` is `[F840]`.
|
||||
|
||||
### What depends on the EEG analysis
|
||||
|
||||
The EEG analysis reads each EDF and writes its quality criteria, channels, duration, sleep, metrics and electrode
|
||||
values back to bronze. Whatever reads a good EEG, or its metrics, waits for it; those rows are tagged **[EEG
|
||||
analysis]** below.
|
||||
|
||||
- **Stored by it:** in `eeg`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min` and the five criteria; all of
|
||||
`eeg_metrica` and `eeg_metrica_electrodo` (§2), and their silver observations (§3).
|
||||
- **Derived from it:** the EEG's quality and validity (`tea_eegs`), its metrics against the references
|
||||
(`tea_eeg_metricas`) (§4), and the gold models that use them: `tea_pasos` (the EEG step), `tea_eegs_periodo` and
|
||||
`tea_alteraciones` (§5).
|
||||
- **Measures:** M29 and M30 directly; M28, M21 and M22 through the EEG stage; M23, M24, M25, M26 and M27 through who
|
||||
is counted, since a child leaves after their first good EEG (the table's last column).
|
||||
- **Seguimiento and the patient summary (§6):** `etapa`, `fecha_etapa`, `pendientes`, `fecha_eeg`, `calidad_eeg`,
|
||||
`alteraciones_eeg` and `alteraciones`, the EEG summary and its alteration filter; the summary's quality panel,
|
||||
alterations and map.
|
||||
- **FHIR (§12.3):** the quality, metric and electrode `Observation`s, and the report's `conclusionCode`.
|
||||
|
||||
What doesn't: the M-CHAT, the ADOS-2, the neuropediatrics note and the orders, and the age group.
|
||||
|
||||
---
|
||||
|
||||
## 2. Bronze: TEA staging (Core, Alembic)
|
||||
|
||||
Eight tables replace the current ten; 76 columns instead of 275. Each study table holds one kind of study, so the
|
||||
instrument and specialty columns go. Prefixes follow the schema's convention.
|
||||
|
||||
| Table | Columns |
|
||||
|---|---|
|
||||
| `pacientes` | `pac_id` PK, `pac_id_hospital`, `pac_fecha_nacimiento` |
|
||||
| `ordenes_estudio` | `ord_id` PK, `ord_pac_id`, `ord_id_hospital` (bounded, indexed: the merge key), `ord_tipo_estudio` (`ADOS2`, `NEUROPEDIATRIA`, `EEG`), `ord_fecha` |
|
||||
| `mchat` | `mch_id` PK, `mch_pac_id`, `mch_ord_id` (usually null), `mch_fecha`, `mch_puntaje` (0 to 20) |
|
||||
| `ados2` | `ado_id` PK, `ado_pac_id`, `ado_ord_id`, `ado_fecha`, `ado_modulo`, `ado_algoritmo`, `ado_css` (1 to 10), `ado_clasificacion`, and the 29 item columns `ado_sa_a2` … `ado_sa_b18`, `ado_rrb_a3` … `ado_rrb_d5` (0 to 3) |
|
||||
| `evaluacion_neuropediatrica` | `neu_id` PK, `neu_pac_id`, `neu_ord_id`, `neu_fecha`, `neu_cie_codigo` |
|
||||
| `eeg` | `eeg_id` PK, `eeg_pac_id`, `eeg_ord_id`, `eeg_id_registro_laboratorio` (bounded, indexed), `eeg_fecha_estudio`, `eeg_con_sueno`, `eeg_canales`, `eeg_duracion_min`, `eeg_canales_amplitud`, `eeg_canales_alta_frecuencia`, `eeg_canales_correlacion`, `eeg_canales_sin_senal`, `eeg_ruido_linea_db`, `eeg_estudio` (`FileBlob`, the EDF) **[EEG analysis]** |
|
||||
| `eeg_metrica` | `met_id` PK, `met_eeg_id`, `met_codigo` (`RITMO_POSTERIOR`, `HUSOS_SUENO_N2`, `HUSOS_SUENO_N3`, `PICOS_PAROXISTICOS`, `GRADIENTE_ANTEROPOSTERIOR`), `met_valor` (null: not evaluable) **[EEG analysis]** |
|
||||
| `eeg_metrica_electrodo` | `mel_id` PK, `mel_met_id`, `mel_electrodo`, `mel_valor` **[EEG analysis]** |
|
||||
|
||||
Notes:
|
||||
- The ADOS-2 domain subtotals and total aren't stored: they're sums of the items' algorithm scores, which is what the
|
||||
WebApp checks. `ado_algoritmo` is new: within a module it depends on the language level (item A1), which no
|
||||
column holds.
|
||||
- `eeg_utilizable` goes: a valid EEG is a good one, and quality comes from the five criteria. The EEG processing
|
||||
(EDF to criteria, metrics and electrode values) writes `eeg_canales`, `eeg_duracion_min`, the criteria and the two
|
||||
metric tables; nothing downstream opens the EDF.
|
||||
- Only measured values are stored. The z-score and the state of a metric come from reference ranges by age group,
|
||||
which are still pending medical review (§5).
|
||||
|
||||
---
|
||||
|
||||
## 3. Silver: the generic tables (Python load, `webapi/orchestration/silver/tea.py`)
|
||||
|
||||
Eight `DeStaging` instead of ten, into `procedimiento` and `observacion_clinica`:
|
||||
|
||||
| Bronze | `procedimiento` (study, class, parent) | `observacion_clinica` |
|
||||
|---|---|---|
|
||||
| `pacientes` | `persona` (`sexo` null) | |
|
||||
| `ordenes_estudio` | `orden`, study from `ord_tipo_estudio` | |
|
||||
| `mchat` | `mchat`, `toma`, its order if any | `mchat.puntaje` |
|
||||
| `ados2` | `ados2`, `encuentro`, its order | `ados2.modulo`, `ados2.algoritmo`, `ados2.clasificacion`, `ados2.css`, `ados2.sa_a2` … `ados2.rrb_d5` |
|
||||
| `evaluacion_neuropediatrica` | `evaluacion_neuropediatrica`, `encuentro`, its order | `evaluacion_neuropediatrica.diagnostico` (ICD-10, `F840`) |
|
||||
| `eeg` | `eeg`, `toma`, its order | `eeg.con_sueno`, `eeg.canales`, `eeg.duracion_min`, `eeg.calidad_amplitud`, `eeg.calidad_alta_frecuencia`, `eeg.calidad_correlacion`, `eeg.calidad_sin_senal`, `eeg.calidad_linea` **[EEG analysis]** |
|
||||
| `eeg_metrica` | results of the EEG `toma` | `eeg.ritmo_posterior`, `eeg.husos_sueno_n2`, `eeg.husos_sueno_n3`, `eeg.picos_paroxisticos`, `eeg.gradiente_anteroposterior` **[EEG analysis]** |
|
||||
| `eeg_metrica_electrodo` | `eeg`, `parte` per electrode (`codigo_fuente` = the electrode), parent the EEG | `eeg.<metrica>` **[EEG analysis]** |
|
||||
|
||||
- The catalog (`core/catalogos/tea.toml`) holds these studies and results; each ADOS-2 item's label and domain live in
|
||||
`cat_resultado`, so the patient summary takes them from there.
|
||||
- `tea_linea_de_tiempo.yml` goes from 29 sources to five: `mchat`, `ados2`, `evaluacion_neuropediatrica`, `eeg` and
|
||||
`orden`.
|
||||
|
||||
---
|
||||
|
||||
## 4. dbt silver (`models/tea/silver/`, ephemeral)
|
||||
|
||||
| Model | Grain | Columns |
|
||||
|---|---|---|
|
||||
| `tea_mchat` | M-CHAT | `procedimiento_id`, `pac_id`, `fecha_mchat`, `puntaje`, `carga_id` |
|
||||
| `tea_ados2` | ADOS-2 | `fecha_ados2`, `modulo`, `algoritmo`, `css`, `clasificacion`, `carga_id` |
|
||||
| `tea_ados2_reactivos` | ADOS-2 × item | `dominio`, `reactivo`, `puntaje`, `puntaje_algoritmo` |
|
||||
| `tea_neuropediatria` | note | `fecha_nota`, `cie_codigo`, `es_tea` (in `cie_tea`), `carga_id` |
|
||||
| `tea_eegs` | EEG | `fecha_eeg`, `con_sueno`, `canales`, `duracion_min`, the five criteria, `calidad` (`BUENO` or `MALO`), `valido` **[EEG analysis]** |
|
||||
| `tea_eeg_metricas` | EEG × metric | `valor`, age group at the EEG, `ref_min`, `ref_max`, `valor_z`, `estado` **[EEG analysis]** |
|
||||
|
||||
---
|
||||
|
||||
## 5. dbt gold (`models/tea/gold/eventos/`) and rules
|
||||
|
||||
| Event model | Grain | Measures |
|
||||
|---|---|---|
|
||||
| `tea_pasos` | patient × step reached, with `paso_orden`, `fecha`, `conocida_en`, `es_tea`, `grupo_edad` | M28, M23, M24, M21, M22 **[EEG analysis]** |
|
||||
| `tea_casos` | patient: the date and `conocida_en` of each step | M26, M27, M25 |
|
||||
| `tea_eegs_periodo` | EEG (`basis: examen`) | M29 **[EEG analysis]** |
|
||||
| `tea_alteraciones` | patient with a good EEG: their first good EEG's date, `conocida_en` and one flag per alteration found in it | M30 **[EEG analysis]** |
|
||||
|
||||
The age group is a stratum, as in CaCu: M21, M22 and M24 publish `TOTAL` with one `grupo_edad` per patient (age at the first M-CHAT, §1) in
|
||||
`measure_report_unidad_estrato` (breakdown and filter), which is the shape the WebApp already reads
|
||||
(`estrato=grupo_edad`). The windows are the page's: 16 to 23, 24 to 29 and 30 to 36 months. A child outside them is not
|
||||
in the cohort and isn't counted; `SIN_DATO` is left for a child without a birth date. This settles the groups-versus-strata question of `tea-port.md`.
|
||||
|
||||
Two constructs the engine doesn't have yet:
|
||||
- **Status at the period's end.** The population is every unit that entered on or before the period's end and
|
||||
hadn't left before its start (its last step dated before the period), not the units with an event inside the
|
||||
period; the category is the furthest step dated on or before that end.
|
||||
CaMa's measures count events dated inside the period, and `elige: mas_grave` chooses only among the period's
|
||||
rows.
|
||||
- **Several groups in one measure**, for M30 only: one group per alteration. The alterations can't be a stratum:
|
||||
`measure_report_unidad_estrato` holds one value per unit, and a patient can have several. The API turns the groups
|
||||
into the stratified rows the WebApp reads (`estrato=alteracion`, figure `fig_c1_barras_alteracion`).
|
||||
|
||||
Rules, as var `tea` in `dbt_project.yml`: `ventanas` (the page's three windows; the kit's 24 to 30 and 31 to 36 go),
|
||||
`edad_min_meses`, `edad_max_meses`, `dias_por_mes`,
|
||||
`cie_tea: [F840]`, `alteracion_z: 2` and the quality thresholds. Seeds: the metric references by age group, the
|
||||
electrode positions and the effect texts.
|
||||
|
||||
---
|
||||
|
||||
## 6. Seguimiento and the patient summary
|
||||
|
||||
As CaCu's (R5): views the WebApi reads, materialized as views because they leave dbt.
|
||||
- `tea_seguimiento`, one row per patient, with dates so the WebApi applies the window and the cut-off: `grupo_edad` (at the
|
||||
first M-CHAT), `fecha_eeg` and `calidad_eeg` (the study's EEG, see below), `mchat`, `css_ados2`, `modulo_ados2`,
|
||||
`alteraciones_eeg` and `alteraciones` (both from the first good EEG, as M30), `etapa`,
|
||||
`fecha_etapa` (the date of the step that set the stage), `diagnostico_tea` (from `neu_cie_codigo`, not from the CSS
|
||||
as the mock fakes it) and `pendientes`.
|
||||
- Every EEG column of the list is about the EEG the study uses, the same one as M30 and the patient summary (owner,
|
||||
2026-11-11): the first good-quality EEG, with `calidad_eeg` `bueno`. A patient without one shows their latest EEG
|
||||
with `calidad_eeg` `malo`, no result and no alterations; a patient without any EEG shows none. `ultimo_eeg` becomes
|
||||
`fecha_eeg`, as it's no longer always the latest.
|
||||
- The list can be filtered by the stage date (owner, 2026-11-11): `etapa_desde` and `etapa_hasta`, inclusive, on
|
||||
`fecha_etapa`, combined with the other filters (`etapa`, age group, M-CHAT, CSS, EEG result, alteration).
|
||||
- The patient summary reads `tea_ados2`, `tea_ados2_reactivos`, `tea_eegs`, `tea_eeg_metricas` and the electrode
|
||||
values; the WebApp draws the region z-scores and the map from the electrode values (§12.3).
|
||||
- The summary shows the EEG the study uses: the patient's first good-quality EEG (owner, 2026-11-11), with its date,
|
||||
quality criteria, alterations and maps, the same EEG M30 and Seguimiento's alterations read. A patient without a
|
||||
good EEG has no EEG in the study; the summary keeps showing their latest EEG with the warning that it isn't valid
|
||||
(owner, 2026-11-11).
|
||||
- Until the metric reference ranges, effect texts and quality thresholds are validated by the domain expert, every
|
||||
alteration stays hidden (owner, 2026-11-11): M30, Seguimiento's alteration columns, filter and EEG summary, and the
|
||||
summary's alterations panel and map. The quality (M29, the quality panel) and the stages still show. The
|
||||
electrode values are stored either way (§2), so the map comes back with the validation.
|
||||
|
||||
---
|
||||
|
||||
## 7. Removing the unused indicators
|
||||
|
||||
The page shows M21 to M30 and nothing else. Everything below is removed, not ported.
|
||||
|
||||
### 7.1 Indicators
|
||||
|
||||
| What | Where | Action |
|
||||
|---|---|---|
|
||||
| K01 to K08, M02, M04, M05, M10, M12, M12b, M15, M17, M18, M19 (18 TOMLs, already retired) | `indicadores_kit/tea/retirados/` | Not converted to dbt (R4b) and not carried into Transformation; deleted with the kit (R7) |
|
||||
| R01 `riesgo_banda` (proposal) and the TEA screening cohort it reads | `indicadores_kit/tea/propuestas/r01_riesgo_banda/`, `tea/cohortes/tamizaje.py`, `cohorte_tamizaje.toml` | Dropped. Its predictors (APGAR, NICU, maternal history, hearing test) leave staging with this design |
|
||||
| The kit's M21 to M25 as they are (CSS-based M21 and M22, M23 by sex, M24 over notes, M25 over the evaluation's date) | `indicadores_kit/tea/familias/` | Not ported: rewritten from §1. Their `casos.toml` don't apply |
|
||||
| TEA risk prediction | WebApi `POST /tea/predict`; mock `respuestas/tea/predict.POST.json`; `models/models/tea` | Out of scope while no TEA model is planned; the WebApp doesn't call it |
|
||||
|
||||
### 7.2 Parameters that go with them
|
||||
|
||||
Not carried from `parametros.toml` into var `tea` (D10):
|
||||
|
||||
| Key | Used only by |
|
||||
|---|---|
|
||||
| `tea.riesgos.horizonte_banda` | R01 |
|
||||
| `tea.cohorte.plazo_ados2_eeg_dias` | the 30-day rule, removed |
|
||||
| `tea.poblacion.css_min_tea` | the kit's M21 and M22 |
|
||||
| `tea.diagnostico.instrumentos_mchat` | the kit's M25; M-CHAT now has its own table |
|
||||
| `tea.instrumentos.informantes_ramos`, `tea.instrumentos.informantes_otros`, `tea.ramos.areas` | RAMOS (M12) |
|
||||
| `tea.atencion.plazo_referencia_evaluacion_dias` | K01 |
|
||||
| `tea.parto.apgar_corte` | M17 |
|
||||
| `tea.antecedentes_maternos.*` (four rules) | the maternal history load |
|
||||
| `tea.catalogos.sexo`, `.resultado_mchat`, `.interpretacion_ramos`, `.grado_hipoacusia`, `.apgar_5min` | M02 and M23 by sex, M05, M12, M15, M17 |
|
||||
|
||||
Kept: `tea.cohorte.edad_min_meses`, `edad_max_meses`, `dias_por_mes`, `ventanas` (with the page's windows), `tea.diagnostico.cie_tea`,
|
||||
`tea.supresion.activa`, `tea.presentacion.*`, `tea.catalogos.sin_dato`, `tea.observacion.inicio_datos`.
|
||||
|
||||
### 7.3 WebApp leftovers
|
||||
|
||||
The retired ids survive only in test data: `indicadores.synthetic-fixtures.ts` (18 entries), and the specs
|
||||
`indicador-catalog-card.spec.ts` (K05), `indicadores-search.spec.ts` (M02) and `indicadores-page.spec.ts` (K01,
|
||||
M02). In the two single-indicator specs they become current ids (M29, M24). The synthetic TEA catalog keeps its
|
||||
shapes under neutral ids and titles (`TEA_SINT_01` to `TEA_SINT_18`): with the real M21 to M30 the page starts the
|
||||
TEA summary's KPI requests, which the navigation and page specs don't expect, and those specs test the generic
|
||||
page. Done on the mock's branch `features/tea-plan-sync` (§11.5).
|
||||
|
||||
### 7.4 Plan and issues
|
||||
|
||||
| Item | Action |
|
||||
|---|---|
|
||||
| R4b.19 [#100](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/100) (TEA `r01_riesgo_banda`) | Close as not planned |
|
||||
| R3.3 [#81](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/81) (TEA screening cohort) | Close as not planned |
|
||||
| R4b.14 to R4b.18 (#95 to #99) | Retitle to the new M21 to M25; drop "equality against the kit's snapshot" from their Done when |
|
||||
| [#128](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/128) to [#131](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/131) (kit fixes to M21 to M25) | Close as superseded by §1: they change kit code that isn't ported, and the owner chose the 10 Nov definitions over theirs, F84 without the subcode included |
|
||||
| [#163](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/163) (TEA port to dbt's semantic layer) | Rewrite from this plan: eight `DeStaging`, ten measures, hand-written cases instead of `kit_oracle_tea.json` |
|
||||
| R1.1 [#48](http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative/issues/48) (parameters from YAML) | Exclude the `[tea.*]` keys of §7.2 from its equality check against the kit's `def_parametro` |
|
||||
| New | One issue each for M26 to M30, Seguimiento and the patient summary |
|
||||
| `plans/kit-exit/oracle/kit_tea.json` and its use in `tea-port.md` (piece 8) | Retired: the new definitions are proven with hand-written cases, not against the kit |
|
||||
|
||||
---
|
||||
|
||||
## 8. Order
|
||||
|
||||
1. Owner approvals (§9), then the bronze revision, import schemas and catalog.
|
||||
2. Silver load, table map, domain lists and synthetic staging (as `tea-port.md` pieces 1 to 4, with §3).
|
||||
3. dbt silver and var `tea`; `dbt build --select tea` on SQLite and on the SQL Server 2016 VM.
|
||||
4. M29 (no new construct), then M26, M27 and M25.
|
||||
5. Status at the period's end: M28 and M23.
|
||||
6. The `grupo_edad` stratum: M24, M21 and M22.
|
||||
7. Several groups per measure: M30.
|
||||
8. `tea_seguimiento` and the patient summary views, and their WebApi endpoints; the WebApp changes of §11.
|
||||
9. The removals of §7 that aren't already done by not porting: parameters, WebApp test data, issues.
|
||||
|
||||
## 9. Approvals
|
||||
|
||||
| What | `AGENTS.md` rule |
|
||||
|---|---|
|
||||
| New TEA staging tables and columns, and dropping the current ones | 4 |
|
||||
| A new Alembic revision instead of the baseline (or a new baseline) | 3 |
|
||||
| Dropping R01 and the TEA screening cohort | owner |
|
||||
|
||||
## 10. Open questions
|
||||
|
||||
None left for the owner (decided 2026-11-11: §1 for the children who never finish and the day counts, §2 and §6 for
|
||||
the electrode values, §6 for the unvalidated references and the patient without a good EEG, §11.1 for the period
|
||||
picker). For the domain expert: the reference ranges, effect texts and quality thresholds (§6), and the LOINC and
|
||||
SNOMED codes marked *to confirm* (§12.3).
|
||||
|
||||
Arising from the state machines (§13.3), for the EEG analysis: how an EEG still waiting for its analysis
|
||||
(`SIN_ANALIZAR`) shows in M29 (a third category, or left out until analysed).
|
||||
|
||||
---
|
||||
|
||||
## 11. WebApp: what changes from `dev`
|
||||
|
||||
The TEA page the plan serves is the WebApp of the mock: branch `features/tea-mock` at `ca511ff` (10 Nov; the remote
|
||||
still has `53edec8`). Against WebApp `dev` (`f4d2a3e`, 30 Oct, the commit ISSSTELEON `dev` pins) it is 21 commits
|
||||
ahead and one behind, about 63 files, +3,000 and -1,150 lines, mostly under `src/app/features/indicadores/`. §11.6
|
||||
has the branches it has to meet on the way to `dev`.
|
||||
|
||||
### 11.1 Changes for every domain
|
||||
|
||||
| Change | Files |
|
||||
|---|---|
|
||||
| One period at a time: the multi-period selector of Resumen becomes a single-period select, for CaCu and CaMa too | `indicador-period-filters.*`, `indicadores-page.*` |
|
||||
| A graphic-indicator selector with an «Ir» link replaces the floating navigation panel (also closes #5) | `indicadores-page.*`; `indicadores-navegacion-panel.*` removed |
|
||||
| Highlight buttons for the groups and categories of a figure | `indicadores-highlight.ts`, `indicador-figure-card.*`, `indicador-figure-panel.ts` |
|
||||
| A C1 donut by stratum | `indicadores-c1-donut.ts` |
|
||||
| Catalog items can name the tabs that show them (`vistas`); C1 cards can carry their own explanatory line (`c1Info`); C2 cards keep their category counts (`categorias`) | `indicadores.models.ts`, `indicadores-kpi.ts` |
|
||||
| `alteracion` admitted as a stratum next to `grupo_edad`, `estatus_seguimiento` and `citologia_alto_grado` | `indicadores.service.ts` |
|
||||
| The follow-up query grows the fields `grupo_edad`, `mchat`, `css`, `etapa`, `alteracion` | `cacu-seguimiento.models.ts` |
|
||||
|
||||
The single-period select stays TEA-only (owner, 2026-11-11): CaCu and CaMa keep the multi-period picker.
|
||||
|
||||
### 11.2 TEA only
|
||||
|
||||
| Feature | Files |
|
||||
|---|---|
|
||||
| Tabs Resumen, Histórico, Seguimiento, Datos y definiciones | `indicadores-page.ts` (`TEA_SECTIONS`) |
|
||||
| Histórico: each indicator over time, with custom periods chosen by year | `indicadores-historico.ts`, `indicadores-historico-figures.ts`, `indicadores-historico-periodos.ts` |
|
||||
| The period summary paragraph, built from the hidden KPI cards | `tea-resumen-periodo.ts`, `indicadores-kpi.ts` (`KPI_RESUMEN_TEA`) |
|
||||
| C2 donut with groups drawn both rings at once; one-ring donut for C2 without groups | `indicadores-tea-c2.ts` |
|
||||
| M30's figure: one bar per alteration, shares that don't add up (`fig_c1_barras_alteracion`) | `indicadores-tea-alteraciones.ts` (new, untracked) |
|
||||
| Seguimiento: filters by EEG result, age group, M-CHAT band, CSS band, stage and alteration; EEG summary of all matching patients; stage and pending steps per patient | `tea-seguimiento.service.ts`, `indicadores-tracking.*` |
|
||||
| Patient summary: ADOS-2 with domains and items, EEG quality by criteria (good or bad), alterations with reference, z-score and effects, topographic map per alteration | `tea-paciente-resumen.*` |
|
||||
|
||||
### 11.3 What the backend must serve for it
|
||||
|
||||
| Route | Contract |
|
||||
|---|---|
|
||||
| `GET /tea/indicadores` | The ten ids of §1, with `estratos` (`grupo_edad` for M21, M22, M24; `alteracion` for M30), `figuras` (`fig_c1_barras_edad`, `fig_c1_barras_apiladas_edad`, `fig_c1_barras_alteracion`, `fig_c2_barras`, `fig_c2_donas`, `fig_c3r_caja`), `tipos_periodo` and `vistas` |
|
||||
| `GET /tea/indicadores/<id>/datos` | `?periodos=` with several periods (Histórico) and `?estrato=grupo_edad` or `alteracion`; C2 categories with label and color; M29 and M30 as in §1 |
|
||||
| `GET /tea/indicadores/<id>/metadatos` | As CaCu's |
|
||||
| `GET /tea/seguimiento` | `meses`, `corte`, `page`, `page_size`, `alteraciones_eeg`, `grupo_edad`, `mchat_min`/`mchat_max`, `css_min`/`css_max`, `etapa`, `alteracion`; each item with the fields of §6; `tipos_alteracion` and `resumen_eeg` (`normales`, `anormales`, `sin_eeg_valido`, `por_alteracion`) |
|
||||
| `GET /tea/seguimiento/<id_seudonimo>` | `ados2` (module, algorithm, domains with items, total, classification, CSS, level) and `eeg` (date, duration, channels, quality and criteria, alterations, maps on shared axes); the pseudonym resolved as in #168 |
|
||||
|
||||
### 11.4 Mock-only parts to replace
|
||||
|
||||
- The TEA Seguimiento and the patient summary accept only `simulado: true`, as CaCu's list does. WebApi `dev` now
|
||||
registers the follow-up and patient-risk routes in every environment (`0cbe390`, 9 Nov), so the WebApp's
|
||||
`simulado` guard is what keeps real data out; lifting it needs the owner's OK.
|
||||
- «Datos de ejemplo» badges on the EEG quality and alterations panels, and «TEA (mock)» comments: the alterations
|
||||
are hidden until the reference ranges and effects are validated (§6), and the badges go then.
|
||||
- The retired ids in the WebApp's test data (§7.3).
|
||||
|
||||
### 11.5 Not in the WebApp yet
|
||||
|
||||
Done in the mock (mock `features/tea-historico`, ISSSTELEON and WebApp `features/tea-mock`): everything in this list
|
||||
except the last two items, plus the indicator generator on the cohort rule of §1 (first good EEG, a bad EEG repeated,
|
||||
leaving after the period of the good one) and the indicator texts.
|
||||
|
||||
- **The patient summary's EEG.** The mock builds the summary from the latest EEG (`ultimo_eeg` in
|
||||
`generar_tea_detalle.py`); it changes to the first good EEG (§6), and the panel says which EEG it is and its date.
|
||||
- **Seguimiento's EEG columns.** `ultimo_eeg` is renamed `fecha_eeg` and holds the study's EEG (§6), in
|
||||
`tea-seguimiento.service.ts` (type and validation), `indicadores-tracking.html` (the «Último EEG» header becomes
|
||||
«EEG del estudio») and the mock's list and generator.
|
||||
- **Seguimiento: the stage date.** A `fecha_etapa` column and a date-range filter on it (`etapa_desde`, `etapa_hasta`),
|
||||
in `tea-seguimiento.service.ts` (type, validation, query), `indicadores-tracking.*` (column, filter) and the
|
||||
mock's list.
|
||||
- **The cohort rule of §1.** The period summary still says «tuvieron algún paso del tamizaje… según su etapa a la
|
||||
fecha de corte», and the mock generator (`generar_tea_casos.py`, `cohorte()`) counts the children with a step in
|
||||
the period at their stage at the cut-off. Both change to the children in the screening during the period, at their
|
||||
stage at its end, leaving after the period of their good EEG.
|
||||
- **The single-period select, TEA only.** The mock WebApp gives every domain one period at a time; CaCu and CaMa get
|
||||
their multi-period picker back (§11.1).
|
||||
- **Alterations hidden until validated.** M30, Seguimiento's alteration columns, filter and EEG summary, and the
|
||||
summary's alterations panel and map stay hidden behind one switch until the references are validated (§6).
|
||||
|
||||
### 11.6 Branches on the way to `dev`
|
||||
|
||||
Checked 2026-11-11 against the Gitea remotes.
|
||||
|
||||
| Branch | Where it stands | What it means for TEA |
|
||||
|---|---|---|
|
||||
| WebApp `dev` (`f4d2a3e`) | One commit the mock lacks: the bitácora page, self-hosted fonts and icons, install-package fixes (reportes, governance, connect) | Merging it into the TEA branch conflicts only in `src/styles.scss` |
|
||||
| `features/cama-mock` (`502fc96`, 9 Nov) | Built on `features/tea-mock` at `53edec8`, plus 22 commits: CaMa on TEA's tabs, the domain menu in the header, the institutional look, general filters in one compact row, search and «Fijar indicador» only from five indicators, cards with a value without «Disponible» | It holds the TEA page except `ca511ff`. Merging `ca511ff` into it conflicts in `cacu-seguimiento.models.ts`, `indicadores-kpi.ts` and `indicadores.service.ts`; eleven more shared files merge cleanly. It also conflicts with `dev` in `src/styles.scss` |
|
||||
| `refactor/kit-exit` (`62cdb25`, 8 Nov) | `dev` plus three commits: a separate KPIs page (`/kpis`) that draws CaCu's measures from FHIR `MeasureReport` bundles | No file in common with the TEA branch, but the contract clashes (§11.7) |
|
||||
|
||||
Order: push `ca511ff`, merge it into `features/cama-mock` (three conflicts), bring `dev` in (`styles.scss`), and merge
|
||||
the result into `dev` by pull request.
|
||||
|
||||
### 11.7 The contract gap with `refactor/kit-exit`
|
||||
|
||||
The TEA page reads the kit's serving contract: `GET /<domain>/indicadores` as a catalog (title, contract, figures,
|
||||
strata), `/indicadores/<id>/datos` with rows per period and stratum, and `/metadatos`. The WebApi on
|
||||
`refactor/kit-exit` (`c430a5b`) serves only `GET /<domain>/indicadores`, as a list of measures (`id`, `url`,
|
||||
`version`, `scoring`), and `GET /<domain>/indicadores/<measure_id>`, a FHIR `MeasureReport`. The same URL means two
|
||||
different things, and nothing serves `/datos` or `/metadatos`, for TEA, CaCu or CaMa.
|
||||
|
||||
One of the two has to give, and it's the owner's decision (#132 point 3 asks for one generic contract):
|
||||
1. **The pages read `MeasureReport`**, as `/kpis` does: the Resumen, Histórico and strata code reads FHIR groups and
|
||||
stratifiers. The catalog fields the page needs (titles, figures, strata, `vistas`, colors, notes) come from the
|
||||
measures' `meta` in dbt. Largest WebApp change; one contract.
|
||||
2. **The WebApi adds the page's contract over the measures**: `/datos` and `/metadatos` built from the dbt measures,
|
||||
and the catalog under a URL that doesn't clash with the measure list. No WebApp change; two contracts.
|
||||
|
||||
Planned: option 1 (owner, 2026-11-11). The WebApi side is §12. On the WebApp side, the indicator page (Resumen,
|
||||
Histórico, the KPI cards and the period summary) reads `Measure` and `MeasureReport` the way `/kpis` already does,
|
||||
and §11.3's `/datos` and `/metadatos` go. Seguimiento and the patient summary move to FHIR too (§12.4, §12.5).
|
||||
|
||||
---
|
||||
|
||||
## 12. WebApi: answering in FHIR
|
||||
|
||||
Every route the TEA page reads, and the rest of the WebApi, gets its FHIR R4 equivalent. Reference: the WebApi on
|
||||
`refactor/kit-exit` (`c430a5b`), which already answers each measure as a `Bundle` of `MeasureReport`s
|
||||
(`webapi/kpis.py`, `metrics.py`, `compositions.py`, `durations.py`). Codes marked *to confirm* need the domain
|
||||
expert: LOINC or SNOMED where one exists, the project's code system otherwise.
|
||||
|
||||
### 12.1 Conventions for every route
|
||||
|
||||
| Point | Today | FHIR |
|
||||
|---|---|---|
|
||||
| Base | Routes under `/<domain>/…`, `/reportes`, `/imports`, `/governance` | One FHIR endpoint per domain database: `/<domain>/fhir/`, FHIR R4 (4.0.1), JSON, `application/fhir+json` |
|
||||
| What the server offers | `GET /api` lists routes | `GET /<domain>/fhir/metadata`: a `CapabilityStatement` with the resources, search parameters and operations below |
|
||||
| Errors | `{"error": "…"}` | `OperationOutcome` (severity, code, Spanish `diagnostics`), same HTTP statuses |
|
||||
| Lists and paging | `items` with `paginacion` (`page`, `page_size`, `total_items`, `total_pages`) | `Bundle` `searchset` with `total` and `link` (`self`, `next`, `previous`); `_count` (at most 200) and the server's paging links |
|
||||
| Patient identity | `id_seudonimo` in the body; `pac_id` in the CaCu risk route | `Patient.id` is the salted pseudonym everywhere; `pac_id` and `pac_id_hospital` never leave; references are `Patient/<pseudonym>`, resolved as in #168 |
|
||||
| Simulated data | `simulado: true` in the body | A `meta.tag` on every resource (system `https://isssteleon.org/fhir/CodeSystem/etiqueta`, code `simulado`); the WebApp guard reads the tag |
|
||||
| Catalogs | `cat_estudio`, `cat_resultado`, `cat_valor`, the TOML catalogs | `CodeSystem` and `ValueSet` resources under `https://isssteleon.org/fhir/`, generated from `core/catalogos/tea.toml`; external systems where they apply: ICD-10 (`http://hl7.org/fhir/sid/icd-10`), observation interpretation (`H`, `L`, `N`), `data-absent-reason` |
|
||||
| Extensions | Three, for cut-offs and the history entry | Each one with a `StructureDefinition` published under `https://isssteleon.org/fhir/StructureDefinition/` |
|
||||
| Checking | Shape checks in the WebApp | Every response checked against FHIR R4 in the WebApi tests, with a FHIR model library or the HL7 validator (a new dependency: owner's approval) |
|
||||
|
||||
### 12.2 Measures
|
||||
|
||||
| Today | FHIR |
|
||||
|---|---|
|
||||
| `GET /<domain>/indicadores`: `{id, url, version, scoring}` | `GET /<domain>/fhir/Measure`: a `Bundle` of `Measure` resources, replacing the page's catalog and `/metadatos`. Title, description, scoring, `group` with each population's `description` (what #2 asks), `stratifier` definitions, `improvementNotation`, and extensions for figures, `vistas`, period types, category labels and colors. Built from each metric's `meta` in dbt |
|
||||
| `GET /<domain>/indicadores/<measure_id>?periodos=…` | One period: `GET /<domain>/fhir/Measure/<id>/$evaluate-measure?periodStart=…&periodEnd=…` (the standard operation), returning one `MeasureReport`. Several periods (Histórico): `GET /<domain>/fhir/MeasureReport?measure=<canonical>&period=…`, a `searchset` with one report per period. `corte_evento` and `corte_conocimiento` stay as custom parameters of both |
|
||||
| `GET /reportes/indicadores` (stored reports) | `GET /<domain>/fhir/MeasureReport` with `measure`, `period` and `date` search; the history entry stays an extension |
|
||||
| `POST /reportes/indicadores/<dominio>/recalcular` | `POST /<domain>/fhir/Measure/$recalcular`, a custom operation returning an `OperationOutcome` |
|
||||
| Domains in the `kpis_blueprint` loop | `tea` added (`tea-port.md` piece 3), with TEA's metrics in the manifest |
|
||||
|
||||
The `MeasureReport` itself:
|
||||
|
||||
| Point | Today | Change |
|
||||
|---|---|---|
|
||||
| `measure` | `tea/M21_…\|0.3.0`, not a URL | An absolute canonical (`https://isssteleon.org/fhir/Measure/<measure_id>\|<version>`), the same one the `Measure` carries |
|
||||
| Scoring of a C2 | `composition`, which isn't a FHIR scoring | `cohort`: the units counted as the initial population, with the categories as a stratifier |
|
||||
| Groups | One group, identified only by `id` | `group.code` on each, and several groups per report where the measure has them (M30: `TOTAL` plus one per alteration) |
|
||||
| Stratifier and stratum identity | `code: [{text}]`, `value: {text}` | Codings: the stratifier's code (`grupo_edad`, the C2's category), and each value with its catalog system, code and display |
|
||||
| C2 with strata | Each stratum's counts summed across categories | `stratum.component` holds the category inside each stratum value, so a breakdown by both survives |
|
||||
| Suppression | Absent | Suppressed counts and scores carry no value and the `data-absent-reason` extension (`masked`); depends on #73 |
|
||||
| Confidence interval | Absent | Lower and upper bounds as extensions of `measureScore`; depends on #73 |
|
||||
| Proportion score | A fraction, without unit | Kept as a fraction (0 to 1), stated in the `Measure`; the WebApp multiplies for display |
|
||||
| Exclusions | Not reported | `denominator-exclusion` with its count where the measure excludes (M24's neuropediatrics notes without F84.0) |
|
||||
| Durations | Median with `q1` and `q3` extensions | Kept; the excluded (no value at the cut-off) as their own population count |
|
||||
|
||||
The engine, for TEA's definitions. These are §5's constructs; the engine that answers them is this WebApi code, not dbt.
|
||||
|
||||
| Construct | Today | Change |
|
||||
|---|---|---|
|
||||
| Age stratum | Kinds `edad_al_inicio_del_periodo`, `linea_de_tiempo_al_inicio_del_periodo`, `del_elegido` | A kind that reads a column of the event model (`grupo_edad`, the age at the first M-CHAT, §1). Age at the period's start contradicts §1 |
|
||||
| Status at the period's end (M28, M23, M24, M21, M22) | Units with a fact dated inside the period | A population rule in `meta`: units entered on or before the period's end and not left before its start; the category is the furthest step dated on or before that end |
|
||||
| Several groups (M30) | `MeasureDefinition.group` is one string | A list of groups, each with its filter, answered and serialized one by one |
|
||||
| Unit of M29 | `basis` of the existing measures | `examen` (oro has no `estudio`) |
|
||||
|
||||
### 12.3 TEA's clinical data as FHIR resources
|
||||
|
||||
What Seguimiento and the patient summary show, read from silver (§3), each kind of fact as its resource:
|
||||
|
||||
| TEA fact | Resource | Content |
|
||||
|---|---|---|
|
||||
| Child | `Patient` | `id` the pseudonym; `birthDate` at month precision; no identifiers, no name |
|
||||
| Order | `ServiceRequest` | `code` the study (ADOS-2, neuropediatrics, EEG); `authoredOn`; `subject` |
|
||||
| M-CHAT | `Observation` | `code` M-CHAT-R/F total (LOINC *to confirm*); `valueInteger` 0 to 20; `effectiveDateTime`; `basedOn` its order if any |
|
||||
| ADOS-2 | `Observation` | `code` ADOS-2 (*to confirm*); `component`s for module, algorithm, CSS, classification, the two domain totals and the 29 items (item codes in the project's `CodeSystem`, labels and domains there); `effectiveDateTime`; `basedOn` |
|
||||
| Neuropediatrics note | `Encounter` and `Condition` | The visit (`serviceType` neuropediatrics, `period`); its diagnosis as a `Condition` (`code` ICD-10, `F840` for TEA, `encounter`, `recordedDate`) |
|
||||
| EEG | `Procedure` and `DiagnosticReport` | The recording as a `Procedure` (`code` electroencephalography, SNOMED *to confirm*); its result as a `DiagnosticReport` (`effectiveDateTime`, `result` the observations below, `conclusionCode` good or bad quality). The EDF as a `Media` with its `Binary`, served only where the file may leave |
|
||||
| EEG quality criteria | `Observation` | One per criterion (`valueInteger` channels or `valueQuantity` dB), `interpretation` good or bad; members of the report **[EEG analysis]** |
|
||||
| EEG metric (alteration) | `Observation` | One per metric: `valueQuantity` with its unit; `referenceRange` for the child's age group at the EEG; `interpretation` `H` (aumentado), `L` (disminuido) or `N`; `dataAbsentReason` when it can't be evaluated (no sleep). The z-score as a `component`. Effect texts live in the `CodeSystem` of the metrics, not in each observation **[EEG analysis]** |
|
||||
| Electrode values | `Observation` | One per metric, a `component` per electrode (`code` the 10-20 electrode, `valueQuantity` the z-score). The WebApp draws the map and the regions from them (#132); `mapas` and `ejes_mapa` leave the API **[EEG analysis]** |
|
||||
|
||||
### 12.4 Seguimiento
|
||||
|
||||
The follow-up list is each child's screening as an `EpisodeOfCare`, which already has the cohort's entry and exit:
|
||||
|
||||
| Field today | FHIR |
|
||||
|---|---|
|
||||
| The row | `EpisodeOfCare`: `patient`, `period.start` the first M-CHAT, `period.end` the first good EEG, `status` `active` while pending and `finished` after it |
|
||||
| `etapa`, `fecha_etapa` | `type` the stage (project `CodeSystem`), and an extension with the stage's date |
|
||||
| `pendientes` | A `CarePlan` per episode, one `activity` per step with its `status` (`completed`, `not-started`) and date |
|
||||
| `grupo_edad`, `mchat`, `css_ados2`, `modulo_ados2`, `diagnostico_tea`, `fecha_eeg`, `calidad_eeg`, `alteraciones_eeg`, `alteraciones` | Included resources (`_include`): the `Patient`, the M-CHAT and ADOS-2 `Observation`s, the `Condition` and the EEG `DiagnosticReport` with its metrics; the age group as an extension of the episode |
|
||||
| Filters | Search parameters on `EpisodeOfCare`: `status`, `date` (the window and the cut-off), `etapa`, `fecha-etapa` (`ge`, `le`: the stage-date filter of §6), `grupo-edad`, `mchat`, `css`, `resultado-eeg`, `alteracion`; each declared as a `SearchParameter` |
|
||||
| `resumen_eeg`, `tipos_alteracion` | `GET /tea/fhir/EpisodeOfCare/$resumen-eeg` with the same filters, returning `Parameters` (normal, abnormal, without a valid EEG, count per alteration); the alteration types are the metrics' `ValueSet` |
|
||||
|
||||
`GET /tea/fhir/EpisodeOfCare?…&_include=…` replaces `GET /tea/seguimiento`. CaCu's follow-up list (`/cacu/seguimiento`)
|
||||
moves to the same shape.
|
||||
|
||||
### 12.5 The patient summary
|
||||
|
||||
`GET /tea/fhir/Patient/<pseudonym>/$resumen-tea` replaces `GET /tea/seguimiento/<id_seudonimo>`: a `Bundle` of type
|
||||
`collection` with the `Patient`, the ADOS-2 `Observation` and the EEG the study uses (the first good one, §6) as its
|
||||
`DiagnosticReport` with the quality, metric and electrode `Observation`s. A patient without a good EEG gets their latest
|
||||
one, with `conclusionCode` bad quality. The ADOS-2 domain bars, the CSS level and the map are drawn by the WebApp from
|
||||
those resources.
|
||||
|
||||
### 12.6 The rest of the WebApi
|
||||
|
||||
| Route family | FHIR |
|
||||
|---|---|
|
||||
| `GET /cacu/pacientes/<pac_id>/riesgo` | `RiskAssessment` (`subject` the pseudonym, `prediction` one per horizon with `probabilityDecimal` and `whenRange`, `basis` the observations used, `method` the model version); cohort membership as a `Group` (the build) with the patient as a member |
|
||||
| `POST /<domain>/predict` | `POST /<domain>/fhir/RiskAssessment/$predict`, returning a `RiskAssessment`. Out for TEA (§7.1) |
|
||||
| `GET /reportes/importaciones`, `/importaciones/descarga` | `AuditEvent` per import (who, when, what, outcome) and `Provenance` on the resources it wrote; the download as a `Binary` |
|
||||
| `POST /imports/commit` | The rows written as a `transaction` `Bundle` of the resources above; uploaded documents as `DocumentReference` with their `Binary`. `POST /imports/validate` maps to `$validate` |
|
||||
| `/imports/connectors`, `/targets`, `/sources/…` (previews, SQL browsing, PDF regions) | Not FHIR: tooling for the import screen, kept as an admin API outside `/<domain>/fhir/` |
|
||||
| `GET /data/<target>` | Not FHIR: raw staging rows. Kept as admin, or removed once imports are checked through the resources |
|
||||
| `/governance/model-versions/…` | Not FHIR (no resource fits a model registry); admin API. A model version used in a prediction is cited from `RiskAssessment.method` |
|
||||
| `/governance/ocr/…` | OCR jobs as `Task` (`status`, `input` the document, `output` the rows); corrections stay admin |
|
||||
| `GET /health` | Unchanged, outside FHIR |
|
||||
|
||||
### 12.7 What it means for the WebApp
|
||||
|
||||
Every reader changes with its route: the indicator page and `/kpis` read `Measure` and `MeasureReport` (§11.7);
|
||||
Seguimiento reads `EpisodeOfCare` bundles with their includes and paging links; the patient summary reads the
|
||||
`$resumen-tea` bundle and draws the ADOS-2 bars and the EEG map itself; CaCu's patient record reads `RiskAssessment`;
|
||||
errors arrive as `OperationOutcome`; the `simulado` guard reads `meta.tag`. §11.3 and §11.5 describe the page as it
|
||||
reads today; this section is where it ends.
|
||||
|
||||
### 12.8 Order
|
||||
|
||||
1. Conventions: the `/<domain>/fhir/` base, `CapabilityStatement`, `OperationOutcome`, the `simulado` tag, the
|
||||
`CodeSystem`s, and response checking in the tests.
|
||||
2. Measures: `Measure`, `$evaluate-measure`, the `MeasureReport` search, canonical URLs, codings, `cohort` for C2,
|
||||
`stratum.component`.
|
||||
3. The engine constructs for TEA (column stratum, status at the period's end, several groups), with TEA's measures.
|
||||
4. TEA's clinical resources (§12.3), then Seguimiento as `EpisodeOfCare` and the patient summary operation.
|
||||
5. Suppression and intervals, with #73.
|
||||
6. The rest (§12.6): `RiskAssessment`, `AuditEvent` and `Provenance`, imports as `transaction`, OCR `Task`s.
|
||||
|
||||
Each step changes what the WebApp, `/kpis` and the CaCu and CaMa answers receive: their readers and the frozen answers
|
||||
of `tests/test_*_measures.py` move with it.
|
||||
|
||||
### 12.9 Approvals
|
||||
|
||||
| What | `AGENTS.md` rule |
|
||||
|---|---|
|
||||
| A FHIR model or validation library in the WebApi | new dependency |
|
||||
| Routes moved under `/<domain>/fhir/` and the old ones removed | owner |
|
||||
| Codes from LOINC and SNOMED (licensing of SNOMED in Mexico) | owner and domain expert |
|
||||
|
||||
---
|
||||
|
||||
## 13. State machines
|
||||
|
||||
The rules of §1 and §6 define these machines. The stored data are dated facts (M-CHAT, ADOS-2, notes, EEG and their
|
||||
analysis); every state below is derived from them at a date: the end of a period for the measures, the cut-off for
|
||||
Seguimiento. Nothing stores a state, so a late fact moves the state back in time when it's loaded.
|
||||
|
||||
### 13.1 A child's screening
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> FUERA_DE_COHORTE: first M-CHAT outside 16 to 36 months
|
||||
[*] --> MCHAT: first M-CHAT at 16 to 36 months
|
||||
MCHAT --> PSICOLOGIA: psychology note (ADOS-2)
|
||||
PSICOLOGIA --> NEUROPEDIATRIA: neuropediatrics note
|
||||
NEUROPEDIATRIA --> EEG: first good-quality EEG
|
||||
EEG --> COMPLETADO: end of the period of that EEG
|
||||
FUERA_DE_COHORTE --> [*]
|
||||
COMPLETADO --> [*]
|
||||
```
|
||||
|
||||
| From | Event (dated fact) | To |
|
||||
|---|---|---|
|
||||
| (start) | First M-CHAT at 16 to 36 completed months | `MCHAT` |
|
||||
| (start) | First M-CHAT outside that range | `FUERA_DE_COHORTE`: never counted |
|
||||
| `MCHAT` | Psychology note (ADOS-2) | `PSICOLOGIA` |
|
||||
| `PSICOLOGIA` | Neuropediatrics note, with any diagnosis | `NEUROPEDIATRIA` |
|
||||
| `NEUROPEDIATRIA` | First good-quality EEG | `EEG` |
|
||||
| `EEG` | The end of the period of that EEG | `COMPLETADO`: no longer counted |
|
||||
|
||||
- Steps go in order; a fact whose previous step is missing doesn't move the child (an EEG before the
|
||||
neuropediatrics note leaves them where they are until the note arrives).
|
||||
- A bad EEG, an EEG still waiting for analysis (§13.3), a later EEG and a second note don't move the child.
|
||||
- Without a good EEG a child never leaves (§1): `MCHAT`, `PSICOLOGIA` and `NEUROPEDIATRIA` have no exit.
|
||||
- **How a period reads it:** a child is counted in a period when their state at its end is `MCHAT`, `PSICOLOGIA`,
|
||||
`NEUROPEDIATRIA` or `EEG` and they weren't `COMPLETADO` at its start; the category of M28 is that state.
|
||||
- **Seguimiento:** `etapa` is the state at the cut-off, `fecha_etapa` the date of the fact that set it, `pendientes`
|
||||
the steps after it. In FHIR it's the `EpisodeOfCare` (`active` until `COMPLETADO`, then `finished`) with its
|
||||
`CarePlan` (§12.4).
|
||||
|
||||
### 13.2 The diagnostic result
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> EN_PROCESO: in the screening, no neuropediatrics note
|
||||
EN_PROCESO --> CONFIRMADO: note with F84.0
|
||||
EN_PROCESO --> SIN_TEA: note without F84.0
|
||||
SIN_TEA --> CONFIRMADO: a later note with F84.0
|
||||
```
|
||||
|
||||
| State | Meaning | Counted in |
|
||||
|---|---|---|
|
||||
| `EN_PROCESO` | No neuropediatrics note by the date | M23 (in process), M24 denominator |
|
||||
| `CONFIRMADO` | Some neuropediatrics note with F84.0 by the date | M23 (confirmed), M24 numerator and denominator, M21 and M22 base, M25 |
|
||||
| `SIN_TEA` | Notes, none with F84.0 | M24 exclusions; out of M23; still in the screening (§13.1) |
|
||||
|
||||
`CONFIRMADO` is final: a later note without F84.0 doesn't undo it. It runs beside §13.1, not after it: the
|
||||
neuropediatrics note moves both.
|
||||
|
||||
### 13.3 One EEG study
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_ANALIZAR: EDF or report loaded
|
||||
SIN_ANALIZAR --> BUENO: analysis, every criterion good
|
||||
SIN_ANALIZAR --> MALO: analysis, some criterion bad
|
||||
BUENO --> [*]
|
||||
MALO --> [*]
|
||||
```
|
||||
|
||||
| State | Meaning | What it feeds **[EEG analysis]** |
|
||||
|---|---|---|
|
||||
| `SIN_ANALIZAR` | Loaded, criteria not written yet | M29 can't grade it; it doesn't move §13.1 or §13.4 |
|
||||
| `BUENO` | Every quality criterion within its threshold | M29 (good); may become the study EEG (§13.4) |
|
||||
| `MALO` | Some criterion out of its threshold | M29 (bad); no result, no alterations |
|
||||
|
||||
A new analysis of the same EEG (new thresholds) can move it between `BUENO` and `MALO`; the states above it are
|
||||
derived again on the next answer. How `SIN_ANALIZAR` shows in M29 is open (§10).
|
||||
|
||||
### 13.4 The patient's study EEG
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_EEG
|
||||
SIN_EEG --> SOLO_MALOS: a bad EEG
|
||||
SIN_EEG --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
SOLO_MALOS --> CON_EEG_DEL_ESTUDIO: a good EEG
|
||||
CON_EEG_DEL_ESTUDIO --> CON_EEG_DEL_ESTUDIO: any later EEG (ignored)
|
||||
```
|
||||
|
||||
| State | Shown in Seguimiento and the summary | Alterations |
|
||||
|---|---|---|
|
||||
| `SIN_EEG` | No EEG | None |
|
||||
| `SOLO_MALOS` | The latest EEG, `calidad_eeg` `malo`, marked not valid | None |
|
||||
| `CON_EEG_DEL_ESTUDIO` | The first good EEG, `calidad_eeg` `bueno` | That EEG's, once per alteration; M30 counts it in its period |
|
||||
|
||||
Entering `CON_EEG_DEL_ESTUDIO` is the same event that moves §13.1 to `EEG`, when the neuropediatrics note is there.
|
||||
|
||||
### 13.5 Showing the alterations
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PROVISIONAL
|
||||
PROVISIONAL --> VALIDADO: domain expert validates references, effects and thresholds
|
||||
```
|
||||
|
||||
| State | Shown |
|
||||
|---|---|
|
||||
| `PROVISIONAL` | Quality (M29, the quality panel) and the stages; every alteration hidden (§6) |
|
||||
| `VALIDADO` | Everything, without the «Datos de ejemplo» badges |
|
||||
|
||||
A change to the references after validation goes back through the domain expert; the switch doesn't return to
|
||||
`PROVISIONAL` on its own.
|
||||
|
||||
### 13.6 A measure's answer for a period
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> SIN_RESPUESTA
|
||||
SIN_RESPUESTA --> RESPONDIDA: first request after a load
|
||||
RESPONDIDA --> RESPONDIDA: same question again (read from the history)
|
||||
RESPONDIDA --> SIN_RESPUESTA: a new load (new knowledge cut-off)
|
||||
```
|
||||
|
||||
The WebApi answers each measure and period on request and keeps the answer by its knowledge cut-off (the start of
|
||||
the last load, §12.2). A new load opens a new cut-off: the next request computes again, and the old answer stays in
|
||||
the history. A change to dbt's models or to var `tea` is a new definition and also computes again.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user