Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d1e9accd85 | |||
| f6d00f51f3 | |||
| 32df6dadf8 | |||
| 362d97af70 | |||
| 461cae1490 | |||
| e6eb3157a3 | |||
| a69db40067 | |||
| e27a5da077 | |||
| 7e4c643c4d | |||
| 4a30d64193 | |||
| a31d987548 | |||
| c6c8bdf3f8 | |||
| 6ff683ad80 | |||
| a43f41727e | |||
| af7ed4495a | |||
| a377ed0eaf | |||
| 4e7b5701e5 | |||
| ef1fd82a42 | |||
| 92c46e4f78 | |||
| 9b9b4b7f8b | |||
| 924c5f17a3 | |||
| 3b024f5314 | |||
| 90c083e305 | |||
| 55ee3cfba7 | |||
| 2f210c4797 | |||
| 0d12c73d15 | |||
| 5370805886 | |||
| 01d0f11dfb | |||
| db2a7804d0 | |||
| 69896d641a | |||
| 5b6e701310 | |||
| 29c9963e5d | |||
| f5819efa7a | |||
| b5a53c587f | |||
| f68babec98 | |||
| b20cd02709 | |||
| 6a0007c372 | |||
| 257ef9bef1 | |||
| 03d0d6388e | |||
| e524041b70 | |||
| 01e80eaefb | |||
| 9a7a4f45b1 |
+4
-4
@@ -1,13 +1,13 @@
|
||||
[submodule "WebApp"]
|
||||
path = WebApp
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
||||
url = ../WebApp.git
|
||||
[submodule "WebApi"]
|
||||
path = WebApi
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
||||
url = ../WebApi.git
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
url = ../models.git
|
||||
[submodule "indicadores_kit"]
|
||||
path = indicadores_kit
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/indicadores_kit.git
|
||||
url = ../indicadores_kit.git
|
||||
branch = dev
|
||||
|
||||
@@ -13,7 +13,7 @@ class ModelPrediction(GovernanceModel, table=True):
|
||||
version that produced it.
|
||||
|
||||
Model training, versioning and promotion live in MLflow, not here
|
||||
(`models.registry`); this row only carries the keys to find that version
|
||||
(`models.io.registry`); this row only carries the keys to find that version
|
||||
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
|
||||
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
|
||||
already uses for its own risk evaluations.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from extraction.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import (
|
||||
DEFAULT_EXTRACTORS,
|
||||
FieldExtractor,
|
||||
@@ -11,6 +12,7 @@ from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_EXTRACTORS",
|
||||
"DiscoveredField",
|
||||
"Evidence",
|
||||
"ExtractedValue",
|
||||
"FieldExtractor",
|
||||
@@ -21,4 +23,5 @@ __all__ = [
|
||||
"PatternExtractor",
|
||||
"RecordExtractor",
|
||||
"SegmentLine",
|
||||
"discover_captions",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Captions a document carries that no registered `FieldSpec` claims.
|
||||
|
||||
`LabeledValueExtractor` only looks for the labels a caller already knows
|
||||
about. A source whose documents carry fields outside today's vocabulary
|
||||
(a hospital's own report layout, a free-form note) still has captions in
|
||||
the `"Campo: valor"` shape; this module finds them so a caller can decide,
|
||||
per caption, whether it matches something in a catalog closely enough to
|
||||
reuse, or is new (see `webapi.imports.schemas.catalog_matching`)."""
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from extraction.nlp.extractors import LabelIndex, SegmentLine
|
||||
from extraction.nlp.fields import Evidence, FieldSpec
|
||||
|
||||
_CAPTION_LINE = re.compile(r"^(?P<caption>[^:=]{2,60}?)\s*[:=]\s*(?P<value>\S.*)$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiscoveredField:
|
||||
"""One `caption: value` line a known `FieldSpec` didn't already claim."""
|
||||
|
||||
caption: str
|
||||
value: str
|
||||
evidence: Evidence
|
||||
|
||||
|
||||
def discover_captions(lines: Sequence[SegmentLine], specs: Sequence[FieldSpec]) -> list[DiscoveredField]:
|
||||
"""Every undiscovered caption, in line order, duplicates kept (the
|
||||
caller decides how to fold repeats across a record's lines)."""
|
||||
index = LabelIndex(lines, specs)
|
||||
found: list[DiscoveredField] = []
|
||||
for line_index, line in enumerate(lines):
|
||||
if index.hits[line_index]:
|
||||
continue # a known label already explains this line
|
||||
match = _CAPTION_LINE.match(line.text.strip())
|
||||
if not match:
|
||||
continue
|
||||
caption, value = match.group("caption").strip(), match.group("value").strip()
|
||||
if not caption or not value:
|
||||
continue
|
||||
found.append(DiscoveredField(caption, value, line.evidence()))
|
||||
return found
|
||||
@@ -3,15 +3,23 @@ from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader, OcrMode
|
||||
from extraction.readers.image import ImageReader
|
||||
from extraction.readers.pdf import PdfReader, combine_pages
|
||||
from extraction.readers.text import TextReader
|
||||
|
||||
READERS: tuple[type[DocumentReader], ...] = (PdfReader, ImageReader)
|
||||
# Tried only once neither a signature nor the file name picked one of
|
||||
# `READERS`: a SQL column or a plain string that isn't a PDF or an image,
|
||||
# read as text as long as it decodes as one instead of being rejected.
|
||||
FALLBACK_READERS: tuple[type[DocumentReader], ...] = (TextReader,)
|
||||
|
||||
|
||||
def reader_for(name: str, raw: bytes, **options) -> DocumentReader:
|
||||
"""The reader whose signature the bytes carry; the file extension only when none does."""
|
||||
"""The reader whose signature the bytes carry, the file extension when
|
||||
none does, and `FALLBACK_READERS` by content only when neither found one."""
|
||||
head = raw[:16]
|
||||
cls = next((c for c in READERS if c.matches_content(head)), None) or next(
|
||||
(c for c in READERS if c.matches_name(name)), None
|
||||
cls = (
|
||||
next((c for c in READERS if c.matches_content(head)), None)
|
||||
or next((c for c in READERS if c.matches_name(name)), None)
|
||||
or next((c for c in FALLBACK_READERS if c.matches_content(head)), None)
|
||||
)
|
||||
if cls is None:
|
||||
raise ExtractionError(f"unsupported document format: {name!r}")
|
||||
@@ -23,14 +31,16 @@ def read_document(name: str, raw: bytes, *, ocr_mode: OcrMode = "auto") -> Docum
|
||||
|
||||
|
||||
def supported_extensions() -> list[str]:
|
||||
return sorted({extension for cls in READERS for extension in cls.extensions})
|
||||
return sorted({extension for cls in (*READERS, *FALLBACK_READERS) for extension in cls.extensions})
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FALLBACK_READERS",
|
||||
"READERS",
|
||||
"DocumentReader",
|
||||
"ImageReader",
|
||||
"PdfReader",
|
||||
"TextReader",
|
||||
"combine_pages",
|
||||
"read_document",
|
||||
"reader_for",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from extraction.document import BBox, Document, Line, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader
|
||||
|
||||
_LINE_HEIGHT_PX = 18
|
||||
|
||||
|
||||
class TextReader(DocumentReader):
|
||||
"""Plain text, one field's content carrying several of its own (a SQL
|
||||
column that isn't a scanned PDF, a note pasted as a string). No OCR: the
|
||||
bytes already are the text, one page, one line per newline.
|
||||
|
||||
The fallback reader, last in `extraction.readers.READERS`: it claims
|
||||
whatever a format-specific reader didn't, as long as it decodes as
|
||||
text, so a source that's neither a PDF nor an image still reaches the
|
||||
same field extraction instead of failing as an unsupported format.
|
||||
"""
|
||||
|
||||
media_type = "text/plain"
|
||||
extensions = ("txt",)
|
||||
|
||||
@classmethod
|
||||
def matches_content(cls, head: bytes) -> bool:
|
||||
"""`head` is only a short prefix (`reader_for` passes 16 bytes), so
|
||||
a multi-byte character can be cut mid-sequence; trimming up to 3
|
||||
trailing bytes covers any such cut without accepting binary data.
|
||||
Printable (plus common whitespace) is required too, so a binary
|
||||
signature that happens to be valid UTF-8 (control bytes are) isn't
|
||||
mistaken for text."""
|
||||
if b"\x00" in head:
|
||||
return False
|
||||
text = None
|
||||
for cut in range(4):
|
||||
trimmed = head[: len(head) - cut] if cut else head
|
||||
if not trimmed:
|
||||
return False
|
||||
try:
|
||||
text = trimmed.decode("utf-8")
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return text is not None and all(ch.isprintable() or ch in "\t\n\r" for ch in text)
|
||||
|
||||
def read(self, name: str, raw: bytes) -> Document:
|
||||
try:
|
||||
text = raw.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ExtractionError(f"not valid UTF-8 text: {exc}") from exc
|
||||
rows = text.splitlines() or [""]
|
||||
lines = [
|
||||
Line(text=row, bbox=BBox(0, index / len(rows), 1, (index + 1) / len(rows)))
|
||||
for index, row in enumerate(rows)
|
||||
]
|
||||
return Document(name=name, media_type=self.media_type, pages=[Page(number=1, lines=lines, source="text")], raw=raw)
|
||||
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
if page_number != 1:
|
||||
raise ExtractionError(f"page {page_number} out of range (1..1)")
|
||||
rows = raw.decode("utf-8", errors="replace").splitlines() or [""]
|
||||
image = Image.new("RGB", (900, max(1, len(rows)) * _LINE_HEIGHT_PX + 20), "white")
|
||||
draw = ImageDraw.Draw(image)
|
||||
for index, row in enumerate(rows):
|
||||
draw.text((10, 10 + index * _LINE_HEIGHT_PX), row, fill="black")
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
@@ -4,6 +4,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Sequence
|
||||
|
||||
from extraction.document import Document, EmbeddedImage
|
||||
from extraction.nlp.discovery import DiscoveredField, discover_captions
|
||||
from extraction.nlp.extractors import DEFAULT_EXTRACTORS, FieldExtractor, RecordExtractor
|
||||
from extraction.nlp.fields import ExtractedValue, FieldSpec
|
||||
from extraction.segmentation import AutoSegmenter, Segment, Segmenter, normalize_key
|
||||
@@ -33,6 +34,10 @@ class ExtractedRecord:
|
||||
images: list[tuple[str, EmbeddedImage]] = field(default_factory=list)
|
||||
key: str | None = None
|
||||
conflicts: list[FieldConflict] = field(default_factory=list)
|
||||
# Captions no known `FieldSpec` claimed (`discover_captions`): what a
|
||||
# source outside today's vocabulary carries, for a caller to match
|
||||
# against a catalog or register as new (catalog_matching, in WebApi).
|
||||
discovered: list[DiscoveredField] = field(default_factory=list)
|
||||
|
||||
def row(self) -> dict[str, Any]:
|
||||
return {name: extracted.value for name, extracted in self.values.items()}
|
||||
@@ -70,6 +75,7 @@ class RecordMerger:
|
||||
target.sources.extend(record.sources)
|
||||
target.images.extend(record.images)
|
||||
target.conflicts.extend(record.conflicts)
|
||||
target.discovered.extend(record.discovered)
|
||||
for name, incoming in record.values.items():
|
||||
current = target.values.get(name)
|
||||
if current is None:
|
||||
@@ -116,7 +122,8 @@ class DocumentExtractor:
|
||||
return self.merger.merge(records) if self.merger else records
|
||||
|
||||
def extract_segment(self, segment: Segment) -> ExtractedRecord:
|
||||
values = self.fields.extract(segment.lines())
|
||||
lines = segment.lines()
|
||||
values = self.fields.extract(lines)
|
||||
key = segment.key
|
||||
if self.key_spec is not None and self.key_spec.name in values:
|
||||
key = normalize_key(values[self.key_spec.name].value)
|
||||
@@ -125,4 +132,5 @@ class DocumentExtractor:
|
||||
sources=[SegmentRef(segment.document.name, list(segment.page_numbers))],
|
||||
images=[(segment.document.name, image) for image in segment.images],
|
||||
key=key,
|
||||
discovered=discover_captions(lines, self.specs),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""`discover_captions`: fails if it stops finding fields a source carries
|
||||
that no registered `FieldSpec` names, or starts re-reporting a field the
|
||||
specs already cover as if it were new."""
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import FieldKind, FieldSpec, SegmentLine, discover_captions
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
|
||||
|
||||
def lines(*texts: str) -> list[SegmentLine]:
|
||||
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 10, 1, (i + 1) / 10))) for i, text in enumerate(texts)]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_known_specs_is_discovered():
|
||||
found = discover_captions(lines("Tipo de muestra: Base líquida"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Tipo de muestra", "Base líquida")]
|
||||
|
||||
|
||||
def test_a_line_a_known_label_already_claims_is_not_rediscovered():
|
||||
found = discover_captions(lines("Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_a_line_without_the_caption_shape_is_ignored():
|
||||
found = discover_captions(lines("Resultado negativo para lesión intraepitelial"), [EXPEDIENTE])
|
||||
assert found == []
|
||||
|
||||
|
||||
def test_several_undiscovered_captions_come_back_in_line_order():
|
||||
found = discover_captions(lines("Instrumento: ADOS-2", "Módulo: 3", "Expediente: EXP-0001"), [EXPEDIENTE])
|
||||
assert [(f.caption, f.value) for f in found] == [("Instrumento", "ADOS-2"), ("Módulo", "3")]
|
||||
@@ -4,7 +4,7 @@ import pytest
|
||||
|
||||
from extraction.testing import scanned_pdf, text_pdf
|
||||
from extraction import DocumentExtractor, ExtractionError, FieldKind, FieldSpec, make_segmenter, read_document
|
||||
from extraction.readers import ImageReader, PdfReader, combine_pages, reader_for
|
||||
from extraction.readers import ImageReader, PdfReader, TextReader, combine_pages, reader_for
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento",))
|
||||
@@ -97,6 +97,21 @@ def test_unknown_format_is_rejected():
|
||||
reader_for("notes.docx", b"PK\x03\x04")
|
||||
|
||||
|
||||
def test_plain_text_is_read_as_a_one_page_document():
|
||||
"""Fails if a source whose field bundle is a plain string (not a PDF or
|
||||
an image) stops being readable, falling back to ExtractionError."""
|
||||
document = read_document("fila_42", "Expediente: EXP-0099\nInstrumento: ADOS-2".encode("utf-8"))
|
||||
assert isinstance(reader_for("fila_42", document.raw), TextReader)
|
||||
assert document.page_count == 1
|
||||
assert [line.text for line in document.pages[0].lines] == ["Expediente: EXP-0099", "Instrumento: ADOS-2"]
|
||||
|
||||
|
||||
def test_plain_text_fallback_does_not_steal_a_known_signature_or_extension():
|
||||
"""Fails if `TextReader` starts winning over a real PDF/image match."""
|
||||
assert isinstance(reader_for("reporte.pdf", b"????"), PdfReader)
|
||||
assert isinstance(reader_for("f.png", b"\x89PNG\r\n\x1a\n" + b"\x00" * 8), ImageReader)
|
||||
|
||||
|
||||
def test_combine_pages_from_several_pdfs():
|
||||
from extraction.readers import combine_pages
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""What dbt owns in a domain's database and Python reads: the timeline view and the queries dbt compiled.
|
||||
|
||||
dbt creates and changes these relations, so there's no ORM class and no Alembic migration for them. Both repositories
|
||||
read on a `SesionDeLectura`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
||||
text, so a compiled query is trusted to be the `select` dbt wrote; a database account that can only read is what
|
||||
guarantees it.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, column, select, table, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from persistance.aristas.plata.timeline import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class DbtRelationError(RuntimeError):
|
||||
"""A relation dbt should have created can't be read."""
|
||||
|
||||
|
||||
def timeline_view(domain: str) -> str:
|
||||
return f"{domain}_linea_de_tiempo"
|
||||
|
||||
|
||||
class DbtTimelineRepository(TimelineRepository):
|
||||
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
|
||||
|
||||
`fecha` comes back as a date on every engine. The filters run in the database; `patients` becomes one bound
|
||||
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
|
||||
"""
|
||||
|
||||
def __init__(self, session_factory: Callable, domain: str):
|
||||
self.view = timeline_view(domain)
|
||||
super().__init__(session_factory, self._query)
|
||||
|
||||
def _query(self, *, patients: Iterable[int] | None, until: date | None, known_until: datetime | None):
|
||||
view = table(self.view, *(column(name, Date) if name == "fecha" else column(name) for name in TIMELINE_COLUMNS))
|
||||
query = select(*(view.c[name] for name in TIMELINE_COLUMNS))
|
||||
if patients is not None:
|
||||
query = query.where(view.c.pac_id.in_(list(patients)))
|
||||
if until is not None:
|
||||
query = query.where(view.c.fecha <= until)
|
||||
if known_until is not None:
|
||||
query = query.where(view.c.conocida_en <= known_until)
|
||||
return query.order_by(view.c.pac_id, view.c.fecha, view.c.fuente_tabla, view.c.fuente_id)
|
||||
|
||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> list[dict]:
|
||||
try:
|
||||
return super().read(patients=patients, until=until, known_until=known_until)
|
||||
except DBAPIError as error:
|
||||
raise DbtRelationError(f"can't read {self.view} ({error.orig}): is it created? "
|
||||
f"Run `dbt run --select {self.view}` in Transformation") from error
|
||||
|
||||
|
||||
class DbtQueryRepository(Repository):
|
||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row."""
|
||||
|
||||
def __init__(self, session_factory: Callable):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def read(self, sql: str) -> list[dict]:
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(text(sql))
|
||||
columns = list(result.keys())
|
||||
return [dict(zip(columns, row)) for row in result]
|
||||
@@ -8,8 +8,13 @@ from persistance.aristas.oro.cohortes import (
|
||||
FINAL,
|
||||
PRELIMINAR,
|
||||
PROCEDENCIA,
|
||||
CohortBuild,
|
||||
CohorteRepository,
|
||||
CohortMember,
|
||||
PatientMembership,
|
||||
PatientRisk,
|
||||
RiesgoFueraDeCohorte,
|
||||
RiskHorizon,
|
||||
cambiar_estado_en,
|
||||
guardar_armado_en,
|
||||
guardar_lote_en,
|
||||
@@ -21,11 +26,16 @@ __all__ = [
|
||||
"PRELIMINAR",
|
||||
"PROCEDENCIA",
|
||||
"CalculoRepository",
|
||||
"CohortBuild",
|
||||
"CohorteRepository",
|
||||
"CohortMember",
|
||||
"MeasureReportRepository",
|
||||
"PatientMembership",
|
||||
"PatientRisk",
|
||||
"PublicacionRepository",
|
||||
"RegistroRepository",
|
||||
"RiesgoFueraDeCohorte",
|
||||
"RiskHorizon",
|
||||
"cambiar_estado_en",
|
||||
"guardar_armado_en",
|
||||
"guardar_lote_en",
|
||||
|
||||
@@ -13,7 +13,8 @@ evaluación solo crece: confirmarla (`preliminary` -> `final`) o anularla
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import datetime, timezone
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import TypeVar
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
@@ -65,6 +66,158 @@ class CohorteRepository(Repository):
|
||||
with self._session_factory() as sesion:
|
||||
return cambiar_estado_en(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||
|
||||
def latest_build(self, url: str) -> int | None:
|
||||
"""The most recent build of the cohort `url`, or `None` if it has none."""
|
||||
build = self.cohortes.CohorteArmado
|
||||
with self._session_factory() as sesion:
|
||||
return sesion.exec(
|
||||
select(build.armado_id).where(build.url == url).order_by(build.armado_id.desc()).limit(1)
|
||||
).first()
|
||||
|
||||
def members(self, build_id: int) -> list["CohortMember"]:
|
||||
"""The members of a build, ordered by `pac_id`; empty if the build doesn't exist."""
|
||||
member = self.cohortes.CohorteMiembro
|
||||
with self._session_factory() as sesion:
|
||||
rows = sesion.exec(select(member).where(member.armado_id == build_id).order_by(member.pac_id)).all()
|
||||
return [CohortMember(row.pac_id, row.fecha_indice, row.indice_fuente_tabla, row.indice_fuente_id)
|
||||
for row in rows]
|
||||
|
||||
def build(self, build_id: int) -> "CohortBuild | None":
|
||||
"""A build's lineage fields, or `None` if it doesn't exist."""
|
||||
with self._session_factory() as sesion:
|
||||
row = sesion.get(self.cohortes.CohorteArmado, build_id)
|
||||
return None if row is None else _cohort_build(row)
|
||||
|
||||
def builds(self, url: str | None = None) -> list["CohortBuild"]:
|
||||
"""Every build, newest first, with its lineage fields; only those of the cohort `url` if given."""
|
||||
armado = self.cohortes.CohorteArmado
|
||||
query = select(armado).order_by(armado.armado_id.desc())
|
||||
if url is not None:
|
||||
query = query.where(armado.url == url)
|
||||
with self._session_factory() as sesion:
|
||||
return [_cohort_build(row) for row in sesion.exec(query).all()]
|
||||
|
||||
|
||||
def membership(self, pac_id: int, url: str) -> "PatientMembership | None":
|
||||
"""The patient in the cohort's latest build: its version, index date and stored variables (`c`, `l`, `r`,
|
||||
`pap_0`, `hpv_0`...); `None` if the cohort has no build or the patient isn't a member of the latest one."""
|
||||
if (build_id := self.latest_build(url)) is None:
|
||||
return None
|
||||
member, variable = self.cohortes.CohorteMiembro, self.cohortes.CohorteVariable
|
||||
with self._session_factory() as sesion:
|
||||
row = sesion.get(member, (build_id, pac_id))
|
||||
if row is None:
|
||||
return None
|
||||
build = sesion.get(self.cohortes.CohorteArmado, build_id)
|
||||
values = sesion.exec(select(variable).where(variable.armado_id == build_id, variable.pac_id == pac_id)).all()
|
||||
return PatientMembership(build_id, url, build.version, row.fecha_indice,
|
||||
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
|
||||
for v in values})
|
||||
|
||||
def current_risk(self, pac_id: int) -> "PatientRisk | None":
|
||||
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
|
||||
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
|
||||
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
|
||||
confirmed."""
|
||||
e = self.cohortes.EvaluacionRiesgo
|
||||
with self._session_factory() as sesion:
|
||||
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
|
||||
for lote_id in batches:
|
||||
latest = _latest_versions(sesion, e, lote_id)
|
||||
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
|
||||
continue
|
||||
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
|
||||
.order_by(e.horizonte_anios)).all()
|
||||
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
|
||||
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
|
||||
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
|
||||
for r in rows])
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatientMembership:
|
||||
"""A patient in a cohort's latest build: which build, from which index date, and its stored variables."""
|
||||
|
||||
armado_id: int
|
||||
url: str
|
||||
version: str
|
||||
fecha_indice: date
|
||||
variables: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RiskHorizon:
|
||||
"""A patient's risk at one horizon, at its latest version."""
|
||||
|
||||
horizonte_anios: float
|
||||
probabilidad: float
|
||||
ic_bajo: float | None
|
||||
ic_alto: float | None
|
||||
estado: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PatientRisk:
|
||||
"""A patient's risks in the current batch, with the model that produced them."""
|
||||
|
||||
lote_id: int
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
evaluado_en: datetime
|
||||
estado_lote: str
|
||||
horizontes: list[RiskHorizon]
|
||||
|
||||
|
||||
def _latest_versions(sesion: Session, e, lote_id: int):
|
||||
"""The latest version of each (patient, horizon) of a batch, as a subquery."""
|
||||
return (select(e.pac_id, e.horizonte_anios, func.max(e.version).label("version"))
|
||||
.where(e.lote_id == lote_id).group_by(e.pac_id, e.horizonte_anios).subquery())
|
||||
|
||||
|
||||
def _same_version(e, latest):
|
||||
return (e.pac_id == latest.c.pac_id) & (e.horizonte_anios == latest.c.horizonte_anios) & (e.version == latest.c.version)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortMember:
|
||||
"""A member of a cohort build: who, from which index date, and the row of its index event."""
|
||||
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortBuild:
|
||||
"""What identifies a cohort build in a model's lineage.
|
||||
|
||||
`datos_as_of` is the clinical cut-off; `conocida_hasta` is what had been loaded when the build was made
|
||||
(`None`: everything loaded at the time). Reading the timeline again with both reproduces the build's input
|
||||
once silver keeps its history.
|
||||
"""
|
||||
|
||||
armado_id: int
|
||||
url: str
|
||||
version: str
|
||||
huella: str
|
||||
marco_sha: str
|
||||
datos_as_of: date
|
||||
conocida_hasta: datetime | None
|
||||
n_miembros: int
|
||||
armado_en: datetime
|
||||
|
||||
|
||||
def _cohort_build(row: SQLModel) -> CohortBuild:
|
||||
"""A `cohorte_armado` row as `CohortBuild`; `conocida_hasta` comes from its parameters."""
|
||||
known_until = json.loads(row.parametros or "{}").get("conocida_hasta")
|
||||
return CohortBuild(row.armado_id, row.url, row.version, row.huella, row.marco_sha, row.datos_as_of,
|
||||
None if known_until is None else datetime.fromisoformat(known_until),
|
||||
row.n_miembros, row.armado_en)
|
||||
|
||||
|
||||
def guardar_armado_en(
|
||||
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación y la verificación."""
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.aristas.plata.carga import (
|
||||
CargaRepository,
|
||||
@@ -9,6 +9,13 @@ from persistance.aristas.plata.carga import (
|
||||
from persistance.aristas.plata.catalogos import CatalogoRepository
|
||||
from persistance.aristas.plata.observacion import ObservacionRepository
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.aristas.plata.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineQueryMissing,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.aristas.plata.vinculos import VinculosRepository
|
||||
from persistance.aristas.plata.vistas import VistasRepository
|
||||
|
||||
@@ -16,6 +23,11 @@ __all__ = [
|
||||
"CargaRepository",
|
||||
"CatalogoRepository",
|
||||
"ObservacionRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineQueryMissing",
|
||||
"TimelineRepository",
|
||||
"VinculosRepository",
|
||||
"VistasRepository",
|
||||
"abrir_carga",
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
|
||||
|
||||
The query is injected. Each domain module binds dbt's view (`persistance.aristas.dbt`); another query, such as
|
||||
the indicator kit's `linea_de_tiempo_plata`, can still be bound with `with_query`. Readers keep the same columns and
|
||||
filters.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date, datetime
|
||||
from typing import Protocol
|
||||
|
||||
from sqlalchemy import Select
|
||||
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.repository import Repository
|
||||
|
||||
TIMELINE_COLUMNS = (
|
||||
"pac_id", "fecha", "conocida_en", "clase", "tipo", "codigo", "valor_codigo", "valor_numerico",
|
||||
"fuente_tabla", "fuente_id",
|
||||
)
|
||||
|
||||
|
||||
class TimelineQuery(Protocol):
|
||||
def __call__(self, *, patients: Iterable[int] | None, until: date | None,
|
||||
known_until: datetime | None) -> Select: ...
|
||||
|
||||
|
||||
class TimelineContractError(ValueError):
|
||||
"""The injected query returned columns other than `TIMELINE_COLUMNS`."""
|
||||
|
||||
|
||||
class TimelineQueryMissing(RuntimeError):
|
||||
"""`read` was called on a repository that has no query yet (see `with_query`)."""
|
||||
|
||||
|
||||
class TimelineRepository(Repository):
|
||||
"""Reads the timeline of some patients, or of everyone, cut at a date and at what was loaded by then.
|
||||
|
||||
Created with a query, or without one and bound later with `with_query`, so neither side names what it
|
||||
can't import.
|
||||
"""
|
||||
|
||||
def __init__(self, session_factory: Callable, query: TimelineQuery | None = None):
|
||||
super().__init__(session_factory, None)
|
||||
self._query = query
|
||||
|
||||
def with_query(self, query: TimelineQuery) -> "TimelineRepository":
|
||||
"""The same repository, reading through `query`."""
|
||||
return TimelineRepository(self._session_factory, query)
|
||||
|
||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> list[dict]:
|
||||
"""One dict per event, keyed by `TIMELINE_COLUMNS`, in the query's order.
|
||||
|
||||
`until` keeps events up to that clinical date; `known_until` keeps rows already loaded at that
|
||||
moment. The query runs on a read-only session.
|
||||
"""
|
||||
if self._query is None:
|
||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
||||
query = self._query(patients=None if patients is None else list(patients), until=until,
|
||||
known_until=known_until)
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(query)
|
||||
columns = tuple(result.keys())
|
||||
if columns != TIMELINE_COLUMNS:
|
||||
raise TimelineContractError(f"expected columns {TIMELINE_COLUMNS}, got {columns}")
|
||||
return [dict(zip(columns, row)) for row in result]
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Assets: what each step of a Hamilton graph reads and produces.
|
||||
|
||||
A function named after the asset it produces returns an `Asset`; its parameters are the assets it
|
||||
reads. Tags describe each producing function: `layer` (a `Layer`), `owner` (an `Owner`),
|
||||
`depends_on` (parameters that only order the step, without passing data) and `deprecated_by` (the
|
||||
dbt selector that will replace it). This module doesn't import Hamilton: `validate` and `mermaid`
|
||||
work on the nodes a driver lists with `list_available_variables()`.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class Layer(StrEnum):
|
||||
BRONZE = "bronce"
|
||||
SILVER = "plata"
|
||||
GOLD = "oro"
|
||||
MODEL = "modelo"
|
||||
|
||||
|
||||
class Owner(StrEnum):
|
||||
EXTERNAL = "externo"
|
||||
PYTHON = "python"
|
||||
DBT = "dbt"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Asset:
|
||||
"""An asset as a step leaves it: a handle to what was written, never the data."""
|
||||
|
||||
name: str
|
||||
rows: int | None = None
|
||||
|
||||
|
||||
class InvalidGraph(ValueError):
|
||||
"""A graph whose assets don't line up; the message lists every problem, one per line."""
|
||||
|
||||
|
||||
def validate(nodes: Iterable, sources: Iterable[str] = ()) -> None:
|
||||
"""Raise `InvalidGraph` unless every asset has a producer or is a declared source, every
|
||||
producing function has valid `layer` and `owner` tags, and every `depends_on` is a parameter."""
|
||||
sources = set(sources)
|
||||
problems = []
|
||||
for node in nodes:
|
||||
if node.is_external_input:
|
||||
if _produces_asset(node) and node.name not in sources:
|
||||
problems.append(f"{node.name}: read as an asset, but nothing produces it and it isn't a declared source")
|
||||
continue
|
||||
if _produces_asset(node):
|
||||
layer, owner = node.tags.get("layer"), node.tags.get("owner")
|
||||
if layer not in {value.value for value in Layer}:
|
||||
problems.append(f"{node.name}: `layer` tag is {layer!r}; expected one of {[value.value for value in Layer]}")
|
||||
if owner not in {value.value for value in Owner}:
|
||||
problems.append(f"{node.name}: `owner` tag is {owner!r}; expected one of {[value.value for value in Owner]}")
|
||||
for name in _tag_values(node, "depends_on"):
|
||||
if name not in _dependencies(node):
|
||||
problems.append(f"{node.name}: `depends_on` names {name!r}, which isn't one of its parameters")
|
||||
if problems:
|
||||
raise InvalidGraph("\n".join(problems))
|
||||
|
||||
|
||||
def mermaid(nodes: Iterable) -> str:
|
||||
"""The asset graph as a Mermaid flowchart: one box per asset with its layer and owner, an arrow
|
||||
from each asset to the assets that read it, dotted when the dependency only orders the step.
|
||||
Functions that don't produce an asset (a dict split with `@extract_fields`, a configuration
|
||||
value) don't appear: an arrow goes through them to the nearest asset upstream."""
|
||||
by_name = {node.name: node for node in nodes}
|
||||
assets = sorted(name for name, node in by_name.items() if _produces_asset(node))
|
||||
lines = ["flowchart LR"]
|
||||
for name in assets:
|
||||
node = by_name[name]
|
||||
layer, owner = node.tags.get("layer", "?"), node.tags.get("owner", "source")
|
||||
lines.append(f' {name}["{name}<br/>{layer} · {owner}"]')
|
||||
for name in assets:
|
||||
order_only = set(_tag_values(by_name[name], "depends_on"))
|
||||
for upstream in sorted(_upstream_assets(by_name, name)):
|
||||
arrow = "-.->" if upstream in order_only else "-->"
|
||||
lines.append(f" {upstream} {arrow} {name}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _produces_asset(node) -> bool:
|
||||
return isinstance(node.type, type) and issubclass(node.type, Asset)
|
||||
|
||||
|
||||
def _dependencies(node) -> set[str]:
|
||||
return set(node.required_dependencies) | set(node.optional_dependencies)
|
||||
|
||||
|
||||
def _tag_values(node, tag: str) -> list[str]:
|
||||
value = node.tags.get(tag)
|
||||
if value is None:
|
||||
return []
|
||||
values = value if isinstance(value, (list, tuple)) else str(value).split(",")
|
||||
return [item.strip() for item in values if item.strip()]
|
||||
|
||||
|
||||
def _upstream_assets(by_name: dict, name: str) -> set[str]:
|
||||
found, pending, seen = set(), list(_dependencies(by_name[name])), set()
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if current in seen or current not in by_name:
|
||||
continue
|
||||
seen.add(current)
|
||||
if _produces_asset(by_name[current]):
|
||||
found.add(current)
|
||||
elif not by_name[current].is_external_input:
|
||||
pending.extend(_dependencies(by_name[current]))
|
||||
return found
|
||||
@@ -41,6 +41,7 @@ from core.cacu.models import (
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
@@ -48,6 +49,7 @@ from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
)
|
||||
@@ -98,6 +100,9 @@ calculo_repository = CalculoRepository(get_cacu_session, MeasureReport, periodo=
|
||||
observar_repository = ObservacionRepository(get_cacu_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cacu_session)
|
||||
vinculos_repository = VinculosRepository(get_cacu_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cacu_session, "cacu")
|
||||
dbt_query_repository = DbtQueryRepository(get_cacu_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
get_cacu_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
|
||||
@@ -41,6 +41,7 @@ from core.cama.models import (
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
@@ -48,6 +49,7 @@ from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
)
|
||||
@@ -98,6 +100,9 @@ calculo_repository = CalculoRepository(get_cama_session, MeasureReport, periodo=
|
||||
observar_repository = ObservacionRepository(get_cama_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cama_session)
|
||||
vinculos_repository = VinculosRepository(get_cama_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cama_session, "cama")
|
||||
dbt_query_repository = DbtQueryRepository(get_cama_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
get_cama_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
|
||||
@@ -44,6 +44,7 @@ from core.tea.models import (
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
@@ -51,6 +52,7 @@ from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
)
|
||||
@@ -104,6 +106,9 @@ calculo_repository = CalculoRepository(get_tea_session, MeasureReport, periodo=D
|
||||
observar_repository = ObservacionRepository(get_tea_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_tea_session)
|
||||
vinculos_repository = VinculosRepository(get_tea_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_tea_session, "tea")
|
||||
dbt_query_repository = DbtQueryRepository(get_tea_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
get_tea_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
|
||||
@@ -33,4 +33,6 @@ packages = ["persistance"]
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
# Only the tests of `persistance.assets` build Hamilton graphs; the package itself doesn't import it.
|
||||
"apache-hamilton>=1.90",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""What this module covers: `persistance.assets` (`validate`, `mermaid`, `Asset`, `Layer`, `Owner`) on real Hamilton graphs.
|
||||
|
||||
Fixtures: no pytest fixtures. The module-level functions `staging`, `hechos`, `registro__python`,
|
||||
`measure_report` and `periodo_observacion` form a small indicator cycle (`CYCLE`); `_nodes` builds a
|
||||
Hamilton driver from some of them and returns its nodes. Tests that need a broken graph define the
|
||||
offending function inside the test.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
|
||||
import pytest
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from hamilton.function_modifiers import config, extract_fields, tag
|
||||
|
||||
from persistance.assets import Asset, InvalidGraph, Layer, Owner, mermaid, validate
|
||||
|
||||
_module_names = itertools.count()
|
||||
|
||||
|
||||
def _nodes(*functions, **settings):
|
||||
"""The nodes of a Hamilton graph built from `functions` (each call gets its own module), configured with `settings`."""
|
||||
module = ad_hoc_utils.create_temporary_module(*functions, module_name=f"assets_graph_{next(_module_names)}")
|
||||
return driver.Builder().with_modules(module).with_config(settings).build().list_available_variables()
|
||||
|
||||
|
||||
@tag(layer="bronce", owner="externo")
|
||||
def staging() -> Asset:
|
||||
"""Source asset (bronze, external): what the ingestion leaves."""
|
||||
return Asset("staging")
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python")
|
||||
def hechos(staging: Asset) -> Asset:
|
||||
"""Silver asset read from `staging`."""
|
||||
return Asset("hechos", 120)
|
||||
|
||||
|
||||
@config.when(registro_owner="python")
|
||||
@extract_fields({"def_parametro": Asset, "dim_periodo": Asset})
|
||||
@tag(layer="plata", owner="python")
|
||||
def registro__python() -> dict:
|
||||
"""One function, two silver assets (`def_parametro`, `dim_periodo`), selected by `registro_owner="python"`."""
|
||||
return {"def_parametro": Asset("def_parametro"), "dim_periodo": Asset("dim_periodo")}
|
||||
|
||||
|
||||
@tag(layer="oro", owner="python")
|
||||
def measure_report(hechos: Asset, def_parametro: Asset, dim_periodo: Asset) -> Asset:
|
||||
"""Gold asset that reads `hechos` and the two `registro` assets."""
|
||||
return Asset("measure_report", 37)
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset, measure_report: Asset) -> Asset:
|
||||
"""Silver asset that reads `hechos` and waits for `measure_report` without using its data (`depends_on`)."""
|
||||
return Asset("periodo_observacion")
|
||||
|
||||
|
||||
CYCLE = (staging, hechos, registro__python, measure_report, periodo_observacion)
|
||||
|
||||
|
||||
def test_a_consistent_cycle_passes():
|
||||
"""Pins down: a cycle where every asset has a producer, valid tags and a real `depends_on` validates,
|
||||
including the assets split out with `@extract_fields`.
|
||||
|
||||
Fails if `validate` rejects a valid graph, or if tags stop reaching the nodes `@extract_fields` creates.
|
||||
"""
|
||||
validate(_nodes(*CYCLE, registro_owner="python"))
|
||||
|
||||
|
||||
def test_an_asset_with_no_producer_must_be_a_declared_source():
|
||||
"""Pins down: an `Asset` input nobody produces is an error unless it's declared as a source.
|
||||
|
||||
Fails if `validate` stops treating Hamilton's required inputs of type `Asset` as missing producers,
|
||||
or ignores `sources`.
|
||||
"""
|
||||
nodes = _nodes(hechos)
|
||||
with pytest.raises(InvalidGraph, match="staging: read as an asset"):
|
||||
validate(nodes)
|
||||
validate(nodes, sources={"staging"})
|
||||
|
||||
|
||||
def test_a_producing_function_needs_valid_layer_and_owner():
|
||||
"""Pins down: a function returning `Asset` carries a `layer` from `Layer` and an `owner` from `Owner`.
|
||||
|
||||
Fails if either check is dropped or the enum values change.
|
||||
"""
|
||||
@tag(layer="platinum")
|
||||
def cohorte_miembro(hechos: Asset) -> Asset:
|
||||
"""An asset with an unknown layer and no owner."""
|
||||
return Asset("cohorte_miembro")
|
||||
|
||||
with pytest.raises(InvalidGraph) as error:
|
||||
validate(_nodes(staging, hechos, cohorte_miembro))
|
||||
assert "cohorte_miembro: `layer` tag is 'platinum'" in str(error.value)
|
||||
assert "cohorte_miembro: `owner` tag is None" in str(error.value)
|
||||
|
||||
|
||||
def test_depends_on_must_name_a_parameter():
|
||||
"""Pins down: `depends_on` names a parameter of the same function, so an order-only dependency is real
|
||||
in the graph.
|
||||
|
||||
Fails if `validate` stops comparing the tag with the node's dependencies.
|
||||
"""
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset) -> Asset:
|
||||
"""Declares `depends_on` on an asset that isn't one of its parameters."""
|
||||
return Asset("periodo_observacion")
|
||||
|
||||
with pytest.raises(InvalidGraph, match="depends_on` names 'measure_report'"):
|
||||
validate(_nodes(staging, hechos, periodo_observacion))
|
||||
|
||||
|
||||
def test_every_problem_is_reported_at_once():
|
||||
"""Pins down: `validate` reports every problem in one error, one per line, instead of stopping at the
|
||||
first.
|
||||
|
||||
Fails if it raises on the first problem or changes the one-line-per-problem format.
|
||||
"""
|
||||
@tag(layer="plata")
|
||||
def cohorte_miembro(staging: Asset) -> Asset:
|
||||
"""Reads `staging`, which nobody produces, and has no owner: two problems."""
|
||||
return Asset("cohorte_miembro")
|
||||
|
||||
with pytest.raises(InvalidGraph) as error:
|
||||
validate(_nodes(cohorte_miembro))
|
||||
assert len(str(error.value).splitlines()) == 2
|
||||
|
||||
|
||||
def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
||||
"""Pins down: `mermaid` draws one box per asset with its layer and owner, an arrow from producer to
|
||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registro`).
|
||||
|
||||
Fails if the diagram format changes, intermediate functions appear, or the order-only arrow stops
|
||||
being dotted.
|
||||
"""
|
||||
diagram = mermaid(_nodes(*CYCLE, registro_owner="python"))
|
||||
assert diagram.startswith("flowchart LR")
|
||||
assert 'hechos["hechos<br/>plata · python"]' in diagram
|
||||
assert " staging --> hechos" in diagram
|
||||
assert " def_parametro --> measure_report" in diagram
|
||||
assert "registro" not in diagram.replace("registro_owner", "")
|
||||
assert " measure_report -.-> periodo_observacion" in diagram
|
||||
assert " hechos --> periodo_observacion" in diagram
|
||||
|
||||
|
||||
def test_enum_values_are_the_tag_values():
|
||||
"""Pins down: the enum values are the strings written in the tags (`"plata"`, `"dbt"`).
|
||||
|
||||
Fails if a value is renamed, which would invalidate every tag already written.
|
||||
"""
|
||||
assert Layer.SILVER == "plata" and Owner.DBT == "dbt"
|
||||
@@ -0,0 +1,125 @@
|
||||
"""What this module covers: the cohort-build reads of `CohorteRepository`: `latest_build`, `members`,
|
||||
`build` and `builds`.
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables and three builds; `_build`
|
||||
writes one `cohorte_armado` row.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cacu.indicadores.models import (
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
)
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.aristas.oro import CohortBuild, CohorteRepository, CohortMember
|
||||
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
|
||||
|
||||
def _build(armado_id, url, fingerprint, known_until=None):
|
||||
"""A `cohorte_armado` row with the parameters the cohort builder writes; `known_until` is its
|
||||
`conocida_hasta`.
|
||||
"""
|
||||
parameters = {"reclutamiento_inicio": "2025-01-01", "reclutamiento_fin": "2026-01-01", "corte": "2025-12-31",
|
||||
"conocida_hasta": known_until}
|
||||
return CohorteArmado(armado_id=armado_id, url=url, version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros=json.dumps(parameters), datos_as_of=date(2025, 12, 31), huella=fingerprint, marco_sha="m" + fingerprint,
|
||||
n_miembros=2, armado_en=datetime(2026, 1, armado_id, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repository():
|
||||
"""Builds 1 and 3 of `cacu/cohorte_vigilancia` and build 2 of `cacu/otra`. Build 3 has patients 20 and
|
||||
10 (inserted in that order) and `conocida_hasta` 2026-01-02 08:00 UTC; build 1 has patient 99 and no
|
||||
load cut-off.
|
||||
"""
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
CaCuModel.metadata.create_all(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
_build(1, "cacu/cohorte_vigilancia", "a"),
|
||||
_build(2, "cacu/otra", "b"),
|
||||
_build(3, "cacu/cohorte_vigilancia", "c", known_until="2026-01-02T08:00:00+00:00"),
|
||||
CohorteMiembro(armado_id=3, pac_id=20, fecha_indice=date(2025, 3, 1), indice_fuente_tabla="citologiacervical",
|
||||
indice_fuente_id="20"),
|
||||
CohorteMiembro(armado_id=3, pac_id=10, fecha_indice=date(2025, 2, 1), indice_fuente_tabla="citologiacervical",
|
||||
indice_fuente_id="10"),
|
||||
CohorteMiembro(armado_id=1, pac_id=99, fecha_indice=date(2024, 1, 1), indice_fuente_tabla="citologiacervical",
|
||||
indice_fuente_id="99"),
|
||||
])
|
||||
session.commit()
|
||||
return CohorteRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def test_latest_build_of_a_cohort_among_several(repository):
|
||||
"""Pins down: `latest_build` returns the highest build id of the given cohort, ignoring other cohorts.
|
||||
|
||||
Fails if it stops filtering by `url` or picks the build by something other than its id.
|
||||
"""
|
||||
assert repository.latest_build("cacu/cohorte_vigilancia") == 3
|
||||
assert repository.latest_build("cacu/otra") == 2
|
||||
|
||||
|
||||
def test_members_of_a_build_in_order(repository):
|
||||
"""Pins down: `members` returns only that build's members, as `CohortMember`, ordered by `pac_id`.
|
||||
|
||||
Fails if the order or the fields of `CohortMember` change, or members of other builds leak in.
|
||||
"""
|
||||
assert repository.members(3) == [
|
||||
CohortMember(10, date(2025, 2, 1), "citologiacervical", "10"),
|
||||
CohortMember(20, date(2025, 3, 1), "citologiacervical", "20"),
|
||||
]
|
||||
|
||||
|
||||
def test_lineage_fields_of_a_build(repository):
|
||||
"""Pins down: `build` returns the lineage fields, with `conocida_hasta` parsed from the build's
|
||||
parameters.
|
||||
|
||||
Fails if a field of `CohortBuild` is dropped or reordered, or `conocida_hasta` stops being read from
|
||||
`parametros`.
|
||||
"""
|
||||
assert repository.build(3) == CohortBuild(3, "cacu/cohorte_vigilancia", "0.2.0", "c", "mc", date(2025, 12, 31),
|
||||
datetime(2026, 1, 2, 8, tzinfo=timezone.utc), 2,
|
||||
datetime(2026, 1, 3, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
def test_a_build_made_without_a_load_cut_has_no_known_until(repository):
|
||||
"""Pins down: a build whose `conocida_hasta` is null reports `None`.
|
||||
|
||||
Fails if a null cut-off is turned into a date.
|
||||
"""
|
||||
assert repository.build(1).conocida_hasta is None
|
||||
|
||||
|
||||
def test_every_build_newest_first_or_those_of_one_cohort(repository):
|
||||
"""Pins down: `builds` lists every build newest first, as `CohortBuild` with its lineage fields
|
||||
(`conocida_hasta` read from the parameters), and only one cohort's with `url`; an unknown cohort gives an
|
||||
empty list.
|
||||
|
||||
Fails if the order changes, the `url` filter is dropped, or a build's fields differ from `build`'s.
|
||||
"""
|
||||
assert [b.armado_id for b in repository.builds()] == [3, 2, 1]
|
||||
assert [b.armado_id for b in repository.builds("cacu/cohorte_vigilancia")] == [3, 1]
|
||||
assert repository.builds("cacu/cohorte_vigilancia")[0] == repository.build(3)
|
||||
assert repository.builds("cacu/no_existe") == []
|
||||
|
||||
|
||||
def test_unknown_cohort_or_build(repository):
|
||||
"""Pins down: an unknown cohort or build gives `None` or an empty list, not an error.
|
||||
|
||||
Fails if any of the three reads raises on missing data.
|
||||
"""
|
||||
assert repository.latest_build("cacu/no_existe") is None
|
||||
assert repository.build(42) is None
|
||||
assert repository.members(42) == []
|
||||
@@ -0,0 +1,86 @@
|
||||
"""What this module covers: `persistance.aristas.dbt`, reading what dbt owns: the timeline from its view
|
||||
(`DbtTimelineRepository`) and the queries it compiled (`DbtQueryRepository`).
|
||||
|
||||
Fixtures: `database`, an in-memory SQLite database with a table behind a `cacu_linea_de_tiempo` view holding three
|
||||
events, dates as text as dbt-sqlite leaves them, and a session factory over it.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS
|
||||
|
||||
EVENTS = [
|
||||
(2, "2025-02-01", "2025-06-01 00:00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
||||
(1, "2025-03-01", "2025-03-02 00:00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
||||
(1, "2025-01-05", "2025-01-06 00:00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def database():
|
||||
"""The view over a plain table, and a session factory on the same in-memory connection."""
|
||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})"))
|
||||
connection.execute(text("create view cacu_linea_de_tiempo as select * from eventos"))
|
||||
for row in EVENTS:
|
||||
connection.execute(text(f"insert into eventos values ({', '.join(':c%d' % i for i in range(10))})"),
|
||||
{f"c{i}": value for i, value in enumerate(row)})
|
||||
return engine, lambda: Session(engine)
|
||||
|
||||
|
||||
def test_timeline_comes_from_the_view_in_order_with_dates(database):
|
||||
"""Pins down: every event of the view, with the column contract, ordered by patient and date, and `fecha` as a
|
||||
date although SQLite stores text. Fails if the view's name, the order or the date type changes."""
|
||||
_, session_factory = database
|
||||
rows = DbtTimelineRepository(session_factory, "cacu").read()
|
||||
|
||||
assert [(row["pac_id"], row["fuente_id"]) for row in rows] == [(1, "1"), (1, "7"), (2, "3")]
|
||||
assert tuple(rows[0]) == TIMELINE_COLUMNS and rows[0]["fecha"] == date(2025, 1, 5)
|
||||
|
||||
|
||||
def test_filters_run_in_the_query(database):
|
||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows. Fails if a filter is ignored."""
|
||||
_, session_factory = database
|
||||
repository = DbtTimelineRepository(session_factory, "cacu")
|
||||
|
||||
assert {row["pac_id"] for row in repository.read(patients=[2])} == {2}
|
||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1))] == ["1"]
|
||||
|
||||
|
||||
def test_a_missing_view_names_the_dbt_command(database):
|
||||
"""Pins down: reading a domain whose view isn't created says which `dbt run` creates it. Fails if the driver's
|
||||
error reaches the caller unexplained."""
|
||||
_, session_factory = database
|
||||
|
||||
with pytest.raises(DbtRelationError, match="dbt run --select cama_linea_de_tiempo"):
|
||||
DbtTimelineRepository(session_factory, "cama").read()
|
||||
|
||||
|
||||
def test_a_compiled_query_gives_one_dict_per_row(database):
|
||||
"""Pins down: a query dbt compiled runs as written and returns its own columns. Fails if the rows lose their
|
||||
column names or the query is altered."""
|
||||
_, session_factory = database
|
||||
rows = DbtQueryRepository(session_factory).read(
|
||||
"with b as (select pac_id from cacu_linea_de_tiempo where tipo = 'biopsia') select distinct pac_id from b")
|
||||
|
||||
assert rows == [{"pac_id": 1}]
|
||||
|
||||
|
||||
def test_reading_writes_nothing(database):
|
||||
"""Pins down: both repositories read on a read-only session and leave the database as it was. Fails if a read
|
||||
starts committing or creating objects."""
|
||||
engine, session_factory = database
|
||||
DbtTimelineRepository(session_factory, "cacu").read()
|
||||
DbtQueryRepository(session_factory).read("select count(*) as n from cacu_linea_de_tiempo")
|
||||
|
||||
with engine.connect() as connection:
|
||||
names = connection.execute(text("select name from sqlite_master order by name")).fetchall()
|
||||
assert names == [("cacu_linea_de_tiempo",), ("eventos",)]
|
||||
@@ -0,0 +1,92 @@
|
||||
"""What this module covers: the per-patient reads of `CohorteRepository` behind the risk route: `membership` (the
|
||||
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons).
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
|
||||
(patient 10 in both, patient 20 only in build 1), patient 10's variables in build 2, and batches written and confirmed
|
||||
through the repository itself.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable,
|
||||
EvaluacionRiesgo, EvaluacionRiesgoLote)
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.aristas.oro import CohorteRepository, RiskHorizon
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
PROVENANCE = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"}
|
||||
|
||||
|
||||
def _build(armado_id):
|
||||
return CohorteArmado(armado_id=armado_id, url=URL, version=f"0.{armado_id}.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella=f"h{armado_id}", marco_sha="m",
|
||||
n_miembros=2, armado_en=datetime(2027, 1, armado_id, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
def _member(armado_id, pac_id):
|
||||
return CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=date(2025, 1, armado_id),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repository():
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
CaCuModel.metadata.create_all(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([_build(1), _build(2), _member(1, 10), _member(1, 20), _member(2, 10)])
|
||||
session.add_all([CohorteVariable(armado_id=2, pac_id=10, variable="pap_0", valor_codigo="ASC-US"),
|
||||
CohorteVariable(armado_id=2, pac_id=10, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
return CohorteRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def _batch(repository, version, risks, armado_id=2):
|
||||
return repository.guardar_lote(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
|
||||
|
||||
def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
||||
"""Pins down: the patient is looked up in the cohort's latest build, and its variables come as code or number.
|
||||
Fails if an older build is used (patient 20 would appear) or a numeric variable is lost."""
|
||||
found = repository.membership(10, URL)
|
||||
|
||||
assert (found.armado_id, found.version, found.fecha_indice) == (2, "0.2.0", date(2025, 1, 2))
|
||||
assert found.variables == {"pap_0": "ASC-US", "c": 0.0}
|
||||
assert repository.membership(20, URL) is None and repository.membership(10, "cacu/otra") is None
|
||||
|
||||
|
||||
def test_an_unconfirmed_batch_is_not_current(repository):
|
||||
"""Pins down: a batch with only preliminary evaluations isn't shown. Fails if a risk nobody confirmed reaches the
|
||||
patient's record."""
|
||||
_batch(repository, "1", [(10, 1.0, 0.2, None, None)])
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
|
||||
def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(repository):
|
||||
"""Pins down: among confirmed batches the newest wins, even when a newer unconfirmed one exists; its horizons come
|
||||
in ascending order with their latest state. Fails if the newest batch is taken regardless of its state, or the
|
||||
horizons come unordered."""
|
||||
first = _batch(repository, "1", [(10, 3.0, 0.3, None, None), (10, 1.0, 0.1, 0.05, 0.2)])
|
||||
repository.cambiar_estado(first, "final", "revisado")
|
||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
||||
|
||||
risk = repository.current_risk(10)
|
||||
|
||||
assert (risk.lote_id, risk.modelo_version, risk.estado_lote) == (first, "1", "final")
|
||||
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
|
||||
|
||||
|
||||
def test_an_annulled_batch_is_no_longer_current(repository):
|
||||
"""Pins down: once a confirmed batch is marked `entered-in-error`, its latest versions aren't final and it stops
|
||||
being current. Fails if any version ever confirmed keeps a withdrawn risk on the record."""
|
||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
||||
repository.cambiar_estado(first, "final", "revisado")
|
||||
repository.cambiar_estado(first, "entered-in-error", "modelo equivocado")
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
@@ -0,0 +1,142 @@
|
||||
"""What this module covers: `TimelineRepository` (column contract, filters, read-only session, binding the
|
||||
query) and the `timeline_repository` each domain module binds to dbt's view.
|
||||
|
||||
Fixtures: `session_factory`, an in-memory SQLite table `timeline_events` with the three events in `ROWS`;
|
||||
`timeline_query` stands in for the injected query over that table.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, create_engine, insert, select
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
||||
from persistance.materializador import SoloLectura
|
||||
|
||||
metadata = MetaData()
|
||||
events = Table(
|
||||
"timeline_events", metadata,
|
||||
Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime),
|
||||
Column("clase", String), Column("tipo", String), Column("codigo", String),
|
||||
Column("valor_codigo", String), Column("valor_numerico", Float),
|
||||
Column("fuente_tabla", String), Column("fuente_id", String),
|
||||
)
|
||||
|
||||
ROWS = [
|
||||
{"pac_id": 1, "fecha": date(2025, 1, 5), "conocida_en": datetime(2025, 1, 6), "clase": "procedimiento",
|
||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "SATISFACTORIA", "valor_numerico": None,
|
||||
"fuente_tabla": "citologiacervical", "fuente_id": "1"},
|
||||
{"pac_id": 1, "fecha": date(2025, 3, 1), "conocida_en": datetime(2025, 3, 2), "clase": "medicion",
|
||||
"tipo": "biopsia", "codigo": "cin", "valor_codigo": "LIEAG", "valor_numerico": None,
|
||||
"fuente_tabla": "biopsiacervical", "fuente_id": "7"},
|
||||
{"pac_id": 2, "fecha": date(2025, 2, 1), "conocida_en": datetime(2025, 6, 1), "clase": "procedimiento",
|
||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": None, "valor_numerico": None,
|
||||
"fuente_tabla": "citologiacervical", "fuente_id": "3"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session_factory():
|
||||
"""Three events: patient 1, a cytology (2025-01-05) and a biopsy (2025-03-01), both loaded early in
|
||||
2025; patient 2, a cytology (2025-02-01) loaded on 2025-06-01.
|
||||
"""
|
||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(insert(events), ROWS)
|
||||
return lambda: Session(engine)
|
||||
|
||||
|
||||
def timeline_query(*, patients, until, known_until):
|
||||
"""Stands in for the injected query: same columns and filters, over a plain table."""
|
||||
query = select(*(events.c[name] for name in TIMELINE_COLUMNS))
|
||||
if patients is not None:
|
||||
query = query.where(events.c.pac_id.in_(patients))
|
||||
if until is not None:
|
||||
query = query.where(events.c.fecha <= until)
|
||||
if known_until is not None:
|
||||
query = query.where(events.c.conocida_en <= known_until)
|
||||
return query.order_by(events.c.pac_id, events.c.fecha)
|
||||
|
||||
|
||||
def test_reads_every_event_with_the_contract_columns(session_factory):
|
||||
"""Pins down: with no filters, `read` returns every event as a dict keyed by `TIMELINE_COLUMNS`, in the
|
||||
query's order.
|
||||
|
||||
Fails if the keys or their order change, or rows are dropped or reordered.
|
||||
"""
|
||||
rows = TimelineRepository(session_factory, timeline_query).read()
|
||||
assert [tuple(row) for row in rows] == [TIMELINE_COLUMNS] * 3
|
||||
assert [(row["pac_id"], row["tipo"]) for row in rows] == [(1, "citologia"), (1, "biopsia"), (2, "citologia")]
|
||||
|
||||
|
||||
def test_filters_reach_the_query(session_factory):
|
||||
"""Pins down: `patients`, `until` and `known_until` reach the query unchanged (an iterator of patients
|
||||
included).
|
||||
|
||||
Fails if a filter is renamed, dropped or not turned into a list.
|
||||
"""
|
||||
repository = TimelineRepository(session_factory, timeline_query)
|
||||
assert [row["fuente_id"] for row in repository.read(patients=[1])] == ["1", "7"]
|
||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 5, 1))] == ["1", "7"]
|
||||
assert repository.read(patients=iter([2]), until=date(2025, 1, 31)) == []
|
||||
|
||||
|
||||
def test_a_query_with_other_columns_breaks_the_contract(session_factory):
|
||||
"""Pins down: `read` refuses a query whose columns aren't exactly `TIMELINE_COLUMNS`.
|
||||
|
||||
Fails if the contract check is removed, or `TIMELINE_COLUMNS` changes without the queries.
|
||||
"""
|
||||
def short_query(*, patients, until, known_until):
|
||||
"""Returns only two of the contract's columns."""
|
||||
return select(events.c.pac_id, events.c.fecha)
|
||||
|
||||
with pytest.raises(TimelineContractError, match="expected columns"):
|
||||
TimelineRepository(session_factory, short_query).read()
|
||||
|
||||
|
||||
def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
"""Pins down: the query runs on a `SesionDeLectura`, so a query that writes is rejected.
|
||||
|
||||
Fails if `read` uses a plain session.
|
||||
"""
|
||||
def writing_query(*, patients, until, known_until):
|
||||
"""Returns an INSERT instead of a SELECT."""
|
||||
return insert(events).values(pac_id=9)
|
||||
|
||||
with pytest.raises(SoloLectura):
|
||||
TimelineRepository(session_factory, writing_query).read()
|
||||
|
||||
|
||||
def test_a_repository_without_a_query_is_bound_with_with_query(session_factory):
|
||||
"""Pins down: a repository created without a query can't read, and `with_query` returns one that can,
|
||||
on the same session factory.
|
||||
|
||||
Fails if reading without a query stops raising `TimelineQueryMissing`, or `with_query` loses the
|
||||
session factory.
|
||||
"""
|
||||
unbound = TimelineRepository(session_factory)
|
||||
with pytest.raises(TimelineQueryMissing):
|
||||
unbound.read()
|
||||
assert len(unbound.with_query(timeline_query).read()) == 3
|
||||
|
||||
|
||||
def test_each_domain_module_reads_its_dbt_view_and_can_be_rebound(session_factory):
|
||||
"""Pins down: `persistance.cacu`, `cama` and `tea` each bind `timeline_repository` to their own dbt view and
|
||||
expose `dbt_query_repository`, and `with_query` still binds another query.
|
||||
|
||||
Fails if a domain module drops either repository, reads another domain's view, or loses `with_query`.
|
||||
"""
|
||||
from persistance import cacu, cama, tea
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
|
||||
for name, domain in (("cacu", cacu), ("cama", cama), ("tea", tea)):
|
||||
assert isinstance(domain.timeline_repository, DbtTimelineRepository)
|
||||
assert domain.timeline_repository.view == f"{name}_linea_de_tiempo"
|
||||
assert isinstance(domain.dbt_query_repository, DbtQueryRepository)
|
||||
rebound = cacu.timeline_repository.with_query(timeline_query)
|
||||
rebound._session_factory = session_factory
|
||||
assert len(rebound.read()) == 3
|
||||
@@ -0,0 +1,8 @@
|
||||
target/
|
||||
dbt_packages/
|
||||
logs/
|
||||
*.duckdb
|
||||
uv.lock
|
||||
.user.yml
|
||||
package-lock.yml
|
||||
.venv/
|
||||
@@ -0,0 +1,69 @@
|
||||
name: isssteleon
|
||||
version: "1.0.0"
|
||||
config-version: 2
|
||||
profile: cacu
|
||||
model-paths: ["models"]
|
||||
test-paths: ["tests"]
|
||||
vars:
|
||||
rec_inicio: "2018-01-01"
|
||||
rec_fin: "2026-12-31"
|
||||
ventana_basal_dias: 90
|
||||
grados_evento: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# Parámetros de corrida: se sobreescriben con --vars al ejecutar
|
||||
periodo_inicio: "2024-01-01"
|
||||
periodo_fin: "2024-07-01"
|
||||
fecha_corte: "2024-12-31"
|
||||
deteccion_grados: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# Parámetros de catálogo CaCu (cacu.parametros en indicadores_kit)
|
||||
calidad_insatisfactoria: "INSATISFACTORIO"
|
||||
citologia_anomala: ["ASC-US", "ASC-H", "LIEBG", "LIEAG", "CIS"]
|
||||
citologia_alto_grado: ["ASC-H", "LIEAG", "CIS"]
|
||||
catalogo_biopsia: ["NORMAL", "LIEBG", "LIEAG", "CIS", "CARCINOMA"]
|
||||
especialidades_diagnostico: ["CLINICA_MUJER_COLPOSCOPIA", "CIRUGIA_ONCOLOGICA"]
|
||||
# CIE-10 without the dot, compared exactly (the kit's cacu.diagnostico.cie and .cie_antecedente; provisional).
|
||||
# A medical note with one of these resolves a cytology:
|
||||
cie_diagnostico: ["Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
|
||||
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
# A note with one of these before the cytology leaves it out: the patient is already a case.
|
||||
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
horizonte_toma_reporte_dias: 60
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
||||
surveillance_cohort:
|
||||
recruitment_start: "2024-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# models/<project>/silver: what dbt derives from silver's procedimiento and observacion_clinica, compiled as
|
||||
# CTEs inside the models that use them (no objects in the database), except the timeline, a view.
|
||||
# models/<project>/gold/<family>: one view per indicator, a folder per family as in the kit.
|
||||
# Run one domain at a time against its own database: dbt build --profile cacu --select cacu
|
||||
models:
|
||||
isssteleon:
|
||||
cacu:
|
||||
silver:
|
||||
+materialized: ephemeral
|
||||
+tags: ["silver"]
|
||||
gold:
|
||||
+materialized: view
|
||||
+tags: ["gold"]
|
||||
cama:
|
||||
silver:
|
||||
+materialized: ephemeral
|
||||
+tags: ["silver"]
|
||||
gold:
|
||||
+materialized: view
|
||||
+tags: ["gold"]
|
||||
tea:
|
||||
silver:
|
||||
+materialized: ephemeral
|
||||
+tags: ["silver"]
|
||||
gold:
|
||||
+materialized: view
|
||||
+tags: ["gold"]
|
||||
|
||||
|
||||
# The project's own macros come first for dbt's dispatched macros (`datediff` on SQLite: macros/datediff.sql).
|
||||
dispatch:
|
||||
- macro_namespace: dbt
|
||||
search_order: ["isssteleon", "dbt"]
|
||||
@@ -0,0 +1,27 @@
|
||||
{#
|
||||
Casts for a model's output columns, so every engine returns the same types. dbt's type names work in
|
||||
CAST on SQLite, SQL Server and PostgreSQL; MySQL only casts to CHAR and SIGNED.
|
||||
#}
|
||||
{% macro as_text(expression) -%}
|
||||
{{ return(adapter.dispatch('as_text', 'isssteleon')(expression)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__as_text(expression) -%}
|
||||
cast({{ expression }} as {{ dbt.type_string() }})
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro mysql__as_text(expression) -%}
|
||||
cast({{ expression }} as char)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro as_integer(expression) -%}
|
||||
{{ return(adapter.dispatch('as_integer', 'isssteleon')(expression)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__as_integer(expression) -%}
|
||||
cast({{ expression }} as {{ dbt.type_int() }})
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro mysql__as_integer(expression) -%}
|
||||
cast({{ expression }} as signed)
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,17 @@
|
||||
{#
|
||||
A date written in the SQL, from a 'YYYY-MM-DD' value (a variable such as `fecha_corte`).
|
||||
|
||||
Elsewhere it's `cast('…' as date)`. SQLite has no date type: that cast yields the number 2025, so on SQLite
|
||||
the date stays an ISO string, which is what its date functions (`julianday`) read.
|
||||
#}
|
||||
{% macro date_literal(value) -%}
|
||||
{{ return(adapter.dispatch('date_literal', 'isssteleon')(value)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__date_literal(value) -%}
|
||||
cast('{{ value }}' as date)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlite__date_literal(value) -%}
|
||||
'{{ value }}'
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,22 @@
|
||||
{#
|
||||
dbt's `datediff` on SQLite, which has no `datediff` function: whole days between two dates, through
|
||||
`julianday`. Only days are needed so far; any other part fails at compile time instead of returning a
|
||||
wrong number. The other engines keep their own `datediff`.
|
||||
#}
|
||||
{% macro sqlite__datediff(first_date, second_date, datepart) -%}
|
||||
{%- if datepart | lower != 'day' -%}
|
||||
{{ exceptions.raise_compiler_error("datediff on SQLite only supports 'day', not '" ~ datepart ~ "'") }}
|
||||
{%- endif -%}
|
||||
cast(julianday({{ second_date }}) - julianday({{ first_date }}) as integer)
|
||||
{%- endmacro %}
|
||||
|
||||
{#
|
||||
On MySQL (dbt-mysql 1.7 has no `datediff` of its own, so dbt would write SQL Server's form): MySQL's
|
||||
`DATEDIFF(a, b)` is the whole days from b to a.
|
||||
#}
|
||||
{% macro mysql__datediff(first_date, second_date, datepart) -%}
|
||||
{%- if datepart | lower != 'day' -%}
|
||||
{{ exceptions.raise_compiler_error("datediff on MySQL only supports 'day', not '" ~ datepart ~ "'") }}
|
||||
{%- endif -%}
|
||||
datediff({{ second_date }}, {{ first_date }})
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,93 @@
|
||||
{#
|
||||
Each patient's timeline, from silver's procedimiento and observacion_clinica: one UNION ALL branch per source
|
||||
(a domain's `fuentes`, declared in its timeline model's YAML). Columns: pac_id, fecha, conocida_en, clase, tipo,
|
||||
codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id.
|
||||
|
||||
Per source:
|
||||
- the procedures of its `clase` (and `estudio_id`, unless null: an order of any study);
|
||||
- its value: the observation of `resultado_id`, read by the result's type in `cat_resultado` (a code is
|
||||
coalesce(valor_id, valor_fuente)), or a number with `valor: numerico`; without a result, the procedure's
|
||||
`columna`, trimmed;
|
||||
- its date and patient: the procedure's, or its parent's (`del_padre`); an observed date (`fecha_resultado`)
|
||||
goes first; `fecha: nacimiento` takes the person's birth date;
|
||||
- `conocida_en`: the start of the load that wrote the row (the observation's, or else the procedure's);
|
||||
- rows without a date are left out, and so are measurements, diagnoses and history without a value.
|
||||
#}
|
||||
{% macro linea_de_tiempo(fuentes) -%}
|
||||
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
||||
from (
|
||||
{%- for f in fuentes %}
|
||||
{% if not loop.first %}union all{% endif %}
|
||||
{{ linea_de_tiempo_fuente(f) }}
|
||||
{%- endfor %}
|
||||
) linea
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
{% macro linea_de_tiempo_fuente(f) -%}
|
||||
{%- set resultado = f.get('resultado_id') -%}
|
||||
{%- set con_fecha = 'padre' if f.get('del_padre') else 'p' -%}
|
||||
{%- set fecha = con_fecha ~ '.fecha' -%}
|
||||
{%- if f.get('fecha_resultado') -%}{%- set fecha = 'coalesce(fecha_observada.valor_fecha, ' ~ fecha ~ ')' -%}{%- endif -%}
|
||||
{%- if f.get('fecha') == 'nacimiento' -%}{%- set fecha = 'persona.fecha_nacimiento' -%}{%- endif -%}
|
||||
{%- if resultado and f.get('valor') == 'numerico' -%}
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
{%- set valor_numerico = 'cast(o.valor_numerico as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif resultado -%}
|
||||
{%- set valor_codigo = as_text(
|
||||
"case r.tipo_valor"
|
||||
~ " when 'codigo' then coalesce(o.valor_id, o.valor_fuente)"
|
||||
~ " when 'booleano' then " ~ as_integer('o.valor_numerico')
|
||||
~ " when 'numero' then o.valor_numerico"
|
||||
~ " when 'fecha' then o.valor_fecha"
|
||||
~ " else o.valor_texto end") -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif f.get('columna') -%}
|
||||
{%- set valor_codigo = "nullif(trim(p." ~ f['columna'] ~ "), '')" -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- else -%}
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- endif %}
|
||||
select
|
||||
{{ con_fecha }}.pac_id as pac_id,
|
||||
{{ fecha }} as fecha,
|
||||
carga.inicio as conocida_en,
|
||||
{{ as_text("'" ~ f['clase_de_linea'] ~ "'") }} as clase,
|
||||
{{ as_text("'" ~ f['tipo'] ~ "'") }} as tipo,
|
||||
{{ as_text("'" ~ (f.get('codigo') or f['tipo']) ~ "'") }} as codigo,
|
||||
{{ valor_codigo }} as valor_codigo,
|
||||
{{ valor_numerico }} as valor_numerico,
|
||||
p.fuente_tabla as fuente_tabla,
|
||||
p.fuente_id as fuente_id
|
||||
from {{ source('silver', 'procedimiento') }} p
|
||||
{%- if resultado %}
|
||||
left join {{ source('silver', 'observacion_clinica') }} o
|
||||
on o.procedimiento_id = p.procedimiento_id and o.resultado_id = '{{ resultado }}'
|
||||
left join {{ source('silver', 'cat_resultado') }} r
|
||||
on r.resultado_id = '{{ resultado }}'
|
||||
{%- endif %}
|
||||
{%- if f.get('del_padre') %}
|
||||
join {{ source('silver', 'procedimiento') }} padre
|
||||
on padre.procedimiento_id = p.padre_id
|
||||
{%- endif %}
|
||||
{%- if f.get('fecha_resultado') %}
|
||||
left join {{ source('silver', 'observacion_clinica') }} fecha_observada
|
||||
on fecha_observada.procedimiento_id = {{ con_fecha }}.procedimiento_id
|
||||
and fecha_observada.resultado_id = '{{ f['fecha_resultado'] }}'
|
||||
{%- endif %}
|
||||
{%- if f.get('fecha') == 'nacimiento' %}
|
||||
join {{ source('silver', 'persona') }} persona
|
||||
on persona.pac_id = {{ con_fecha }}.pac_id
|
||||
{%- endif %}
|
||||
join {{ source('silver', 'carga') }} carga
|
||||
on carga.carga_id = {{ 'coalesce(o.carga_id, p.carga_id)' if resultado else 'p.carga_id' }}
|
||||
where p.clase = '{{ f['clase'] }}'
|
||||
and {{ fecha }} is not null
|
||||
{%- if f.get('estudio_id') %}
|
||||
and p.estudio_id = '{{ f['estudio_id'] }}'
|
||||
{%- endif %}
|
||||
{%- if f['clase_de_linea'] in ['medicion', 'diagnostico', 'antecedente'] %}
|
||||
and ({{ valor_codigo }} is not null or {{ valor_numerico }} is not null)
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,16 @@
|
||||
version: 2
|
||||
|
||||
# Silver, the same tables in every domain: each domain has its own database, chosen by the profile
|
||||
# (`--profile cacu|cama|tea`). Written by the Python load; dbt only reads them.
|
||||
sources:
|
||||
- name: silver
|
||||
schema: main
|
||||
tables:
|
||||
- name: procedimiento
|
||||
- name: observacion_clinica
|
||||
- name: persona
|
||||
- name: carga
|
||||
- name: cat_estudio
|
||||
- name: cat_resultado
|
||||
- name: cat_valor
|
||||
- name: dim_fecha
|
||||
@@ -0,0 +1,80 @@
|
||||
version: 2
|
||||
|
||||
# The surveillance cohort, one query per rule. Each is compiled, not created: `models cohorts build` reads the compiled
|
||||
# SQL from the manifest and chains the rules in `order`. A new exclusion is one query and one entry here; it returns the
|
||||
# `pac_id` of everyone it flags and reads only the index date and the data, never another exclusion, so the study
|
||||
# population doesn't depend on the order. `order` only says which rule is charged for a patient several flag.
|
||||
# Parameters: the `surveillance_cohort` var in dbt_project.yml.
|
||||
models:
|
||||
- name: cacu_surveillance_all_patients
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_vigilancia
|
||||
kind: population
|
||||
cutoff: "{{ var('surveillance_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('surveillance_cohort') | tojson }}"
|
||||
- name: cacu_surveillance_index_date
|
||||
description: First cytology in the patient's history, if it falls in the recruitment window. Sets the index date.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: index}}
|
||||
- name: cacu_surveillance_excl_prior_event
|
||||
description: Biopsy with the outcome before the index date, so not at risk of a first event.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: prior_event, order: 1}}
|
||||
- name: cacu_surveillance_excl_no_index_result
|
||||
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: no_index_result, order: 2}}
|
||||
|
||||
unit_tests:
|
||||
- name: prior_event_flags_an_earlier_biopsy_with_the_outcome
|
||||
description: >
|
||||
Pins down: patient 1 has a biopsy with the outcome before the index date. Patient 2's is on the index date, patient
|
||||
3's has no outcome and patient 4's is a cytology, so none of them is flagged. Fails if the date comparison, the
|
||||
grades or the event type change.
|
||||
model: cacu_surveillance_excl_prior_event
|
||||
overrides:
|
||||
vars:
|
||||
surveillance_cohort: {recruitment_start: "2024-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"]}
|
||||
given:
|
||||
- input: ref('cacu_surveillance_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-01' as fecha_indice union all select 2, '2025-01-01'
|
||||
union all select 3, '2025-01-01' union all select 4, '2025-01-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-06-01' as fecha, 'biopsia' as tipo, 'LIEAG' as valor_codigo
|
||||
union all select 2, '2025-01-01', 'biopsia', 'LIEAG'
|
||||
union all select 3, '2024-06-01', 'biopsia', 'NORMAL'
|
||||
union all select 4, '2024-06-01', 'bethesda', 'LIEAG'
|
||||
expect:
|
||||
rows:
|
||||
- {pac_id: 1}
|
||||
- name: no_index_result_ignores_results_of_other_cytologies
|
||||
description: >
|
||||
Pins down: patient 1 has a result on its index cytology and patient 2 has an HPV result there, so neither is
|
||||
flagged. Patient 3's only result belongs to another cytology and patient 4's has no value, so both are. Fails if the
|
||||
rule stops matching the index cytology or counts an empty result.
|
||||
model: cacu_surveillance_excl_no_index_result
|
||||
overrides:
|
||||
vars:
|
||||
surveillance_cohort: {recruitment_start: "2024-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"]}
|
||||
given:
|
||||
- input: ref('cacu_surveillance_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, 'citologiacervical' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
union all select 2, 'citologiacervical', 'b' union all select 3, 'citologiacervical', 'c'
|
||||
union all select 4, 'citologiacervical', 'd'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, 'bethesda' as tipo, 'citologiacervical' as fuente_tabla, 'a' as fuente_id, '2025-01-01' as fecha, 'NORMAL' as valor_codigo
|
||||
union all select 2, 'vph', 'citologiacervical', 'b', '2025-01-01', 'POSITIVO'
|
||||
union all select 3, 'bethesda', 'citologiacervical', 'other', '2025-01-01', 'NORMAL'
|
||||
union all select 4, 'bethesda', 'citologiacervical', 'd', '2025-01-01', null
|
||||
expect:
|
||||
rows:
|
||||
- {pac_id: 3}
|
||||
- {pac_id: 4}
|
||||
@@ -0,0 +1,3 @@
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
select pac_id
|
||||
from {{ source('silver', 'persona') }}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{# Candidates whose index cytology has neither a cytology result nor an HPV result. #}
|
||||
{% set p = var('surveillance_cohort') %}
|
||||
select c.pac_id
|
||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
||||
where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo in ('bethesda', 'vph')
|
||||
and e.fuente_tabla = c.indice_fuente_tabla
|
||||
and e.fuente_id = c.indice_fuente_id
|
||||
and e.fecha <= '{{ p.cutoff }}'
|
||||
and e.valor_codigo is not null
|
||||
)
|
||||
@@ -0,0 +1,8 @@
|
||||
{# Candidates with a biopsy showing the outcome before their index date. #}
|
||||
{% set p = var('surveillance_cohort') %}
|
||||
select distinct c.pac_id
|
||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
|
||||
where e.tipo = 'biopsia'
|
||||
and e.fecha < c.fecha_indice
|
||||
and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
|
||||
@@ -0,0 +1,12 @@
|
||||
{# The patient's first cytology up to the cut-off, if it falls in the recruitment window. #}
|
||||
{% set p = var('surveillance_cohort') %}
|
||||
with cytologies as (
|
||||
select
|
||||
pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_id) as position
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where tipo = 'citologia' and fecha <= '{{ p.cutoff }}'
|
||||
)
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
|
||||
from cytologies
|
||||
where position = 1 and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
-- CACU_CONFIRMACION_CITOLOGIA: confirmación por biopsia según resultado citológico. Unidad: paciente.
|
||||
-- población: pacientes cuya última citología válida del periodo es de alto grado (citologia_alto_grado)
|
||||
-- categoría: grado más grave de biopsia originada por esa citología (ligada por toma_id);
|
||||
-- SIN_BIOPSIA si no tiene ninguna; SIN_DATO si tiene pero sin grado
|
||||
-- gravedad: orden de catalogo_biopsia, de menos a más grave
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Último resultado válido por paciente, con su toma_id para ligar biopsias
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
procedimiento_id as toma_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, toma_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
),
|
||||
|
||||
de_alto_grado as (
|
||||
select pac_id, toma_id
|
||||
from ultimo_resultado
|
||||
where resultado in ({% for g in var("citologia_alto_grado") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
),
|
||||
|
||||
-- Biopsia más grave ligada a la toma de esa citología
|
||||
por_gravedad as (
|
||||
select
|
||||
d.pac_id,
|
||||
b.grado,
|
||||
row_number() over (
|
||||
partition by d.pac_id
|
||||
order by
|
||||
case b.grado
|
||||
{% for g in var("catalogo_biopsia") %}
|
||||
when '{{ g }}' then {{ loop.index }}
|
||||
{% endfor %}
|
||||
else 0
|
||||
end desc,
|
||||
b.fecha_reporte desc,
|
||||
b.fuente_id desc
|
||||
) as lugar
|
||||
from de_alto_grado d
|
||||
join biopsias b
|
||||
on b.toma_id = d.toma_id
|
||||
and b.pac_id = d.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
biopsia_mas_grave as (
|
||||
select pac_id, grado
|
||||
from por_gravedad
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
d.pac_id as unidad_id,
|
||||
'TOTAL' as grupo,
|
||||
case
|
||||
when b.pac_id is null then 'SIN_BIOPSIA'
|
||||
else coalesce(b.grado, 'SIN_DATO')
|
||||
end as categoria
|
||||
from de_alto_grado d
|
||||
left join biopsia_mas_grave b on b.pac_id = d.pac_id
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_confirmacion_citologia
|
||||
description: "Confirmación por biopsia del resultado citológico de alto grado (C2). Población: pacientes cuya última citología válida del periodo es de alto grado."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
citologia_alto_grado: cacu.citologia_alto_grado
|
||||
catalogo_biopsia: cacu.catalogo_biopsia
|
||||
poblaciones:
|
||||
initial-population: "Pacientes cuya última citología válida del periodo es de alto grado"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: categoria
|
||||
description: "Grado más grave de biopsia ligada a esa citología; SIN_BIOPSIA o SIN_DATO"
|
||||
@@ -0,0 +1,106 @@
|
||||
-- CACU_DIAS_TOMA_DIAGNOSTICO: días naturales de la toma de citología al diagnóstico. Unidad: examen. C3r.
|
||||
-- initial-population: citologías del periodo medibles (sin antecedente previo y con horizonte vencido o diagnóstico)
|
||||
-- measure-observation: de ellas, con diagnóstico, con los días
|
||||
--
|
||||
-- El diagnóstico es la primera nota con CIE en cie_diagnostico y especialidad en
|
||||
-- especialidades_diagnostico, posterior a la toma y dentro del horizonte.
|
||||
-- Se excluyen tomas de pacientes con nota con CIE en cie_antecedente anterior a la toma.
|
||||
-- Workaround SQLite 3.40: primer_antecedente y join a diagnosticos se calculan una vez
|
||||
-- mediante uniones, no subconsultas correlacionadas (ver consultas/tiempos.py).
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
notas as (
|
||||
select * from {{ ref('cacu_notas') }}
|
||||
),
|
||||
|
||||
-- Notas que cuentan como diagnóstico: CIE en la lista Y especialidad conocida
|
||||
diagnosticos as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_diagnostico") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.especialidad in ({% for e in var("especialidades_diagnostico") %}'{{ e }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
-- Notas que cuentan como antecedente (incidencia previa)
|
||||
antecedentes as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_antecedente") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select fuente_id, pac_id, fecha_toma as toma
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Primer antecedente por paciente (calculado una vez, no correlacionado)
|
||||
primer_antecedente as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from antecedentes
|
||||
group by pac_id
|
||||
),
|
||||
|
||||
-- Primer diagnóstico posterior a la toma y dentro del horizonte, por toma
|
||||
tomas_con_fechas as (
|
||||
select
|
||||
t.fuente_id,
|
||||
t.pac_id,
|
||||
t.toma,
|
||||
pa.fecha as antecedente,
|
||||
min(d.fecha) as diagnostico
|
||||
from tomas_del_periodo t
|
||||
left join primer_antecedente pa
|
||||
on pa.pac_id = t.pac_id
|
||||
left join diagnosticos d
|
||||
on d.pac_id = t.pac_id
|
||||
and d.fecha > t.toma
|
||||
and {{ dbt.datediff("t.toma", "d.fecha", "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }}
|
||||
group by t.fuente_id, t.pac_id, t.toma, pa.fecha
|
||||
),
|
||||
|
||||
-- Excluir tomas de pacientes con antecedente anterior a la toma
|
||||
tomas as (
|
||||
select fuente_id, pac_id, toma, diagnostico
|
||||
from tomas_con_fechas
|
||||
where antecedente is null or antecedente >= toma
|
||||
),
|
||||
|
||||
con_estado as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
toma,
|
||||
diagnostico,
|
||||
diagnostico is null
|
||||
and {{ dbt.datediff("toma", date_literal(var("fecha_corte")), "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }} as pendiente
|
||||
from tomas
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select fuente_id as unidad_id, pac_id, 'TOTAL' as grupo
|
||||
from con_estado
|
||||
where not pendiente
|
||||
),
|
||||
|
||||
observacion as (
|
||||
select
|
||||
fuente_id as unidad_id,
|
||||
pac_id,
|
||||
'TOTAL' as grupo,
|
||||
{{ dbt.datediff("toma", "diagnostico", "day") }} as valor
|
||||
from con_estado
|
||||
where diagnostico is not null
|
||||
)
|
||||
|
||||
select 'initial-population' as poblacion, unidad_id, pac_id, grupo, null as valor from poblacion_inicial
|
||||
union all
|
||||
select 'measure-observation' as poblacion, unidad_id, pac_id, grupo, valor from observacion
|
||||
@@ -0,0 +1,29 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_dias_toma_diagnostico
|
||||
description: "Días naturales de la toma de citología al diagnóstico en nota médica (C3r). Unidad: examen. Excluye tomas de pacientes con diagnóstico previo."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
contrato: C3r
|
||||
unidad: examen
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
horizonte_toma_diagnostico_dias: cacu.horizontes.toma_diagnostico_dias
|
||||
especialidades_diagnostico: cacu.diagnostico.especialidades
|
||||
poblaciones:
|
||||
initial-population: "Citologías medibles: sin antecedente previo y con horizonte vencido o diagnóstico al corte"
|
||||
measure-observation: "De ellas, con primera nota de diagnóstico, con los días"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "initial-population | measure-observation"
|
||||
- name: unidad_id
|
||||
description: "fuente_id de la citología"
|
||||
- name: pac_id
|
||||
description: "pac_id del paciente (para estratificación)"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: valor
|
||||
description: "Días naturales de toma a primera nota de diagnóstico (NULL en initial-population)"
|
||||
@@ -0,0 +1,44 @@
|
||||
-- CACU_EU13: pacientes tamizadas con lesión confirmada por biopsia.
|
||||
-- denominador: pacientes con citología tomada en el periodo
|
||||
-- numerador: de ellas, las que tienen biopsia reportada con grado en deteccion_grados,
|
||||
-- originada por una de sus citologías del periodo (ligada por toma_id)
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select distinct
|
||||
procedimiento_id,
|
||||
pac_id
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
),
|
||||
|
||||
denominador as (
|
||||
select unidad_id from poblacion_inicial
|
||||
),
|
||||
|
||||
numerador as (
|
||||
select distinct t.pac_id as unidad_id
|
||||
from tomas_del_periodo t
|
||||
join biopsias b
|
||||
on b.toma_id = t.procedimiento_id
|
||||
and b.pac_id = t.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and b.grado in ({% for g in var("deteccion_grados") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
)
|
||||
|
||||
select 'denominador' as poblacion, unidad_id from denominador
|
||||
union all
|
||||
select 'numerador' as poblacion, unidad_id from numerador
|
||||
@@ -0,0 +1,22 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu13
|
||||
description: "Pacientes tamizadas con lesión confirmada por biopsia (C1). Denominador: con citología en el periodo. Numerador: con biopsia ligada a esa citología con grado en deteccion_grados."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU13"
|
||||
contrato: C1
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
deteccion_grados: cacu.deteccion_grados
|
||||
poblaciones:
|
||||
denominador: "Pacientes con citología tomada en el periodo"
|
||||
numerador: "De ellas, con biopsia reportada con grado en deteccion_grados"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "denominador | numerador"
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
@@ -0,0 +1,49 @@
|
||||
-- CACU_EU7: distribución de resultados citológicos por semestre. Unidad: paciente.
|
||||
-- población: pacientes con ≥1 citología tomada en el periodo
|
||||
-- resultado: último resultado válido del periodo a la fecha de corte; SIN_DATO si ninguna
|
||||
-- válida: tiene resultado, reportada al corte, calidad ≠ calidad_insatisfactoria
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
pac_id as unidad_id,
|
||||
coalesce(resultado, 'SIN_DATO') as categoria,
|
||||
'TOTAL' as grupo
|
||||
from ultimo_resultado
|
||||
@@ -0,0 +1,23 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu7
|
||||
description: "Distribución de resultados citológicos por semestre (C2). Último resultado válido por paciente al corte; SIN_DATO si ninguno válido."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU7"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
poblaciones:
|
||||
initial-population: "Pacientes con ≥1 citología tomada en el periodo"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: categoria
|
||||
description: "Resultado citológico (bethesda) o SIN_DATO"
|
||||
- name: grupo
|
||||
description: "TOTAL (sin desgloses por ahora)"
|
||||
@@ -0,0 +1,31 @@
|
||||
-- CACU_IND1: pacientes tamizadas con resultado citológico anómalo. Unidad: paciente. C1.
|
||||
-- denominador: pacientes con ≥1 citología tomada en el periodo
|
||||
-- numerador: de ellas, las que tienen alguna con resultado en citologia_anomala
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select
|
||||
pac_id,
|
||||
resultado
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
denominador as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
),
|
||||
|
||||
numerador as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
where resultado in ({% for r in var("citologia_anomala") %}'{{ r }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
)
|
||||
|
||||
select 'denominador' as poblacion, unidad_id from denominador
|
||||
union all
|
||||
select 'numerador' as poblacion, unidad_id from numerador
|
||||
@@ -0,0 +1,21 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_ind1
|
||||
description: "Pacientes tamizadas con resultado citológico anómalo (C1). Denominador: con ≥1 citología en el periodo. Numerador: con algún resultado en citologia_anomala."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_IND1"
|
||||
contrato: C1
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
citologia_anomala: cacu.citologia_anomala
|
||||
poblaciones:
|
||||
denominador: "Pacientes con ≥1 citología tomada en el periodo"
|
||||
numerador: "De ellas, con algún resultado en citologia_anomala"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "denominador | numerador"
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
@@ -0,0 +1,66 @@
|
||||
-- CACU_TIEMPO_REPORTE: días naturales de la toma de citología a su resultado. Unidad: examen. C3r.
|
||||
-- initial-population: citologías tomadas en el periodo que ya se pueden medir
|
||||
-- (con resultado al corte o con el horizonte ya vencido)
|
||||
-- measure-observation: de ellas, las que tienen resultado, con sus días
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
tomas as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
fecha_toma as toma,
|
||||
case
|
||||
when fecha_reporte <= '{{ var("fecha_corte") }}' then fecha_reporte
|
||||
end as reporte
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
con_estado as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
toma,
|
||||
reporte,
|
||||
reporte is null
|
||||
and {{ dbt.datediff("toma", date_literal(var("fecha_corte")), "day") }}
|
||||
< {{ var("horizonte_toma_reporte_dias") }} as pendiente
|
||||
from tomas
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select fuente_id as unidad_id, pac_id, 'TOTAL' as grupo
|
||||
from con_estado
|
||||
where not pendiente
|
||||
),
|
||||
|
||||
observacion as (
|
||||
select
|
||||
fuente_id as unidad_id,
|
||||
pac_id,
|
||||
'TOTAL' as grupo,
|
||||
{{ dbt.datediff("toma", "reporte", "day") }} as valor
|
||||
from con_estado
|
||||
where reporte is not null
|
||||
)
|
||||
|
||||
-- Typed output: the same columns and types on every engine (and SQLite reports no type for an untyped literal).
|
||||
select
|
||||
{{ as_text("'initial-population'") }} as poblacion,
|
||||
{{ as_text("unidad_id") }} as unidad_id,
|
||||
{{ as_integer("pac_id") }} as pac_id,
|
||||
{{ as_text("grupo") }} as grupo,
|
||||
{{ as_integer("null") }} as valor
|
||||
from poblacion_inicial
|
||||
union all
|
||||
select
|
||||
{{ as_text("'measure-observation'") }},
|
||||
{{ as_text("unidad_id") }},
|
||||
{{ as_integer("pac_id") }},
|
||||
{{ as_text("grupo") }},
|
||||
{{ as_integer("valor") }}
|
||||
from observacion
|
||||
@@ -0,0 +1,64 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_tiempo_reporte
|
||||
description: "Días naturales de la toma de citología a su resultado (C3r). Unidad: examen."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_TIEMPO_REPORTE"
|
||||
contrato: C3r
|
||||
unidad: examen
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
horizonte_toma_reporte_dias: cacu.horizontes.toma_reporte_dias
|
||||
poblaciones:
|
||||
initial-population: "Citologías del periodo medibles al corte (con resultado o con horizonte vencido)"
|
||||
measure-observation: "De ellas, las que tienen resultado, con los días de toma a reporte"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "initial-population | measure-observation"
|
||||
- name: unidad_id
|
||||
description: "fuente_id de la citología"
|
||||
- name: pac_id
|
||||
description: "pac_id del paciente (para estratificación)"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: valor
|
||||
description: "Días naturales de toma a reporte (NULL en initial-population)"
|
||||
|
||||
unit_tests:
|
||||
- name: tiempo_reporte_counts_days_with_the_engine_s_datediff
|
||||
description: >
|
||||
Pins down: days from sample to report are whole calendar days, across a month boundary (A, 30) and
|
||||
across the end of February (B, 10); a sample without a report still inside the horizon is pending and
|
||||
left out (C, 44 days < 60); one past the horizon counts in the population without a value (D). On
|
||||
SQLite this goes through the project's `sqlite__datediff`. Fails if `datediff` counts anything but
|
||||
whole days, takes its arguments in another order, or the horizon check changes side.
|
||||
model: cacu_tiempo_reporte
|
||||
overrides:
|
||||
vars:
|
||||
periodo_inicio: "2025-01-01"
|
||||
periodo_fin: "2025-07-01"
|
||||
fecha_corte: "2025-07-15"
|
||||
horizonte_toma_reporte_dias: 60
|
||||
given:
|
||||
- input: ref('cacu_citologias')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as procedimiento_id, 'citologiacervical' as fuente_tabla, 'A' as fuente_id, 1 as pac_id,
|
||||
'2025-01-10' as fecha_toma, null as orden_numero, null as calidad_muestra, null as resultado,
|
||||
'2025-02-09' as fecha_reporte, null as vph, null as genotipo_16_18
|
||||
union all
|
||||
select 2, 'citologiacervical', 'B', 2, '2025-02-20', null, null, null, '2025-03-02', null, null
|
||||
union all
|
||||
select 3, 'citologiacervical', 'C', 3, '2025-06-01', null, null, null, null, null, null
|
||||
union all
|
||||
select 4, 'citologiacervical', 'D', 4, '2025-03-01', null, null, null, null, null, null
|
||||
expect:
|
||||
rows:
|
||||
- {poblacion: initial-population, unidad_id: A, pac_id: 1, grupo: TOTAL, valor: null}
|
||||
- {poblacion: initial-population, unidad_id: B, pac_id: 2, grupo: TOTAL, valor: null}
|
||||
- {poblacion: initial-population, unidad_id: D, pac_id: 4, grupo: TOTAL, valor: null}
|
||||
- {poblacion: measure-observation, unidad_id: A, pac_id: 1, grupo: TOTAL, valor: 30}
|
||||
- {poblacion: measure-observation, unidad_id: B, pac_id: 2, grupo: TOTAL, valor: 10}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
Una fila por biopsia REPORTE con su grado y el procedimiento_id de la toma
|
||||
de citología que la originó (toma_id).
|
||||
|
||||
Jerarquía: toma_citologia → orden_biopsia → reporte_biopsia
|
||||
- p_rep.padre_id = procedimiento_id de la orden biopsia
|
||||
- p_ord.padre_id = procedimiento_id de la toma citología
|
||||
|
||||
padre_id es el padre_id del procedimiento en silver.
|
||||
Equivalente dbt de plata.py::biopsias().
|
||||
*/
|
||||
|
||||
SELECT
|
||||
p_rep.procedimiento_id,
|
||||
p_rep.fuente_tabla,
|
||||
p_rep.fuente_id,
|
||||
p_rep.pac_id,
|
||||
p_rep.fecha AS fecha_reporte,
|
||||
o_grado.valor_id AS grado,
|
||||
p_ord.fecha AS fecha_solicitud,
|
||||
p_ord.orden_numero,
|
||||
p_toma.procedimiento_id AS toma_id,
|
||||
p_toma.pac_id AS toma_pac_id,
|
||||
p_toma.fecha AS fecha_toma
|
||||
FROM {{ source('silver', 'procedimiento') }} p_rep
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_grado
|
||||
ON o_grado.procedimiento_id = p_rep.procedimiento_id
|
||||
AND o_grado.resultado_id = 'biopsia.grado'
|
||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_ord
|
||||
ON p_ord.procedimiento_id = p_rep.padre_id
|
||||
AND p_ord.estudio_id = 'biopsia'
|
||||
AND p_ord.clase = 'orden'
|
||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_toma
|
||||
ON p_toma.procedimiento_id = p_ord.padre_id
|
||||
AND p_toma.estudio_id = 'citologia'
|
||||
AND p_toma.clase = 'toma'
|
||||
WHERE p_rep.estudio_id = 'biopsia'
|
||||
AND p_rep.clase = 'reporte'
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Una fila por citología TOMA con sus resultados (bethesda, VPH).
|
||||
Los tres procedimientos (toma, reporte-citología, reporte-vph) comparten
|
||||
fuente_id = cit_id porque los tres vienen de la misma fila de citologia_cervical.
|
||||
|
||||
Equivalente dbt de plata.py::citologias().
|
||||
*/
|
||||
|
||||
SELECT
|
||||
p_toma.procedimiento_id,
|
||||
p_toma.fuente_tabla,
|
||||
p_toma.fuente_id,
|
||||
p_toma.pac_id,
|
||||
p_toma.fecha AS fecha_toma,
|
||||
p_toma.orden_numero,
|
||||
o_cal.valor_id AS calidad_muestra,
|
||||
o_beth.valor_id AS resultado,
|
||||
p_rep.fecha AS fecha_reporte,
|
||||
o_vph.valor_id AS vph,
|
||||
o_vph_g.valor_numerico AS genotipo_16_18
|
||||
FROM {{ source('silver', 'procedimiento') }} p_toma
|
||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_rep
|
||||
ON p_rep.fuente_tabla = p_toma.fuente_tabla
|
||||
AND p_rep.fuente_id = p_toma.fuente_id
|
||||
AND p_rep.estudio_id = 'citologia'
|
||||
AND p_rep.clase = 'reporte'
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_beth
|
||||
ON o_beth.procedimiento_id = p_rep.procedimiento_id
|
||||
AND o_beth.resultado_id = 'citologia.bethesda'
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_cal
|
||||
ON o_cal.procedimiento_id = p_toma.procedimiento_id
|
||||
AND o_cal.resultado_id = 'citologia.calidad_muestra'
|
||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_vph
|
||||
ON p_vph.fuente_tabla = p_toma.fuente_tabla
|
||||
AND p_vph.fuente_id = p_toma.fuente_id
|
||||
AND p_vph.estudio_id = 'vph'
|
||||
AND p_vph.clase = 'reporte'
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_vph
|
||||
ON o_vph.procedimiento_id = p_vph.procedimiento_id
|
||||
AND o_vph.resultado_id = 'vph.resultado'
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_vph_g
|
||||
ON o_vph_g.procedimiento_id = p_vph.procedimiento_id
|
||||
AND o_vph_g.resultado_id = 'vph.genotipo_16_18'
|
||||
WHERE p_toma.estudio_id = 'citologia'
|
||||
AND p_toma.clase = 'toma'
|
||||
@@ -0,0 +1,4 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cacu_linea_de_tiempo.yml. #}
|
||||
{{ config(materialized = 'view') }}
|
||||
|
||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
||||
@@ -0,0 +1,23 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_linea_de_tiempo
|
||||
description: >
|
||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
||||
observation is adding a source here.
|
||||
config:
|
||||
meta:
|
||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
||||
# del_padre (date and patient from the parent procedure).
|
||||
fuentes:
|
||||
- {estudio_id: "citologia", clase: "toma", resultado_id: "citologia.calidad_muestra", clase_de_linea: "procedimiento", tipo: "citologia", codigo: "citologia_cervical"}
|
||||
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.bethesda", clase_de_linea: "medicion", tipo: "bethesda", codigo: "bethesda"}
|
||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.resultado", clase_de_linea: "medicion", tipo: "vph", codigo: "vph"}
|
||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.genotipo_16_18", clase_de_linea: "medicion", tipo: "vph_genotipo_16_18", valor: "numerico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "cin"}
|
||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Una fila por nota médica (colposcopia / diagnostico / tratamiento) con sus observaciones
|
||||
-- en columnas. Equivalente de cacu_citologias para el dominio de notas.
|
||||
-- Fuente: procedimiento + observacion_clinica (silver); nunca bronze.
|
||||
|
||||
select
|
||||
p.procedimiento_id,
|
||||
p.fuente_id,
|
||||
p.pac_id,
|
||||
p.fecha,
|
||||
p.estudio_id as tipo_nota, -- colposcopia | diagnostico | tratamiento
|
||||
o_cie.valor_id as cie_codigo, -- ya normalizado en staging (sin espacios ni puntos)
|
||||
o_esp.valor_id as especialidad
|
||||
from {{ source('silver', 'procedimiento') }} p
|
||||
left join {{ source('silver', 'observacion_clinica') }} o_cie
|
||||
on o_cie.procedimiento_id = p.procedimiento_id
|
||||
and o_cie.resultado_id = 'nota_medica.diagnostico'
|
||||
left join {{ source('silver', 'observacion_clinica') }} o_esp
|
||||
on o_esp.procedimiento_id = p.procedimiento_id
|
||||
and o_esp.resultado_id = 'nota_medica.especialidad'
|
||||
where p.fuente_tabla = 'notamedica'
|
||||
@@ -0,0 +1,4 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cama_linea_de_tiempo.yml. #}
|
||||
{{ config(materialized = 'view') }}
|
||||
|
||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
||||
@@ -0,0 +1,21 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cama_linea_de_tiempo
|
||||
description: >
|
||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
||||
observation is adding a source here.
|
||||
config:
|
||||
meta:
|
||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
||||
# del_padre (date and patient from the parent procedure).
|
||||
fuentes:
|
||||
- {estudio_id: "mastografia", clase: "toma", resultado_id: "mastografia.calidad_imagen", clase_de_linea: "procedimiento", tipo: "mastografia", codigo: "mastografia"}
|
||||
- {estudio_id: "mastografia", clase: "reporte", resultado_id: "mastografia.birads", clase_de_linea: "medicion", tipo: "birads", codigo: "birads"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "grado_histologico"}
|
||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
||||
@@ -0,0 +1,4 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: tea_linea_de_tiempo.yml. #}
|
||||
{{ config(materialized = 'view') }}
|
||||
|
||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
||||
@@ -0,0 +1,44 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_linea_de_tiempo
|
||||
description: >
|
||||
Each patient's timeline: every fact of silver (procedimiento ⟕ observacion_clinica) in one shape and
|
||||
in order. One source per kind of fact: study, procedure class and result, with what the timeline calls
|
||||
it (`clase_de_linea`, `tipo`, `codigo`) and where its value and date come from. Adding a kind of
|
||||
observation is adding a source here.
|
||||
config:
|
||||
meta:
|
||||
# estudio_id (null: any study), clase, resultado_id (null: the value comes from `columna` of the
|
||||
# procedure), clase_de_linea, tipo; optional: codigo (default: tipo), valor (codigo | numerico),
|
||||
# columna, fecha (procedimiento | nacimiento), fecha_resultado (an observed date that goes first),
|
||||
# del_padre (date and patient from the parent procedure).
|
||||
fuentes:
|
||||
- {estudio_id: "evaluacion_psicologica", clase: "encuentro", resultado_id: "evaluacion_psicologica.instrumento_tamizaje", clase_de_linea: "procedimiento", tipo: "evaluacion_psicologica", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion"}
|
||||
- {estudio_id: "mchat", clase: "toma", resultado_id: "mchat.interpretacion", clase_de_linea: "medicion", tipo: "instrumento", codigo: "M_CHAT_R_F", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion", del_padre: true}
|
||||
- {estudio_id: "ramos", clase: "toma", resultado_id: "ramos.interpretacion", clase_de_linea: "medicion", tipo: "instrumento", codigo: "RAMOS", fecha_resultado: "evaluacion_psicologica.fecha_evaluacion", del_padre: true}
|
||||
- {estudio_id: "eeg", clase: "toma", resultado_id: "eeg.utilizable", clase_de_linea: "procedimiento", tipo: "eeg", codigo: "electroencefalograma", valor: "numerico"}
|
||||
- {estudio_id: "pea", clase: "toma", resultado_id: "pea.grado_hipoacusia", clase_de_linea: "medicion", tipo: "pea"}
|
||||
- {estudio_id: "parto", clase: "encuentro", resultado_id: "parto.apgar_5min", clase_de_linea: "antecedente", tipo: "apgar_5min", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "parto", clase: "encuentro", resultado_id: "parto.ingreso_ucin", clase_de_linea: "antecedente", tipo: "ingreso_ucin", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.antecedente_aborto", clase_de_linea: "antecedente", tipo: "antecedente_aborto", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.asma", clase_de_linea: "antecedente", tipo: "asma", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.crisis_convulsivas", clase_de_linea: "antecedente", tipo: "crisis_convulsivas", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.diabetes_gestacional", clase_de_linea: "antecedente", tipo: "diabetes_gestacional", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.embarazo_multiple", clase_de_linea: "antecedente", tipo: "embarazo_multiple", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.enfermedad_autoinmune", clase_de_linea: "antecedente", tipo: "enfermedad_autoinmune", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.estres_agudo", clase_de_linea: "antecedente", tipo: "estres_agudo", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.farmaco_riesgo_neurodesarrollo", clase_de_linea: "antecedente", tipo: "farmaco_riesgo_neurodesarrollo", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipertension_preeclampsia", clase_de_linea: "antecedente", tipo: "hipertension_preeclampsia", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipertiroidismo", clase_de_linea: "antecedente", tipo: "hipertiroidismo", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipotiroidismo", clase_de_linea: "antecedente", tipo: "hipotiroidismo", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.hipoxia_materna", clase_de_linea: "antecedente", tipo: "hipoxia_materna", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.incompatibilidad_rh", clase_de_linea: "antecedente", tipo: "incompatibilidad_rh", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.infeccion_gestacion", clase_de_linea: "antecedente", tipo: "infeccion_gestacion", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.liquido_amniotico", clase_de_linea: "antecedente", tipo: "liquido_amniotico", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.migrana", clase_de_linea: "antecedente", tipo: "migrana", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.proceso_proinflamatorio", clase_de_linea: "antecedente", tipo: "proceso_proinflamatorio", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.tabaquismo_gestacion", clase_de_linea: "antecedente", tipo: "tabaquismo_gestacion", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: "historia_perinatal", clase: "encuentro", resultado_id: "historia_perinatal.trastorno_neurologico", clase_de_linea: "antecedente", tipo: "trastorno_neurologico", valor: "numerico", fecha: "nacimiento"}
|
||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
||||
@@ -0,0 +1,87 @@
|
||||
# One profile per domain (`--profile cacu|cama|tea`; `cacu` by default) and one target per engine
|
||||
# (`--target sqlite|sqlserver|postgres|mysql`; `sqlite` by default). Every value comes from the environment;
|
||||
# nothing secret is written here.
|
||||
#
|
||||
# sqlite <DOMAIN>_DB_PATH: the domain's .db file. DBT_SCHEMA_DIR: where dbt-sqlite keeps any other
|
||||
# schema as its own .db file. dbt-sqlite attaches every .db it finds there, so it must never be
|
||||
# the folder of the domains' databases (a domain's views would then be opened under another
|
||||
# name and break).
|
||||
# others DBT_HOST, DBT_PORT, DBT_USER, DBT_PASSWORD, and <DOMAIN>_DBT_DATABASE (the domain's
|
||||
# database; by default, the domain's name).
|
||||
#
|
||||
# `mysql` runs with the `mysql` dependency group (dbt-core 1.7): `uv run --only-group mysql dbt ...`.
|
||||
|
||||
cacu:
|
||||
target: sqlite
|
||||
outputs:
|
||||
sqlite: &sqlite
|
||||
type: sqlite
|
||||
threads: 1
|
||||
database: main
|
||||
schema: main
|
||||
schemas_and_paths:
|
||||
main: "{{ env_var('CACU_DB_PATH', 'cacu.db') }}"
|
||||
schema_directory: "{{ env_var('DBT_SCHEMA_DIR', 'target/schemas') }}"
|
||||
sqlserver: &sqlserver
|
||||
type: sqlserver
|
||||
backend: mssql-python # Microsoft's driver: no system ODBC libraries needed
|
||||
server: "{{ env_var('DBT_HOST', 'localhost') }}"
|
||||
port: "{{ env_var('DBT_PORT', '1433') | as_number }}"
|
||||
database: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
||||
schema: dbo
|
||||
user: "{{ env_var('DBT_USER', '') }}"
|
||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
||||
encrypt: true
|
||||
trust_cert: true
|
||||
threads: 4
|
||||
postgres: &postgres
|
||||
type: postgres
|
||||
host: "{{ env_var('DBT_HOST', 'localhost') }}"
|
||||
port: "{{ env_var('DBT_PORT', '5432') | as_number }}"
|
||||
dbname: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
||||
schema: public
|
||||
user: "{{ env_var('DBT_USER', '') }}"
|
||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
||||
threads: 4
|
||||
mysql: &mysql
|
||||
type: mysql
|
||||
server: "{{ env_var('DBT_HOST', 'localhost') }}"
|
||||
port: "{{ env_var('DBT_PORT', '3306') | as_number }}"
|
||||
schema: "{{ env_var('CACU_DBT_DATABASE', 'cacu') }}"
|
||||
username: "{{ env_var('DBT_USER', '') }}"
|
||||
password: "{{ env_var('DBT_PASSWORD', '') }}"
|
||||
threads: 4
|
||||
|
||||
cama:
|
||||
target: sqlite
|
||||
outputs:
|
||||
sqlite:
|
||||
<<: *sqlite
|
||||
schemas_and_paths:
|
||||
main: "{{ env_var('CAMA_DB_PATH', 'cama.db') }}"
|
||||
sqlserver:
|
||||
<<: *sqlserver
|
||||
database: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
||||
postgres:
|
||||
<<: *postgres
|
||||
dbname: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
||||
mysql:
|
||||
<<: *mysql
|
||||
schema: "{{ env_var('CAMA_DBT_DATABASE', 'cama') }}"
|
||||
|
||||
tea:
|
||||
target: sqlite
|
||||
outputs:
|
||||
sqlite:
|
||||
<<: *sqlite
|
||||
schemas_and_paths:
|
||||
main: "{{ env_var('TEA_DB_PATH', 'tea.db') }}"
|
||||
sqlserver:
|
||||
<<: *sqlserver
|
||||
database: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
||||
postgres:
|
||||
<<: *postgres
|
||||
dbname: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
||||
mysql:
|
||||
<<: *mysql
|
||||
schema: "{{ env_var('TEA_DBT_DATABASE', 'tea') }}"
|
||||
@@ -0,0 +1,26 @@
|
||||
[project]
|
||||
name = "transformation"
|
||||
version = "0.1.0"
|
||||
description = "dbt transformation layer: bronze → silver (observacion/procedimiento) → gold (cohorts, indicators)."
|
||||
requires-python = ">=3.12,<3.14"
|
||||
dependencies = []
|
||||
|
||||
# dbt-core lives in the groups, one per engine: dbt-mysql still requires dbt-core 1.7, while the others run on
|
||||
# 1.12, so `mysql` is installed on its own (`uv sync --only-group mysql`). What must run on MySQL stays within
|
||||
# dbt 1.7: its `unit_tests` are ignored there.
|
||||
[dependency-groups]
|
||||
sqlite = ["dbt-core>=1.12,<1.13", "dbt-sqlite>=1.10"]
|
||||
sqlserver = ["dbt-core>=1.12,<1.13", "dbt-sqlserver[mssql]>=1.12.2"]
|
||||
postgres = ["dbt-core>=1.12,<1.13", "dbt-postgres>=1.10"]
|
||||
mysql = ["dbt-core>=1.7,<1.8", "dbt-mysql>=1.7,<1.8"]
|
||||
|
||||
[tool.uv]
|
||||
package = false
|
||||
default-groups = ["sqlite"]
|
||||
# dbt-sqlite 1.10 asks for an older dbt-adapters than dbt-core 1.12 needs; it runs on the newer one.
|
||||
override-dependencies = ["dbt-adapters>=1.24.5,<2"]
|
||||
conflicts = [
|
||||
[{ group = "mysql" }, { group = "sqlite" }],
|
||||
[{ group = "mysql" }, { group = "sqlserver" }],
|
||||
[{ group = "mysql" }, { group = "postgres" }],
|
||||
]
|
||||
+1
-1
Submodule WebApi updated: fce6ccd40a...7d0213eda7
+1
-1
Submodule indicadores_kit updated: 5142e57ce7...a6dad8cd91
+1
-1
Submodule models updated: f9d3b8f67e...ae2310754f
Reference in New Issue
Block a user