Compare commits

..

9 Commits

Author SHA1 Message Date
Roberto Treviño 43a20f9759 ISSSTELEON 2fe5301 2026-12-01 09:59:50 -06:00
Roberto Treviño cd2be42bdc ISSSTELEON 4ddbabd 2026-11-30 08:20:04 -06:00
Roberto Treviño 5c6279e141 ISSSTELEON 70cde6d 2026-11-30 06:38:09 -06:00
Roberto Treviño 513588a0be ISSSTELEON 606a2ef 2026-11-29 23:48:36 -06:00
Roberto Treviño ac589df787 ISSSTELEON d16d5ce 2026-11-29 21:31:37 -06:00
Roberto Treviño 4063234f1f ISSSTELEON 2ff634c 2026-11-29 21:15:41 -06:00
Roberto Treviño d51ea84818 ISSSTELEON 50289a5 2026-11-29 21:13:39 -06:00
Roberto Treviño 9cf82ce111 ISSSTELEON e1d3887 2026-11-29 20:21:38 -06:00
Roberto Treviño b9ed108855 ISSSTELEON 8a7974a 2026-11-29 18:09:05 -06:00
486 changed files with 32024 additions and 364226 deletions
-111
View File
@@ -1,111 +0,0 @@
name: ci
on:
push:
branches: [rebuild]
pull_request:
branches: [rebuild]
env:
# Submodule URLs are SSH; the runner reaches the same repos over the server's HTTP.
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
jobs:
python: # the whole suite, nothing skipped: SQLite and PostgreSQL, OCR included
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: platform
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
POSTGRES_TEST_URL: postgresql://postgres:postgres@postgres:5432/platform
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
PGHOST: postgres
FHIR_VALIDATOR_JAR: /opt/fhir/validator_cli.jar
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- run: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless postgresql-common
# pg_dump of the server's version (backups), as in the product's image.
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
apt-get install -y --no-install-recommends postgresql-client-17
- name: HL7 validator, pinned
run: |
mkdir -p /opt/fhir
curl -sLo /opt/fhir/validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar
echo "9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f /opt/fhir/validator_cli.jar" | sha256sum -c
- name: Synthea, pinned
run: |
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
- uses: astral-sh/setup-uv@v5
- run: uv sync --locked
- run: uv run ruff check
- run: uv run ruff format --check
- run: uv run lint-imports
- run: uv run pytest -q -rs -m "not webapp" # the pages run in the web job
web:
runs-on: ubuntu-latest
services:
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- uses: astral-sh/setup-uv@v5
- uses: actions/setup-node@v4
with:
node-version: '24'
- name: Generated API client matches the API
run: |
uv sync --locked
uv run python -m webapi.openapi > WebApp/openapi.json
cd WebApp && npm ci && npm run api
git diff --exit-code -- . || { echo 'Run: npm run api (after exporting openapi.json)'; exit 1; }
- working-directory: WebApp
run: npx ng build
- working-directory: WebApp
run: npx ng test --watch=false
- name: Every page loads from the API (Playwright over a loaded platform)
run: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
(cd WebApp && npx playwright install --with-deps chromium)
uv run pytest -q -rs -m webapp
+5 -8
View File
@@ -1,10 +1,7 @@
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
.env
/deploy/.env
/data/
/WebApp/node_modules/
/WebApp/dist/
/WebApp/.angular/
-12
View File
@@ -1,12 +0,0 @@
[submodule "WebApi"]
path = WebApi
url = ../WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ../WebApp.git
branch = rebuild
[submodule "models"]
path = models
url = ../models.git
branch = rebuild
-26
View File
@@ -1,26 +0,0 @@
[importlinter]
root_packages =
core
persistance
models
webapi
synthetic
[importlinter:contract:layers]
name = WebApi and models sit on Persistance, which sits on Core
type = layers
layers =
webapi | models
persistance
core
[importlinter:contract:synthetic]
name = Product packages never import the synthetic hospital
type = forbidden
source_modules =
core
persistance
models
webapi
forbidden_modules =
synthetic
+1
View File
@@ -0,0 +1 @@
+50 -50
View File
@@ -1,16 +1,8 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
CASE = ["CIS", "carcinoma"]
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
@@ -19,73 +11,81 @@ KPNC = {
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
INDEX_SAMPLE_DAYS = 30
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
CYTOLOGY_BEFORE_DAYS = 365 # a procedure's cytology was reported this long before at most
POST_TREATMENT_INDEX_AFTER_DAYS = 90
POST_TREATMENT_LOOKBACK_DAYS = 365
POST_COLPOSCOPY_VISIT = 1
REFERRAL_LOOKBACK_DAYS = 365
CYTOLOGY_BEFORE_DAYS = 365
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
SAMPLE_TO_DIAGNOSIS_DAYS = 120
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
] # fmt: skip
"Z014",
"Z124",
"B977",
"R876",
"N87",
"N870",
"N871",
"N872",
"N879",
"D06",
"D060",
"D061",
"D067",
"D069",
"C53",
"C530",
"C531",
"C538",
"C539",
]
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
# The PPVs of a procedure: groups of its cytology (each holds the more severe squamous ones)
# and of its histology; the first histology group is the score's.
"sample_to_report": 60,
"sample_to_treatment": 180,
"diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60,
"sample_to_biopsy": 60,
"result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60,
"biopsy_to_diagnosis": 60,
}
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"]
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"]
DETECTION = ["HSIL", "CIS", "carcinoma"]
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"]
PROCEDURE_CYTOLOGY = {
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS"],
"hsil_plus": ["HSIL", "CIS"],
}
PROCEDURE_HISTOLOGY = {
"cin1_plus": ["LSIL", *CIN2_PLUS], "cin2_plus": CIN2_PLUS, "carcinoma": CANCER,
} # fmt: skip
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
"cin1_plus": ["LSIL", *CIN2_PLUS],
"cin2_plus": CIN2_PLUS,
"carcinoma": CANCER,
}
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)]
RISK_BAND_MODEL = "cacu.cin2_pim"
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)]
def dbt_vars() -> dict:
"""What dbt reads (`var('cacu')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+6 -18
View File
@@ -1,49 +1,37 @@
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
it is read in. The list holds every patient with a cytology sampled within the window
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
from collections.abc import Iterable
from datetime import date
from core import cacu
from core.cacu.measures import follow_up_status
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
DEFAULT_HORIZON = 5.0
WINDOWS = cacu.FOLLOW_UP_WINDOWS
STATUS_SYSTEM = "cacu-follow-up-status"
PROCEDURES = ("colposcopy", "treatment")
REPORT_FACTS = {"cervical_cytology": "route"} # what followed the sample
REPORT_FACTS = {"cervical_cytology": "route"}
def status(row: dict, cutoff: date) -> str:
"""Her follow-up status by the end of the cut-off day."""
return follow_up_status(row, cutoff, through=True)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
her status."""
return [{**r, "status": status(r, cutoff)} for r in rows]
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
"""Her current risk of an outcome at a horizon (years): from the latest index date any
of the outcome's models scored her at; the highest when several did."""
prefix = OUTCOMES[outcome]
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
if not mine:
return None
latest = max(str(r["index_date"]) for r in mine)
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
latest = max((str(r["index_date"]) for r in mine))
return max((r["probability"] for r in mine if str(r["index_date"]) == latest))
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
horizon: float) -> list[dict]: # fmt: skip
"""The list in reading order. `rows` come most recent first; by risk, highest first,
unscored patients last, ties kept most recent first."""
def ordered(
rows: list[dict], sort: str, risks: dict[str, list[dict]], horizon: float
) -> list[dict]:
if sort == "-recent":
return rows
outcome = sort.removeprefix("-risk-")
+283 -119
View File
@@ -1,7 +1,4 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from datetime import date
from core import cacu
from core.measures import (
NO_BIOPSY,
@@ -18,36 +15,38 @@ from core.measures import (
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
for first, status in (
("first_case", "case"),
("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy"),
):
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
return (valid(row), as_day(row["sample_date"]), row["sample_id"])
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
return (
*latest(row),
reported,
row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))),
desc(row.get("biopsy_id")),
)
def result(row: dict) -> str:
@@ -55,7 +54,6 @@ def result(row: dict) -> str:
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
@@ -64,12 +62,11 @@ def histology(row: dict) -> str:
def case_before(row: dict) -> bool:
"""Whether she was a case already: at the procedure's cytology, or at it without one."""
return follow_up_status(row, as_day(row["sample_date"] or row["date"])) == "case"
def earliest(row: dict) -> tuple:
return -as_day(row["date"]).toordinal(), row["procedure_id"]
return (-as_day(row["date"]).toordinal(), row["procedure_id"])
def groups_by_cytology(row: dict, p=None) -> list[str]:
@@ -78,18 +75,15 @@ def groups_by_cytology(row: dict, p=None) -> list[str]:
return [g for g, results in cacu.PROCEDURE_CYTOLOGY.items() if row["result"] in results]
SIGN = {True: "positive", False: "negative"} # SQLite answers booleans as 1 and 0: the same keys
SIGN = {True: "positive", False: "negative"}
def groups_by_hpv(row: dict, p=None) -> list[str]:
"""Her HPV result and, apart, each genotype found (they overlap)."""
said = [SIGN[row["hpv"]]] if row["hpv"] in SIGN else []
return [*said, *(g for g in ("hpv_16", "hpv_18") if row[g])] or [NO_DATA]
def round_of(row: dict, p=None) -> str:
"""Subsequent: screened before, as her form says, or past colposcopy or treatment at the
sample. Initial: the first screening of her life."""
if row["sample_date"] is None:
return NO_DATA
if follow_up_status(row, as_day(row["sample_date"])) in ("post_colposcopy", "post_treatment"):
@@ -99,8 +93,7 @@ def round_of(row: dict, p=None) -> str:
def hpv_genotype(row: dict) -> str:
"""What an HPV report says, a null never read as a negative."""
hpv, found = row["hpv"], [g for g in ("16", "18") if row[f"hpv_{g}"]]
hpv, found = (row["hpv"], [g for g in ("16", "18") if row[f"hpv_{g}"]])
if not hpv:
return "inconsistent" if found else "no_result" if hpv is None else "negative"
if row["hpv_16"] is None or row["hpv_18"] is None:
@@ -109,7 +102,6 @@ def hpv_genotype(row: dict) -> str:
def biopsy_answer(row: dict) -> str:
"""What became of a biopsy requested, by its report."""
if row["report_date"] is None:
return "pending"
if as_day(row["report_date"]) < as_day(row["date"]):
@@ -120,114 +112,286 @@ def biopsy_answer(row: dict) -> str:
def ppv(id: str, title: str, procedure: str, counted) -> Measure:
"""Of the patients with the procedure in the period (her first), those whose histology is
LIEBG or more; those already cases are left out."""
levels = tuple((name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()) # fmt: skip
levels = tuple(
(
(name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()
)
)
return Measure(
id, title, "procedures",
Proportion(levels[0][1], denominator=lambda r: counted(r) and not case_before(r),
order=earliest, levels=levels, date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv),
("round", round_of))),
id,
title,
"procedures",
Proportion(
levels[0][1],
denominator=lambda r: counted(r) and (not case_before(r)),
order=earliest,
levels=levels,
date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv), ("round", round_of)),
),
params={"type": procedure},
facts={"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18")},
facts={
"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18"),
},
dated={"report_date": ("histology",)},
) # fmt: skip
)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
NO_HISTORY = lambda row: row["history"] == 0
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of)))),
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(AGE, STATUS, ("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], []))
for g in ("hpv_16", "hpv_18")))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "samples",
Composition(lambda r: (), hpv_genotype, unit="sample_id",
where=lambda r: r["report_date"] is not None and any(
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))),
MEASURES = {
m.id: m
for m in [
Measure(
"IND1",
"Pacientes con citología anormal",
"samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL),
"decrease",
group="principal",
),
Measure(
"CACU_EU13",
"Tasa de detección histopatológica",
"sample_biopsies",
Proportion(
lambda r: (
r.get("histology") in cacu.DETECTION and r.get("biopsy_report_date") is not None
),
strata=(AGE, STATUS),
),
group="principal",
),
Measure(
"CACU_EU7",
"Pacientes evaluadas por resultado de citología",
"samples",
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of))),
),
Measure(
"CACU_VPH",
"Pacientes evaluadas por resultado de VPH",
"samples",
Composition(
lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(
AGE,
STATUS,
("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], [])) for g in ("hpv_16", "hpv_18")),
),
),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")},
),
Measure(
"CACU_VPH_GENOTIPO",
"Resultados de VPH por genotipo",
"samples",
Composition(
lambda r: (),
hpv_genotype,
unit="sample_id",
where=lambda r: (
r["report_date"] is not None
and any((r[c] is not None for c in ("hpv", "hpv_16", "hpv_18")))
),
),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
description="Reportes de VPH, por fecha de toma."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "procedures",
Composition(lambda r: (), lambda r: r["histology"] or NO_DATA,
unit="procedure_id", date="report_date",
where=lambda r: r["report_date"] is not None),
params={"type": "biopsy"}, known="report_known_at",
description="Reportes de biopsia, por fecha de reporte."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia", "procedures",
description="Reportes de VPH, por fecha de toma.",
),
Measure(
"CACU_BIOPSIA_RESULTADOS",
"Resultados de biopsia cervical",
"procedures",
Composition(
lambda r: (),
lambda r: r["histology"] or NO_DATA,
unit="procedure_id",
date="report_date",
where=lambda r: r["report_date"] is not None,
),
params={"type": "biopsy"},
known="report_known_at",
description="Reportes de biopsia, por fecha de reporte.",
),
Measure(
"CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia",
"procedures",
Composition(lambda r: (), biopsy_answer, unit="procedure_id", date="date"),
params={"type": "biopsy"},
facts={"report_known_at": ("histology", "report_date")},
dated={"report_date": ("histology",)},
description="Solicitudes de biopsia registradas, por fecha de solicitud."),
ppv("CACU_VPP_COLPOSCOPIA", "Valor predictivo positivo de la colposcopía", "colposcopy",
lambda r: True),
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo de tamizaje a diagnóstico por CIE-10",
description="Solicitudes de biopsia registradas, por fecha de solicitud.",
),
ppv(
"CACU_VPP_COLPOSCOPIA",
"Valor predictivo positivo de la colposcopía",
"colposcopy",
lambda r: True,
),
ppv(
"CACU_VPP_BIOPSIA",
"Valor predictivo positivo de la biopsia",
"biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None,
),
Measure(
"CACU_TIEMPO_DIAGNOSTICO_CIE10",
"Tiempo de tamizaje a diagnóstico por CIE-10",
"samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
strata=(("diagnosis_code",
lambda r, p: r["diagnosis_code"] or NO_DATA),)), "decrease"),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
Duration(
"days_sample_diagnosis",
"diagnosis_date",
"sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS,
units=NO_HISTORY,
strata=(("diagnosis_code", lambda r, p: r["diagnosis_code"] or NO_DATA),),
),
"decrease",
),
Measure(
"CACU_CONFIRMACION_CITOLOGIA",
"Confirmación histopatológica",
"sample_biopsies",
Composition(
latest_most_severe_biopsy,
histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,),
),
),
Measure(
"CACU_EU_TIEMPO_REPORTE",
"Tiempo de toma a resultado de citología",
"samples",
Duration(
"days_sample_result",
"result_date",
"sample_date",
H["sample_to_report"],
ended="report_date",
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_DIAGNOSTICO",
"Tiempo de tamizaje a diagnóstico",
"samples",
Duration(
"days_sample_diagnosis",
"diagnosis_date",
"sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS,
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_TRATAMIENTO",
"Tiempo de tamizaje a tratamiento",
"samples",
Duration(
"days_sample_treatment",
"treatment_date",
"sample_date",
H["sample_to_treatment"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"Tiempo de diagnóstico a tratamiento",
"samples",
Duration(
"days_diagnosis_treatment",
"diagnosis_treatment_date",
"diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_COLPOSCOPIA",
"Tiempo de toma de muestra a colposcopía",
"samples",
Duration(
"days_sample_colposcopy",
"colposcopy_date",
"sample_date",
H["sample_to_colposcopy"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_BIOPSIA",
"Tiempo de toma de muestra a resultado de biopsia",
"samples",
Duration(
"days_sample_biopsy",
"biopsy_date",
"sample_date",
H["sample_to_biopsy"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_RESULTADO_COLPOSCOPIA",
"Tiempo de resultado a colposcopía",
"samples",
Duration(
"days_result_colposcopy",
"result_colposcopy_date",
"result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_COLPOSCOPIA_BIOPSIA",
"Tiempo de colposcopía a biopsia",
"samples",
Duration(
"days_colposcopy_biopsy",
"biopsy_date",
"result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0 and r["result_colposcopy_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_BIOPSIA_DIAGNOSTICO",
"Tiempo de biopsia a diagnóstico",
"samples",
Duration(
"days_biopsy_diagnosis",
"biopsy_diagnosis_date",
"biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None,
),
"decrease",
),
Measure(
"CACU_RIESGO_BANDA",
"Banda de riesgo de CIN2+ en vigilancia",
"risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
periods=("semester",),
params={"model": cacu.RISK_BAND_MODEL},
),
]
}
+44 -32
View File
@@ -1,48 +1,60 @@
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
and models import them. Codes are the platform's (core.catalog)."""
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
# benign one; a 4 without subcategory weighs less than 4A.
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
# Biopsy grades, least to most severe.
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"]
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
CANCER = ["in_situ", "invasive"] # detected (detection rate)
CANCER = ["in_situ", "invasive"]
INVASIVE = ["invasive"]
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
# window (start inclusive, end exclusive).
SURVIVAL_GRADES = ["invasive"]
RECRUITMENT = ("2018-01-01", "2027-01-01")
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
# specialty;
# - history: a breast cancer note, whoever wrote it.
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
HISTORY_ICD10 = [
"D05", "D050", "D051", "D057", "D059",
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
] # fmt: skip
"D05",
"D050",
"D051",
"D057",
"D059",
"C50",
"C500",
"C501",
"C502",
"C503",
"C504",
"C505",
"C506",
"C508",
"C509",
]
DIAGNOSIS_ICD10 = [
"Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92",
"Z123",
"N60",
"N600",
"N601",
"N602",
"N603",
"N604",
"N608",
"N609",
"N61",
"N62",
"N63",
"N64",
"N640",
"N641",
"N642",
"N643",
"N644",
"N645",
"N648",
"N649",
"D24",
"R92",
*HISTORY_ICD10,
] # fmt: skip
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
]
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
# The follow-up list: patients whose latest mammogram, taken within the window before the
# cut-off, is BI-RADS 4 to 6.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)]
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
FOLLOW_UP_WINDOW = 3
def dbt_vars() -> dict:
"""What dbt reads (`var('cama')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+22 -32
View File
@@ -1,17 +1,4 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
from core.measures import as_day
@@ -19,23 +6,21 @@ WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES = ("treatment",) # by kind (persistance.fhir: CaMa's procedure read)
REPORT_FACTS = {"mammography": "diagnosis_days"} # days from the mammogram to its diagnosis
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
PROCEDURES = ("treatment",)
REPORT_FACTS = {"mammography": "diagnosis_days"}
URGENT = ["5", "6"]
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
return (as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
exam, report = (as_day(row["exam_date"]), as_day(row["report_date"]))
if row["birads"] is None or report is None or (not exam <= report <= cutoff):
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
@@ -48,28 +33,33 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
shown = max(
mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]), default=None
)
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
status, priority = ("cancer", "high")
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
status, priority = ("biopsy_no_result", "medium")
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
status, priority = ("benign_biopsy", "low")
out.append(
{
"person_id": person,
"birth_date": row["birth_date"],
"status": status,
"priority": priority,
"recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}
)
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
+158 -91
View File
@@ -1,10 +1,3 @@
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
with no data instead of being left out."""
from core import cama
from core.measures import (
NO_BIOPSY,
@@ -18,27 +11,37 @@ from core.measures import (
)
H = cama.HORIZONS
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
REPORT = {
"report_known_at": (
"report_date",
"birads",
"birads_rank",
"days_sample_report",
"report_diagnosis_date",
"days_report_diagnosis",
)
}
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
def reported(row: dict) -> bool:
"""A mammogram with a reported BI-RADS."""
return row["birads"] is not None and row["report_date"] is not None
def most_severe(row: dict) -> tuple:
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
return (reported(row), row["birads_rank"] or 0, as_day(row["exam_date"]))
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
return (
*most_severe(row),
counted,
desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])),
desc(row["biopsy_id"]),
)
def birads(row: dict) -> str:
@@ -46,91 +49,155 @@ def birads(row: dict) -> str:
def biopsy_histology(row: dict) -> str:
"""The chosen biopsy's grade (NO_BIOPSY when her mammogram led to none reported)."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row["histology"] or NO_DATA
def should_be_biopsied(row: dict) -> bool:
"""A reported mammogram whose BI-RADS asks for a biopsy (the confirmation's denominator)."""
return reported(row) and row["birads"] in cama.SUSPICIOUS
def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
NO_HISTORY = lambda row: row["history"] == 0
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
MEASURES = {
m.id: m
for m in [
Measure(
"CAMA_BIRADS",
"Distribución de BI-RADS",
"mammograms",
Composition(most_severe, birads, date="exam_date"),
facts=REPORT,
),
Measure(
"CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"),
facts=REPORT,
),
Measure(
"CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6",
"mammograms",
Composition(
most_severe, birads, where=four_to_six, unit="mammogram_id", date="exam_date"
),
facts=REPORT,
),
Measure(
"CAMA_BIRADS_CANCER_INVASOR",
"BI-RADS de la mastografía previa a un cáncer invasor",
"biopsies",
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
known="report_known_at"),
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
date="report_date"),
known="report_known_at"),
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
strata=(BIRADS,), date="exam_date"),
facts=REPORT | BIOPSY),
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: r["report_date"] is not None
and r["birads"] in cama.SUSPICIOUS,
unit="mammogram_id", date="exam_date"),
"increase", group="principal", facts=REPORT | BIOPSY),
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
Composition(
lambda r: (r["birads"] is not None, as_day(r["report_date"]), r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE,
date="report_date",
),
known="report_known_at",
),
Measure(
"CAMA_BIOPSIAS",
"Distribución de resultados de biopsia",
"biopsies",
Proportion(lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id", date="report_date"),
group="principal", known="report_known_at"),
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
"decrease", facts=DIAGNOSIS),
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
date="report_date"),
"decrease", known="report_known_at"),
# Pending the analysts' validation (LOTE-3-CAMA-REBUILD.md): the biopsy is the one whose
# request names the mammogram, the first reported if several; the horizon is the
# diagnosis's, as no other is set.
Measure("CAMA_DIAS_RESULTADO_BIOPSIA",
"Tiempo de resultado de mastografía a resultado de biopsia", "mammogram_first_biopsy",
Duration("days_report_biopsy", "biopsy_report_date", "report_date", H["to_diagnosis"],
units=should_be_biopsied, unit="mammogram_id", date="report_date"),
"decrease", facts=REPORT | {"biopsy_known_at": ("biopsy_report_date",
"days_report_biopsy")},
description=(
"PROVISIONAL, pendiente de validación metodológica de los analistas. Días del "
"reporte de la mastografía (BI-RADS 4, 4A, 4B, 4C o 5) al reporte de la primera "
"biopsia reportada cuya solicitud nombra esa mastografía; sin vínculo explícito "
"no hay medición. Horizonte de 180 días reutilizado del tramo a diagnóstico "
"(no hay uno propio). Por decidir: fuente real del vínculo, cohorte, selección "
"con varias biopsias, horizonte, historia de cáncer y fechas inconsistentes."
)),
]} # fmt: skip
Composition(
lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA,
unit="biopsy_id",
date="report_date",
),
known="report_known_at",
),
Measure(
"CAMA_HISTOPATOLOGIA_BIRADS",
"Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(
then_its_most_severe_biopsy,
biopsy_histology,
admit=four_to_six,
strata=(BIRADS,),
date="exam_date",
),
facts=REPORT | BIOPSY,
),
Measure(
"CAMA_CONFIRMACION_BIRADS45",
"Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(
lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: (
r["report_date"] is not None and r["birads"] in cama.SUSPICIOUS
),
unit="mammogram_id",
date="exam_date",
),
"increase",
group="principal",
facts=REPORT | BIOPSY,
),
Measure(
"CAMA_TASA_DETECCION_HISTOPATOLOGICA",
"Tasa de detección histopatológica",
"biopsies",
Proportion(
lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id",
date="report_date",
),
group="principal",
known="report_known_at",
),
Measure(
"CAMA_EU38A",
"Días de la toma de la mastografía a su resultado",
"mammograms",
Duration(
"days_sample_report",
"report_date",
"exam_date",
H["sample_to_report"],
unit="mammogram_id",
date="exam_date",
),
"decrease",
facts=REPORT,
),
Measure(
"CAMA_DIAS_TOMA_DIAGNOSTICO",
"Tiempo de tamizaje a diagnóstico",
"mammograms",
Duration(
"days_sample_diagnosis",
"diagnosis_date",
"exam_date",
H["to_diagnosis"],
units=NO_HISTORY,
unit="mammogram_id",
date="exam_date",
),
"decrease",
facts=DIAGNOSIS,
),
Measure(
"CAMA_DIAS_RESULTADO_DIAGNOSTICO",
"Tiempo de resultado a diagnóstico",
"mammograms",
Duration(
"days_report_diagnosis",
"report_diagnosis_date",
"report_date",
H["to_diagnosis"],
units=NO_HISTORY,
unit="mammogram_id",
date="report_date",
),
"decrease",
known="report_known_at",
),
]
}
+8 -34
View File
@@ -1,24 +1,12 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
@@ -26,12 +14,12 @@ class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
external: bool = False
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
date: str
parent: EventClass | None = None
@@ -41,7 +29,7 @@ class FieldDef(BaseModel):
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
codes: dict[str, str] = {}
pattern: str | None = None
unit: str | None = None
required: bool = False
@@ -58,7 +46,7 @@ class FieldDef(BaseModel):
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
key: list[str]
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@@ -89,7 +77,6 @@ def systems() -> dict[str, System]:
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
@@ -98,13 +85,11 @@ def files() -> dict[str, list[str]]:
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
@@ -121,25 +106,17 @@ def studies() -> dict[str, Study]:
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
_TYPES: dict[str, Any] = {"boolean": bool, "number": float, "date": date, "text": str, "file": str}
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
kind: Any = Literal[tuple(f.codes)]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
@@ -149,27 +126,24 @@ def _annotation(f: FieldDef) -> Any:
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = { # titled as the catalog names them (forms and review show the titles)
fields = {
name: (_annotation(f), Field(... if f.required else None, title=f.title))
for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found = create_model(study, __base__=Record, **fields)
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
-2
View File
@@ -1,4 +1,3 @@
# Cervical cancer screening.
cervical_cytology:
title: Citología cervical
key: [sample_date]
@@ -72,7 +71,6 @@ cervical_cytology:
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# What the cytologist adds in words. A finding is true when stated, otherwise unknown.
findings: {type: text, event: report, title: Hallazgos adicionales}
finding_inflammation: {type: boolean, event: report, title: "Hallazgo: inflamación"}
finding_reactive: {type: boolean, event: report, title: "Hallazgo: cambios reactivos"}
-1
View File
@@ -1,4 +1,3 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
-1
View File
@@ -1,4 +1,3 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
-2
View File
@@ -1,5 +1,3 @@
# The code systems the platform's fields take their codes from. External systems are named by
# their canonical URI; only the codes a field allows are listed with the field.
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
-3
View File
@@ -1,5 +1,3 @@
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
# is the common clinical note (specialty pediatric_neurology).
mchat:
title: M-CHAT-R/F
key: [screening_date]
@@ -22,7 +20,6 @@ ados2:
title: Módulo
system: ados2-module
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
pointing: {type: number, event: encounter, title: Señalar}
gestures: {type: number, event: encounter, title: Gestos}
+1 -19
View File
@@ -1,16 +1,5 @@
"""A site's codes in platform terms: FHIR ConceptMaps (R4B), as data a site's configuration
holds, never code. A new laboratory that writes "Negativo para lesión" for NILM, or "F" for
female, is one more element in its ConceptMap.
Each group maps the site's codes (`source`, any URI the site uses) onto one system the
platform's fields take their codes from (`target`): a catalog system (core.catalog), FHIR's
administrative gender (identity `sex`), or the platform's yes/no system (boolean fields).
"""
from collections.abc import Iterable
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog
GENDER = "http://hl7.org/fhir/administrative-gender"
@@ -20,8 +9,6 @@ _BOOLEAN_CODES = {"true", "false"}
def systems(field: str) -> dict[str, set[str] | None]:
"""The systems a field of this name takes codes from, each with its allowed codes
(None: any code of the system)."""
found: dict[str, set[str] | None] = {}
if field == "sex":
found[GENDER] = _GENDER_CODES
@@ -40,8 +27,6 @@ def systems(field: str) -> dict[str, set[str] | None]:
def problems(cm: ConceptMap) -> list[str]:
"""Why this map can't be used: a group onto a system no field takes, or a target code
its field doesn't allow."""
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
for study in catalog.studies().values():
for name in study.fields:
@@ -60,8 +45,6 @@ def problems(cm: ConceptMap) -> list[str]:
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
"""A field's translations, site code (case ignored) -> platform code, from the groups
of these maps that target a system the field takes."""
targets = systems(field)
found = {}
for cm in maps:
@@ -76,7 +59,6 @@ def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
"""A sender's coding (system, code) as (platform system, code), when a map knows it."""
for cm in maps:
for group in cm.group or []:
if group.source != source:
@@ -84,5 +66,5 @@ def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str,
for element in group.element:
if element.code.casefold() == code.casefold():
for target in element.target or []:
return group.target, target.code
return (group.target, target.code)
return None
-6
View File
@@ -1,7 +1,3 @@
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
import importlib
from enum import StrEnum
from types import ModuleType
@@ -14,7 +10,6 @@ class Domain(StrEnum):
def part(domain: Domain, name: str = "") -> ModuleType | None:
"""The domain's module `name` (its package without one), or None while it has none."""
path = f"core.{domain.value}" + (f".{name}" if name else "")
try:
return importlib.import_module(path)
@@ -25,6 +20,5 @@ def part(domain: Domain, name: str = "") -> ModuleType | None:
def measures(domain: Domain) -> dict:
"""The domain's measures by id (none for a domain without them yet)."""
found = part(domain, "measures")
return found.MEASURES if found else {}
+340 -240
View File
@@ -1,15 +1,6 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
@@ -22,7 +13,6 @@ from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
FHIR_VERSION = "4.3.0"
@@ -32,72 +22,102 @@ CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"tea-follow-up-status": ("Estatus de seguimiento", {
"mchat_only": "Solo M-CHAT", "psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica", "eeg": "Con EEG",
}),
"tea-case": ("Estado del caso", {
"confirmed": "Diagnóstico confirmado", "in_process": "En proceso",
"not_confirmed": "Sin TEA",
}),
"tea-eeg-status": ("Estatus de EEG", {
"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido",
}),
# an EEG metric outside its age band: `<metric>:above` or `<metric>:below`
"cacu-procedure": (
"Procedimientos de CaCu",
{"colposcopy": "Colposcopia", "treatment": "Tratamiento"},
),
"cacu-follow-up-status": (
"Estatus de seguimiento",
{
"case": "Caso (cáncer)",
"pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia",
"post_treatment": "Post tratamiento",
},
),
"cama-follow-up-status": (
"Estatus de seguimiento",
{
"cancer": "Diagnóstico confirmado",
"pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado",
"benign_biopsy": "Biopsia benigna",
},
),
"tea-follow-up-status": (
"Estatus de seguimiento",
{
"mchat_only": "Solo M-CHAT",
"psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica",
"eeg": "Con EEG",
},
),
"tea-case": (
"Estado del caso",
{
"confirmed": "Diagnóstico confirmado",
"in_process": "En proceso",
"not_confirmed": "Sin TEA",
},
),
"tea-eeg-status": (
"Estatus de EEG",
{"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido"},
),
"tea-eeg-alteration": ("Alteración del EEG", {}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía", "diagnosis_code": "Diagnóstico CIE-10",
"cytology": "Citología previa", "hpv": "VPH de la citología previa",
"level": "Histología confirmada", "round": "Tamizaje inicial o subsecuente",
"hpv_16": "VPH 16", "hpv_18": "VPH 18",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
"follow-up-priority": (
"Prioridad de seguimiento",
{"high": "Alta", "medium": "Media", "low": "Baja"},
),
"measure-stratifier": (
"Estratos de indicadores",
{
"category": "Categoría",
"age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento",
"result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía",
"diagnosis_code": "Diagnóstico CIE-10",
"cytology": "Citología previa",
"hpv": "VPH de la citología previa",
"level": "Histología confirmada",
"round": "Tamizaje inicial o subsecuente",
"hpv_16": "VPH 16",
"hpv_18": "VPH 18",
},
),
"risk-model": ("Modelos de riesgo", {}),
}
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
codes = {
c: d
for s in catalog.studies().values()
for f in s.fields.values()
if f.system == name
for c, d in f.codes.items()
}
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Where a duration is scored: the whole, and each stratum with a score of its own.
DURATIONS = ["MeasureReport.group.measureScore",
"MeasureReport.group.stratifier.stratum.measureScore"] # fmt: skip
# Our extensions: name -> (value type, the elements they extend).
CODE_SYSTEMS["catalog-field"] = (
"Campos de los estudios",
{f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()},
)
DURATIONS = [
"MeasureReport.group.measureScore",
"MeasureReport.group.stratifier.stratum.measureScore",
]
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
@@ -109,16 +129,12 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
# whether the biopsy's record names the cytology (recorded) or its dates do (inferred)
"colposcopy-date": ("date", ["DiagnosticReport"]),
"biopsy-request-date": ("date", ["DiagnosticReport"]),
"biopsy-date": ("date", ["DiagnosticReport"]),
"biopsy-link": ("code", ["DiagnosticReport"]),
"diagnosis-date": ("date", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
"tea-age-group": ("string", ["Patient"]),
"tea-case": ("Coding", ["Patient"]),
"tea-eeg-status": ("Coding", ["Patient"]),
@@ -126,16 +142,15 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"tea-last-eeg": ("date", ["Patient"]),
"mchat-score": ("integer", ["Patient"]),
"ados2-css": ("integer", ["Patient"]),
} # fmt: skip
}
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
return "".join((part.capitalize() for part in code.replace("_", "-").split("-")))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
return str(uuid.uuid5(_IDS, "|".join((str(k) for k in key))))
def _day(value) -> str | None:
@@ -145,7 +160,6 @@ def _day(value) -> str | None:
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
@@ -166,10 +180,14 @@ def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
# A report's facts (a domain's `REPORT_FACTS` read): their column -> the extension.
_REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
"requested": "biopsy-request-date", "biopsy": "biopsy-date",
"link": "biopsy-link", "diagnosis": "diagnosis-date"} # fmt: skip
_REPORT_FACTS = {
"days": "days-to-diagnosis",
"colposcopy": "colposcopy-date",
"requested": "biopsy-request-date",
"biopsy": "biopsy-date",
"link": "biopsy-link",
"diagnosis": "diagnosis-date",
}
def report_facts(row: dict) -> list[dict]:
@@ -185,12 +203,7 @@ def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
@@ -199,8 +212,9 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
found["extension"] = [
ext("follow-up-status", "Coding", coding(status_system, row["status"]))
]
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
@@ -212,13 +226,14 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
found["link"] = [
{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]
]
return Patient.model_validate(found)
def _tea_listed(row: dict) -> list[dict]:
"""What TEA's list shows of a child, when she is on it (core.tea.follow_up)."""
found = []
if row.get("age_group"):
found.append(ext("tea-age-group", "string", row["age_group"]))
@@ -236,21 +251,26 @@ def _tea_listed(row: dict) -> list[dict]:
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
return Patient.model_validate(
{
"resourceType": "Patient",
"id": person_id,
"active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}
)
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {
"valueCodeableConcept": {
"coding": [{"system": system.url, "code": value}],
"text": value,
}
}
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
@@ -262,8 +282,6 @@ def _value(f: catalog.FieldDef, value) -> dict:
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
@@ -276,72 +294,79 @@ def known(study: str, row: dict, cutoff) -> dict:
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
root = next((e for e in spec.events.values() if e.parent is None))
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
container = _id(study, person, *key)
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
observations.append(
Observation.model_validate(
{
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
}
)
)
if visit:
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
encounter = Encounter.model_validate(
{
"resourceType": "Encounter",
"id": container,
"status": "finished",
"class": {
"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB",
},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}
)
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
report = DiagnosticReport.model_validate(
{
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}
)
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written; or
a study of the catalog that is a diagnosis (`study`: a breast recurrence), by its name
and its coded field (`code`: where it recurred)."""
person, day = row["person_id"], _day(row["note_date"])
person, day = (row["person_id"], _day(row["note_date"]))
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
if study := row.get("study"):
code = concept("study", study)
system = next((f.system for f in catalog.studies()[study].fields.values()
if f.type == "code"), None) # fmt: skip
system = next(
(f.system for f in catalog.studies()[study].fields.values() if f.type == "code"), None
)
if system and row.get("code"):
where = coding(system, row["code"])
code["coding"].append(where)
@@ -349,74 +374,93 @@ def condition(row: dict) -> Condition:
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty") or study),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"category": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis",
}
]
}
],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
}
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict, domain: str = "cacu") -> Procedure:
"""A procedure the timeline inferred (`gold.<domain>_events`; CaCu: colposcopy,
treatment; CaMa: each treatment by its kind), coded in `<domain>-procedure`."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept(f"{domain}-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
person, day = (row["person_id"], _day(row["date"]))
return Procedure.model_validate(
{
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept(f"{domain}-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}
)
SCENARIO_SEPARATOR = " | " # as models.survival joins them
SCENARIO_SEPARATOR = " | "
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval; and the clinical scenarios of the model's
report she falls in (an extension each), for her record to draw their curves."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
interval = [ext(name, "decimal", h[key]) for name, key in bounds if h.get(key) is not None]
predictions.append(
{
"probabilityDecimal": h["probability"],
"whenRange": {
"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM, "code": "a"}
},
**({"extension": interval} if interval else {}),
}
)
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
"display": models.title(model)}],
"text": f"{models.title(model)} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**({"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (scenarios := [n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR)
if n]) else {}),
}) # fmt: skip
return RiskAssessment.model_validate(
{
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {
"coding": [
{"system": CODES + "risk-model", "code": model, "display": models.title(model)}
],
"text": f"{models.title(model)} v{row['version']}",
},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**(
{"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (
scenarios := [
n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR) if n
]
)
else {}
),
}
)
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
SCORING = {
"proportion": "proportion",
"continuous-variable": "continuous-variable",
"composition": "cohort",
}
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
@@ -424,15 +468,15 @@ def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATIONS = {
"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"],
}
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
@@ -442,18 +486,21 @@ def stratifier_code(name: str) -> dict:
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
criteria = {
"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']",
}
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
"population": [
{"code": {"coding": [{"system": POPULATION, "code": c}]}, "criteria": criteria}
for c in POPULATIONS[m.rule.kind]
],
}
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
group["stratifier"] = [
{"id": s, "code": stratifier_code(s), "criteria": criteria} for s in strata
]
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
@@ -462,83 +509,136 @@ def measure(m, domain: str) -> Measure:
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind],
}
]
},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
}
if m.description:
found["description"] = m.description
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
found["improvementNotation"] = {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement,
}
]
}
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
"name": _name(name),
"title": title, "status": "active", "caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
return [
CodeSystem.model_validate(
{
"resourceType": "CodeSystem",
"id": name,
"url": CODES + name,
"name": _name(name),
"title": title,
"status": "active",
"caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}
)
for name, (title, concepts) in CODE_SYSTEMS.items()
]
def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
"kind": "complex-type", "abstract": False, "type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
]},
})) # fmt: skip
found.append(
StructureDefinition.model_validate(
{
"resourceType": "StructureDefinition",
"id": name,
"url": url,
"name": _name(name),
"status": "active",
"fhirVersion": FHIR_VERSION,
"kind": "complex-type",
"abstract": False,
"type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {
"element": [
{
"id": "Extension",
"path": "Extension",
"max": "*" if name == "period-type" else "1",
},
{
"id": "Extension.extension",
"path": "Extension.extension",
"max": "0",
},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{
"id": "Extension.value[x]",
"path": "Extension.value[x]",
"min": 1,
"type": [{"code": value_type}],
},
]
},
}
)
)
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
"Months before the cut-off a cytology puts a patient on the list"),
"follow-up-window": (
"Patient",
"number",
"Months before the cut-off a cytology puts a patient on the list",
),
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
"reporting-period": ("MeasureReport", "token",
"A semester (2025-S1) or a month (2025-03) the report covers"),
"reporting-period": (
"MeasureReport",
"token",
"A semester (2025-S1) or a month (2025-03) the report covers",
),
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
} # fmt: skip
}
def search_parameters() -> list[SearchParameter]:
return [SearchParameter.model_validate({
"resourceType": "SearchParameter", "id": code,
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
"status": "active", "description": description, "code": code, "base": [base],
"type": kind,
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
return [
SearchParameter.model_validate(
{
"resourceType": "SearchParameter",
"id": code,
"url": f"{BASE}/SearchParameter/{code}",
"name": _name(code),
"status": "active",
"description": description,
"code": code,
"base": [base],
"type": kind,
}
)
for code, (base, kind, description) in SEARCH_PARAMETERS.items()
]
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
+33 -39
View File
@@ -1,21 +1,7 @@
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
target nodes take, the same rows a site's map and extract nodes give. One silver,
two doors.
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
Encounter (one study instance). Every report also gives an identity row, its subject's, so
the link node joins it to its person the way it joins any document: by identifiers, name and
birth date. Codes in the platform's own systems pass as they are; any other code goes through
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
target holds the row saying why.
"""
import hashlib
from collections.abc import Iterable
from typing import Any
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog, concept_map
from core.fhir import CODES
from core.pipeline import RECORD
@@ -26,18 +12,14 @@ FIELD = CODES + "catalog-field"
def record(sender: str, reference: str) -> str:
"""A sent resource's record id: stable across resends of the same resource."""
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
def resources(bundle: dict) -> dict[str, dict]:
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
def _entries(bundle: dict) -> dict[str, dict]:
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
found = {}
for entry in bundle.get("entry", []):
r = entry.get("resource") or {}
@@ -49,7 +31,6 @@ def _entries(bundle: dict) -> dict[str, dict]:
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
"""A coding as a code of `system`: as it is when already there, else through the maps."""
if coding.get("system") == system:
return coding.get("code")
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
@@ -61,7 +42,6 @@ def _codings(concept: dict | None) -> list[dict]:
def identity(patient: dict) -> dict[str, Any]:
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
found: dict[str, Any] = {}
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
for i in patient.get("identifier", []):
@@ -86,7 +66,7 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
for coding in codings:
if url and (code := _translated(maps, coding, url)) is not None:
return code
return codings[0].get("code") if codings else None # kept as sent: held, saying why
return codings[0].get("code") if codings else None
for key in ("valueBoolean", "valueString", "valueInteger"):
if key in observation:
return observation[key]
@@ -98,54 +78,68 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
subject), `death` (Patients who died), or a study of the catalog (each report or
encounter of it, with its results as fields)."""
maps = list(maps)
sent = resources(bundle)
named = _entries(bundle) # what a reference may name
named = _entries(bundle)
def subject(r: dict) -> dict | None:
return named.get((r.get("subject") or {}).get("reference", ""))
if entity == "identity":
out = [{**identity(r), RECORD: record(sender, ref)}
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
out = [
{**identity(r), RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient"
]
for ref, r in sent.items():
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
out.append({**identity(p), RECORD: record(sender, ref)})
return out
if entity == "death":
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
return [
{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")
]
spec = catalog.studies()[entity]
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
root = next(e for e in spec.events.values() if e.parent is None)
root = next((e for e in spec.events.values() if e.parent is None))
out = []
for ref, r in sent.items():
if r["resourceType"] != kind:
continue
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
if not any((_translated(maps, c, STUDY) == entity for c in _codings(code))):
continue
row: dict[str, Any] = {RECORD: record(sender, ref)}
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
(r.get("period") or {}).get("start")) # fmt: skip
start = (
r.get("effectiveDateTime")
if kind == "DiagnosticReport"
else (r.get("period") or {}).get("start")
)
if start:
row[root.date] = start[:10]
if kind == "DiagnosticReport":
reported = next((x.get("valueDate") for x in r.get("extension", [])
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
reported = next(
(
x.get("valueDate")
for x in r.get("extension", [])
if x.get("url", "").endswith("/report-date")
),
None,
)
reported = reported or (r.get("issued") or "")[:10] or None
if reported:
row[spec.events["report"].date] = reported
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
else:
mine = {ref, *(k for k, v in named.items() if v is r)}
results = [o for o in sent.values() if o["resourceType"] == "Observation"
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
results = [
o
for o in sent.values()
if o["resourceType"] == "Observation"
and (o.get("encounter") or {}).get("reference") in mine
]
for o in filter(None, results):
for coding in _codings(o.get("code")):
name = _translated(maps, coding, FIELD) or ""
-17
View File
@@ -1,25 +1,8 @@
"""What every domain's follow-up list shares (pure). A domain with a list has a module
`core.<domain>.follow_up` with:
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
(years, for orders by risk; None without one);
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
`follow_up` read (persistance.fhir);
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
"""
import calendar
from datetime import date
def window_start(cutoff: date, months: int) -> date:
"""The first day of the window: `months` before the cut-off (the month's last day when
shorter), plus one day."""
total = cutoff.year * 12 + cutoff.month - 1 - months
year, month = divmod(total, 12)
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
+129 -142
View File
@@ -1,18 +1,3 @@
"""The measure engine: what a domain's measure counts, evaluated per period over the rows gold
gives (pure, no IO), and the FHIR R4B MeasureReport each evaluation is served as. Each domain
declares its measures in `core.<domain>.measures` (`MEASURES`).
Three kinds, as FHIR scores them:
- proportion: patients in the denominator and, of them, in the numerator; with a Wilson
95% interval;
- composition: patients split by the category of their latest valid fact in the period;
- continuous variable: days per unit, summarized by the median and inclusive quartiles. A
unit still within its horizon without an end isn't measured yet, so it is left out.
Rows are known from `known_at`; an evaluation `as_of` a moment uses only rows known by then
(all of them by default). Durations count to the event cut-off, `as_of`'s day by default.
"""
import functools
import math
import statistics
@@ -21,9 +6,7 @@ from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from datetime import UTC, date, datetime
from typing import ClassVar
from fhir.resources.R4B.measurereport import MeasureReport
from core.fhir import EXTENSION, measure_url, stratifier_code
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
@@ -36,11 +19,10 @@ NO_BIOPSY = "no_biopsy"
@dataclass(frozen=True)
class Period:
start: date
end: date # exclusive
end: date
@classmethod
def parse(cls, text: str) -> "Period":
"""A semester (`2025-S1`) or a month (`2025-03`)."""
year, part = text.split("-")
if part.startswith("S"):
first = 1 if part == "S1" else 7
@@ -49,23 +31,21 @@ class Period:
date(int(year), 7, 1) if first == 1 else date(int(year) + 1, 1, 1),
)
month = int(part)
return cls(date(int(year), month, 1),
date(int(year) + month // 12, month % 12 + 1, 1)) # fmt: skip
return cls(date(int(year), month, 1), date(int(year) + month // 12, month % 12 + 1, 1))
@functools.cached_property
def _iso(self) -> tuple[str, str]:
return self.start.isoformat(), self.end.isoformat()
return (self.start.isoformat(), self.end.isoformat())
def __contains__(self, day) -> bool:
if isinstance(day, str): # ISO days sort as the days they name
if isinstance(day, str):
start, end = self._iso
return start <= day[:10] < end
return day is not None and self.start <= as_day(day) < self.end
def as_day(value) -> date | None:
"""A day, from a date, a datetime or ISO text."""
if value is None or isinstance(value, date) and not isinstance(value, datetime):
if value is None or (isinstance(value, date) and (not isinstance(value, datetime))):
return value
if isinstance(value, datetime):
return value.date()
@@ -74,12 +54,10 @@ def as_day(value) -> date | None:
@functools.lru_cache(maxsize=65536)
def _iso_day(text: str) -> date:
"""Parsed once per day: every period scans every row."""
return date.fromisoformat(text)
def _moment(value) -> datetime | None:
"""A moment; one stored without an offset is UTC (how the platform stores them)."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
@@ -87,7 +65,6 @@ def _moment(value) -> datetime | None:
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
birth = as_day(birth)
if birth is None:
return NO_DATA
@@ -95,12 +72,10 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
for low, high in groups:
if low <= age <= high:
return f"{low}-{high}"
lowest, highest = groups[0][0], groups[-1][1]
lowest, highest = (groups[0][0], groups[-1][1])
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
# A stratum: its name and the value a row takes in a period; a list when it takes several (its
# groups overlap) or none.
Stratum = tuple[str, Callable[[dict, "Period"], "str | list[str]"]]
@@ -115,29 +90,21 @@ class Result:
score_extensions: dict[str, float] = field(default_factory=dict)
unit: str | None = None
strata: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)
# A stratum crossed with the category: (its name, "category") -> (value, category) ->
# counts (a composition by clinical scenario and result, say).
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
default_factory=dict
)
# A stratum value's own score: (stratum, value) -> score, its extensions and unit.
scores: dict[tuple[str, str], tuple[float, dict[str, float], str]] = field(default_factory=dict)
def wilson(k: int, n: int) -> tuple[float, float]:
p = k / n
centre, half = p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n))
low, high = (centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n)
return round(max(low, 0.0), 12), round(min(high, 1.0), 12)
centre, half = (p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)))
low, high = ((centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n))
return (round(max(low, 0.0), 12), round(min(high, 1.0), 12))
@dataclass(frozen=True)
class Proportion:
"""Units with a row dated in the period that meets `denominator` and, of them, those
with such a row that also meets `numerator`; with a Wilson 95% interval. With `order`, a
unit counts with one row only, the one it ranks highest. `levels` are other numerators
over the same denominator: the stratifier `level`."""
numerator: Callable[[dict], bool]
strata: tuple[Stratum, ...] = ()
denominator: Callable[[dict], bool] = lambda row: True
@@ -146,7 +113,6 @@ class Proportion:
unit: str = "person_id"
date: str = "sample_date"
kind: str = "proportion"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
@@ -180,16 +146,11 @@ class Proportion:
def desc(value) -> tuple:
"""A sort key on which a value ranks above a missing one."""
return (value is not None, value)
@dataclass(frozen=True)
class Composition:
"""Units by the category of one row each: of a unit's rows dated in the period (that meet
`where`), the one `order` ranks highest. Only units whose chosen row is `admit`ted count.
The chosen row's `category` is the first stratifier; `strata` add others."""
order: Callable[[dict], tuple]
category: Callable[[dict], str]
admit: Callable[[dict], bool] = lambda row: True
@@ -198,7 +159,6 @@ class Composition:
unit: str = "person_id"
date: str = "sample_date"
kind: str = "composition"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
@@ -217,32 +177,28 @@ class Composition:
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
for name, stratum in self.strata: # each also by category
for name, stratum in self.strata:
pairs: dict[tuple[str, str], dict[str, int]] = {}
for row in chosen.values():
for value in groups(stratum(row, period)):
key = (value, self.category(row))
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
crossed[(name, "category")] = pairs
crossed[name, "category"] = pairs
n = len(chosen)
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
crossed=crossed) # fmt: skip
return Result(
{"initial-population": n, "measure-observation": n}, strata=strata, crossed=crossed
)
def quartiles(values: list[float]) -> tuple[float, dict[str, float]]:
"""The median, and the quartiles as score extensions."""
if len(values) == 1:
return values[0], {"q1": values[0], "q3": values[0]}
return (values[0], {"q1": values[0], "q3": values[0]})
q1, median, q3 = statistics.quantiles(values, n=4, method="inclusive")
return median, {"q1": q1, "q3": q3}
return (median, {"q1": q1, "q3": q3})
@dataclass(frozen=True)
class Duration:
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
interval `ended` (default: has an `end`) without a value, like a sample reported
unsatisfactory, is in the initial population but not measured."""
value: str
end: str
start: str
@@ -253,18 +209,17 @@ class Duration:
unit: str = "sample_id"
date: str = "sample_date"
kind: str = "continuous-variable"
# Keeps each unit's last row, then reads only those dated in the period.
dated_only: ClassVar[bool] = True
one_per_unit: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
measured, initial = [], 0
measured, initial = ([], 0)
grouped: dict[str, dict[str, list[float]]] = {name: {} for name, _ in self.strata}
for row in {r[self.unit]: r for r in rows}.values():
if row[self.date] not in period or not self.units(row):
continue
end = as_day(row.get(self.end))
has = row.get(self.value) is not None and end is not None and end <= cutoff
has = row.get(self.value) is not None and end is not None and (end <= cutoff)
if has:
measured.append(float(row[self.value]))
for name, stratum in self.strata:
@@ -279,19 +234,24 @@ class Duration:
return Result(found)
median, spread = quartiles(measured)
return Result(
found, median, spread, unit="d",
strata={name: {v: {"measure-observation": len(days)} for v, days in values.items()}
for name, values in grouped.items()},
scores={(name, v): (*quartiles(days), "d")
for name, values in grouped.items() for v, days in values.items()},
) # fmt: skip
found,
median,
spread,
unit="d",
strata={
name: {v: {"measure-observation": len(days)} for v, days in values.items()}
for name, values in grouped.items()
},
scores={
(name, v): (*quartiles(days), "d")
for name, values in grouped.items()
for v, days in values.items()
},
)
@dataclass(frozen=True)
class RiskBand:
"""Patients indexed in the period, by the band their risk falls in (NO_DATA unscored):
`bands` are (name, upper cut), the last one's cut None."""
bands: tuple[tuple[str, float | None], ...]
kind: str = "composition"
@@ -301,19 +261,16 @@ class RiskBand:
for row in mine:
band = NO_DATA
if (p := row.get("probability")) is not None:
band = next(name for name, cut in self.bands if cut is None or p < cut)
band = next((name for name, cut in self.bands if cut is None or p < cut))
bands.setdefault(band, {"initial-population": 0})["initial-population"] += 1
n = len(mine)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": bands}) # fmt: skip
return Result(
{"initial-population": n, "measure-observation": n}, strata={"category": bands}
)
@dataclass(frozen=True)
class AtEnd:
"""The units on the books at a period's end: entered (`entry`) before it ended and not
gone (`exit`) before it began. Each is in the latest of `states` (name, date column, in
order) it reached before the end."""
entry: str
exit: str
states: tuple[tuple[str, str], ...]
@@ -322,28 +279,26 @@ class AtEnd:
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
found = {}
for row in rows:
entry, gone = as_day(row.get(self.entry)), as_day(row.get(self.exit))
entry, gone = (as_day(row.get(self.entry)), as_day(row.get(self.exit)))
if entry is None or entry >= period.end or (gone is not None and gone < period.start):
continue
reached = [n for n, c in self.states
if (d := as_day(row.get(c))) is not None and d < period.end] # fmt: skip
reached = [
n
for n, c in self.states
if (d := as_day(row.get(c))) is not None and d < period.end
]
if reached:
found[row[self.unit]] = (row, reached[-1])
return found
def reached(row: dict, column: str, period: Period) -> bool:
"""A date reached by the period's end."""
day = as_day(row.get(column))
return day is not None and day < period.end
@dataclass(frozen=True)
class StatusProportion:
"""Of the units on the books at the end (`population`) that meet `denominator`, those
that meet `numerator`; both see the unit's row, its state and the period. Strata count
every unit on the books, so a stratum with none in the denominator still shows."""
population: AtEnd
denominator: Callable[[dict, str, Period], bool]
numerator: Callable[[dict, str, Period], bool]
@@ -359,8 +314,10 @@ class StatusProportion:
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, (row, _) in units.items():
cell = values.setdefault(stratum(row, period), {
"initial-population": 0, "denominator": 0, "numerator": 0}) # fmt: skip
cell = values.setdefault(
stratum(row, period),
{"initial-population": 0, "denominator": 0, "numerator": 0},
)
cell["initial-population"] += unit in den
cell["denominator"] += unit in den
cell["numerator"] += unit in num
@@ -373,8 +330,6 @@ class StatusProportion:
@dataclass(frozen=True)
class StatusComposition:
"""The units on the books at the end, by their state; only `admit`ted states count."""
population: AtEnd
admit: Callable[[str], bool] = lambda state: True
kind: str = "composition"
@@ -385,16 +340,13 @@ class StatusComposition:
for state in states:
categories.setdefault(state, {"initial-population": 0})["initial-population"] += 1
n = len(states)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": categories}) # fmt: skip
return Result(
{"initial-population": n, "measure-observation": n}, strata={"category": categories}
)
@dataclass(frozen=True)
class StatusDuration:
"""Days (`value`) per unit on the books at the end, for those whose interval ended
(`end`) before the period's end and by the cut-off; every unit on the books is in the
initial population."""
population: AtEnd
value: str
end: str
@@ -402,9 +354,13 @@ class StatusDuration:
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = self.population.units(rows, period)
measured = [float(r[self.value]) for r, _ in units.values()
if r.get(self.value) is not None and reached(r, self.end, period)
and as_day(r[self.end]) <= cutoff] # fmt: skip
measured = [
float(r[self.value])
for r, _ in units.values()
if r.get(self.value) is not None
and reached(r, self.end, period)
and (as_day(r[self.end]) <= cutoff)
]
found = {"initial-population": len(units), "measure-observation": len(measured)}
if not measured:
return Result(found)
@@ -415,26 +371,30 @@ class StatusDuration:
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | StatusComposition
| StatusDuration) # fmt: skip
Rule = (
Proportion
| Composition
| Duration
| RiskBand
| StatusProportion
| StatusComposition
| StatusDuration
)
@dataclass(frozen=True)
class Measure:
id: str
title: str
rows: str # which gold rows it reads (see persistance.measures)
rows: str
rule: Rule
improvement: str | None = None
version: str = "1.0.0"
periods: tuple[str, ...] = ("semester", "month")
group: str = "TOTAL"
params: dict = field(default_factory=dict) # bound into the read of its rows
known: str = "known_at" # when a row's unit became known: before then it isn't counted
# Facts a row carries that became known apart from the row itself: their `known_at`
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
params: dict = field(default_factory=dict)
known: str = "known_at"
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
# The same by the event cutoff: a date column -> the columns it dates.
dated: dict[str, tuple[str, ...]] = field(default_factory=dict)
description: str | None = None
@@ -446,15 +406,24 @@ def evaluate(
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> Result:
"""The measure over the rows known `as_of` (all by default) for one period; durations
count to `event_cutoff` (default: `as_of`'s day, or today)."""
as_of = _moment(as_of)
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
if measure.dated:
rows = [{**row, **dict.fromkeys(c for day, cols in measure.dated.items()
if (as_day(row.get(day)) or cutoff) > cutoff
for c in (day, *cols))} for row in rows] # fmt: skip
if as_of is None: # every row and fact is known
rows = [
{
**row,
**dict.fromkeys(
(
c
for day, cols in measure.dated.items()
if (as_day(row.get(day)) or cutoff) > cutoff
for c in (day, *cols)
)
),
}
for row in rows
]
if as_of is None:
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
def known(column: str, row: dict) -> bool:
@@ -475,15 +444,11 @@ def evaluate_periods(
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> list[Result]:
"""`evaluate` for each period. A rule that reads only the rows dated in the period gets
just those, in their order: the rows are indexed by month once (periods are whole
months), not scanned once per period. One that keeps a row per unit first gets them
already kept."""
rule = measure.rule
rows = rows if isinstance(rows, list) else list(rows)
if as_of is not None or not getattr(rule, "dated_only", False):
return [evaluate(measure, rows, p, as_of, event_cutoff) for p in periods]
if getattr(rule, "one_per_unit", False): # the same for every period: done once
if getattr(rule, "one_per_unit", False):
rows = list({row[rule.unit]: row for row in rows}.values())
months: dict[tuple[int, int], list[int]] = defaultdict(list)
for i, row in enumerate(rows):
@@ -491,7 +456,7 @@ def evaluate_periods(
months[day.year, day.month].append(i)
found = []
for period in periods:
mine = sorted(i for (y, m), ids in months.items() if date(y, m, 1) in period for i in ids)
mine = sorted((i for (y, m), ids in months.items() if date(y, m, 1) in period for i in ids))
found.append(evaluate(measure, [rows[i] for i in mine], period, None, event_cutoff))
return found
@@ -511,46 +476,68 @@ def _score(value: float, extensions: dict[str, float], unit: str | None) -> dict
def report(
measure: Measure, period: Period, result: Result, as_of: datetime | None
) -> MeasureReport:
"""The evaluation as a FHIR R4B MeasureReport (validated when built)."""
group: dict = {
"id": measure.group,
"population": [_population(c, n) for c, n in result.populations.items()],
}
if result.score is not None:
group["measureScore"] = _score(result.score, result.score_extensions, result.unit)
elif measure.rule.kind == "composition": # a cohort scores its count
elif measure.rule.kind == "composition":
group["measureScore"] = {"value": result.populations["initial-population"]}
if result.strata:
group["stratifier"] = [
{"id": name, "code": [stratifier_code(name)],
"stratum": [{"value": {"text": value},
"population": [_population(c, n) for c, n in cells.items()],
**({"measureScore": _score(*result.scores[name, value])}
if (name, value) in result.scores else {})}
for value, cells in sorted(values.items())]}
{
"id": name,
"code": [stratifier_code(name)],
"stratum": [
{
"value": {"text": value},
"population": [_population(c, n) for c, n in cells.items()],
**(
{"measureScore": _score(*result.scores[name, value])}
if (name, value) in result.scores
else {}
),
}
for value, cells in sorted(values.items())
],
}
for name, values in result.strata.items()
] + [
{"id": f"{a}-{b}", "code": [stratifier_code(a), stratifier_code(b)],
"stratum": [{"component": [{"code": stratifier_code(a), "value": {"text": va}},
{"code": stratifier_code(b), "value": {"text": vb}}],
"population": [_population(c, n) for c, n in cells.items()]}
for (va, vb), cells in sorted(values.items())]}
{
"id": f"{a}-{b}",
"code": [stratifier_code(a), stratifier_code(b)],
"stratum": [
{
"component": [
{"code": stratifier_code(a), "value": {"text": va}},
{"code": stratifier_code(b), "value": {"text": vb}},
],
"population": [_population(c, n) for c, n in cells.items()],
}
for (va, vb), cells in sorted(values.items())
],
}
for (a, b), values in result.crossed.items()
] # fmt: skip
]
found = {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary", # with no score when nothing in the period could be measured
"type": "summary",
"measure": f"{measure_url(measure.id)}|{measure.version}",
"period": {"start": period.start.isoformat(),
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
"period": {
"start": period.start.isoformat(),
"end": date.fromordinal(period.end.toordinal() - 1).isoformat(),
},
"date": datetime.now().astimezone().isoformat(),
"group": [group],
} # fmt: skip
}
if as_of is not None:
found["extension"] = [{"url": EXTENSION + "corte-conocimiento",
"valueDateTime": _moment(as_of).isoformat()}] # fmt: skip
found["extension"] = [
{"url": EXTENSION + "corte-conocimiento", "valueDateTime": _moment(as_of).isoformat()}
]
if measure.improvement:
found["improvementNotation"] = {"coding": [{"system": IMPROVEMENT,
"code": measure.improvement}]} # fmt: skip
found["improvementNotation"] = {
"coding": [{"system": IMPROVEMENT, "code": measure.improvement}]
}
return MeasureReport.model_validate(found)
-4
View File
@@ -1,6 +1,3 @@
"""The models' names as the pages and FHIR resources show them (`<domain>.<model>`). A model
without one is shown by its code."""
TITLES: dict[str, str] = {
"cacu.cin2_logistic": "Riesgo de LIEAG+ (regresión logística)",
"cacu.cin2_pim": "Riesgo de LIEAG+ en vigilancia",
@@ -22,5 +19,4 @@ TITLES: dict[str, str] = {
def title(model: str) -> str:
"""`model` (`<domain>.<name>`) as the pages name it."""
return TITLES.get(model, model.split(".", 1)[-1])
+66 -140
View File
@@ -1,17 +1,8 @@
"""The ingestion DSL: a graph an operator draws, and the pure steps it needs. No IO here.
A pipeline is one versioned JSON document of nodes; each node names its inputs (the edges).
Every node kind wraps one library operation and outputs one table, so any node's output can
be previewed and a run can restart from the node that changed. Each kind's JSON Schema is
the form the canvas shows for it. Nothing in a graph is specific to one hospital in code.
"""
import re
from datetime import datetime
from graphlib import CycleError, TopologicalSorter
from typing import Annotated, Any, ClassVar, Literal
from urllib.parse import urlsplit, urlunsplit
import dateparser
from pydantic import (
BaseModel,
@@ -22,25 +13,26 @@ from pydantic import (
field_validator,
model_validator,
)
from core import catalog, sources
from core.schema import ENTITIES
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
ID_PATTERN = "^[a-z][a-z0-9_]*$"
Id = Annotated[str, Field(pattern=ID_PATTERN, max_length=40)]
ImportPath = Annotated[str, Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")]
EntityName = Literal[tuple(ENTITIES)] # type: ignore[valid-type]
# How the forms name each entity: identity, and each study by its catalog title.
ENTITY_TITLES = {"identity": "Identidad de la persona",
**{name: spec.title for name, spec in catalog.studies().items()}} # fmt: skip
ImportPath = Annotated[str, Field(pattern="^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$")]
EntityName = Literal[tuple(ENTITIES)]
ENTITY_TITLES = {
"identity": "Identidad de la persona",
**{name: spec.title for name, spec in catalog.studies().items()},
}
def _says(title: str, description: str = "", options: dict[str, str] | None = None,
advanced: bool = False, keys: Literal["field"] | None = None) -> Any: # fmt: skip
"""A field as the canvas form shows it: its title and help in the operator's words,
for a fixed set of values how each one reads, and whether only the "Avanzado" tab
shows it (what a guided dialog fills instead); a map keyed by platform fields says so
(`keys="field"`), so its keys are picked by their titles."""
def _says(
title: str,
description: str = "",
options: dict[str, str] | None = None,
advanced: bool = False,
keys: Literal["field"] | None = None,
) -> Any:
extra: dict[str, Any] = {}
if options:
listed = [{"value": k, "label": v} for k, v in options.items()]
@@ -59,41 +51,32 @@ class Position(BaseModel):
class Node(BaseModel):
model_config = ConfigDict(extra="forbid")
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1)
id: Id
inputs: list[Id] = []
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
position: Position | None = None # where the canvas drew it
position: Position | None = None
class Guided(BaseModel):
"""How the Conectar dialog drew a source: its type (core.sources) and the answers given.
The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none."""
model_config = ConfigDict(extra="forbid")
type: str
answers: dict[str, Any] = {}
class Source(Node):
"""One table, file set or API resource, copied as it is (dlt). Merged on the source's
own primary key or `primary_key`; replaced whole when it has none."""
inputs_allowed = (0, 0)
kind: Literal["source"] = "source"
# any dlt source or resource, e.g. dlt.sources.sql_database:sql_table
source: Annotated[
ImportPath, _says("Fuente dlt", "Módulo:función de la fuente dlt.", advanced=True)
]
args: Annotated[
dict[str, Any], _says("Argumentos", "Los de la fuente dlt.", advanced=True)
] = {}
resource: Annotated[ # which resource, when the source has several
str | None,
_says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True),
resource: Annotated[
str | None, _says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True)
] = None
then: Annotated[ # a dlt transformer piped after (file contents, Excel)
then: Annotated[
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
] = None
primary_key: Annotated[
@@ -104,22 +87,18 @@ class Source(Node):
@model_validator(mode="before")
@classmethod
def _made_from_answers(cls, data: Any) -> Any:
"""A guided source's dlt fields always follow its answers. A source drawn by hand
that a catalog type makes exactly is read as that type, so the dialog edits it."""
if isinstance(data, dict) and not data.get("guided") and data.get("source"):
if isinstance(data, dict) and (not data.get("guided")) and data.get("source"):
if found := sources.recognise(data):
data = {**data, "guided": {"type": found[0], "answers": found[1]}}
if isinstance(data, dict) and data.get("guided"):
guided = data["guided"]
guided = guided.model_dump() if isinstance(guided, BaseModel) else guided
if MASK not in repr(guided.get("answers", {})): # masked: shown, not run
if MASK not in repr(guided.get("answers", {})):
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
return data
class Read(Node):
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
kind: Literal["read"] = "read"
column: Annotated[
str, _says("Columna con los archivos", "Donde la entrada trae cada documento.")
@@ -138,16 +117,12 @@ class Condition(BaseModel):
"matches": "coincide con la expresión",
"present": "tiene algún valor",
},
), # fmt: skip
),
]
value: Annotated[str, _says("Valor", "Lo que se busca; por ejemplo «citología».")] = ""
class Route(Node):
"""Only the rows where every condition holds (e.g. reports titled "Citología"). An
`otherwise` route takes the rows of its input that none of the other routes on that
input take (documents nobody recognises, for a reviewer), then its own conditions."""
kind: Literal["route"] = "route"
when: Annotated[list[Condition], _says("Pasan las filas donde")] = []
otherwise: Annotated[
@@ -156,37 +131,23 @@ class Route(Node):
class Map(Node):
"""Columns to platform fields, the site's codes translated by its ConceptMap
(core.concept_map), and its date formats."""
kind: Literal["map"] = "map"
fields: Annotated[ # platform field -> column
fields: Annotated[
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
]
concept_map: Annotated[ # the site's codes in platform terms
concept_map: Annotated[
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
] = None
formats: Annotated[ # platform field -> strptime format
formats: Annotated[
dict[str, str], _says("Formatos de fecha", "Por ejemplo %d/%m/%Y.", keys="field")
] = {}
# platform field -> a value in platform terms that every row has, though no column says
# it (a table of neurology notes: their specialty)
values: Annotated[
dict[str, str], _says("Valores fijos", "Un dato igual para todas las filas.", keys="field")
] = {}
class Extract(Node):
"""Platform fields read from text, each kept with the text it was read from.
`auto` asks the LLM when one is configured and answering, else applies `patterns`;
with neither, the row is held. Patterns are regexes with one group, per field (the
LLM can propose them from sample documents); their values go through the ConceptMap
and `formats` as in `map`."""
kind: Literal["extract"] = "extract"
# the text to read; several columns are read as one document, in their order (an
# outsourced result joined to the order it answers)
column: Annotated[str | list[str], _says("Columna con el texto")]
entity: Annotated[
EntityName, _says("Estudio", "Qué estudio se saca del documento.", ENTITY_TITLES)
@@ -200,14 +161,12 @@ class Extract(Node):
"llm": "Con el modelo de lenguaje",
"patterns": "Con patrones",
},
), # fmt: skip
),
] = "auto"
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
patterns: Annotated[ # platform field -> regex with one group
patterns: Annotated[
dict[str, str], _says("Patrones", "Dato → expresión con un grupo ( ).", keys="field")
] = {}
# platform field -> a column of the row taken as it is, not read from the text (an EEG
# report joined to its recording: the date from the report, the file from the column)
columns: Annotated[
dict[str, str],
_says("Datos tomados de columnas", "Dato → columna, sin leer el texto.", keys="field"),
@@ -224,16 +183,11 @@ class Extract(Node):
return v
def text(self, row: dict[str, Any]) -> str:
"""The row's text this node reads."""
columns = [self.column] if isinstance(self.column, str) else self.column
return "\n".join(str(row[c]) for c in columns if row.get(c))
return "\n".join((str(row[c]) for c in columns if row.get(c)))
class Fhir(Node):
"""FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
entity: identity, death or a study (core.fhir_in). The sender's own codes go through
its ConceptMap."""
kind: Literal["fhir"] = "fhir"
column: Annotated[str, _says("Columna con el FHIR")] = "doc"
entity: Annotated[EntityName, _says("Estudio", options=ENTITY_TITLES)]
@@ -241,11 +195,9 @@ class Fhir(Node):
class Join(Node):
"""Two inputs side by side where their columns match."""
inputs_allowed = (2, 2)
kind: Literal["join"] = "join"
on: Annotated[ # (left column, right column)
on: Annotated[
list[tuple[str, str]],
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
]
@@ -254,7 +206,7 @@ class Join(Node):
_says(
"Cuáles quedan",
options={"inner": "Solo las que tienen pareja", "left": "Todas las de la izquierda"},
), # fmt: skip
),
] = "inner"
@@ -262,23 +214,22 @@ IDENTIFIERS = ("record_number", "curp", "nss")
class Link(Node):
"""Identity rows from every input, grouped into persons (Splink).
Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
and `r.` for the two records); persons are the connected groups. A person whose
records disagree on birth date or sex is held for review as a whole. Pairs Splink
scores above `review` that ended up apart are queued as possible matches."""
inputs_allowed = (1, None)
kind: Literal["link"] = "link"
fields: Annotated[list[str], _says("Datos que comparar")] = [
"record_number", "full_name", "curp", "nss", "birth_date", "sex"] # fmt: skip
rules: Annotated[ # empty: the defaults for `fields` (see default_rules)
"record_number",
"full_name",
"curp",
"nss",
"birth_date",
"sex",
]
rules: Annotated[
list[str],
_says(
"Reglas",
"Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).",
), # fmt: skip
),
] = []
review: Annotated[
float,
@@ -287,13 +238,12 @@ class Link(Node):
] = 0.5
def default_rules(self) -> list[str]:
"""The same identifier, unless the birth dates differ; or the same birth date and
the same name (as compared: upper case, no accents, single spaces)."""
dob = "birth_date" in self.fields
same_dob = (
" and (l.birth_date is null or r.birth_date is null"
" or l.birth_date = r.birth_date)" if dob else ""
) # fmt: skip
" and (l.birth_date is null or r.birth_date is null or l.birth_date = r.birth_date)"
if dob
else ""
)
rules = [f"l.{f} = r.{f}{same_dob}" for f in IDENTIFIERS if f in self.fields]
if dob and "full_name" in self.fields:
rules.append("l.birth_date = r.birth_date and l.full_name = r.full_name")
@@ -301,14 +251,10 @@ class Link(Node):
class Target(Node):
"""Rows of platform fields into one platform entity, each row given its person by the
one `link` node among the inputs. Rule breaks are held for review."""
inputs_allowed = (2, None)
kind: Literal["target"] = "target"
entity: Annotated[
EntityName,
_says("Estudio", "En qué estudio de la plataforma se guarda.", ENTITY_TITLES),
EntityName, _says("Estudio", "En qué estudio de la plataforma se guarda.", ENTITY_TITLES)
]
@field_validator("entity")
@@ -336,7 +282,7 @@ class Pipeline(BaseModel):
lo, hi = n.inputs_allowed
if not lo <= len(n.inputs) <= (hi if hi is not None else len(n.inputs)):
raise ValueError(f"{n.id}: {n.kind} takes {lo}..{hi} inputs")
if missing := set(n.inputs) - set(ids):
if missing := (set(n.inputs) - set(ids)):
raise ValueError(f"{n.id}: no node {sorted(missing)}")
kinds = {n.id: n.kind for n in self.nodes}
for n in self.nodes:
@@ -349,15 +295,14 @@ class Pipeline(BaseModel):
return self
def order(self) -> list[AnyNode]:
"""Nodes in an order where every input runs before the nodes that read it."""
by_id = {n.id: n for n in self.nodes}
graph = TopologicalSorter({n.id: n.inputs for n in self.nodes})
return [by_id[i] for i in graph.static_order()]
RECORD = "_record" # the source row every row comes from (hash of that row)
HELD = "_held" # why a row may not reach silver (list of reasons) or None
QUOTES = "_quotes" # what text each LLM value was read from
RECORD = "_record"
HELD = "_held"
QUOTES = "_quotes"
def matches(node: Route, row: dict[str, Any]) -> bool:
@@ -376,38 +321,32 @@ def matches(node: Route, row: dict[str, Any]) -> bool:
def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list[dict]:
"""Left rows with the matching right rows' columns (a clashing name gets `__<right>`)."""
index: dict[tuple, list[dict]] = {}
for r in right:
index.setdefault(tuple(r.get(b) for _, b in node.on), []).append(r)
index.setdefault(tuple((r.get(b) for _, b in node.on)), []).append(r)
out = []
for row in left:
found = index.get(tuple(row.get(a) for a, _ in node.on), [])
found = index.get(tuple((row.get(a) for a, _ in node.on)), [])
for r in found or ([{}] if node.how == "left" else []):
extra = {(k if k not in row else f"{k}__{right_id}"): v for k, v in r.items()}
extra = {k if k not in row else f"{k}__{right_id}": v for k, v in r.items()}
out.append({**row, **extra, RECORD: row[RECORD]})
return out
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
Codes = dict[str, dict[str, str]]
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
"""A raw value as the platform field expects it: the site's code translated (its
ConceptMap, case ignored), then its date format: a strptime format (spaces inside the
value ignored when the format has none), or `dateparser:<language>` for dates written
out ("9 de diciembre de 2025"). A value that doesn't parse is kept as written, so the
target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = _SPACE.sub(" ", raw.strip()) # a value read across a line break is one value
raw = _SPACE.sub(" ", raw.strip())
raw = codes.get(field, {}).get(raw.casefold(), raw)
fmt = node.formats.get(field)
if fmt and fmt.startswith("dateparser:"):
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
return found.date() if found else raw
if fmt:
if " " not in fmt: # OCR may split a number ("25/01/1 967")
if " " not in fmt:
raw = "".join(raw.split())
try:
return datetime.strptime(raw, fmt).date()
@@ -424,7 +363,6 @@ def map_row(node: Map, row: dict[str, Any], codes: Codes) -> dict[str, Any]:
def validate(entity: str, values: dict[str, Any]) -> list[str]:
"""Why these values break the platform schema; empty if they don't."""
try:
ENTITIES[entity].model_validate(values)
except ValidationError as e:
@@ -432,28 +370,25 @@ def validate(entity: str, values: dict[str, Any]) -> list[str]:
return []
_SPACE = re.compile(r"\s+")
_SPACE = re.compile("\\s+")
def grounded(quote: str | None, text: str) -> bool:
"""An LLM value counts only if the text it says it read is really in the document."""
if not quote:
return False
norm = lambda s: _SPACE.sub(" ", s).strip().casefold() # noqa: E731
norm = lambda s: _SPACE.sub(" ", s).strip().casefold()
return norm(quote) in norm(text)
def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
"""Each record of an LLM answer as (values, quotes, reasons to hold it). A value whose
quote is not in the text is dropped, and the record is held saying so."""
out = []
for record in answer.get("records", []):
values, quotes, held = {}, {}, []
values, quotes, held = ({}, {}, [])
for field, got in record.items():
if not got or got.get("value") is None:
continue
if grounded(got.get("quote"), text):
values[field], quotes[field] = got["value"], got["quote"]
values[field], quotes[field] = (got["value"], got["quote"])
else:
held.append(f"{field}: not found in the document as quoted")
out.append((values, quotes, held))
@@ -461,9 +396,7 @@ def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, dict, list[str]]]:
"""One record from the node's patterns: (values, quotes, reasons to hold it). A value
found this way is grounded by construction: the quote is the matched text."""
values, quotes = {}, {}
values, quotes = ({}, {})
for field, pattern in node.patterns.items():
if found := re.search(pattern, text, re.IGNORECASE):
values[field] = convert(node, field, found.group(1), codes)
@@ -474,8 +407,6 @@ def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, d
def answer_schema(entity: str) -> dict:
"""JSON Schema for an LLM answer: every record of `entity` found, each field with the
quote it was read from."""
fields = {
f: (create_model(f"{entity}_{f}", value=(info.annotation, None), quote=(str, "")), None)
for f, info in ENTITIES[entity].model_fields.items()
@@ -485,7 +416,7 @@ def answer_schema(entity: str) -> dict:
MASK = "********"
_SECRET_KEY = re.compile(r"pass|secret|token|key", re.IGNORECASE)
_SECRET_KEY = re.compile("pass|secret|token|key", re.IGNORECASE)
def _mask(key: str, value: Any) -> Any:
@@ -503,8 +434,6 @@ def _mask(key: str, value: Any) -> Any:
def _secret_answers(guided: "Guided") -> set[str]:
"""Answers masked whole (a password); a sign-in's account keeps who it is and masks
its tokens and client secret, like any argument."""
fields = sources.catalog().types[guided.type].fields
return {k for k, f in fields.items() if f.type == "password"}
@@ -513,15 +442,15 @@ def _masked_source(n: "Source") -> "Source":
update: dict[str, Any] = {"args": _mask("", n.args)}
if n.guided:
secret = _secret_answers(n.guided)
answers = {k: MASK if k in secret and v not in (None, "") else _mask(k, v)
for k, v in n.guided.answers.items()} # fmt: skip
answers = {
k: MASK if k in secret and v not in (None, "") else _mask(k, v)
for k, v in n.guided.answers.items()
}
update["guided"] = n.guided.model_copy(update={"answers": answers})
return n.model_copy(update=update)
def redacted(pipeline: Pipeline) -> Pipeline:
"""The pipeline with every secret in its sources masked (arguments and the dialog's
answers), as the API shows it."""
nodes = [_masked_source(n) if n.kind == "source" else n for n in pipeline.nodes]
return pipeline.model_copy(update={"nodes": nodes})
@@ -538,18 +467,15 @@ def _restore(new: Any, old: Any, where: str) -> Any:
def restored(new: Pipeline, old: Pipeline | None) -> Pipeline:
"""A pipeline sent back by the UI with masks where secrets were: the saved secrets are
kept. A mask with nothing saved behind it is refused."""
saved = {n.id: n for n in old.nodes if n.kind == "source"} if old else {}
nodes = [_restored_source(n, saved.get(n.id)) if n.kind == "source" else n
for n in new.nodes] # fmt: skip
nodes = [_restored_source(n, saved.get(n.id)) if n.kind == "source" else n for n in new.nodes]
return new.model_copy(update={"nodes": nodes})
def _restored_source(new: "Source", old: "Source | None") -> "Source":
if not new.guided:
return new.model_copy(update={"args": _restore(new.args, old and old.args, new.id)})
kept = old.guided.answers if old and old.guided and old.guided.type == new.guided.type else {}
kept = old.guided.answers if old and old.guided and (old.guided.type == new.guided.type) else {}
secret = _secret_answers(new.guided)
answers = {}
for k, v in new.guided.answers.items():
+1 -19
View File
@@ -1,18 +1,8 @@
"""The platform schema: the only fixed shape in ingestion. Every source is mapped onto it.
`identity` is what a record says about whom it belongs to; every other entity is a study of
the clinical catalog (core.catalog), whose natural key and fields the catalog declares. Two
values for one key that disagree are a conflict. `person` is never a field: record linkage
over `identity` values assigns it.
"""
import re
from datetime import date
from enum import StrEnum
from typing import ClassVar
from pydantic import BaseModel, ConfigDict, Field, field_validator
from core import catalog
@@ -21,16 +11,12 @@ class Sex(StrEnum):
MALE = "male"
# Systems of the identifiers a person carries. A record number's system is where it came
# from (`urn:isssteleon:<pipeline>:<node>`): a hospital has as many as it has sources.
IDENTIFIER_SYSTEMS = {
"curp": "https://isssteleon.org/fhir/sid/curp",
"nss": "https://isssteleon.org/fhir/sid/nss",
}
RECORD_NUMBER_SYSTEM = "urn:isssteleon:"
_DATE = re.compile(r"\d{1,4}[/.-]\d{1,2}[/.-]\d{1,4}")
_DATE = re.compile("\\d{1,4}[/.-]\\d{1,2}[/.-]\\d{1,4}")
class Entity(BaseModel):
@@ -39,8 +25,6 @@ class Entity(BaseModel):
class Identity(Entity):
"""What a record says about whom it belongs to. Input to linkage, never trusted alone."""
record_number: str | None = Field(None, title="Número de expediente")
full_name: str | None = Field(None, title="Nombre completo")
curp: str | None = Field(None, title="CURP")
@@ -51,8 +35,6 @@ class Identity(Entity):
@field_validator("record_number")
@classmethod
def _not_a_date(cls, v: str | None) -> str | None:
"""A date read where a record number should be (a report's date beside "No.
Registro:", say) would join strangers: the record waits for a reviewer instead."""
if v is not None and _DATE.fullmatch(v.strip()):
raise ValueError("a date is not a record number")
return v
+48 -74
View File
@@ -1,42 +1,26 @@
"""The kinds of source an operator can connect, as the Conectar dialog walks them through.
It is data (`types.yaml` beside this module): each type says what to ask (its fields, in
plain words), how the answers become a pipeline's `Source` node (a dlt source and its
arguments), and what "Probar conexión" can list from it. A new kind of source is a new entry,
never code; a site's own source is configuration (the answers saved in its pipeline).
Templates: a string that is exactly "{field}" takes the answer as given (a number stays a
number, a "{field[part]}" one part of a structured answer such as a sign-in's; an empty
optional answer drops the key, and a block whose every answer is empty
goes with it); inside a longer string, `{field:url}` quotes
the answer for a URL's user or password, `{field:path}` for a URL's path, and `{field:last}`
takes the last part of a link (a folder's id in a shared link).
"""
import re
import string
from functools import cache
from pathlib import Path
from typing import Any, Literal
from urllib.parse import quote, unquote
import yaml
from pydantic import BaseModel, ConfigDict, model_validator
HERE = Path(__file__).parent
FieldType = Literal[
"text", # a line of text
"text",
"number",
"password", # never shown back; masked like any secret
"select", # one of `options`
"folder", # a folder on the server, browsed under the roots the operator mounted
"server_file", # a file on the server, browsed the same way
"upload", # files sent from the user's computer; holds the folder they landed in
"url", # a web address, or a path typed in
"oauth", # "Iniciar sesión con …": holds the provider's refresh token
"table", # picked from what "Probar conexión" listed
"format", # how to read the files: one of the catalog's `formats`
"columns", # some of the table's columns (a list), picked from its first rows
"password",
"select",
"folder",
"server_file",
"upload",
"url",
"oauth",
"table",
"format",
"columns",
]
@@ -54,23 +38,20 @@ class FieldSpec(BaseModel):
placeholder: str = ""
required: bool = True
default: Any = None
options: list[Option] = [] # select
provider: str | None = None # oauth: microsoft, google
advanced: bool = False # shown under "Más opciones"
options: list[Option] = []
provider: str | None = None
advanced: bool = False
@model_validator(mode="after")
def _complete(self):
if self.type == "select" and not self.options:
if self.type == "select" and (not self.options):
raise ValueError("a select field lists its options")
if self.type == "oauth" and not self.provider:
if self.type == "oauth" and (not self.provider):
raise ValueError("an oauth field names its provider")
return self
class Listing(BaseModel):
"""What "Probar conexión" shows: a database's tables (the resources of `source`, built
from `args`), or the first rows the type's own node reads (files, records)."""
model_config = ConfigDict(extra="forbid")
kind: Literal["tables", "rows"]
source: str | None = None
@@ -84,7 +65,7 @@ class SourceType(BaseModel):
description: str
icon: str
fields: dict[str, FieldSpec]
source: str # the dlt source or resource the node runs
source: str
args: dict[str, Any] = {}
resource: str | None = None
then: str | None = None
@@ -96,17 +77,15 @@ class SourceType(BaseModel):
named = _placeholders([self.source, self.args, self.resource, self.then])
if self.listing:
named |= _placeholders([self.listing.source, self.listing.args])
if unknown := named - set(self.fields):
if unknown := (named - set(self.fields)):
raise ValueError(f"templates name unknown fields {sorted(unknown)}")
return self
class Provider(BaseModel):
"""A sign-in button's OAuth 2.0 provider (authorization code flow)."""
model_config = ConfigDict(extra="forbid")
title: str
env: str # prefix of the server's settings for its app registration
env: str
authorize_url: str
token_url: str
scope: str
@@ -123,7 +102,7 @@ class Catalog(BaseModel):
model_config = ConfigDict(extra="forbid")
groups: dict[str, Group]
providers: dict[str, Provider]
formats: list[Option] # how a file is read: the `then` of a filesystem source
formats: list[Option]
types: dict[str, SourceType]
@model_validator(mode="after")
@@ -138,7 +117,7 @@ class Catalog(BaseModel):
class MissingAnswer(ValueError):
"""An answer the type needs was left empty; its message names it in plain words."""
pass
@cache
@@ -179,8 +158,8 @@ _DROP = object()
def _fill(template: Any, values: dict[str, Any]) -> Any:
named = _placeholders(template)
if isinstance(template, dict) and named and all(values.get(n) in (None, "") for n in named):
return _DROP # a block whose every answer is empty (an optional token's auth)
if isinstance(template, dict) and named and all((values.get(n) in (None, "") for n in named)):
return _DROP
if isinstance(template, dict):
filled = {k: _fill(v, values) for k, v in template.items()}
return {k: v for k, v in filled.items() if v is not _DROP}
@@ -189,8 +168,8 @@ def _fill(template: Any, values: dict[str, Any]) -> Any:
if not isinstance(template, str):
return template
parts = list(_FORMAT.parse(template))
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
name = parts[0][1] # "{account}", or a part of it: "{account[drive_id]}"
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and (not parts[0][2]):
name = parts[0][1]
if values.get(_base(name)) in (None, ""):
return _DROP
value = _FORMAT.get_field(name, (), values)[0]
@@ -199,9 +178,8 @@ def _fill(template: Any, values: dict[str, Any]) -> Any:
def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The answers with defaults filled in; a required answer missing is refused."""
spec = catalog().types[type_id]
if unknown := set(given) - set(spec.fields):
if unknown := (set(given) - set(spec.fields)):
raise ValueError(f"{type_id}: no fields {sorted(unknown)}")
out = {}
for name, field in spec.fields.items():
@@ -215,8 +193,6 @@ def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The `Source` node fields (source, args, resource, then, primary_key) the answers
make."""
spec = catalog().types[type_id]
values = answers(type_id, given)
made = {
@@ -230,17 +206,18 @@ def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
def listing(type_id: str, given: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""For a type that lists tables: the dlt source and arguments that list them. The
table field may still be empty (it is what the listing helps pick)."""
spec = catalog().types[type_id]
if not spec.listing or spec.listing.kind != "tables" or not spec.listing.source:
if not spec.listing or spec.listing.kind != "tables" or (not spec.listing.source):
return None
relaxed = {n: (given.get(n) or f.default) for n, f in spec.fields.items()}
missing = [f.label for n, f in spec.fields.items()
if f.required and f.type != "table" and relaxed[n] in (None, "")] # fmt: skip
relaxed = {n: given.get(n) or f.default for n, f in spec.fields.items()}
missing = [
f.label
for n, f in spec.fields.items()
if f.required and f.type != "table" and (relaxed[n] in (None, ""))
]
if missing:
raise MissingAnswer("falta " + ", ".join(f"«{m}»" for m in missing))
return _fill(spec.listing.source, relaxed), _fill(spec.listing.args, relaxed)
raise MissingAnswer("falta " + ", ".join((f"«{m}»" for m in missing)))
return (_fill(spec.listing.source, relaxed), _fill(spec.listing.args, relaxed))
class _NoMatch(Exception):
@@ -248,14 +225,13 @@ class _NoMatch(Exception):
def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
"""The answers that make `template` give `value`, into `found` (_NoMatch when none)."""
if isinstance(template, dict):
if not isinstance(value, dict) or set(value) - set(template):
raise _NoMatch
for key, part in template.items():
if key in value:
_take(part, value[key], found)
elif not _placeholders(part): # a fixed key the node lacks
elif not _placeholders(part):
raise _NoMatch
return
if isinstance(template, list):
@@ -269,14 +245,14 @@ def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
raise _NoMatch
return
parts = list(_FORMAT.parse(template))
if any(name and ("[" in name or "." in name) for _, name, _, _ in parts):
raise _NoMatch # an answer's part (an account's drive): not read back
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
_answer(found, parts[0][1], value) # the whole value, whatever its type
if any((name and ("[" in name or "." in name) for _, name, _, _ in parts)):
raise _NoMatch
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and (not parts[0][2]):
_answer(found, parts[0][1], value)
return
if not isinstance(value, str):
raise _NoMatch
pattern, names = "", []
pattern, names = ("", [])
for literal, name, spec, _ in parts:
pattern += re.escape(literal)
if name:
@@ -297,8 +273,6 @@ def _answer(found: dict[str, Any], name: str, value: Any) -> None:
def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""The catalog type and answers that make a source node drawn by hand, when one makes
exactly it (its source, args, resource and reader): what lets the dialog edit it."""
made = {k: node.get(k) for k in ("source", "args", "resource", "then")}
made["args"] = made["args"] or {}
for type_id, spec in catalog().types.items():
@@ -312,22 +286,22 @@ def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
continue
_take(template, made[key], found)
numbers = {n for n, f in spec.fields.items() if f.type == "number"}
given = {n: (int(v) if n in numbers and isinstance(v, str) and v.isdigit() else v)
for n, v in found.items() if n in spec.fields} # fmt: skip
given = {
n: int(v) if n in numbers and isinstance(v, str) and v.isdigit() else v
for n, v in found.items()
if n in spec.fields
}
rendered = render(type_id, given)
except (_NoMatch, ValueError):
continue
if all(rendered[k] == made[k] for k in ("source", "resource", "then")) and _same_args(
if all((rendered[k] == made[k] for k in ("source", "resource", "then"))) and _same_args(
rendered["args"] or {}, made["args"], spec
):
return type_id, given
return (type_id, given)
return None
def _same_args(rendered: dict, drawn: dict, spec: "SourceType") -> bool:
"""The same arguments, but for those the type fills from its fields' defaults (rows per
batch, say) where the drawn node left them to the source: how much it reads at a time,
not what."""
defaults = {f"{{{n}}}": f.default for n, f in spec.fields.items() if f.default is not None}
for key, value in rendered.items():
if key in drawn:
-5
View File
@@ -1,5 +1,3 @@
# The kinds of source the Conectar dialog offers (core.sources). Words are what the operator
# reads: plain Spanish, no jargon. Each type becomes one pipeline `Source` node.
groups:
database:
@@ -15,9 +13,6 @@ groups:
title: Web
description: Un sistema que entrega sus datos por internet (una API) o envía FHIR.
# The sign-in buttons. The app registration (client id and secret) is the site's IT's, set
# on the server as <ENV>_CLIENT_ID and <ENV>_CLIENT_SECRET (Microsoft also <ENV>_TENANT_ID,
# default "organizations"); `{tenant}` in an endpoint takes it.
providers:
microsoft:
title: Microsoft
+26 -22
View File
@@ -1,18 +1,8 @@
"""TEA clinical parameters: the one place they are set. dbt reads them as vars, the measures
import them. Codes are the platform's (core.catalog)."""
# The screening cohort: children whose first M-CHAT is at this age (completed months, from
# the age in months rounded to one decimal), in these windows.
AGE_GROUPS = [(16, 23), (24, 29), (30, 36)]
DAYS_PER_MONTH = 30.4375
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months: the list's windows, as CaCu's and CaMa's
# A neurology note with one of these confirms the diagnosis (ICD-10, with the dot).
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
CONFIRMING_ICD10 = ["F84.0"]
NEUROLOGY = "pediatric_neurology" # the specialty of the notes the screening counts
# ADOS-2 calibrated severity (CSS): the lowest total reaching CSS 2..10, by module and
# algorithm (Module 1) and whether the child is under five. Items score 0 to 3; a 3 counts
# as 2. The values are approximate published ones, kept as data.
NEUROLOGY = "pediatric_neurology"
ADOS2_CSS = {
("module_1", "few_to_no_words", True): [4, 7, 11, 14, 16, 18, 20, 22, 24],
("module_1", "few_to_no_words", False): [6, 9, 12, 15, 17, 19, 21, 23, 25],
@@ -22,21 +12,35 @@ ADOS2_CSS = {
("module_2", None, False): [3, 6, 8, 10, 11, 13, 15, 17, 19],
("module_3", None, None): [2, 4, 7, 8, 9, 11, 13, 15, 17],
}
# Classification by CSS: below 3 no spectrum, 3-4 autism spectrum, 5 or more autism.
ADOS2_CLASSIFICATION = [("non_spectrum", 3), ("autism_spectrum", 5), ("autism", None)]
# The Module 1 items that only the "few to no words" algorithm prints.
FEW_TO_NO_WORDS_ITEMS = ["joint_attention_response", "intonation"]
SOCIAL_AFFECT_ITEMS = [
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact", "facial_expressions",
"gaze_integration", "shared_enjoyment", "response_to_name", "ignoring", "requesting",
"showing", "joint_attention_initiation", "joint_attention_response",
"social_overtures_quality", "social_overtures_caregiver", "reciprocal_communication",
"vocalization_directed",
"pointing",
"gestures",
"unusual_eye_contact",
"facial_expressions",
"gaze_integration",
"shared_enjoyment",
"response_to_name",
"ignoring",
"requesting",
"showing",
"joint_attention_initiation",
"joint_attention_response",
"social_overtures_quality",
"social_overtures_caregiver",
"reciprocal_communication",
"rapport_quality",
] # fmt: skip
RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_sensory_interest",
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
]
RESTRICTED_REPETITIVE_ITEMS = [
"intonation",
"stereotyped_language",
"unusual_sensory_interest",
"hand_finger_mannerisms",
"repetitive_interests",
]
def dbt_vars() -> dict:
"""What dbt reads (`var('tea')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper() and k != "ADOS2_CSS"}
+23 -20
View File
@@ -1,23 +1,18 @@
"""ADOS-2 scoring (pure): the calibrated severity score (CSS) and classification of one
evaluation from its items (core.tea). The total is the sum of the items given, a 3 counting
as 2; an evaluation without items in either domain is not scored."""
from datetime import date
from core import tea
TODDLER_BANDS = {True: (10, 16), False: (8, 14)} # 20 months or younger: (mild, severe) totals
TODDLER_BANDS = {True: (10, 16), False: (8, 14)}
def algorithm(row: dict) -> str | None:
"""Module 1's algorithm, from the items its report prints."""
if row.get("module") != "module_1":
return None
printed = any(row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS)
printed = any((row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS))
return "few_to_no_words" if printed else "some_words"
def total(row: dict) -> int | None:
def domain(items: list[str]) -> list[int]:
return [min(int(row[i]), 2) for i in items if row.get(i) is not None]
@@ -27,22 +22,30 @@ def total(row: dict) -> int | None:
def score(row: dict, birth: date | None) -> tuple[int | None, str | None]:
"""(CSS, classification); (None, None) when it can't be scored."""
found, module = total(row), row.get("module")
found, module = (total(row), row.get("module"))
if found is None or module is None:
return None, None
return (None, None)
months = (row["evaluation_date"] - birth).days / tea.DAYS_PER_MONTH if birth else None
if module == "toddler":
mild, severe = TODDLER_BANDS[months is not None and months <= 20]
band = "severe_concern" if found >= severe else (
"mild_to_moderate_concern" if found >= mild else "non_spectrum") # fmt: skip
return None, band
band = (
"severe_concern"
if found >= severe
else "mild_to_moderate_concern"
if found >= mild
else "non_spectrum"
)
return (None, band)
under_five = months is not None and months < 60
keys = [(module, algorithm(row), under_five), (module, algorithm(row), None),
(module, None, under_five), (module, None, None)] # fmt: skip
keys = [
(module, algorithm(row), under_five),
(module, algorithm(row), None),
(module, None, under_five),
(module, None, None),
]
cuts = next((tea.ADOS2_CSS[k] for k in keys if k in tea.ADOS2_CSS), None)
if cuts is None:
return None, None
css = 1 + sum(c <= found for c in cuts)
label = next(n for n, below in tea.ADOS2_CLASSIFICATION if below is None or css < below)
return css, label
return (None, None)
css = 1 + sum((c <= found for c in cuts))
label = next((n for n, below in tea.ADOS2_CLASSIFICATION if below is None or css < below))
return (css, label)
-16
View File
@@ -1,14 +1,5 @@
"""What the EEG–ADOS-2 association relates (pure configuration, models.tea.association):
each EEG biomarker's deviation from its age curve (z) in a zone, against the ADOS-2 items
that zone is linked to, or against the calibrated severity (CSS).
An item counts as altered at ALTERED or more (its algorithm score: 0 to 2, a 3 counting as
2, and 7, 8 or 9, "not applicable", as 0); the CSS at CSS_HIGH or more. Items are numbered
as the old platform numbered them, which names each outcome `ados2_item_NN`."""
from core import tea
# The 22 items, in their number's order, and the modules that administer each.
ITEMS = {
1: ("vocalization_directed", ("toddler", "module_1")),
2: ("pointing", ("toddler", "module_1", "module_2")),
@@ -34,8 +25,6 @@ ITEMS = {
22: ("repetitive_interests", ("toddler", "module_1", "module_2")),
}
assert [n for n, _ in ITEMS.values()] == tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
# The items each zone's spikes are related to.
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
@@ -48,7 +37,6 @@ ZONE_ITEMS = {
}
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
# Each biomarker's EEG metric (models.tea.eeg.biomarkers.CODES).
BIOMARKERS = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
@@ -56,12 +44,10 @@ BIOMARKERS = {
"gradient": "anteroposterior_gradient",
}
ZONED = ("spikes", "spindles")
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
NOT_APPLICABLE = (7, 8, 9)
# Below this many children with item scores the association is fitted on the CSS only.
MIN_ITEM_CHILDREN = 10
ADJUST = ("age_months", "module")
@@ -71,8 +57,6 @@ def item_code(n: int) -> str:
def pairs(level: str) -> list[dict]:
"""Every (biomarker, zone, predictor, outcome) the association fits at `level`: `item`
(each zone against its items) or `domain` (against the CSS)."""
def outcomes(numbers) -> list[tuple[str, object]]:
return [("item", n) for n in numbers] if level == "item" else [("domain", CSS)]
+27 -29
View File
@@ -1,16 +1,4 @@
"""TEA's follow-up list (pure): the children of the screening cohort active in the window, where
each stands on the route by the cut-off day, and their EEG.
- status (the route): mchat_only, psychology (ADOS-2), neuropediatrics (a neurology note), eeg
(a good EEG after it);
- case: confirmed (the neurologist confirmed TEA), not_confirmed, or in_process;
- EEG: the study EEG is her first valid one known by the cut-off, else her latest; its status
is no_valid_eeg without a valid one, abnormal when any of its metrics falls outside the age
curve's band (its alterations, each `<metric>:<above|below>`), else normal.
A child is on the list when any step of hers happened within the window."""
from datetime import date
from core import tea
from core.measures import as_day
from core.tea import ados2
@@ -21,10 +9,15 @@ DEFAULT_HORIZON = None
STATUS_SYSTEM = "tea-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"),
("eeg_date", "eeg")) # fmt: skip
DATES = ("mchat_date", "psychology_date", "neuro_date", "confirmed_date", "not_confirmed_date",
"eeg_date") # fmt: skip
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"), ("eeg_date", "eeg"))
DATES = (
"mchat_date",
"psychology_date",
"neuro_date",
"confirmed_date",
"not_confirmed_date",
"eeg_date",
)
def _by(day, cutoff: date) -> date | None:
@@ -49,8 +42,6 @@ def case(row: dict, cutoff: date) -> str:
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each child's screening row joined to her EEGs and their metrics outside the band
(one row per child, EEG and such metric), who is on the list, most recent step first."""
children: dict[str, dict] = {}
eegs: dict[str, dict[str, dict]] = {}
for row in rows:
@@ -74,9 +65,9 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
continue
mine = sorted(eegs.get(person, {}).values(), key=lambda e: e["date"])
valid = [e for e in mine if e["valid"]]
study = valid[0] if valid else (mine[-1] if mine else None)
study = valid[0] if valid else mine[-1] if mine else None
if not valid:
eeg_status, altered = "no_valid_eeg", []
eeg_status, altered = ("no_valid_eeg", [])
else:
altered = sorted(study["altered"])
eeg_status = "abnormal" if altered else "normal"
@@ -84,19 +75,26 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
if row.get("module") and as_day(row.get("evaluation_date")):
evaluated = {**row, "evaluation_date": as_day(row["evaluation_date"])}
css, _ = ados2.score(evaluated, as_day(row.get("birth_date")))
out.append({
"person_id": person, "birth_date": row.get("birth_date"),
"status": stage(row, cutoff), "priority": None, "recent": recent,
"age_group": row.get("age_group"), "case": case(row, cutoff),
"eeg_status": eeg_status, "alterations": altered,
"last_eeg": mine[-1]["date"] if mine else None,
"mchat_score": row.get("score"), "ados2_css": css,
}) # fmt: skip
out.append(
{
"person_id": person,
"birth_date": row.get("birth_date"),
"status": stage(row, cutoff),
"priority": None,
"recent": recent,
"age_group": row.get("age_group"),
"case": case(row, cutoff),
"eeg_status": eeg_status,
"alterations": altered,
"last_eeg": mine[-1]["date"] if mine else None,
"mchat_score": row.get("score"),
"ados2_css": css,
}
)
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A child's status exists only on the list."""
return None
+93 -43
View File
@@ -1,10 +1,3 @@
"""TEA's measures (`core.measures` evaluates them), over gold's screening chain: one row per
child of the cohort (`gold.tea_screening`) with the day she reached each step, and her EEGs
(`gold.tea_eegs`).
A child is on the books from her first M-CHAT until the period after her chain ended with a
good EEG; in a period she is in the latest step, and diagnosis state, reached by its end."""
from core.measures import (
AtEnd,
Composition,
@@ -16,44 +9,101 @@ from core.measures import (
reached,
)
DIAGNOSIS = AtEnd("mchat_date", "eeg_date", (
("in_process", "mchat_date"), ("not_confirmed", "not_confirmed_date"),
("confirmed", "confirmed_date"),
)) # fmt: skip
STEPS = AtEnd("mchat_date", "eeg_date", (
("mchat_only", "mchat_date"), ("psychology", "psychology_date"),
("neuropediatrics", "neuro_date"), ("eeg", "eeg_date"),
)) # fmt: skip
DIAGNOSIS = AtEnd(
"mchat_date",
"eeg_date",
(
("in_process", "mchat_date"),
("not_confirmed", "not_confirmed_date"),
("confirmed", "confirmed_date"),
),
)
STEPS = AtEnd(
"mchat_date",
"eeg_date",
(
("mchat_only", "mchat_date"),
("psychology", "psychology_date"),
("neuropediatrics", "neuro_date"),
("eeg", "eeg_date"),
),
)
AGE = ("age_group", lambda row, p: row["age_group"])
CONFIRMED = lambda row, state, p: state == "confirmed" # noqa: E731
MEASURES = {m.id: m for m in [
Measure("M21_DIAGNOSTICADOS_CON_EEG", "Pacientes con diagnóstico de TEA con EEG",
CONFIRMED = lambda row, state, p: state == "confirmed"
MEASURES = {
m.id: m
for m in [
Measure(
"M21_DIAGNOSTICADOS_CON_EEG",
"Pacientes con diagnóstico de TEA con EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)),
"increase"),
Measure("M22_DIAGNOSTICADOS_SIN_EEG", "Pacientes con diagnóstico de TEA sin EEG",
StatusProportion(
DIAGNOSIS, CONFIRMED, lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)
),
"increase",
),
Measure(
"M22_DIAGNOSTICADOS_SIN_EEG",
"Pacientes con diagnóstico de TEA sin EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: not reached(row, "eeg_date", p), strata=(AGE,)),
"decrease"),
Measure("M23_PACIENTES_EVALUADOS", "Pacientes evaluados por resultado diagnóstico",
StatusProportion(
DIAGNOSIS,
CONFIRMED,
lambda row, s, p: not reached(row, "eeg_date", p),
strata=(AGE,),
),
"decrease",
),
Measure(
"M23_PACIENTES_EVALUADOS",
"Pacientes evaluados por resultado diagnóstico",
"screening",
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process"))),
Measure("M24_CONFIRMACION_DIAGNOSTICO", "Confirmación diagnóstica", "screening",
StatusProportion(DIAGNOSIS, lambda row, s, p: s in ("confirmed", "in_process"),
CONFIRMED, strata=(AGE,)),
"increase"),
Measure("M25_DIAS_MCHAT_DIAGNOSTICO", "Días de M-CHAT a diagnóstico positivo", "screening",
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"), "decrease"),
Measure("M26_DIAS_MCHAT_ADOS2", "Días de M-CHAT a ADOS-2", "screening",
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"), "decrease"),
Measure("M27_DIAS_ADOS2_DIAGNOSTICO", "Días de ADOS-2 a valoración neuropediátrica",
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process")),
),
Measure(
"M24_CONFIRMACION_DIAGNOSTICO",
"Confirmación diagnóstica",
"screening",
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"), "decrease"),
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
Measure("M29_CALIDAD_EEG", "Calidad del EEG", "eegs",
Composition(lambda r: (as_day(r["study_date"]),), lambda r: r["quality"],
unit="eeg_id", date="study_date")),
]} # fmt: skip
StatusProportion(
DIAGNOSIS,
lambda row, s, p: s in ("confirmed", "in_process"),
CONFIRMED,
strata=(AGE,),
),
"increase",
),
Measure(
"M25_DIAS_MCHAT_DIAGNOSTICO",
"Días de M-CHAT a diagnóstico positivo",
"screening",
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"),
"decrease",
),
Measure(
"M26_DIAS_MCHAT_ADOS2",
"Días de M-CHAT a ADOS-2",
"screening",
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"),
"decrease",
),
Measure(
"M27_DIAS_ADOS2_DIAGNOSTICO",
"Días de ADOS-2 a valoración neuropediátrica",
"screening",
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"),
"decrease",
),
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
Measure(
"M29_CALIDAD_EEG",
"Calidad del EEG",
"eegs",
Composition(
lambda r: (as_day(r["study_date"]),),
lambda r: r["quality"],
unit="eeg_id",
date="study_date",
),
),
]
}
-10
View File
@@ -1,4 +1,3 @@
# One Python image for the API, the Dagster webserver and the Dagster daemon.
FROM python:3.12-slim AS app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
@@ -8,14 +7,10 @@ COPY --from=ghcr.io/astral-sh/uv:0.12.21 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PROJECT_ENVIRONMENT=/venv PATH=/venv/bin:$PATH
WORKDIR /app
COPY . .
# Optional extras a machine opts into (`--extra dask` where a Dask cluster runs the batches).
ARG EXTRAS=""
RUN uv sync --frozen --no-dev $EXTRAS
ENV ISSSTELEON_DATA=/data DAGSTER_HOME=/data/dagster DLT_DATA_DIR=/data/dlt
# The same image plus the dev tools: what CI and `docker compose run --rm test` run.
# The HL7 validator is pinned by checksum; its FHIR 4.3.0 packages are fetched here, once,
# so tests validate offline.
FROM app AS test
RUN apt-get update \
&& apt-get install -y --no-install-recommends default-jre-headless \
@@ -27,18 +22,13 @@ RUN echo '{"resourceType":"Basic","code":{"text":"warm-up"}}' > /tmp/warm.json \
&& java -jar /opt/fhir/validator_cli.jar /tmp/warm.json -version 4.3.0 -tx n/a > /dev/null \
&& rm /tmp/warm.json
ENV FHIR_VALIDATOR_JAR=/opt/fhir/validator_cli.jar
# Synthea, pinned: seeded synthetic patients sent through the FHIR door in tests.
ADD --checksum=sha256:ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 \
https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar \
/opt/synthea/synthea.jar
ENV SYNTHEA_JAR=/opt/synthea/synthea.jar
RUN uv sync --frozen
# The pages (-m webapp) run in CI's web job, which has Node and a browser.
CMD ["pytest", "-q", "-rs", "-m", "not webapp"]
# A Dask worker for testing on a cluster (not part of the product): the app's Python and code
# with the `dask` extra, run as the cluster runs its workers (user dask, one thread per math
# library). The cluster gives the command (`dask worker <scheduler>`).
FROM app AS dask-worker
RUN uv sync --frozen --no-dev --extra dask \
&& useradd --uid 10001 --create-home dask
-2
View File
@@ -1,4 +1,3 @@
{# Whole days from `a` to `b` (dates), on every engine the platform runs on. #}
{% macro days_between(a, b) -%}
{{ return(adapter.dispatch('days_between', 'isssteleon')(a, b)) }}
{%- endmacro %}
@@ -11,7 +10,6 @@
cast(julianday({{ b }}) - julianday({{ a }}) as integer)
{%- endmacro %}
{# The run's as-of date: `var('as_of')` when given, else the day dbt runs. #}
{% macro as_of() -%}
'{{ var("as_of", run_started_at.strftime("%Y-%m-%d")) }}'
{%- endmacro %}
-3
View File
@@ -1,6 +1,3 @@
{# The first event of `kind` after each unit's `start` (on that day too when not `strict`),
fewer than `days` later: one row per unit that has one. Units are the CTE `units`, keyed
by `key`, with the person's `person_id`. #}
{% macro first_after(name, start, kind, days, strict=true, units='sample', key='sample_id') %}
{{ name }} as (
select s.{{ key }}, min(e.date) as date
@@ -1,9 +1,3 @@
{#
A survival cohort over a domain's timeline (`<domain>_events`): every patient indexed at her
first biopsy reported with one of `grades`, within the recruitment window (start inclusive,
end exclusive), up to the as-of date. Out (`excluded_by`): no birth date (no age at the
index), a death on or before the index.
#}
{% macro first_biopsy_cohort(events, grades, recruitment) %}
with timeline as (
select * from {{ ref(events) }} where date <= {{ as_of() }}
@@ -1,4 +1,3 @@
{# Use the declared schema as is (bronze, silver, gold), on SQLite and PostgreSQL alike. #}
{% macro generate_schema_name(custom_schema_name, node) -%}
{{ custom_schema_name if custom_schema_name else target.schema }}
{%- endmacro %}
-1
View File
@@ -1,4 +1,3 @@
{# The later of two dates; empty when either is (a step counts once the previous one was reached). #}
{% macro later(a, b) -%}
case when {{ a }} is null or {{ b }} is null then null
when {{ b }} > {{ a }} then {{ b }} else {{ a }} end
-7
View File
@@ -1,10 +1,3 @@
{#
One study, wide: one row per study instance (person and the study's key), one column per
field of the catalog (core.catalog), from the long `silver.observation`. `known_at` is when
anything of the instance was first known, `<event>_known_at` when its event was (a report can
arrive loads after its sample). A subquery, for
`from {{ pivot('cervical_cytology') }} as c`, or a whole model.
#}
{% macro pivot(study) -%}
{%- set s = var('catalog')[study] -%}
(
-2
View File
@@ -1,10 +1,8 @@
{#- Whether a bronze table exists yet (nothing staged there before the first run). -#}
{% macro staged_exists(name) -%}
{{ return(execute and adapter.get_relation(this.database, 'bronze', name) is not none) }}
{%- endmacro %}
{# Whether a bronze table has a column (one a later version of its writer added). #}
{% macro staged_has_column(name, column) -%}
{%- if not execute -%}{{ return(false) }}{%- endif -%}
{%- set relation = adapter.get_relation(this.database, 'bronze', name) -%}
-2
View File
@@ -1,9 +1,7 @@
{# A list of values as a SQL list: ('a', 'b'). #}
{% macro sql_list(values) -%}
({% for v in values %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
{%- endmacro %}
{# Upper case without Spanish accents, so free text compares with written patterns. #}
{% macro plain_upper(column) -%}
{%- set pairs = [('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u'),
('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U')] -%}
@@ -1,14 +1,3 @@
{#
After colposcopy (KPNC's post-colposcopy tables): the patient's first colposcopy is an
episode whose result is known at the last report of the biopsies ordered that day (at the
colposcopy itself when none were); indexed at the POST_COLPOSCOPY_VISIT-th cytology sample
after that result and before any later colposcopy, in the recruitment window. Out, in
order: a biopsy ordered that day without a report (unreported_biopsy); an outcome biopsy
up to the index (outcome_by_index); a cervical cancer history (cancer_history); a
hysterectomy (hysterectomy); a treatment (prior_treatment), each up to the index; no
cytology or HPV result in the REFERRAL_LOOKBACK_DAYS before the colposcopy (no_referral);
an index sample without both a cytology and an HPV result (no_cotest).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,10 +1,3 @@
{#
After treatment: indexed at the first cytology sample more than
POST_TREATMENT_INDEX_AFTER_DAYS after the patient's first treatment, in the recruitment
window. Out, in order: no biopsy result in the POST_TREATMENT_LOOKBACK_DAYS up to the
treatment (no_pretreatment_biopsy); an outcome biopsy between treatment and index
(outcome_before_index); an index sample with no cytology or HPV result (no_index_result).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,8 +1,3 @@
{#
Screening surveillance: indexed at the patient's first cytology sample, when it falls in
the recruitment window. Out, in order: an outcome biopsy (CIN2+) before the index
(prior_outcome); an index sample with no cytology or HPV result (no_index_result).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
@@ -1,3 +1,2 @@
{# Survival: indexed at the first biopsy reported as carcinoma or carcinoma in situ (core.cacu CASE). #}
{% set p = var('cacu') %}
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment) }}
@@ -1,5 +1,3 @@
{# Every patient with a clinical event up to the as-of date, indexed at her first one. No
window and no rules: models that set their own index start from here. #}
with ranked as (
select
person_id, date,
@@ -1,18 +1,3 @@
{#
Every CaCu patient's timeline: one row per event, in one shape, from silver. Results are
dated when they were reported; a cytology's results and a biopsy's order and report share
their source (`source_table`, `source_id`), so a model can tell which sample a result
belongs to.
Procedures silver has no record of are inferred from notes and biopsies (core.cacu):
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
- colposcopy: once a patient has been assessed (a diagnosis note within
SAMPLE_TO_DIAGNOSIS_DAYS after a cytology sample), a later colposcopy-clinic note that
says so (reason, ICD-10 or diagnosis text), and the biopsies ordered on such a day (at
their order and at their report);
- treatment: a note with a treatment ICD-10 after the first colposcopy;
- history: a note with a cervical cancer ICD-10.
#}
{% set p = var('cacu') %}
with cytology as (
@@ -1,8 +1,3 @@
{#
One row per CaCu patient: the first day of each follow-up step, from her timeline. Her
status at any day follows from them (core.measures.follow_up_status): a case (a biopsy
reported CASE grade), after treatment, after colposcopy, or before colposcopy.
#}
{% set p = var('cacu') %}
select
p.person_id,
@@ -1,12 +1,3 @@
{#
One row per colposcopy day and per biopsy of a patient, with the cytology that led to it and
the histology that answers it.
- The cytology: the one the biopsy's record names (`link` recorded), else her latest valid
one reported before the procedure, at most CYTOLOGY_BEFORE_DAYS before (inferred).
- A colposcopy's histology: the most severe reported of the biopsies requested from that day
and within the colposcopy_to_biopsy horizon.
cacu_events also dates a colposcopy at the report of a biopsy taken at it: not a day of one.
#}
{% set p = var('cacu') %}
with biopsy as (
select
@@ -1,6 +1,3 @@
{# The latest risk batch of each CaCu model: from its champion version, one row per
patient and horizon (years from her index date; 0 is the index visit itself), with the
report's clinical scenarios she is in (survival's). #}
select model, version, person_id, index_date, horizon_years, probability, ci_low, ci_high,
{% if staged_has_column('model_scores', 'scenarios') -%} scenarios
{%- else -%} cast(null as {{ dbt.type_string() }}) as scenarios {%- endif %},
@@ -1,5 +1,3 @@
{# The biopsies each cytology sample led to, with the grade's severity (core.cacu
BIOPSY_SEVERITY, from 1; -1 a report without a grade, 0 a grade outside it). #}
{% set p = var('cacu') %}
select
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
@@ -1,12 +1,3 @@
{#
One row per cytology sample: the unit CaCu's cytology and screening-route measures count
over, with the intervals they measure. A sample's result date is its report's when the
report has a result (an unsatisfactory sample's report is not a result). Each interval ends at the first event of a kind
after its start (`first_after`), within that measure's horizon (core.cacu): diagnosis,
treatment and colposcopy from the timeline; the biopsy is the first report of a biopsy
the sample led to. `history`: a cervical cancer note before the sample. The patient's
first treatment and colposcopy give her follow-up status at any date.
#}
{% set p = var('cacu') %}
{% set h = p.horizons %}
with sample as (
@@ -1,8 +1,3 @@
{#
One row per breast biopsy, with the mammogram that led to it (the patient's, taken on
`mammogram_exam_date`) and that mammogram's BI-RADS. `histology_rank` orders grades from
least to most severe (core.cama): -1 for a report without one.
#}
{% set p = var('cama') %}
select
b.person_id,
@@ -1,4 +1,2 @@
{# Recurrence: the patients of the survival cohort (indexed at the first invasive biopsy
report, core.cama SURVIVAL_GRADES), followed for a recurrence (models.cama.recurrence.site). #}
{% set p = var('cama') %}
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
@@ -1,3 +1,2 @@
{# Survival: indexed at the first invasive biopsy report (core.cama SURVIVAL_GRADES). #}
{% set p = var('cama') %}
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
@@ -1,18 +1,3 @@
{#
Every CaMa patient's timeline (whoever has a mammogram or a breast biopsy): one row per
event, in the shape of the other domains' timelines. Results are dated when they were
reported; a mammogram's report and a biopsy's order and report share their source
(`source_table`, `source_id`), and a biopsy names the mammogram that led to it
(`value_code` of `biopsy_order`).
A biopsy report's results (histologic type, grade, receptors, Ki-67, size, positive nodes,
stage) are one event each, dated with the report; each treatment is an event at its start,
each recurrence at its diagnosis (`value_code`: local, regional or distant).
Procedures silver has no record of are inferred from notes (core.cama):
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
- history: a note with a breast cancer ICD-10, whoever wrote it.
#}
{% set p = var('cama') %}
with mammogram as (
@@ -1,17 +1,7 @@
{#
One row per mammogram and each reported biopsy it led to (one row with no biopsy when it led
to none): what the measures that follow a mammogram to its biopsy count over. The biopsy is
the one whose request names the mammogram (`cama_biopsies`); none is matched by dates.
`days_report_biopsy`: days from the mammogram's report to the biopsy's report; empty when
either date is missing, and when the biopsy was reported before the mammogram (inconsistent).
#}
select
m.*,
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
b.report_known_at as biopsy_known_at,
case
when b.report_date >= m.report_date then {{ days_between('m.report_date', 'b.report_date') }}
end as days_report_biopsy
b.report_known_at as biopsy_known_at
from {{ ref('cama_mammograms') }} as m
left join {{ ref('cama_biopsies') }} as b
on b.mammogram_id = m.mammogram_id and b.report_date is not null
@@ -1,10 +1,3 @@
{#
One row per mammogram: the unit CaMa's mammography measures count over, with the intervals
they measure. A diagnosis resolves a mammogram when it is the patient's first diagnosis note
after it (on the report's day too, counted from the report), within the horizon (core.cama).
`history`: a breast cancer note before the mammogram. Each fact keeps when it became known:
the sample, its report, and the diagnosis note.
#}
{% set p = var('cama') %}
with sample as (
select
@@ -1,5 +1,3 @@
{# The latest risk batch of each CaMa model: from its champion version, one row per patient
and horizon (years from her index date), with the report's clinical scenarios she is in. #}
select model, version, person_id, index_date, horizon_years, probability, ci_low, ci_high,
{% if staged_has_column('model_scores', 'scenarios') -%} scenarios
{%- else -%} cast(null as {{ dbt.type_string() }}) as scenarios {%- endif %},
@@ -1,4 +1,3 @@
{# Every EEG with its analysis verdict (the EEG job's `bronze.eeg_analysis`, by signal hash). #}
select e.person_id, e.study_date, e.edf,
{%- if staged_exists('eeg_analysis') %}
a.valid
@@ -1,9 +1,4 @@
{%- do ref('tea_eegs') %}
{#
One row per EEG metric (the EEG job's `bronze.eeg_metrics`), with the age curve's score of
its value (`bronze.eeg_scores`, when a curve in production scored it): what the EEG pages
and FHIR read.
#}
{%- if not staged_exists('eeg_metrics') %}
select
cast(null as {{ dbt.type_string() }}) as person_id, cast(null as {{ dbt.type_string() }}) as eeg_id,
@@ -1,8 +1,3 @@
{#
One row per EEG of a child of the screening cohort, with its analysis (the EEG job's
`bronze.eeg_analysis`, by the signal's hash): `quality` good (valid), bad (not valid) or
not_analyzed (no analysis yet, or no signal).
#}
select
e.person_id,
{{ dbt.concat(['e.person_id', "'|'", 'cast(e.study_date as ' ~ dbt.type_string() ~ ')']) }} as eeg_id,
@@ -1,4 +1,3 @@
{# Every TEA child's timeline, in the shape of the other domains' (the default cut-off reads it). #}
select person_id, screening_date as date, known_at, 'mchat' as type,
cast(null as {{ dbt.type_string() }}) as value_code,
cast(score as {{ dbt.type_float() }}) as value_num,
@@ -1,10 +1,3 @@
{#
One row per child of the screening cohort (her first M-CHAT at 16 to 36 months, or with no
birth date), with the day she reached each step. A step counts once the previous one was
reached: its day is the later of the two (core.tea):
psychology (first ADOS-2) <- M-CHAT; neurology (first note) and its confirming or
non-confirming verdict <- psychology; EEG (first good one) <- neurology.
#}
{% set p = var('tea') %}
with mchat as (
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- ados2, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('ados2') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_biopsy, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_biopsy') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_recurrence, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_recurrence') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- breast_treatment, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('breast_treatment') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_biopsy') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_cytology') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('clinical_note') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- death, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('death') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- eeg, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('eeg') }} as p
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- mammography, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('mammography') }} as p
-1
View File
@@ -1,3 +1,2 @@
{{ config(materialized='table') }}
{#- mchat, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('mchat') }} as p
@@ -1,12 +1,3 @@
{#
Silver: every clinical value, long. One row per field of one study instance (a person and
the study's key, e.g. her cytology sampled on a day), from what targets staged:
- rows a reviewer rejected (review_log) stay out; rows a rule held never got here;
- rows of one instance are one record: values that complement each other are merged; a
field with two different values is a conflict, and the whole instance stays out until a
reviewer rejects the wrong row;
- an instance is known from when its first row was (`known_at`).
#}
{%- if not staged_exists('staged__observation') %}
select
cast(null as {{ dbt.type_string() }}) as person_id,
-5
View File
@@ -1,8 +1,3 @@
{#
One row per person the link nodes found, with what her records agree on. A person whose
records disagree on birth date or sex is held whole by the link node, so what is left
agrees and min() only picks the one value.
#}
select
person_id,
min(birth_date) as birth_date,
@@ -1,8 +1,3 @@
{#
Every identifier a person carries: CURP and NSS under their own systems, and each record
number under the system of the source it came from (a site has as many as it has
sources). Records held by the link node (a torn person) give none until reviewed.
#}
{%- set ids = var('identifiers') %}
with identity as (
select * from {{ source('bronze', 'staged__identity') }}
@@ -1,7 +1,3 @@
{#
Persons a review merged into another: the replaced id and the one that replaced it (the
latest decision). A replaced id keeps resolving, to its survivor.
#}
{%- if not staged_exists('person_link') %}
select cast(null as {{ dbt.type_string() }}) as person_id,
cast(null as {{ dbt.type_string() }}) as replaced_by
@@ -1,4 +1,3 @@
{#- Every name a person's records give (as the link node compared them). -#}
select distinct person_id, full_name as text
from {{ source('bronze', 'staged__identity') }}
where _held is null and person_id is not null and full_name is not null
@@ -1,5 +1,3 @@
{#- Every value silver holds is a field of its study, and a code is one its field allows
(core.catalog). -#}
select o.study, o.field, o.value_text
from {{ ref('observation') }} as o
where not (
@@ -1,4 +1,3 @@
{#- Silver holds one value per field of a study instance. -#}
select person_id, study, instance, field
from {{ ref('observation') }}
group by person_id, study, instance, field
+1
View File
@@ -0,0 +1 @@
+30 -43
View File
@@ -1,23 +1,3 @@
"""Backups of a deployment: everything the platform keeps lives in its data folder
(`ISSSTELEON_DATA`), so a backup is that folder at one moment, checked and restorable.
- SQLite databases (the platform's schemas, Dagster's runs, MLflow's registry) are copied with
SQLite's online backup, consistent while the stack runs. Run as the Dagster job `backup`,
it holds the `writes` slot, so no ingestion, training or scoring writes meanwhile.
- Every other file (MLflow's artifacts, uploads, dlt's state, the sign-in secret) is copied.
- A PostgreSQL platform database (PLATFORM_DATABASE_URL) is dumped with pg_dump.
- Left out: what is downloaded again or rebuilt (BACKUP_EXCLUDE, default the local LLM's
weights), SQLite's -wal/-shm files and temporary spools.
Each backup is a folder `<BACKUP_DIR>/<UTC time>` with `manifest.json`: the version, a sha256
per file and the row count of every table. Only finished backups get their final name; the
newest BACKUP_KEEP are kept.
python -m persistance.backup create [--to DIR]
python -m persistance.backup verify DIR
python -m persistance.backup restore DIR [--force] (with the stack stopped)
"""
import argparse
import hashlib
import json
@@ -29,7 +9,6 @@ import sys
from datetime import UTC, datetime
from fnmatch import fnmatch
from pathlib import Path
from persistance.config import DATA_DIR, platform_url
MANIFEST = "manifest.json"
@@ -59,7 +38,7 @@ def excluded() -> list[str]:
def _skipped(rel: Path) -> bool:
return any(fnmatch(part, p) for part in rel.parts for p in (*SKIPPED, *excluded()))
return any((fnmatch(part, p) for part in rel.parts for p in (*SKIPPED, *excluded())))
def _is_sqlite(path: Path) -> bool:
@@ -89,8 +68,6 @@ def _copy_sqlite(source: Path, target: Path) -> None:
dst = sqlite3.connect(target)
try:
src.backup(dst)
# A copy at rest: no WAL (the platform turns it back on when it connects), so reading
# the backup leaves no -wal/-shm files beside it.
dst.execute("PRAGMA journal_mode=DELETE")
finally:
dst.close()
@@ -98,7 +75,6 @@ def _copy_sqlite(source: Path, target: Path) -> None:
def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
"""A new backup of `data` under `to` (default BACKUP_DIR); returns its folder."""
root = (to or backup_dir()).resolve()
if root == data.resolve() or data.resolve() in root.parents:
raise ValueError(f"the backups ({root}) must be outside the data folder ({data})")
@@ -107,7 +83,7 @@ def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
partial.mkdir(parents=True)
files: dict[str, dict] = {}
try:
for source in sorted(p for p in data.rglob("*") if p.is_file()):
for source in sorted((p for p in data.rglob("*") if p.is_file())):
rel = source.relative_to(data)
if _skipped(rel):
continue
@@ -119,14 +95,22 @@ def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
else:
shutil.copy2(source, target)
entry = {"kind": "file"}
files[rel.as_posix()] = {**entry, "bytes": target.stat().st_size,
"sha256": _sha256(target)} # fmt: skip
files[rel.as_posix()] = {
**entry,
"bytes": target.stat().st_size,
"sha256": _sha256(target),
}
url = platform_url()
if not url.startswith("sqlite"):
subprocess.run(["pg_dump", "--format=custom", f"--file={partial / PG_DUMP}",
"--dbname", url], check=True) # fmt: skip
files[PG_DUMP] = {"kind": "pg_dump", "bytes": (partial / PG_DUMP).stat().st_size,
"sha256": _sha256(partial / PG_DUMP)} # fmt: skip
subprocess.run(
["pg_dump", "--format=custom", f"--file={partial / PG_DUMP}", "--dbname", url],
check=True,
)
files[PG_DUMP] = {
"kind": "pg_dump",
"bytes": (partial / PG_DUMP).stat().st_size,
"sha256": _sha256(partial / PG_DUMP),
}
manifest = {
"created": stamp,
"version": os.environ.get("ISSSTELEON_VERSION", "dev"),
@@ -144,13 +128,12 @@ def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
def _prune(root: Path) -> None:
done = sorted(p for p in root.iterdir() if p.is_dir() and (p / MANIFEST).exists())
done = sorted((p for p in root.iterdir() if p.is_dir() and (p / MANIFEST).exists()))
for old in done[: max(0, len(done) - keep())]:
shutil.rmtree(old)
def verify(folder: Path) -> list[str]:
"""What is wrong with a backup (missing or changed files); empty when it is whole."""
manifest = json.loads((folder / MANIFEST).read_text())
problems = []
for rel, entry in manifest["files"].items():
@@ -163,11 +146,9 @@ def verify(folder: Path) -> list[str]:
def _holds_platform(held: list[Path]) -> bool:
"""Whether a platform is already there: its SQLite files, or its PostgreSQL schemas."""
if platform_url().startswith("sqlite"):
return any(p.name.startswith("platform") for p in held)
return any((p.name.startswith("platform") for p in held))
from sqlalchemy import inspect
from persistance.destination import engine
with engine().connect() as con:
@@ -175,10 +156,6 @@ def _holds_platform(held: list[Path]) -> bool:
def restore(folder: Path, data: Path = DATA_DIR, force: bool = False) -> None:
"""The backup's files into `data` (with the stack stopped). Checked first: a damaged
backup restores nothing. A data folder that already has a platform needs `force`; what
it held is moved aside (`.before-restore-<time>/` inside it), so nothing newer than the
backup mixes with it, and nothing is lost."""
if problems := verify(folder):
raise ValueError("the backup is damaged: " + "; ".join(problems))
manifest = json.loads((folder / MANIFEST).read_text())
@@ -200,8 +177,18 @@ def restore(folder: Path, data: Path = DATA_DIR, force: bool = False) -> None:
shutil.copy2(folder / rel, temporary)
temporary.replace(target)
if PG_DUMP in manifest["files"]:
subprocess.run(["pg_restore", "--clean", "--if-exists", "--no-owner",
"--dbname", platform_url(), str(folder / PG_DUMP)], check=True) # fmt: skip
subprocess.run(
[
"pg_restore",
"--clean",
"--if-exists",
"--no-owner",
"--dbname",
platform_url(),
str(folder / PG_DUMP),
],
check=True,
)
def main() -> None:
-2
View File
@@ -1,5 +1,3 @@
"""Where the platform data lives. One env var per location; SQLite by default."""
import os
from pathlib import Path
+4 -13
View File
@@ -1,14 +1,8 @@
"""A site's configuration, append-only: every save is a new version; runs name the one they
used. Two kinds: pipelines (the drawn graphs) and concept maps (the site's codes in
platform terms, FHIR ConceptMaps)."""
from datetime import UTC, datetime
import dlt
from fhir.resources.R4B.conceptmap import ConceptMap
from pydantic import BaseModel
from sqlalchemy import inspect, text
from core.pipeline import Pipeline
from persistance.destination import engine, platform
@@ -26,7 +20,7 @@ def latest_version(item_id: str, kind: str = "pipelines") -> int:
def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
version = latest_version(item_id, kind) + 1
row = {
"pipeline_id": item_id, # the item's id, whichever kind
"pipeline_id": item_id,
"version": version,
"doc": doc.model_dump_json(exclude_none=True),
"saved_at": datetime.now(UTC),
@@ -38,13 +32,11 @@ def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
def listing(kind: str = "pipelines") -> list[dict]:
"""Every item's id with its latest version and when it was saved."""
with engine().connect() as con:
if not inspect(con).has_table(kind, schema="config"):
return []
sql = text(
"select pipeline_id, max(version) as version, max(saved_at) as saved_at "
f"from config.{kind} group by pipeline_id order by pipeline_id"
f"select pipeline_id, max(version) as version, max(saved_at) as saved_at from config.{kind} group by pipeline_id order by pipeline_id"
)
return [dict(r) for r in con.execute(sql).mappings()]
@@ -54,7 +46,7 @@ def get(item_id: str, version: int | None = None, kind: str = "pipelines"):
sql = text(f"select doc from config.{kind} where pipeline_id = :id and version = :v")
with engine().connect() as con:
doc = con.execute(sql, {"id": item_id, "v": version}).scalar_one()
return version, KINDS[kind].model_validate_json(doc)
return (version, KINDS[kind].model_validate_json(doc))
def pipelines() -> list[dict]:
@@ -62,11 +54,10 @@ def pipelines() -> list[dict]:
def concept_map(item_id: str) -> ConceptMap:
"""The latest version of a concept map."""
return get(item_id, kind="concept_maps")[1]
if __name__ == "__main__": # python -m persistance.config_log <kind> <id> <doc.json>
if __name__ == "__main__":
import sys
from pathlib import Path
+2 -12
View File
@@ -1,15 +1,6 @@
"""The platform database (SQLite now, PostgreSQL later): the dlt destination that writes it
and the engine that reads it.
On SQLite each schema is its own file (`platform__<schema>.db`, as dlt lays it out),
attached under its name, so the same SQL (`bronze.raw__...`) runs on both engines.
"""
from functools import cache
import dlt
from sqlalchemy import Engine, create_engine, event, make_url
from persistance.config import DATA_DIR, platform_url
SCHEMAS = ("bronze", "silver", "gold", "config")
@@ -31,14 +22,13 @@ def _sqlite(attach: bool) -> Engine:
def platform():
if platform_url().startswith("sqlite"):
return dlt.destinations.sqlalchemy(_sqlite(attach=False)) # dlt attaches its own
return dlt.destinations.sqlalchemy(_sqlite(attach=False))
return dlt.destinations.postgres(platform_url())
@cache
def engine() -> Engine:
"""For reading: every platform schema reachable by name."""
url = platform_url()
if url.startswith("sqlite"):
return _sqlite(attach=True)
return create_engine(make_url(url).set(drivername="postgresql+psycopg2")) # dlt's driver
return create_engine(make_url(url).set(drivername="postgresql+psycopg2"))
+166 -134
View File
@@ -1,19 +1,12 @@
"""The EEG analysis as the platform keeps it, by signal (the EDF's content hash, silver's
`eeg.edf`): its verdict and measures (`bronze.eeg_analysis`), its checks (`bronze.eeg_checks`)
and its metrics (`bronze.eeg_metrics`), written by the analysis job; the age curves' scores of
each metric (`bronze.eeg_scores`), by the scoring job. dbt places them in gold (tea)."""
import json
from datetime import UTC, date, datetime
import dlt
from sqlalchemy import inspect, text
from persistance import files
from persistance.destination import engine, platform
def _text() -> dict: # a new dict per column: dlt writes the column's name into it
def _text() -> dict:
return {"data_type": "text", "nullable": True}
@@ -87,24 +80,22 @@ SCORES = {
def _write(name: str, rows: list[dict], columns: dict, key: str = "key") -> None:
if rows:
resource = dlt.resource(rows, name=name, primary_key=key, columns=columns,
write_disposition="merge") # fmt: skip
resource = dlt.resource(
rows, name=name, primary_key=key, columns=columns, write_disposition="merge"
)
dlt.pipeline(name, destination=platform(), dataset_name="bronze").run(resource)
def pending() -> list[dict]:
"""The hospital's EEG signals not analysed yet, each with the child's birth date."""
with engine().connect() as con:
done = inspect(con).has_table("eeg_analysis", schema="bronze")
where = "and e.edf not in (select edf from bronze.eeg_analysis)" if done else ""
sql = text(f"""
select distinct e.edf, p.birth_date from silver.eeg as e
left join silver.person as p on p.person_id = e.person_id
where e.edf is not null {where}
""") # fmt: skip
sql = text(
f"\n select distinct e.edf, p.birth_date from silver.eeg as e\n left join silver.person as p on p.person_id = e.person_id\n where e.edf is not null {where}\n "
)
rows = [dict(r) for r in con.execute(sql).mappings()]
for r in rows: # SQLite gives dates as text
if r["birth_date"] is not None and not isinstance(r["birth_date"], date):
for r in rows:
if r["birth_date"] is not None and (not isinstance(r["birth_date"], date)):
r["birth_date"] = date.fromisoformat(str(r["birth_date"])[:10])
return rows
@@ -117,104 +108,122 @@ def signal(edf: str) -> bytes:
def save_analyses(analyses: dict[str, object]) -> None:
"""Analyses by signal hash (models.tea.eeg.analysis.Analysis)."""
now = datetime.now(UTC)
found, checks, metrics = [], [], []
found, checks, metrics = ([], [], [])
for edf, a in analyses.items():
found.append({
"edf": edf, "valid": a.valid, "level": a.level, "age_months": a.age_months,
"clean_fraction": a.clean_fraction, "bad_channels": a.bad_channels,
"channels": a.channels, "duration_min": a.duration_min,
"line_noise_db": a.line_noise_db, "sleep": a.sleep,
"features": json.dumps(a.features), "error": a.error, "analysed_at": now,
}) # fmt: skip
found.append(
{
"edf": edf,
"valid": a.valid,
"level": a.level,
"age_months": a.age_months,
"clean_fraction": a.clean_fraction,
"bad_channels": a.bad_channels,
"channels": a.channels,
"duration_min": a.duration_min,
"line_noise_db": a.line_noise_db,
"sleep": a.sleep,
"features": json.dumps(a.features),
"error": a.error,
"analysed_at": now,
}
)
checks += [{**c, "key": f"{edf}|{i}", "edf": edf} for i, c in enumerate(a.checks)]
metrics += [{"key": f"{edf}|{m.code}", "edf": edf, "code": m.code, "value": m.value,
"electrodes": json.dumps(m.electrodes), "zones": json.dumps(m.zones)}
for m in a.metrics] # fmt: skip
metrics += [
{
"key": f"{edf}|{m.code}",
"edf": edf,
"code": m.code,
"value": m.value,
"electrodes": json.dumps(m.electrodes),
"zones": json.dumps(m.zones),
}
for m in a.metrics
]
_write("eeg_analysis", found, ANALYSIS, key="edf")
_write("eeg_checks", checks, CHECKS)
_write("eeg_metrics", metrics, METRICS)
def analysed() -> list[dict]:
"""Every valid analysis with its metrics: what the age curves score."""
with engine().connect() as con:
if not inspect(con).has_table("eeg_metrics", schema="bronze"):
return []
sql = text("""
select a.edf, a.age_months, a.features, m.code, m.value, m.electrodes, m.zones
from bronze.eeg_analysis as a join bronze.eeg_metrics as m on m.edf = a.edf
where a.valid
""") # fmt: skip
sql = text(
"\n select a.edf, a.age_months, a.features, m.code, m.value, m.electrodes, m.zones\n from bronze.eeg_analysis as a join bronze.eeg_metrics as m on m.edf = a.edf\n where a.valid\n "
)
rows = [dict(r) for r in con.execute(sql).mappings()]
out: dict[str, dict] = {}
for r in rows:
first = {"edf": r["edf"], "age_months": r["age_months"],
"features": json.loads(r["features"]), "metrics": []} # fmt: skip
first = {
"edf": r["edf"],
"age_months": r["age_months"],
"features": json.loads(r["features"]),
"metrics": [],
}
one = out.setdefault(r["edf"], first)
one["metrics"].append({"code": r["code"], "value": r["value"],
"electrodes": json.loads(r["electrodes"]),
"zones": json.loads(r["zones"])}) # fmt: skip
one["metrics"].append(
{
"code": r["code"],
"value": r["value"],
"electrodes": json.loads(r["electrodes"]),
"zones": json.loads(r["zones"]),
}
)
return list(out.values())
def ruled_out(as_of: date) -> list[dict]:
"""The age curves' reference group on the site: each valid EEG, studied by `as_of`, of a
child whose neurology verdict ruled TEA out by then (gold `tea_screening`) and that no
confirming verdict followed by then. Each as the curves train on it: its key (the
signal's hash), age in months and features."""
with engine().connect() as con:
if not (inspect(con).has_table("eeg_analysis", schema="bronze")
and inspect(con).has_table("tea_screening", schema="gold")): # fmt: skip
if not (
inspect(con).has_table("eeg_analysis", schema="bronze")
and inspect(con).has_table("tea_screening", schema="gold")
):
return []
sql = text("""
select a.edf, a.age_months, a.features
from bronze.eeg_analysis as a
join silver.eeg as e on e.edf = a.edf
join gold.tea_screening as s on s.person_id = e.person_id
where a.valid and a.error is null
and cast(e.study_date as varchar(10)) <= :as_of
and cast(s.not_confirmed_date as varchar(10)) <= :as_of
and (s.confirmed_date is null or cast(s.confirmed_date as varchar(10)) > :as_of)
order by a.edf
""") # fmt: skip (ISO days compare as text on both engines)
sql = text(
"\n select a.edf, a.age_months, a.features\n from bronze.eeg_analysis as a\n join silver.eeg as e on e.edf = a.edf\n join gold.tea_screening as s on s.person_id = e.person_id\n where a.valid and a.error is null\n and cast(e.study_date as varchar(10)) <= :as_of\n and cast(s.not_confirmed_date as varchar(10)) <= :as_of\n and (s.confirmed_date is null or cast(s.confirmed_date as varchar(10)) > :as_of)\n order by a.edf\n "
)
rows = con.execute(sql, {"as_of": as_of.isoformat()}).mappings()
return [{"key": r["edf"], "age_months": r["age_months"], "valid": True, "error": None,
"features": json.loads(r["features"])} for r in rows] # fmt: skip
return [
{
"key": r["edf"],
"age_months": r["age_months"],
"valid": True,
"error": None,
"features": json.loads(r["features"]),
}
for r in rows
]
def association_inputs(metrics: dict[str, str]) -> list[dict]:
"""What the EEG–ADOS-2 association reads: each valid EEG with the child's age at it, her
birth date, her first ADOS-2 (module and items) and the z its champion age curves gave
(`metrics`: biomarker -> EEG metric code), each `z_<biomarker>` or, by zone,
`z_<biomarker>_<zone>`. Oldest first per child."""
with engine().connect() as con:
has = lambda t, s: inspect(con).has_table(t, schema=s) # noqa: E731
has = lambda t, s: inspect(con).has_table(t, schema=s)
if not (has("eeg_analysis", "bronze") and has("ados2", "silver")):
return []
eegs = [dict(r) for r in con.execute(text("""
select e.person_id, cast(e.study_date as varchar(10)) as study_date, a.edf,
a.age_months, cast(p.birth_date as varchar(10)) as birth_date
from bronze.eeg_analysis as a join silver.eeg as e on e.edf = a.edf
left join silver.person as p on p.person_id = e.person_id
where a.valid and a.age_months is not null
order by e.person_id, e.study_date, a.edf
""")).mappings()] # fmt: skip
eegs = [
dict(r)
for r in con.execute(
text(
"\n select e.person_id, cast(e.study_date as varchar(10)) as study_date, a.edf,\n a.age_months, cast(p.birth_date as varchar(10)) as birth_date\n from bronze.eeg_analysis as a join silver.eeg as e on e.edf = a.edf\n left join silver.person as p on p.person_id = e.person_id\n where a.valid and a.age_months is not null\n order by e.person_id, e.study_date, a.edf\n "
)
).mappings()
]
first: dict[str, dict] = {}
for r in con.execute(text("""
select * from silver.ados2
order by person_id, case when evaluation_date is null then 1 else 0 end,
evaluation_date
""")).mappings(): # fmt: skip
for r in con.execute(
text(
"\n select * from silver.ados2\n order by person_id, case when evaluation_date is null then 1 else 0 end,\n evaluation_date\n "
)
).mappings():
first.setdefault(r["person_id"], dict(r))
z: dict[str, dict[str, float]] = {}
if has("eeg_scores", "bronze"):
codes = {code: b for b, code in metrics.items()}
for r in con.execute(text("""
select edf, metric, part, site, z from bronze.eeg_scores
where part in ('value', 'zones') and z is not null
""")).mappings(): # fmt: skip
for r in con.execute(
text(
"\n select edf, metric, part, site, z from bronze.eeg_scores\n where part in ('value', 'zones') and z is not null\n "
)
).mappings():
b = codes.get(r["metric"])
if b is not None:
name = f"z_{b}" if r["part"] == "value" else f"z_{b}_{r['site']}"
@@ -228,7 +237,6 @@ def association_inputs(metrics: dict[str, str]) -> list[dict]:
def save_association(model: str, associations: list[dict], scores: list[dict]) -> None:
"""The champion association's pairs and each EEG's probabilities, replacing the last."""
with engine().begin() as con:
for table in ("ados2_association", "ados2_association_scores"):
if inspect(con).has_table(table, schema="bronze"):
@@ -238,24 +246,21 @@ def save_association(model: str, associations: list[dict], scores: list[dict]) -
def relation(edf: str) -> list[dict]:
"""One EEG's probabilities under the champion association, each with its pair."""
with engine().connect() as con:
if not inspect(con).has_table("ados2_association_scores", schema="bronze"):
return []
return [dict(r) for r in con.execute(text("""
select s.biomarker, a.metric, s.zone, s.outcome_code, a.kind, a.event, s.z,
s.probability, s.reference_probability, s.observed, a.odds_ratio,
a.ci_low, a.ci_high, a.q, a.n, s.model
from bronze.ados2_association_scores as s
join bronze.ados2_association as a
on a.model = s.model and a.biomarker = s.biomarker and a.zone = s.zone
and a.outcome_code = s.outcome_code
where s.edf = :e order by a.q, s.biomarker, s.zone
"""), {"e": edf}).mappings()] # fmt: skip
return [
dict(r)
for r in con.execute(
text(
"\n select s.biomarker, a.metric, s.zone, s.outcome_code, a.kind, a.event, s.z,\n s.probability, s.reference_probability, s.observed, a.odds_ratio,\n a.ci_low, a.ci_high, a.q, a.n, s.model\n from bronze.ados2_association_scores as s\n join bronze.ados2_association as a\n on a.model = s.model and a.biomarker = s.biomarker and a.zone = s.zone\n and a.outcome_code = s.outcome_code\n where s.edf = :e order by a.q, s.biomarker, s.zone\n "
),
{"e": edf},
).mappings()
]
def save_scores(scenario: str, rows: list[dict]) -> None:
"""One age curve's scores of every EEG, replacing what it scored before."""
with engine().begin() as con:
if inspect(con).has_table("eeg_scores", schema="bronze"):
con.execute(text("delete from bronze.eeg_scores where scenario = :s"), {"s": scenario})
@@ -267,62 +272,89 @@ def _id(person_id: str, study_date) -> str:
def studies() -> list[dict]:
"""Every EEG with its analysis verdict (none while not analysed), newest first."""
with engine().connect() as con:
analysed = inspect(con).has_table("eeg_analysis", schema="bronze")
verdict = "a.valid, a.level, a.error, a.edf as analysed" if analysed else (
"null as valid, null as level, null as error, null as analysed") # fmt: skip
verdict = (
"a.valid, a.level, a.error, a.edf as analysed"
if analysed
else "null as valid, null as level, null as error, null as analysed"
)
join = "left join bronze.eeg_analysis as a on a.edf = e.edf" if analysed else ""
sql = text(f"""
select e.person_id, e.study_date, e.lab_record_id, {verdict}
from silver.eeg as e {join}
order by e.study_date desc, e.person_id
""") # fmt: skip
sql = text(
f"\n select e.person_id, e.study_date, e.lab_record_id, {verdict}\n from silver.eeg as e {join}\n order by e.study_date desc, e.person_id\n "
)
rows = [dict(r) for r in con.execute(sql).mappings()]
return [{"id": _id(r["person_id"], r["study_date"]), "person_id": r["person_id"],
"study_date": str(r["study_date"])[:10], "lab_record_id": r["lab_record_id"],
"analysed": r["analysed"] is not None or r["error"] is not None,
"valid": r["valid"], "level": r["level"]} for r in rows] # fmt: skip
return [
{
"id": _id(r["person_id"], r["study_date"]),
"person_id": r["person_id"],
"study_date": str(r["study_date"])[:10],
"lab_record_id": r["lab_record_id"],
"analysed": r["analysed"] is not None or r["error"] is not None,
"valid": r["valid"],
"level": r["level"],
}
for r in rows
]
def study(eeg_id: str) -> dict | None:
"""One EEG's verdict, age and metrics, each with its age curve's score and band (its 5th,
50th and 95th percentiles at her age) when scored."""
person, day = eeg_id.split("|")
with engine().connect() as con:
if not inspect(con).has_table("eeg_analysis", schema="bronze"):
return None
head = con.execute(text("""
select a.edf, a.valid, a.level, a.age_months from silver.eeg as e
join bronze.eeg_analysis as a on a.edf = e.edf
where e.person_id = :p and cast(e.study_date as varchar(10)) = :d
"""), {"p": person, "d": day}).mappings().first() # fmt: skip
head = (
con.execute(
text(
"\n select a.edf, a.valid, a.level, a.age_months from silver.eeg as e\n join bronze.eeg_analysis as a on a.edf = e.edf\n where e.person_id = :p and cast(e.study_date as varchar(10)) = :d\n "
),
{"p": person, "d": day},
)
.mappings()
.first()
)
if head is None:
return None
scored = inspect(con).has_table("eeg_scores", schema="bronze")
score = ("s.z, s.outside, s.p5, s.median, s.p95, s.model" if scored else
"null as z, null as outside, null as p5, null as median, null as p95, "
"null as model") # fmt: skip
join = ("left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code "
"and s.part = 'value'") if scored else "" # fmt: skip
metrics = con.execute(text(f"""
select m.code, m.value, m.electrodes, m.zones, {score}
from bronze.eeg_metrics as m {join}
where m.edf = :e and m.value is not null order by m.code
"""), {"e": head["edf"]}).mappings() # fmt: skip
score = (
"s.z, s.outside, s.p5, s.median, s.p95, s.model"
if scored
else "null as z, null as outside, null as p5, null as median, null as p95, null as model"
)
join = (
"left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code and s.part = 'value'"
if scored
else ""
)
metrics = con.execute(
text(
f"\n select m.code, m.value, m.electrodes, m.zones, {score}\n from bronze.eeg_metrics as m {join}\n where m.edf = :e and m.value is not null order by m.code\n "
),
{"e": head["edf"]},
).mappings()
found = [dict(m) for m in metrics]
sites: dict[tuple[str, str, str], float | None] = {}
if scored:
for r in con.execute(text("""
select metric, part, site, z from bronze.eeg_scores
where edf = :e and part in ('zones', 'electrodes')
"""), {"e": head["edf"]}).mappings(): # fmt: skip
sites[(r["metric"], r["part"], r["site"])] = r["z"]
for r in con.execute(
text(
"\n select metric, part, site, z from bronze.eeg_scores\n where edf = :e and part in ('zones', 'electrodes')\n "
),
{"e": head["edf"]},
).mappings():
sites[r["metric"], r["part"], r["site"]] = r["z"]
for m in found:
for part in ("zones", "electrodes"):
values = json.loads(m[part] or "{}")
m[part] = [{"site": k, "value": v, "z": sites.get((m["code"], part, k))}
for k, v in values.items() if v is not None and v == v] # fmt: skip
return {"id": eeg_id, "valid": head["valid"], "level": head["level"],
"age_months": head["age_months"], "metrics": found,
"relation": relation(head["edf"])} # fmt: skip
m[part] = [
{"site": k, "value": v, "z": sites.get((m["code"], part, k))}
for k, v in values.items()
if v is not None and v == v
]
return {
"id": eeg_id,
"valid": head["valid"],
"level": head["level"],
"age_months": head["age_months"],
"metrics": found,
"relation": relation(head["edf"]),
}
+18 -132
View File
@@ -1,159 +1,50 @@
"""The rows the FHIR resources are built from (core.fhir): persons, their identifiers and
names, and every study instance of the catalog (`silver.<study>`), up to a cut-off day."""
from datetime import date
from sqlalchemy import bindparam, inspect, text
from core import catalog
from persistance.destination import engine
PERSONS = """
select p.person_id, p.birth_date, p.sex, d.death_date{extra}
from silver.person as p
left join (select person_id, min(death_date) as death_date from silver.death
group by person_id) as d on d.person_id = p.person_id{join}
"""
PERSONS = "\n select p.person_id, p.birth_date, p.sex, d.death_date{extra}\n from silver.person as p\n left join (select person_id, min(death_date) as death_date from silver.death\n group by person_id) as d on d.person_id = p.person_id{join}\n"
CACU_PERSONS = PERSONS.format(
extra=", f.first_case, f.first_treatment, f.first_colposcopy",
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
)
CAMA_PERSONS = PERSONS.format(extra="", join="")
COMMON = {
"names": "select person_id, text from silver.person_name where person_id in :persons",
"identifiers": """
select person_id, system, value from silver.person_identifier
where person_id in :persons order by system, value
""",
"identifiers": "\n select person_id, system, value from silver.person_identifier\n where person_id in :persons order by system, value\n ",
"replaced": "select person_id, replaced_by from silver.person_link where person_id = :id",
"replaces": """
select person_id, replaced_by from silver.person_link where replaced_by in :persons
""",
"condition": """
select person_id, note_date, specialty, icd10, reason, diagnosis_text
from silver.clinical_note
where person_id in :persons and note_date <= :cutoff
and (icd10 is not null or diagnosis_text is not null)
order by person_id, note_date
""",
# The timeline's inferred procedures of these kinds (the domain's `PROCEDURES`).
"procedure": """
select distinct person_id, date, type from gold.{domain}_events
where person_id in :persons and date <= :cutoff and type in :types
order by person_id, date, type
""",
"risk": """
select model, version, person_id, index_date, horizon_years, probability, ci_low,
ci_high, scenarios, scored_at
from gold.{domain}_risk
where person_id in :persons
order by person_id, model, index_date, horizon_years
""",
"replaces": "\n select person_id, replaced_by from silver.person_link where replaced_by in :persons\n ",
"condition": "\n select person_id, note_date, specialty, icd10, reason, diagnosis_text\n from silver.clinical_note\n where person_id in :persons and note_date <= :cutoff\n and (icd10 is not null or diagnosis_text is not null)\n order by person_id, note_date\n ",
"procedure": "\n select distinct person_id, date, type from gold.{domain}_events\n where person_id in :persons and date <= :cutoff and type in :types\n order by person_id, date, type\n ",
"risk": "\n select model, version, person_id, index_date, horizon_years, probability, ci_low,\n ci_high, scenarios, scored_at\n from gold.{domain}_risk\n where person_id in :persons\n order by person_id, model, index_date, horizon_years\n ",
}
TEA_PERSONS = PERSONS.format(extra="", join="")
READS = {
"cacu": {
"person": CACU_PERSONS + " where p.person_id = :id",
"persons": CACU_PERSONS + " order by p.person_id",
# The list: whoever had a cytology sampled within [start, cutoff], with the latest one.
"follow_up": f"""
select x.*, w.recent from ({CACU_PERSONS}) as x
join (select person_id, max(sample_date) as recent from silver.cervical_cytology
where sample_date >= :start and sample_date <= :cutoff
group by person_id) as w on w.person_id = x.person_id
order by w.recent desc, x.person_id
""",
# What followed each sample by the cut-off (gold): her colposcopy, her biopsy (its first
# request, and its report) and her diagnosis, with the days to it.
"route": """
select s.person_id, s.sample_date,
case when s.history = 0 and s.diagnosis_date <= :cutoff
then s.days_sample_diagnosis end as days,
case when s.diagnosis_date <= :cutoff then s.diagnosis_date end as diagnosis,
case when s.colposcopy_date <= :cutoff then s.colposcopy_date end as colposcopy,
case when s.biopsy_date <= :cutoff then s.biopsy_date end as biopsy,
b.requested, b.link
from gold.cacu_samples as s
left join (select person_id, sample_date, min(date) as requested, min(link) as link
from gold.cacu_procedures
where type = 'biopsy' and date <= :cutoff and person_id in :persons
group by person_id, sample_date) as b
on b.person_id = s.person_id and b.sample_date = s.sample_date
where s.person_id in :persons
""",
"follow_up": f"\n select x.*, w.recent from ({CACU_PERSONS}) as x\n join (select person_id, max(sample_date) as recent from silver.cervical_cytology\n where sample_date >= :start and sample_date <= :cutoff\n group by person_id) as w on w.person_id = x.person_id\n order by w.recent desc, x.person_id\n ",
"route": "\n select s.person_id, s.sample_date,\n case when s.history = 0 and s.diagnosis_date <= :cutoff\n then s.days_sample_diagnosis end as days,\n case when s.diagnosis_date <= :cutoff then s.diagnosis_date end as diagnosis,\n case when s.colposcopy_date <= :cutoff then s.colposcopy_date end as colposcopy,\n case when s.biopsy_date <= :cutoff then s.biopsy_date end as biopsy,\n b.requested, b.link\n from gold.cacu_samples as s\n left join (select person_id, sample_date, min(date) as requested, min(link) as link\n from gold.cacu_procedures\n where type = 'biopsy' and date <= :cutoff and person_id in :persons\n group by person_id, sample_date) as b\n on b.person_id = s.person_id and b.sample_date = s.sample_date\n where s.person_id in :persons\n ",
},
"tea": {
"person": TEA_PERSONS + " where p.person_id = :id",
"persons": TEA_PERSONS + " order by p.person_id",
# The list's candidates (core.tea.follow_up): each child of the screening cohort, with
# her latest M-CHAT score and ADOS-2 by the cut-off, her EEGs and, of each, the metrics
# outside the age curve's band (one row per child, EEG and such metric).
"follow_up": """
select s.*, mc.score, {ados2}, e.eeg_id, e.study_date as eeg_study_date, e.valid,
m.code as metric, m.outside
from gold.tea_screening as s
left join (select person_id, max(screening_date) as last_mchat from silver.mchat
where screening_date <= :cutoff group by person_id) as lm
on lm.person_id = s.person_id
left join silver.mchat as mc
on mc.person_id = lm.person_id and mc.screening_date = lm.last_mchat
left join (select person_id, max(evaluation_date) as last_ados from silver.ados2
where evaluation_date <= :cutoff group by person_id) as la
on la.person_id = s.person_id
left join silver.ados2 as a
on a.person_id = la.person_id and a.evaluation_date = la.last_ados
left join gold.tea_eegs as e on e.person_id = s.person_id
left join gold.tea_eeg_metrics as m
on m.eeg_id = e.eeg_id and m.outside is not null and m.outside <> 0
where s.mchat_date <= :cutoff
""".replace("{ados2}", ", ".join(f"a.{f}" for f in catalog.studies()["ados2"].fields)),
"follow_up": "\n select s.*, mc.score, {ados2}, e.eeg_id, e.study_date as eeg_study_date, e.valid,\n m.code as metric, m.outside\n from gold.tea_screening as s\n left join (select person_id, max(screening_date) as last_mchat from silver.mchat\n where screening_date <= :cutoff group by person_id) as lm\n on lm.person_id = s.person_id\n left join silver.mchat as mc\n on mc.person_id = lm.person_id and mc.screening_date = lm.last_mchat\n left join (select person_id, max(evaluation_date) as last_ados from silver.ados2\n where evaluation_date <= :cutoff group by person_id) as la\n on la.person_id = s.person_id\n left join silver.ados2 as a\n on a.person_id = la.person_id and a.evaluation_date = la.last_ados\n left join gold.tea_eegs as e on e.person_id = s.person_id\n left join gold.tea_eeg_metrics as m\n on m.eeg_id = e.eeg_id and m.outside is not null and m.outside <> 0\n where s.mchat_date <= :cutoff\n ".replace(
"{ados2}", ", ".join((f"a.{f}" for f in catalog.studies()["ados2"].fields))
),
},
"cama": {
"person": CAMA_PERSONS + " where p.person_id = :id",
"persons": CAMA_PERSONS + " order by p.person_id",
# Her treatments, by kind (the timeline's `treatment` events carry it as their code).
"procedure": """
select distinct person_id, date, value_code as type from gold.cama_events
where person_id in :persons and date <= :cutoff and type in :types
and value_code is not null
order by person_id, date, type
""",
# What clinical notes diagnosed, and each recurrence (a study of the catalog).
"condition": """
select person_id, note_date, specialty, icd10, reason, diagnosis_text,
null as study, null as code
from silver.clinical_note
where person_id in :persons and note_date <= :cutoff
and (icd10 is not null or diagnosis_text is not null)
union all
select person_id, diagnosis_date, null, null, null, null, 'breast_recurrence', site
from silver.breast_recurrence
where person_id in :persons and diagnosis_date <= :cutoff
order by person_id, note_date
""",
# Days from a mammogram to its diagnosis, when known by the cut-off (gold; as the
# indicator, only without a breast cancer note before it).
"diagnosis_days": """
select person_id, exam_date as sample_date, days_sample_diagnosis as days
from gold.cama_mammograms
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
""",
# The list's candidates: each reported mammogram by the cut-off and its biopsies
# (core.cama.follow_up picks the latest per patient and places her in the window).
"follow_up": """
select * from gold.cama_mammogram_biopsies
where birads is not null and report_date <= :cutoff
""",
"procedure": "\n select distinct person_id, date, value_code as type from gold.cama_events\n where person_id in :persons and date <= :cutoff and type in :types\n and value_code is not null\n order by person_id, date, type\n ",
"condition": "\n select person_id, note_date, specialty, icd10, reason, diagnosis_text,\n null as study, null as code\n from silver.clinical_note\n where person_id in :persons and note_date <= :cutoff\n and (icd10 is not null or diagnosis_text is not null)\n union all\n select person_id, diagnosis_date, null, null, null, null, 'breast_recurrence', site\n from silver.breast_recurrence\n where person_id in :persons and diagnosis_date <= :cutoff\n order by person_id, note_date\n ",
"diagnosis_days": "\n select person_id, exam_date as sample_date, days_sample_diagnosis as days\n from gold.cama_mammograms\n where person_id in :persons and history = 0 and diagnosis_date <= :cutoff\n ",
"follow_up": "\n select * from gold.cama_mammogram_biopsies\n where birads is not null and report_date <= :cutoff\n ",
},
}
def rows(domain: str, kind: str, **params) -> list[dict]:
"""The rows of one kind for the domain. `persons` (and `types`) limit them to those;
none when the table doesn't exist yet (no risk batch)."""
sql = text((READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain))
for many in ("persons", "types"):
if many in params:
@@ -161,19 +52,16 @@ def rows(domain: str, kind: str, **params) -> list[dict]:
if not params[many]:
return []
with engine().connect() as con:
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
if kind == "risk" and (not inspect(con).has_table(f"{domain}_risk", schema="gold")):
return []
return [dict(r) for r in con.execute(sql, params).mappings()]
def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
"""A study's instances of these persons that began by the cut-off (its first event's
date), as `silver.<study>` holds them; what was known by then is core.fhir.known's."""
spec = catalog.studies()[study]
first = next(e.date for e in spec.events.values() if e.parent is None)
first = next((e.date for e in spec.events.values() if e.parent is None))
sql = text(
f"select * from silver.{study} where person_id in :persons and {first} <= :cutoff "
f"order by person_id, {first}"
f"select * from silver.{study} where person_id in :persons and {first} <= :cutoff order by person_id, {first}"
).bindparams(bindparam("persons", expanding=True))
if not persons:
return []
@@ -184,8 +72,6 @@ def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
def last_data_day(domain: str) -> date | None:
"""The last day anything happened in the domain's timeline (up to today): the default
cut-off."""
sql = text(f"select max(date) from gold.{domain}_events where date <= :today")
with engine().connect() as con:
if not inspect(con).has_table(f"{domain}_events", schema="gold"):
+24 -30
View File
@@ -1,38 +1,31 @@
"""Files kept whole (a PDF report, an EEG's signal), once each, by content hash. A source keeps
every binary value it collects here and passes on its hash, so the nodes after it carry a
reference, never the content; `read` and the analyses fetch the content by hash, and a
catalog `file` field holds the hash in silver."""
import hashlib
import os
import shutil
import tempfile
from pathlib import Path
from sqlalchemy import Column, LargeBinary, MetaData, Table, Text, inspect, text
from sqlalchemy.types import TypeEngine
from persistance.destination import engine
TABLE = "files"
INSERT_BYTES = 32_000_000 # file contents per insert
FILES = Table(TABLE, MetaData(), Column("key", Text, primary_key=True),
Column("content", LargeBinary, nullable=False), schema="bronze") # fmt: skip
INSERT_BYTES = 32000000
FILES = Table(
TABLE,
MetaData(),
Column("key", Text, primary_key=True),
Column("content", LargeBinary, nullable=False),
schema="bronze",
)
def key(content: bytes) -> str:
return hashlib.sha256(content).hexdigest()
FLUSH_BYTES = 256_000_000 # file contents stored per load
FLUSH_BYTES = 256000000
class Collector:
"""A dlt map that replaces each binary value of a row with its hash, spooling each new
content to a folder on disk (ISSSTELEON_DATA) so a source of large files (scans, EEG
recordings) never holds them in memory; `keep` stores them once the rows have loaded
(a dlt load can't run inside another's extract), FLUSH_BYTES at a time."""
def __init__(self):
self.spool = Path(tempfile.mkdtemp(prefix="files-", dir=os.environ.get("ISSSTELEON_DATA")))
self.keys: list[str] = []
@@ -67,13 +60,10 @@ class Collector:
def reference_type(sql_type: TypeEngine) -> TypeEngine:
"""For a source that reflects its columns' types (dlt's `sql_table`): a binary column
is text, since what it carries from the source on is the file's hash."""
return Text() if isinstance(sql_type, LargeBinary) else sql_type
def known(keys: set[str]) -> set[str]:
"""Which of these hashes the platform already keeps."""
with engine().connect() as con:
if not keys or not inspect(con).has_table(TABLE, schema="bronze"):
return set()
@@ -82,41 +72,45 @@ def known(keys: set[str]) -> set[str]:
def keep(contents: dict[str, bytes]) -> None:
"""Contents by hash, each written once, straight into the table (SQLAlchemy, a few at a
time): a load through dlt would write every file as base64 JSON and hold it."""
if not contents:
return
with engine().begin() as con:
FILES.create(con, checkfirst=True)
columns = {c["name"] for c in inspect(con).get_columns(TABLE, schema="bronze")}
have = set(con.execute(text(f"select key from bronze.{TABLE}")).scalars())
batch, size = [], 0
batch, size = ([], 0)
for k, c in contents.items():
if k in have:
continue
row = {"key": k, "content": c}
if "_dlt_id" in columns: # a table an earlier platform made through dlt
if "_dlt_id" in columns:
row |= {"_dlt_load_id": "files", "_dlt_id": k[:14]}
batch.append(row)
size += len(c)
if size >= INSERT_BYTES:
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
batch, size = [], 0
batch, size = ([], 0)
if batch:
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
def _with_dlt():
return Table(TABLE, MetaData(), Column("key", Text, primary_key=True),
Column("content", LargeBinary), Column("_dlt_load_id", Text),
Column("_dlt_id", Text), schema="bronze").insert() # fmt: skip
return Table(
TABLE,
MetaData(),
Column("key", Text, primary_key=True),
Column("content", LargeBinary),
Column("_dlt_load_id", Text),
Column("_dlt_id", Text),
schema="bronze",
).insert()
def content(key: str) -> bytes | None:
"""A file's content, or None when the platform has no file with that hash."""
with engine().connect() as con:
if not inspect(con).has_table(TABLE, schema="bronze"):
return None
found = con.execute(text(f"select content from bronze.{TABLE} where key = :k"),
{"k": key}).scalar() # fmt: skip
found = con.execute(
text(f"select content from bronze.{TABLE} where key = :k"), {"k": key}
).scalar()
return bytes(found) if found is not None else None
+28 -30
View File
@@ -1,41 +1,35 @@
"""What the models read from gold, and the risk batches they write back."""
from datetime import UTC, date, datetime
import dlt
import pandas as pd
from sqlalchemy import inspect, text
from persistance.destination import engine, platform
TIMELINE = ["person_id", "index_date", "date", "type", "value_code", "value_num",
"source_table", "source_id", "record_number"] # fmt: skip
TIMELINE = [
"person_id",
"index_date",
"date",
"type",
"value_code",
"value_num",
"source_table",
"source_id",
"record_number",
]
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
"""The events (`gold.<events>`) up to `as_of` (default: today) of every member of
`gold.<cohort>`, each with her index date and her record number (the lowest of the
hospital's numbers for her: a deterministic order among patients), in date order."""
sql = text(f"""
select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,
e.source_table, e.source_id, n.record_number
from gold.{events} as e
join gold.{cohort} as c on c.person_id = e.person_id
left join (select person_id, min(record_number) as record_number
from bronze.staged__identity group by person_id) as n
on n.person_id = e.person_id
where c.excluded_by is null and e.date <= :as_of
order by e.person_id, e.date, e.source_table, e.source_id
""") # fmt: skip
sql = text(
f"\n select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,\n e.source_table, e.source_id, n.record_number\n from gold.{events} as e\n join gold.{cohort} as c on c.person_id = e.person_id\n left join (select person_id, min(record_number) as record_number\n from bronze.staged__identity group by person_id) as n\n on n.person_id = e.person_id\n where c.excluded_by is null and e.date <= :as_of\n order by e.person_id, e.date, e.source_table, e.source_id\n "
)
with engine().connect() as con:
found = pd.read_sql(sql, con, params={"as_of": (as_of or date.today()).isoformat()})
return found.astype({"value_num": float})[TIMELINE]
def person_numbers() -> dict[str, str]:
"""Each person's record numbers as the link node compared them (for checks and reviews)."""
sql = text("select distinct person_id, record_number from bronze.staged__identity "
"where person_id is not null and record_number is not null") # fmt: skip
sql = text(
"select distinct person_id, record_number from bronze.staged__identity where person_id is not null and record_number is not null"
)
with engine().connect() as con:
return dict(con.execute(sql).fetchall())
@@ -44,15 +38,19 @@ SCORES = "model_scores"
def save_scores(model: str, version: int, scores: pd.DataFrame) -> None:
"""A model's risk batch into `bronze.model_scores`, replacing its previous batch; dbt
places it in gold (`cacu_risk`)."""
with engine().begin() as con:
if inspect(con).has_table(SCORES, schema="bronze"):
con.execute(text(f"delete from bronze.{SCORES} where model = :m"), {"m": model})
rows = scores.assign(model=model, version=version, scored_at=datetime.now(UTC))
resource = dlt.resource(rows.to_dict("records"), name=SCORES, write_disposition="append",
columns={"ci_low": {"data_type": "double", "nullable": True},
"ci_high": {"data_type": "double", "nullable": True},
"scenarios": {"data_type": "text", "nullable": True},
"index_date": {"data_type": "date"}}) # fmt: skip
resource = dlt.resource(
rows.to_dict("records"),
name=SCORES,
write_disposition="append",
columns={
"ci_low": {"data_type": "double", "nullable": True},
"ci_high": {"data_type": "double", "nullable": True},
"scenarios": {"data_type": "text", "nullable": True},
"index_date": {"data_type": "date"},
},
)
dlt.pipeline(SCORES, destination=platform(), dataset_name="bronze").run(resource)
+5 -41
View File
@@ -1,60 +1,24 @@
"""The gold rows each domain's measures are evaluated over (core.measures), by the name a
measure gives (`Measure.rows`)."""
from sqlalchemy import inspect, text
from persistance.destination import engine
READS = {
"cacu": {
"samples": "select * from gold.cacu_samples",
"sample_biopsies": """
select s.*, b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.severity
from gold.cacu_samples as s
left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id
""",
"procedures": """
select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history,
s.report_known_at as cytology_known_at,
f.first_case, f.first_treatment, f.first_colposcopy
from gold.cacu_procedures as p
left join gold.cacu_samples as s
on s.person_id = p.person_id and s.sample_date = p.sample_date
left join gold.cacu_follow_up as f on f.person_id = p.person_id
where p.type = :type
""",
"risk": """
select c.person_id, coalesce(r.index_date, c.index_date) as index_date,
r.probability, r.scored_at as known_at
from gold.cacu_cohort_surveillance as c
join gold.cacu_risk as r on r.person_id = c.person_id
where c.excluded_by is null and r.model = :model and r.horizon_years = 0
""",
"sample_biopsies": "\n select s.*, b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.severity\n from gold.cacu_samples as s\n left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id\n ",
"procedures": "\n select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history,\n s.report_known_at as cytology_known_at,\n f.first_case, f.first_treatment, f.first_colposcopy\n from gold.cacu_procedures as p\n left join gold.cacu_samples as s\n on s.person_id = p.person_id and s.sample_date = p.sample_date\n left join gold.cacu_follow_up as f on f.person_id = p.person_id\n where p.type = :type\n ",
"risk": "\n select c.person_id, coalesce(r.index_date, c.index_date) as index_date,\n r.probability, r.scored_at as known_at\n from gold.cacu_cohort_surveillance as c\n join gold.cacu_risk as r on r.person_id = c.person_id\n where c.excluded_by is null and r.model = :model and r.horizon_years = 0\n ",
},
"cama": {
"mammograms": "select * from gold.cama_mammograms",
"biopsies": "select * from gold.cama_biopsies where report_date is not null",
"mammogram_biopsies": "select * from gold.cama_mammogram_biopsies",
# One row per mammogram: its first reported biopsy (ties: the lowest id), or the row
# with none. The biopsy is the one whose request names the mammogram.
"mammogram_first_biopsy": """
select * from (
select *, row_number() over (
partition by mammogram_id order by biopsy_report_date, biopsy_id) as nth
from gold.cama_mammogram_biopsies
) as x where nth = 1
""",
},
"tea": {
"screening": "select * from gold.tea_screening",
"eegs": "select * from gold.tea_eegs",
},
"tea": {"screening": "select * from gold.tea_screening", "eegs": "select * from gold.tea_eegs"},
}
def rows(domain: str, kind: str, **params) -> list[dict]:
"""The rows of one kind; none while their tables don't exist (no risk batch yet)."""
with engine().connect() as con:
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
if kind == "risk" and (not inspect(con).has_table(f"{domain}_risk", schema="gold")):
return []
return [dict(r) for r in con.execute(text(READS[domain][kind]), params).mappings()]
+62 -62
View File
@@ -1,6 +1,3 @@
"""Node outputs: every node of a pipeline writes one bronze table, `n__<pipeline>__<node>`,
through its own dlt pipeline. Targets write into one staging table per entity."""
import hashlib
import json
import uuid
@@ -8,11 +5,9 @@ from collections.abc import Iterable, Iterator
from datetime import UTC, datetime
from importlib import import_module
from inspect import signature
import dlt
from dlt.extract import DltResource, DltSource
from sqlalchemy import inspect, text
from core.pipeline import RECORD, Source
from persistance import files
from persistance.destination import engine, platform
@@ -32,7 +27,6 @@ def _load(path: str):
def _record(row: dict) -> dict:
"""Stamp a source row with its record id: the hash of the row as it came in."""
raw = json.dumps(
row, sort_keys=True, default=lambda v: v.hex() if isinstance(v, bytes) else str(v)
)
@@ -40,14 +34,13 @@ def _record(row: dict) -> dict:
def resources(source: str, args: dict) -> list[str]:
"""What a source offers to pick from (a database's tables, a folder's readers...)."""
made = _load(source)(**args)
return sorted(made.resources) if isinstance(made, DltSource) else [made.name]
def _resource(node: Source) -> DltResource:
source, args = _load(node.source), dict(node.args)
if "type_adapter_callback" in signature(source).parameters: # it reflects column types
source, args = (_load(node.source), dict(node.args))
if "type_adapter_callback" in signature(source).parameters:
args.setdefault("type_adapter_callback", files.reference_type)
made = source(**args)
if isinstance(made, DltSource):
@@ -55,16 +48,14 @@ def _resource(node: Source) -> DltResource:
if node.resource is None and len(found) != 1:
raise ValueError(f"{node.id}: pick one resource of {sorted(found)}")
made = found[node.resource] if node.resource else next(iter(found.values()))
return made | _load(node.then)() if node.then else made # a fresh transformer each time
return made | _load(node.then)() if node.then else made
def shown(row: dict) -> dict:
"""A row as JSON: file contents shown by size, never sent whole."""
return {k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v for k, v in row.items()}
def preview(node: Source, limit: int) -> list[dict]:
"""The first rows a source node would load, read with the same dlt resource."""
out: list[dict] = []
for item in _resource(node).add_limit(limit):
out.extend(item if isinstance(item, list) else [item])
@@ -72,16 +63,14 @@ def preview(node: Source, limit: int) -> list[dict]:
def run_source(pipeline_id: str, node: Source):
"""Merged on the source's own primary key (or the configured one); replaced whole when
there is none, so a rerun never duplicates rows."""
collected = files.Collector() # files are kept once; the row carries their hash
collected = files.Collector()
made = _resource(node).add_map(_record).add_map(collected)
made.apply_hints(table_name=table(pipeline_id, node.id))
if node.primary_key:
made.apply_hints(primary_key=node.primary_key)
keyed = any(c.get("primary_key") for c in made.compute_table_schema()["columns"].values())
keyed = any((c.get("primary_key") for c in made.compute_table_schema()["columns"].values()))
made.apply_hints(write_disposition="merge" if keyed else "replace")
with engine().connect() as con: # a source's cursor (dlt state) starts over with its table
with engine().connect() as con:
fresh = not inspect(con).has_table(table(pipeline_id, node.id), schema="bronze")
try:
loaded = _pipeline(table(pipeline_id, node.id)).run(
@@ -95,16 +84,12 @@ def run_source(pipeline_id: str, node: Source):
def write(pipeline_id: str, node_id: str, rows: Iterable[dict], columns: dict | None = None):
"""A node's output, rewritten whole on every run."""
name = table(pipeline_id, node_id)
resource = dlt.resource(rows, name=name, columns=columns, write_disposition="replace")
return _pipeline(name).run(resource)
def rows(pipeline_id: str, node_id: str) -> Iterator[dict]:
"""A node's output, without dlt's own bookkeeping columns; none if it never produced
a row (dlt creates a table on its first row). Binary values come back as bytes on
every engine (PostgreSQL's driver gives memoryview)."""
name = table(pipeline_id, node_id)
with engine().connect() as con:
if not inspect(con).has_table(name, schema="bronze"):
@@ -118,40 +103,47 @@ def rows(pipeline_id: str, node_id: str) -> Iterator[dict]:
def stage(entity: str, pipeline_id: str, node_id: str, rows: list[dict], columns: dict):
"""A target's rows into `bronze.staged__<entity>`, replacing what that target wrote
before. Many pipelines and targets share the table; dbt places it into silver. Each row
keeps `known_at`, when the platform first had it: a source row that changes is a new
record, so it is known from the run that brought the change."""
name = f"staged__{entity}"
known: dict[tuple, datetime] = {}
with engine().begin() as con:
if inspect(con).has_table(name, schema="bronze"):
where = {"p": pipeline_id, "t": node_id}
found = con.execute(text(f"select {RECORD}, _index, known_at from bronze.{name} "
"where _pipeline = :p and _target = :t"), where) # fmt: skip
found = con.execute(
text(
f"select {RECORD}, _index, known_at from bronze.{name} where _pipeline = :p and _target = :t"
),
where,
)
known = {(r, i): k for r, i, k in found}
con.execute(
text(f"delete from bronze.{name} where _pipeline = :p and _target = :t"), where
)
now = datetime.now(UTC)
tagged = [
{**r, "_pipeline": pipeline_id, "_target": node_id,
"known_at": known.get((r[RECORD], r.get("_index", 0)), now)}
{
**r,
"_pipeline": pipeline_id,
"_target": node_id,
"known_at": known.get((r[RECORD], r.get("_index", 0)), now),
}
for r in rows
] # fmt: skip
]
resource = dlt.resource(tagged, name=name, columns=columns, write_disposition="append")
return _pipeline(name).run(resource)
def reject(entity: str, record: str, reason: str, by: str):
"""A reviewer's decision that one record's row must not reach silver (append-only)."""
row = {"entity": entity, RECORD: record, "reason": reason, "by": by,
"decided_at": datetime.now(UTC)} # fmt: skip
row = {
"entity": entity,
RECORD: record,
"reason": reason,
"by": by,
"decided_at": datetime.now(UTC),
}
return _pipeline("review_log").run([row], table_name="review_log", write_disposition="append")
def cached(name: str, keys: set[str]) -> dict[str, dict]:
"""Rows of a content-keyed cache (`bronze.<name>`, keyed by `key`) for these keys."""
with engine().connect() as con:
if not keys or not inspect(con).has_table(name, schema="bronze"):
return {}
@@ -161,13 +153,13 @@ def cached(name: str, keys: set[str]) -> dict[str, dict]:
def remember(name: str, rows: list[dict], columns: dict):
if rows:
resource = dlt.resource(rows, name=name, primary_key="key", columns=columns,
write_disposition="merge") # fmt: skip
resource = dlt.resource(
rows, name=name, primary_key="key", columns=columns, write_disposition="merge"
)
_pipeline(name).run(resource)
def rejected(entity: str) -> set[str]:
"""Records reviewers rejected for this entity."""
with engine().connect() as con:
if not inspect(con).has_table("review_log", schema="bronze"):
return set()
@@ -176,16 +168,19 @@ def rejected(entity: str) -> set[str]:
def decide_persons(record_l: str, record_r: str, same: bool, by: str):
"""A reviewer's answer to "are these the same person?" (append-only; latest wins)."""
row = {"record_l": record_l, "record_r": record_r, "same": same, "by": by,
"decided_at": datetime.now(UTC)} # fmt: skip
row = {
"record_l": record_l,
"record_r": record_r,
"same": same,
"by": by,
"decided_at": datetime.now(UTC),
}
return _pipeline("review_persons").run(
[row], table_name="review_persons", write_disposition="append"
)
def person_decisions() -> dict[frozenset, bool]:
"""Each pair of records reviewers judged, and their latest answer."""
with engine().connect() as con:
if not inspect(con).has_table("review_persons", schema="bronze"):
return {}
@@ -194,17 +189,20 @@ def person_decisions() -> dict[frozenset, bool]:
def correct(record: str, field: str, value: str, by: str, entity: str = "identity"):
"""A reviewer's correction of one field of one record (append-only; latest wins). The
source keeps its value; linking (identity fields) or the study's target uses it."""
row = {RECORD: record, "entity": entity, "field": field, "value": value, "by": by,
"decided_at": datetime.now(UTC)} # fmt: skip
row = {
RECORD: record,
"entity": entity,
"field": field,
"value": value,
"by": by,
"decided_at": datetime.now(UTC),
}
return _pipeline("review_corrections").run(
[row], table_name="review_corrections", write_disposition="append"
)
def corrections() -> dict[str, dict[str, str]]:
"""The latest correction of each field of each record."""
with engine().connect() as con:
if not inspect(con).has_table("review_corrections", schema="bronze"):
return {}
@@ -218,33 +216,35 @@ def corrections() -> dict[str, dict[str, str]]:
def stable_persons(clusters: dict[str, list[str]]) -> dict[str, str]:
"""A person id for each cluster of records (the link node's persons) that survives
reruns and reviews: a cluster keeps an id its records already had (the earliest minted
when several meet, the others then `replaced_by` it); a cluster whose records had none
gets a new UUID; an id whose records part goes with the larger part. Assignments and
replacements are appended to `bronze.person_registry` and `bronze.person_link`."""
known, minted = {}, {}
known, minted = ({}, {})
with engine().connect() as con:
if inspect(con).has_table("person_registry", schema="bronze"):
sql = text("select _record, person_id, assigned_at from bronze.person_registry "
"order by assigned_at") # fmt: skip
sql = text(
"select _record, person_id, assigned_at from bronze.person_registry order by assigned_at"
)
for record, person, at in con.execute(sql):
known[record] = person # the latest assignment wins
known[record] = person
minted.setdefault(person, at)
now = datetime.now(UTC)
found, taken, assigned, links = {}, set(), [], []
found, taken, assigned, links = ({}, set(), [], [])
for cluster, records in sorted(clusters.items(), key=lambda c: (-len(c[1]), c[0])):
ids = {known[r] for r in records if r in known} - taken
person = min(ids, key=lambda i: (str(minted[i]), i)) if ids else str(uuid.uuid4())
links += [{"person_id": old, "replaced_by": person, "linked_at": now}
for old in sorted(ids - {person})] # fmt: skip
links += [
{"person_id": old, "replaced_by": person, "linked_at": now}
for old in sorted(ids - {person})
]
taken |= ids | {person}
found[cluster] = person
assigned += [{RECORD: r, "person_id": person, "assigned_at": now}
for r in records if known.get(r) != person] # fmt: skip
assigned += [
{RECORD: r, "person_id": person, "assigned_at": now}
for r in records
if known.get(r) != person
]
if assigned:
_pipeline("person_registry").run(assigned, table_name="person_registry",
write_disposition="append") # fmt: skip
_pipeline("person_registry").run(
assigned, table_name="person_registry", write_disposition="append"
)
if links:
_pipeline("person_link").run(links, table_name="person_link", write_disposition="append")
return found
+24 -38
View File
@@ -1,12 +1,3 @@
"""dlt readers a pipeline's source names: transformers for files found by dlt's
`filesystem` source (in a source's `then`), and the FHIR door's inbox.
CSV, JSONL and Parquet use dlt's own readers (`dlt.sources.filesystem:readers`); these
cover what dlt doesn't ship. `fsspec_files` finds files on any filesystem fsspec has an
implementation for (a Windows share, OneDrive, SharePoint...), where dlt's own `filesystem`
source lists only the few it knows; the same readers read them.
"""
import hashlib
import json
import mimetypes
@@ -14,17 +5,22 @@ import posixpath
from collections.abc import Iterator
from datetime import UTC, datetime
from typing import Any
import dlt
import fsspec
import pandas as pd
from dlt.sources.filesystem import FileItemDict
from sqlalchemy import inspect, text
from persistance.destination import engine, platform
MODIFIED = ("mtime", "modified", "last_modified", "LastModified", "lastModifiedDateTime",
"updated", "created") # what fsspec implementations call it # fmt: skip
MODIFIED = (
"mtime",
"modified",
"last_modified",
"LastModified",
"lastModifiedDateTime",
"updated",
"created",
)
def _modified(info: dict) -> datetime:
@@ -45,10 +41,7 @@ def fsspec_files(
storage_options: dict[str, Any] | None = None,
files_per_page: int = 100,
):
"""The files under `url` matching `file_glob`, on any fsspec filesystem (its protocol
names the implementation; `storage_options` are its arguments): pages of items the
`filesystem` readers take, as dlt's own `FileItemDict`, like dlt's `filesystem`."""
fs, root = fsspec.core.url_to_fs(url, **(storage_options or {}))
fs, root = fsspec.core.url_to_fs(url, **storage_options or {})
root = root.rstrip("/")
page: list[FileItemDict] = []
for path in sorted(fs.glob(posixpath.join(root, file_glob) if root else file_glob)):
@@ -56,14 +49,19 @@ def fsspec_files(
if info.get("type") != "file":
continue
name = posixpath.basename(path)
page.append(FileItemDict({
"file_url": fs.unstrip_protocol(path),
"file_name": name,
"relative_path": posixpath.relpath(path, root or "/"),
"mime_type": mimetypes.guess_type(name)[0] or "application/octet-stream",
"modification_date": _modified(info),
"size_in_bytes": info.get("size"),
}, fs)) # fmt: skip
page.append(
FileItemDict(
{
"file_url": fs.unstrip_protocol(path),
"file_name": name,
"relative_path": posixpath.relpath(path, root or "/"),
"mime_type": mimetypes.guess_type(name)[0] or "application/octet-stream",
"modification_date": _modified(info),
"size_in_bytes": info.get("size"),
},
fs,
)
)
if len(page) == files_per_page:
yield page
page = []
@@ -73,7 +71,6 @@ def fsspec_files(
@dlt.transformer(primary_key="file_url", write_disposition="merge")
def read_bytes(items: Iterator[FileItemDict]):
"""Each file whole, so later stages never go back to the source."""
for item in items:
yield {
"file_url": item["file_url"],
@@ -85,7 +82,6 @@ def read_bytes(items: Iterator[FileItemDict]):
@dlt.transformer
def read_excel(items: Iterator[FileItemDict]):
"""Every sheet's rows, as text, with the file and sheet they came from."""
for item in items:
with item.open() as f:
sheets = pd.read_excel(f, sheet_name=None, dtype=str)
@@ -96,8 +92,6 @@ def read_excel(items: Iterator[FileItemDict]):
@dlt.transformer(primary_key=("file_name", "line"), write_disposition="merge")
def read_tsv(items: Iterator[FileItemDict]):
"""Tab-separated text (how public research datasets are published): every value as
written, with the file and the line it came from (the order a dataset is published in)."""
for item in items:
with item.open() as f:
frame = pd.read_csv(f, sep="\t", dtype=str, low_memory=False)
@@ -109,8 +103,6 @@ INBOX = "fhir_inbox"
def receive(sender: str, bundle: dict) -> str:
"""A Bundle a standard hospital posted, into `bronze.fhir_inbox` as sent (append-only);
its pipeline's source reads it back (`fhir_inbox`)."""
received = datetime.now(UTC)
key = hashlib.sha256(json.dumps(bundle, sort_keys=True).encode()).hexdigest()
row = {"id": key, "sender": sender, "received_at": received, "doc": json.dumps(bundle)}
@@ -121,13 +113,7 @@ def receive(sender: str, bundle: dict) -> str:
@dlt.resource(primary_key="id", write_disposition="merge")
def fhir_inbox(
sender: str,
received_at=dlt.sources.incremental("received_at"), # noqa: B008 -- dlt's cursor idiom
):
"""The Bundles a sender posted to the FHIR door: a pipeline's source node. Each run
reads only what arrived since the last one (dlt's cursor; ties at the boundary are
dropped by the primary key)."""
def fhir_inbox(sender: str, received_at=dlt.sources.incremental("received_at")):
with engine().connect() as con:
if not inspect(con).has_table(INBOX, schema="bronze"):
return
+27 -30
View File
@@ -1,28 +1,25 @@
"""Model versions, in MLflow's registry. Each version keeps its reports as artifacts under
`reports/`; the `champion` alias, the version risk batches come from, moves only to a
version that has the reports the site requires: PROMOTION_REPORTS, a comma-separated list
(default: all three; a test deployment may leave out the clinical validation). Where MLflow
is comes from MLFLOW_TRACKING_URI."""
import os
import tempfile
from importlib.metadata import version as installed
from pathlib import Path
import mlflow
from mlflow import MlflowClient
REPORTS = ("technical_validation", "interpretability", "clinical_validation")
CHAMPION = "champion"
EXPERIMENT = "isssteleon"
# What a version needs to load, pinned to what trained it. Declared, so MLflow doesn't import
# the model in a subprocess to guess them (minutes, outside a uv project).
REQUIREMENTS = ("mlflow-skinny", "numpy", "pandas", "scipy", "scikit-learn", "joblib",
"cloudpickle") # fmt: skip
REQUIREMENTS = (
"mlflow-skinny",
"numpy",
"pandas",
"scipy",
"scikit-learn",
"joblib",
"cloudpickle",
)
def required() -> list[str]:
"""The reports a version needs before it can be promoted, as the site configured them."""
found = [r.strip() for r in os.environ.get("PROMOTION_REPORTS", "").split(",") if r.strip()]
if unknown := [r for r in found if r not in REPORTS]:
raise ValueError(f"PROMOTION_REPORTS names {unknown}; reports are {list(REPORTS)}")
@@ -34,7 +31,6 @@ class MissingReports(ValueError):
def register(name: str, python_model, params: dict, metrics: dict, reports: dict) -> int:
"""A new version of `name`: the model, its parameters and metrics, and its reports."""
mlflow.set_experiment(EXPERIMENT)
with mlflow.start_run(run_name=name):
mlflow.log_params(params)
@@ -42,14 +38,15 @@ def register(name: str, python_model, params: dict, metrics: dict, reports: dict
for report, data in reports.items():
mlflow.log_dict(data, f"reports/{report}.json")
info = mlflow.pyfunc.log_model(
name="model", python_model=python_model, registered_model_name=name,
name="model",
python_model=python_model,
registered_model_name=name,
pip_requirements=[f"{p}=={installed(p)}" for p in REQUIREMENTS],
) # fmt: skip
)
return int(info.registered_model_version)
def reports(name: str, version: int) -> dict[str, str]:
"""The reports a version has: report name -> artifact path."""
client = MlflowClient()
run = client.get_model_version(name, str(version)).run_id
found = {Path(a.path).stem: a.path for a in client.list_artifacts(run, "reports")}
@@ -57,18 +54,16 @@ def reports(name: str, version: int) -> dict[str, str]:
def report(name: str, version: int, report: str) -> tuple[str, bytes] | None:
"""A version's report as stored: its file name and content; None when it has none."""
path = reports(name, version).get(report)
if path is None:
return None
run = MlflowClient().get_model_version(name, str(version)).run_id
with tempfile.TemporaryDirectory() as tmp:
local = mlflow.artifacts.download_artifacts(run_id=run, artifact_path=path, dst_path=tmp)
return Path(path).name, Path(local).read_bytes()
return (Path(path).name, Path(local).read_bytes())
def add_report(name: str, version: int, report: str, filename: str, content: bytes) -> None:
"""A report added to a version after training (the clinical validation)."""
if report not in REPORTS:
raise ValueError(f"no report {report!r}; reports are {list(REPORTS)}")
run = MlflowClient().get_model_version(name, str(version)).run_id
@@ -79,7 +74,6 @@ def add_report(name: str, version: int, report: str, filename: str, content: byt
def promote(name: str, version: int) -> None:
"""Make a version the champion, if it has the reports the site requires."""
if missing := [r for r in required() if r not in reports(name, version)]:
raise MissingReports(f"{name} v{version} has no {', '.join(missing)}")
MlflowClient().set_registered_model_alias(name, CHAMPION, str(version))
@@ -89,26 +83,29 @@ def versions(name: str) -> list[dict]:
client = MlflowClient()
out = []
for found in client.search_model_versions(f"name = '{name}'"):
v = client.get_model_version(name, found.version) # the search leaves aliases out
v = client.get_model_version(name, found.version)
run = client.get_run(v.run_id)
out.append({
"version": int(v.version), "created": v.creation_timestamp, "aliases": v.aliases,
"metrics": run.data.metrics, "params": run.data.params,
"reports": sorted(reports(name, int(v.version))),
}) # fmt: skip
out.append(
{
"version": int(v.version),
"created": v.creation_timestamp,
"aliases": v.aliases,
"metrics": run.data.metrics,
"params": run.data.params,
"reports": sorted(reports(name, int(v.version))),
}
)
return sorted(out, key=lambda v: v["version"])
def champion(name: str):
"""(version, model) of the champion, or None when no version was promoted."""
try:
found = MlflowClient().get_model_version_by_alias(name, CHAMPION)
except mlflow.exceptions.MlflowException:
return None
return int(found.version), mlflow.pyfunc.load_model(f"models:/{name}@{CHAMPION}")
return (int(found.version), mlflow.pyfunc.load_model(f"models:/{name}@{CHAMPION}"))
def names(prefix: str) -> list[str]:
"""Registered models whose name starts with `prefix` (a domain: `cacu.`)."""
found = MlflowClient().search_registered_models(f"name LIKE '{prefix}%'")
return sorted(m.name for m in found)
return sorted((m.name for m in found))
+54 -51
View File
@@ -1,15 +1,11 @@
"""What waits for a reviewer: rows a rule held, rows in conflict, possible same persons."""
import json
from sqlalchemy import inspect, text
from core.pipeline import HELD, RECORD
from persistance import config_log, nodes
from persistance.destination import engine
from persistance.nodes import table
PREVIEW = 300 # characters of a document's text shown to say what it is
PREVIEW = 300
def _exists(con, name: str, schema: str) -> bool:
@@ -17,20 +13,16 @@ def _exists(con, name: str, schema: str) -> bool:
def held(entity: str) -> list[dict]:
"""Rows a target held and no reviewer has rejected yet, with the reasons and the values
as they came."""
with engine().connect() as con:
if not _exists(con, "staged__held", "bronze"):
return []
decided = (
f"and not exists (select 1 from bronze.review_log r where r.entity = h.study "
f"and r.{RECORD} = h.{RECORD})"
f"and not exists (select 1 from bronze.review_log r where r.entity = h.study and r.{RECORD} = h.{RECORD})"
if _exists(con, "review_log", "bronze")
else ""
)
sql = text(
f"select h._pipeline, h._target, h.{RECORD}, h.{HELD}, h._raw "
f"from bronze.staged__held h where h.study = :e {decided}"
f"select h._pipeline, h._target, h.{RECORD}, h.{HELD}, h._raw from bronze.staged__held h where h.study = :e {decided}"
)
return [
{**r, HELD: json.loads(r[HELD]), "_raw": json.loads(r["_raw"] or "{}")}
@@ -39,66 +31,72 @@ def held(entity: str) -> list[dict]:
def conflicts(entity: str) -> list[dict]:
"""Accepted rows that silver left out: rows of one study instance (person and key) that
disagree, each row with its values. Rejecting the wrong ones (`nodes.reject`) lets the
next run place the rest."""
with engine().connect() as con:
if not _exists(con, "staged__observation", "bronze"):
return []
rejected = (
f"and not exists (select 1 from bronze.review_log r where r.entity = s.study "
f"and r.{RECORD} = s.{RECORD})"
f"and not exists (select 1 from bronze.review_log r where r.entity = s.study and r.{RECORD} = s.{RECORD})"
if _exists(con, "review_log", "bronze")
else ""
)
# An anti-join, not a correlated `not exists`: SQLite indexes a join on the fly, but
# scans silver once per staged row for the subquery.
silvered = _exists(con, "observation", "silver")
join = (
"left join silver.observation v on v.person_id = s.person_id "
"and v.study = s.study and v.instance = s.instance"
"left join silver.observation v on v.person_id = s.person_id and v.study = s.study and v.instance = s.instance"
if silvered
else ""
)
placed = "and v.person_id is null" if silvered else ""
sql = text(
f"select s.* from bronze.staged__observation s {join} where s.study = :e "
f"and s.person_id is not null {rejected} {placed} "
f"order by s.person_id, s.instance, s.{RECORD}, s._index"
f"select s.* from bronze.staged__observation s {join} where s.study = :e and s.person_id is not null {rejected} {placed} order by s.person_id, s.instance, s.{RECORD}, s._index"
)
rows: dict[tuple, dict] = {}
for r in con.execute(sql, {"e": entity}).mappings():
row = rows.setdefault((r[RECORD], r["_index"]), {
"person_id": r["person_id"], RECORD: r[RECORD], "_index": r["_index"],
"_pipeline": r["_pipeline"], "_target": r["_target"]}) # fmt: skip
row = rows.setdefault(
(r[RECORD], r["_index"]),
{
"person_id": r["person_id"],
RECORD: r[RECORD],
"_index": r["_index"],
"_pipeline": r["_pipeline"],
"_target": r["_target"],
},
)
values = (r[c] for c in ("value_text", "value_num", "value_bool", "value_date"))
row[r["field"]] = next((v for v in values if v is not None), None)
return list(rows.values())
def persons(pipeline_id: str, link_node: str) -> dict[str, list[dict]]:
"""What a link node leaves to a reviewer:
- `to_settle`: persons that may belong to another (usually records with no demographics
whose identifier is one typo from a patient's), each with its possible owners;
- `torn`: persons whose records disagree on birth date or sex, with every record, so
the wrong one can be rejected (entity `identity`);
- `unnamed`: persons whose records name nobody (a scan whose name line wasn't read),
for a reviewer to say whose they are."""
with engine().connect() as con:
queue, torn = table(pipeline_id, f"{link_node}__review"), table(pipeline_id, link_node)
queue, torn = (table(pipeline_id, f"{link_node}__review"), table(pipeline_id, link_node))
settle: dict[str, dict] = {}
if _exists(con, queue, "bronze"):
for r in con.execute(text(f"select * from bronze.{queue}")).mappings():
r = {k: v for k, v in r.items() if not k.startswith("_dlt_")}
entry = settle.setdefault(r["person"], {"person": r["person"], **{
k.removeprefix("person_"): v for k, v in r.items() if k.startswith("person_")
}, "candidates": []}) # fmt: skip
entry["candidates"].append({
"candidate": r["candidate"], "reason": r["reason"],
"probability": r["probability"],
**{k.removeprefix("candidate_"): v for k, v in r.items()
if k.startswith("candidate_")},
}) # fmt: skip
entry = settle.setdefault(
r["person"],
{
"person": r["person"],
**{
k.removeprefix("person_"): v
for k, v in r.items()
if k.startswith("person_")
},
"candidates": [],
},
)
entry["candidates"].append(
{
"candidate": r["candidate"],
"reason": r["reason"],
"probability": r["probability"],
**{
k.removeprefix("candidate_"): v
for k, v in r.items()
if k.startswith("candidate_")
},
}
)
held: dict[str, dict[str, dict]] = {"torn": {}, "unnamed": {}}
if _exists(con, torn, "bronze"):
sql = text(f"select * from bronze.{torn} where {HELD} is not null order by person_id")
@@ -110,20 +108,25 @@ def persons(pipeline_id: str, link_node: str) -> dict[str, list[dict]]:
person["records"].append(record)
for entry in settle.values():
entry["candidates"].sort(key=lambda c: -(c["probability"] or 0))
return {"to_settle": list(settle.values()), "torn": list(held["torn"].values()),
"unnamed": list(held["unnamed"].values())} # fmt: skip
return {
"to_settle": list(settle.values()),
"torn": list(held["torn"].values()),
"unnamed": list(held["unnamed"].values()),
}
def unrecognised(pipeline_id: str) -> list[dict]:
"""Rows that reached a pipeline's `otherwise` routes (documents no route recognises),
each with the route and the start of its text; files shown by size."""
_, pipeline = config_log.get(pipeline_id)
out = []
for node in pipeline.nodes:
if node.kind == "route" and node.otherwise:
for row in nodes.rows(pipeline_id, node.id):
shown = {k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v
for k, v in row.items() if k != "text"} # fmt: skip
out.append({"route": node.id, **shown,
"preview": (row.get("text") or "")[:PREVIEW]}) # fmt: skip
shown = {
k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v
for k, v in row.items()
if k != "text"
}
out.append(
{"route": node.id, **shown, "preview": (row.get("text") or "")[:PREVIEW]}
)
return out
+26 -27
View File
@@ -1,16 +1,8 @@
"""Silver: what targets staged, placed by dbt, and the dbt build that also derives gold.
Clinical values are staged long, one row per field of a study instance
(`bronze.staged__observation`); rows a rule held wait in `bronze.staged__held`. Identity rows,
the link node's, stay one row per record (`bronze.staged__identity`)."""
import json
import types
import typing
from datetime import date
from dbt.cli.main import dbtRunner
from core import catalog
from core.domains import Domain, part
from core.pipeline import HELD, QUOTES, RECORD
@@ -21,42 +13,40 @@ _DLT_TYPES = {date: "date", bool: "bool", float: "double", int: "bigint"}
def _text() -> dict:
return {"data_type": "text", "nullable": True} # a new dict per column: dlt names it
return {"data_type": "text", "nullable": True}
_BOOKKEEPING = {
"person_id": _text(), RECORD: _text(), QUOTES: _text(),
"_index": {"data_type": "bigint"}, "known_at": {"data_type": "timestamp"},
} # fmt: skip
# One row per field of one study instance: its value in the column of its type.
"person_id": _text(),
RECORD: _text(),
QUOTES: _text(),
"_index": {"data_type": "bigint"},
"known_at": {"data_type": "timestamp"},
}
OBSERVATION = {
"study": _text(), "instance": _text(), "field": _text(), "value_text": _text(),
"study": _text(),
"instance": _text(),
"field": _text(),
"value_text": _text(),
"value_num": {"data_type": "double", "nullable": True},
"value_bool": {"data_type": "bool", "nullable": True},
"value_date": {"data_type": "date", "nullable": True},
**_BOOKKEEPING,
} # fmt: skip
# One row per held record of a study: why, and its values as they came.
}
HELD_ROWS = {"study": _text(), HELD: _text(), "_raw": _text(), **_BOOKKEEPING}
def identity_columns() -> dict:
"""dlt column hints for `bronze.staged__identity`: every identity field typed, even
when a load has no value for it, plus the bookkeeping columns."""
out = {}
for name, field in Identity.model_fields.items():
kind = field.annotation
if isinstance(kind, types.UnionType) or typing.get_origin(kind) is typing.Union:
kind = next(a for a in typing.get_args(kind) if a is not type(None))
kind = next((a for a in typing.get_args(kind) if a is not type(None)))
out[name] = {"data_type": _DLT_TYPES.get(kind, "text"), "nullable": True}
return {**out, **_BOOKKEEPING, HELD: _text(), "_raw": _text(), "_source": _text()}
def build(select: list[str], as_of: date | None = None) -> None:
"""Run and test these dbt models (`<model>+`: with all that derive from it). The
catalog and each domain's clinical parameters (`var('<domain>')`) come from Core; `as_of`
(default: today) is the date the data are taken up to."""
domains = {d.value: found.dbt_vars() for d in Domain if (found := part(d)) is not None}
variables = {
"catalog": catalog.dbt_vars(),
@@ -66,9 +56,18 @@ def build(select: list[str], as_of: date | None = None) -> None:
}
if as_of is not None:
variables["as_of"] = as_of.isoformat()
result = dbtRunner().invoke([
"build", "--project-dir", str(DBT_DIR), "--profiles-dir", str(DBT_DIR),
"--select", *select, "--vars", json.dumps(variables),
]) # fmt: skip
result = dbtRunner().invoke(
[
"build",
"--project-dir",
str(DBT_DIR),
"--profiles-dir",
str(DBT_DIR),
"--select",
*select,
"--vars",
json.dumps(variables),
]
)
if not result.success:
raise RuntimeError(f"dbt build failed: {result.exception or result.result}")
Submodule WebApi deleted from fee6a6622d

Some files were not shown because too many files have changed in this diff Show More