Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fe5301fd1 |
+65
-5
@@ -7,25 +7,80 @@ on:
|
||||
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:
|
||||
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
|
||||
- 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
|
||||
@@ -43,9 +98,14 @@ jobs:
|
||||
run: npx ng build
|
||||
- working-directory: WebApp
|
||||
run: npx ng test --watch=false
|
||||
- name: TEA pages over the synthetic hospital (Playwright)
|
||||
- name: Every page loads from the API (Playwright over a loaded platform)
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript
|
||||
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
|
||||
|
||||
+43
-16
@@ -1,10 +1,16 @@
|
||||
"""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"]
|
||||
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
|
||||
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
|
||||
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
|
||||
FOLLOW_UP_WINDOW = 3
|
||||
|
||||
# Index cytology in the six KPNC categories, least to most severe.
|
||||
KPNC = {
|
||||
"NILM": ["NILM"],
|
||||
"ASC-US": ["ASC-US"],
|
||||
@@ -13,28 +19,35 @@ 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
|
||||
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12
|
||||
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
|
||||
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
|
||||
POST_TREATMENT_LOOKBACK_DAYS = 365
|
||||
POST_COLPOSCOPY_VISIT = 1
|
||||
REFERRAL_LOOKBACK_DAYS = 365
|
||||
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
|
||||
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
|
||||
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
|
||||
DIAGNOSIS_ICD10 = [
|
||||
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
|
||||
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
|
||||
@@ -44,21 +57,35 @@ 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"]
|
||||
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"]
|
||||
DETECTION = ["HSIL", "CIS", "carcinoma"]
|
||||
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"]
|
||||
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)]
|
||||
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.
|
||||
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
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
"""What dbt reads (`var('cacu')`)."""
|
||||
return {k.lower(): v for k, v in globals().items() if k.isupper()}
|
||||
|
||||
@@ -1,27 +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": "diagnosis_days"}
|
||||
REPORT_FACTS = {"cervical_cytology": "route"} # what followed the sample
|
||||
|
||||
|
||||
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:
|
||||
@@ -32,6 +42,8 @@ def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float |
|
||||
|
||||
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."""
|
||||
if sort == "-recent":
|
||||
return rows
|
||||
outcome = sort.removeprefix("-risk-")
|
||||
|
||||
+122
-2
@@ -1,3 +1,5 @@
|
||||
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core import cacu
|
||||
@@ -16,6 +18,9 @@ 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))
|
||||
@@ -29,14 +34,17 @@ def follow_up_status(row: dict, at: date, through: bool = False) -> str:
|
||||
|
||||
|
||||
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"]
|
||||
|
||||
|
||||
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
|
||||
@@ -47,6 +55,7 @@ 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:
|
||||
@@ -54,8 +63,82 @@ def histology(row: dict) -> str:
|
||||
return row.get("histology") or NO_DATA
|
||||
|
||||
|
||||
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"]
|
||||
|
||||
|
||||
def groups_by_cytology(row: dict, p=None) -> list[str]:
|
||||
if row["result"] is None:
|
||||
return [NO_DATA]
|
||||
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
|
||||
|
||||
|
||||
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"):
|
||||
return "subsequent"
|
||||
history = row["screening_history"]
|
||||
return NO_DATA if history is None else "initial" if history == "never" else "subsequent"
|
||||
|
||||
|
||||
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}"]]
|
||||
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:
|
||||
return "positive_incomplete"
|
||||
return "positive_" + ("_".join(found) or "other")
|
||||
|
||||
|
||||
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"]):
|
||||
return "inconsistent"
|
||||
if row["histology"] is None:
|
||||
return "no_grade"
|
||||
return "high_grade" if row["histology"] in cacu.CIN2_PLUS else "below_high_grade"
|
||||
|
||||
|
||||
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
|
||||
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))),
|
||||
params={"type": procedure},
|
||||
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_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
|
||||
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"])
|
||||
@@ -67,7 +150,44 @@ MEASURES = {m.id: m for m in [
|
||||
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))),
|
||||
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",
|
||||
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",
|
||||
"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,
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
"""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"]
|
||||
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
|
||||
|
||||
# Biopsy grades, least to most severe.
|
||||
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
|
||||
CANCER = ["in_situ", "invasive"]
|
||||
CANCER = ["in_situ", "invasive"] # detected (detection rate)
|
||||
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",
|
||||
@@ -20,12 +32,17 @@ DIAGNOSIS_ICD10 = [
|
||||
*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)]
|
||||
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
|
||||
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
|
||||
# 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
|
||||
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()}
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
"""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
|
||||
@@ -7,9 +19,9 @@ WINDOWS = cama.FOLLOW_UP_WINDOWS
|
||||
SORTS = ("-recent",)
|
||||
DEFAULT_HORIZON = None
|
||||
STATUS_SYSTEM = "cama-follow-up-status"
|
||||
PROCEDURES = ("treatment",)
|
||||
REPORT_FACTS = {"mammography": "diagnosis_days"}
|
||||
URGENT = ["5", "6"]
|
||||
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
|
||||
|
||||
|
||||
def _ranked(row: dict) -> tuple:
|
||||
@@ -17,6 +29,8 @@ def _ranked(row: dict) -> tuple:
|
||||
|
||||
|
||||
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:
|
||||
@@ -55,6 +69,7 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> None:
|
||||
"""A patient's status exists only on the list."""
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
"""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,14 +25,17 @@ 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"])
|
||||
|
||||
|
||||
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
|
||||
@@ -36,6 +46,7 @@ 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
|
||||
@@ -45,7 +56,7 @@ 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_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
|
||||
BIRADS = ("birads", lambda row, p: row["birads"])
|
||||
|
||||
MEASURES = {m.id: m for m in [
|
||||
|
||||
@@ -1,3 +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
|
||||
@@ -8,6 +17,8 @@ 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"]
|
||||
|
||||
|
||||
@@ -15,12 +26,12 @@ class System(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
url: str
|
||||
title: str
|
||||
external: bool = False
|
||||
external: bool = False # a standard system we name but don't publish
|
||||
|
||||
|
||||
class Event(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
date: str
|
||||
date: str # the field that dates it
|
||||
parent: EventClass | None = None
|
||||
|
||||
|
||||
@@ -30,7 +41,7 @@ class FieldDef(BaseModel):
|
||||
event: EventClass
|
||||
title: str
|
||||
system: str | None = None
|
||||
codes: dict[str, str] = {}
|
||||
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
|
||||
pattern: str | None = None
|
||||
unit: str | None = None
|
||||
required: bool = False
|
||||
@@ -47,7 +58,7 @@ class FieldDef(BaseModel):
|
||||
class Study(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
key: list[str]
|
||||
key: list[str] # fields that, with the person, identify one study instance
|
||||
events: dict[EventClass, Event]
|
||||
fields: dict[str, FieldDef]
|
||||
|
||||
@@ -78,6 +89,7 @@ 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"))
|
||||
@@ -86,11 +98,13 @@ 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":
|
||||
@@ -107,6 +121,8 @@ 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] = ""
|
||||
@@ -118,7 +134,7 @@ _TYPES: dict[str, Any] = {
|
||||
"date": date,
|
||||
"text": str,
|
||||
"file": str,
|
||||
} # fmt: skip
|
||||
} # fmt: skip (a file field holds its content hash)
|
||||
|
||||
|
||||
def _annotation(f: FieldDef) -> Any:
|
||||
@@ -133,8 +149,9 @@ 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 = {
|
||||
fields = { # titled as the catalog names them (forms and review show the titles)
|
||||
name: (_annotation(f), Field(... if f.required else None, title=f.title))
|
||||
for name, f in spec.fields.items()
|
||||
}
|
||||
@@ -145,12 +162,14 @@ def model(study: str) -> type[Record]:
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Cervical cancer screening.
|
||||
cervical_cytology:
|
||||
title: Citología cervical
|
||||
key: [sample_date]
|
||||
@@ -6,6 +7,49 @@ cervical_cytology:
|
||||
report: {date: report_date, parent: sample}
|
||||
fields:
|
||||
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
|
||||
screening_history:
|
||||
type: code
|
||||
event: sample
|
||||
title: Detección de cáncer de cérvix
|
||||
system: cervical-screening-history
|
||||
codes:
|
||||
never: Primera vez en la vida
|
||||
within_1_year: Un año o menos
|
||||
2_years: Dos años
|
||||
3_or_more_years: Tres o más años
|
||||
gynecologic_condition:
|
||||
type: code
|
||||
event: sample
|
||||
title: Condición ginecoobstétrica a la detección
|
||||
system: gynecologic-condition
|
||||
codes:
|
||||
postpartum: Puerperio posparto o posaborto
|
||||
pregnant: Embarazo actual
|
||||
iud: DIU in situ
|
||||
hormonal_treatment: Tratamiento hormonal
|
||||
other_treatment: Otro tratamiento ginecológico
|
||||
postmenopausal: Posmenopausia
|
||||
hysterectomy: Histerectomía
|
||||
not_applicable: No aplica
|
||||
presenting_symptom:
|
||||
type: code
|
||||
event: sample
|
||||
title: Actualmente presenta
|
||||
system: presenting-symptom
|
||||
codes:
|
||||
discharge: Flujo
|
||||
vulvar_itching: Prurito o ardor vulvar
|
||||
abnormal_bleeding: Sangrado anormal
|
||||
none: Ninguno
|
||||
cervix_appearance:
|
||||
type: code
|
||||
event: sample
|
||||
title: A la exploración se observa
|
||||
system: cervix-appearance
|
||||
codes:
|
||||
healthy: Cuello sano
|
||||
lesion: Cuello anormal con lesión
|
||||
not_seen: No se observa cuello
|
||||
report_date: {type: date, event: report, title: Fecha de reporte}
|
||||
adequacy:
|
||||
type: code
|
||||
@@ -28,6 +72,35 @@ 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"}
|
||||
finding_vaginosis: {type: boolean, event: report, title: "Hallazgo: cambio en la flora sugestiva de vaginosis bacteriana"}
|
||||
finding_candida: {type: boolean, event: report, title: "Hallazgo: microorganismos micóticos morfológicamente compatibles con Candida sp"}
|
||||
finding_bacillary_cytolysis: {type: boolean, event: report, title: "Hallazgo: aumento de la flora bacilar con citólisis de las células intermedias"}
|
||||
finding_cytolysis: {type: boolean, event: report, title: "Hallazgo: citólisis de las células intermedias"}
|
||||
finding_trichomonas: {type: boolean, event: report, title: "Hallazgo: trichomonas vaginalis"}
|
||||
finding_leptothrix: {type: boolean, event: report, title: "Hallazgo: microorganismos bacterianos morfológicamente compatibles con Leptothrix"}
|
||||
finding_actinomyces: {type: boolean, event: report, title: "Hallazgo: microorganismos morfológicamente compatibles con Actinomyces sp"}
|
||||
finding_actinomyces_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con Actinomyces sp"}
|
||||
finding_herpes_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con virus herpes simple"}
|
||||
finding_tubular_metaplasia: {type: boolean, event: report, title: "Hallazgo: metaplasia escamosa tubular"}
|
||||
finding_keratotic: {type: boolean, event: report, title: "Hallazgo: cambios queratósicos"}
|
||||
finding_pregnancy: {type: boolean, event: report, title: "Hallazgo: cambios asociados al embarazo"}
|
||||
finding_atrophy: {type: boolean, event: report, title: "Hallazgo: atrofia"}
|
||||
finding_hypoestrogenism: {type: boolean, event: report, title: "Hallazgo: hipoestrogenismo"}
|
||||
finding_radiotherapy: {type: boolean, event: report, title: "Hallazgo: efecto de radioterapia"}
|
||||
finding_iud_changes: {type: boolean, event: report, title: "Hallazgo: cambios compatibles con presencia de dispositivo intrauterino"}
|
||||
finding_glandular_cells: {type: boolean, event: report, title: "Hallazgo: células glandulares post-histerectomía"}
|
||||
finding_bacteria: {type: boolean, event: report, title: "Hallazgo: bacterias"}
|
||||
finding_herpes_image: {type: boolean, event: report, title: "Hallazgo: imagen del virus del herpes"}
|
||||
finding_fungi: {type: boolean, event: report, title: "Hallazgo: hongos"}
|
||||
finding_radiation: {type: boolean, event: report, title: "Hallazgo: radiación"}
|
||||
finding_repair: {type: boolean, event: report, title: "Hallazgo: reparación"}
|
||||
finding_iud_effect: {type: boolean, event: report, title: "Hallazgo: efecto del DIU"}
|
||||
finding_endometrial_cells: {type: boolean, event: report, title: "Hallazgo: presencia de células endometriales en pacientes de 40 años o más"}
|
||||
finding_none: {type: boolean, event: report, title: "Hallazgo: ninguno"}
|
||||
|
||||
cervical_biopsy:
|
||||
title: Biopsia cervical
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Breast cancer screening.
|
||||
mammography:
|
||||
title: Mastografía
|
||||
key: [exam_date]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Studies every domain shares.
|
||||
clinical_note:
|
||||
title: Nota médica
|
||||
key: [note_date, specialty]
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
# 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)
|
||||
who-cervical-histology:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
|
||||
title: Clasificación OMS de lesiones cervicales (histología)
|
||||
cervical-screening-history:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
|
||||
title: Detección de cáncer de cérvix
|
||||
gynecologic-condition:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/gynecologic-condition
|
||||
title: Condición ginecoobstétrica a la detección
|
||||
presenting-symptom:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/presenting-symptom
|
||||
title: Actualmente presenta
|
||||
cervix-appearance:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/cervix-appearance
|
||||
title: A la exploración se observa
|
||||
bi-rads:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
|
||||
title: BI-RADS
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# 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]
|
||||
@@ -20,6 +22,7 @@ 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,3 +1,12 @@
|
||||
"""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
|
||||
@@ -11,6 +20,8 @@ _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
|
||||
@@ -29,6 +40,8 @@ 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:
|
||||
@@ -47,6 +60,8 @@ 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:
|
||||
@@ -61,6 +76,7 @@ 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:
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
"""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
|
||||
@@ -10,6 +14,7 @@ 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)
|
||||
@@ -20,5 +25,6 @@ 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 {}
|
||||
|
||||
+127
-102
@@ -1,3 +1,11 @@
|
||||
"""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
|
||||
@@ -15,8 +23,7 @@ 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, tea
|
||||
from core.tea import ados2_items
|
||||
from core import catalog, models
|
||||
|
||||
FHIR_VERSION = "4.3.0"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
@@ -27,6 +34,7 @@ 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",
|
||||
@@ -39,63 +47,36 @@ CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
|
||||
"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-result": ("Resultado del EEG", {
|
||||
"abnormal": "Anormal", "normal": "Normal",
|
||||
"no_valid_eeg": "Sin EEG válido", "not_scored": "Sin analizar",
|
||||
"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`
|
||||
"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", "alteration": "Alteración del EEG",
|
||||
"sex": "Sexo", "age_sex": "Grupo de edad y sexo",
|
||||
"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", {}),
|
||||
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
for _system, _title, _codes in (
|
||||
("tea-eeg-metric", "Métricas del EEG", tea.EEG_METRICS),
|
||||
("tea-eeg-zone", "Zonas del EEG", (
|
||||
"frontal_left", "frontal_right", "frontal_midline", "central", "parietal",
|
||||
"temporal_left", "temporal_right", "occipital", "posterior", "global",
|
||||
)),
|
||||
("eeg-electrode-10-20", "Electrodos del EEG", (
|
||||
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4", "T5",
|
||||
"P3", "Pz", "P4", "T6", "O1", "O2", "A1", "A2", "Oz", "Fpz", "EKG", "LOC", "ROC",
|
||||
)),
|
||||
("tea-eeg-check", "Controles de calidad del EEG", (
|
||||
"file", "dead-channel", "frozen", "saturated", "inf-values", "own-gaps", "bridge",
|
||||
"amplitude", "does-not-correlate", "intermittent-contact", "intermittent-bursts",
|
||||
"aux-amplitude", "clean-windows", "internal-coverage", "bad-scalp-triage",
|
||||
"usable-scalp", "triage-level", "line-noise",
|
||||
)),
|
||||
("tea-eeg-quality", "Calidad del EEG", ("good", "bad", "not_analyzed")),
|
||||
("tea-eeg-validity", "Validez del EEG", ("valid", "not_valid")),
|
||||
("tea-association", "Asociaciones del EEG con el ADOS-2", ()),
|
||||
("tea-ados2-classification", "Clasificación del ADOS-2", (
|
||||
*(code for code, _ in tea.ADOS2_CLASSIFICATION),
|
||||
"mild_to_moderate_concern", "severe_concern",
|
||||
)),
|
||||
): # fmt: skip
|
||||
CODE_SYSTEMS[_system] = (_title, {code: code for code in _codes})
|
||||
|
||||
CODE_SYSTEMS["ados2-domain"] = ("Dominios del ADOS-2", dict(ados2_items.DOMAINS))
|
||||
CODE_SYSTEMS["ados2-subdomain"] = ("Subdominios del ADOS-2", dict(ados2_items.SUBDOMAINS))
|
||||
for _module, _items in ados2_items.ITEMS.items():
|
||||
CODE_SYSTEMS[f"ados2-item-{_module}"] = (
|
||||
f"Ítems del ADOS-2: {catalog.studies()['ados2'].fields['module'].codes[_module]}",
|
||||
{item.code: item.title for item in _items},
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
@@ -107,54 +88,49 @@ def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
|
||||
|
||||
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
|
||||
|
||||
EXTENSIONS: dict[str, tuple[str | None, list[str]]] = {
|
||||
# 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).
|
||||
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
|
||||
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
|
||||
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
|
||||
"q1": ("decimal", DURATIONS),
|
||||
"q3": ("decimal", DURATIONS),
|
||||
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
|
||||
"period-type": ("code", ["Measure"]),
|
||||
"follow-up-status": ("Coding", ["Patient"]),
|
||||
"follow-up-priority": ("Coding", ["Patient"]),
|
||||
"tea-step": ("code", ["Patient"]),
|
||||
"tea-age-group": ("code", ["Patient"]),
|
||||
"tea-case": ("code", ["Patient"]),
|
||||
"tea-eeg-result": ("code", ["Patient"]),
|
||||
"tea-mchat": ("decimal", ["Patient"]),
|
||||
"tea-css": ("integer", ["Patient"]),
|
||||
"tea-alterations": ("integer", ["Patient"]),
|
||||
"report-date": ("date", ["DiagnosticReport"]),
|
||||
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
|
||||
"eeg-duration-min": ("decimal", ["DiagnosticReport"]),
|
||||
"eeg-age-months": ("decimal", ["DiagnosticReport"]),
|
||||
"eeg-channels": ("integer", ["DiagnosticReport"]),
|
||||
"eeg-check-decisive": ("boolean", ["Observation"]),
|
||||
"eeg-z": ("decimal", ["Observation", "Observation.component"]),
|
||||
"eeg-outside": ("integer", ["Observation", "Observation.component"]),
|
||||
"curve-centiles": (None, ["Observation"]),
|
||||
"association-model-version": ("string", ["RiskAssessment"]),
|
||||
"association-cohort": ("integer", ["RiskAssessment"]),
|
||||
"association-level": ("string", ["RiskAssessment"]),
|
||||
"association-reliable": ("boolean", ["RiskAssessment.prediction"]),
|
||||
"association-headline": ("boolean", ["RiskAssessment.prediction"]),
|
||||
"association-odds-ratio": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"association-ci-low": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"association-ci-high": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"association-q": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"association-reference-probability": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"association-same-direction": ("boolean", ["RiskAssessment.prediction"]),
|
||||
"ados2-domain": ("Coding", ["Observation.component"]),
|
||||
"ados2-subdomain": ("Coding", ["Observation.component"]),
|
||||
# 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"]),
|
||||
"tea-eeg-alteration": ("Coding", ["Patient"]),
|
||||
"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("-"))
|
||||
|
||||
|
||||
@@ -168,11 +144,12 @@ def _day(value) -> str | None:
|
||||
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
|
||||
|
||||
|
||||
def _moment(value) -> datetime | 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))
|
||||
return found if found.tzinfo else found.replace(tzinfo=UTC)
|
||||
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
|
||||
|
||||
|
||||
def coding(system: str, code: str) -> dict:
|
||||
@@ -189,11 +166,31 @@ 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
|
||||
|
||||
|
||||
def report_facts(row: dict) -> list[dict]:
|
||||
found = []
|
||||
for column, name in _REPORT_FACTS.items():
|
||||
if (value := row.get(column)) is not None:
|
||||
kind = EXTENSIONS[name][0]
|
||||
found.append(ext(name, kind, {"integer": int, "date": _day}.get(kind, str)(value)))
|
||||
return found
|
||||
|
||||
|
||||
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"]
|
||||
@@ -207,18 +204,9 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
|
||||
if row.get("priority"):
|
||||
priority = coding("follow-up-priority", row["priority"])
|
||||
found["extension"].append(ext("follow-up-priority", "Coding", priority))
|
||||
if status_system == "tea-follow-up-status":
|
||||
for field, name, kind in (
|
||||
("step", "tea-step", "code"),
|
||||
("age_group", "tea-age-group", "code"),
|
||||
("case", "tea-case", "code"),
|
||||
("eeg_result", "tea-eeg-result", "code"),
|
||||
("mchat_score", "tea-mchat", "decimal"),
|
||||
("css", "tea-css", "integer"),
|
||||
("alterations", "tea-alterations", "integer"),
|
||||
):
|
||||
if row.get(field) is not None:
|
||||
found.setdefault("extension", []).append(ext(name, kind, row[field]))
|
||||
found.setdefault("extension", []).extend(_tea_listed(row))
|
||||
if not found["extension"]:
|
||||
del found["extension"]
|
||||
if row.get("names"):
|
||||
found["name"] = [{"text": n} for n in row["names"]]
|
||||
if row.get("identifiers"):
|
||||
@@ -229,7 +217,27 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
|
||||
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"]))
|
||||
for key, system in (("case", "tea-case"), ("eeg_status", "tea-eeg-status")):
|
||||
if row.get(key):
|
||||
found.append(ext(system, "Coding", coding(system, row[key])))
|
||||
for altered in row.get("alterations") or []:
|
||||
found.append(ext("tea-eeg-alteration", "Coding", coding("tea-eeg-alteration", altered)))
|
||||
if row.get("last_eeg"):
|
||||
found.append(ext("tea-last-eeg", "date", _day(row["last_eeg"])))
|
||||
for key, name in (("mchat_score", "mchat-score"), ("ados2_css", "ados2-css")):
|
||||
if row.get(key) is not None:
|
||||
found.append(ext(name, "integer", int(row[key])))
|
||||
return found
|
||||
|
||||
|
||||
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"}],
|
||||
@@ -237,6 +245,7 @@ def replaced_patient(person_id: str, replaced_by: str) -> Patient:
|
||||
|
||||
|
||||
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:
|
||||
@@ -253,6 +262,8 @@ 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():
|
||||
@@ -265,13 +276,16 @@ 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)
|
||||
effective = _day(row.get(root.date))
|
||||
container = _id(study, person, *key)
|
||||
container = _id(study, person, *key) # its report, or the encounter its notes are of
|
||||
visit = "report" not in spec.events
|
||||
observations = []
|
||||
for name, f in spec.fields.items():
|
||||
@@ -287,7 +301,7 @@ def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> l
|
||||
**({"effectiveDateTime": effective} if effective else {}),
|
||||
**_value(f, row[name]),
|
||||
})) # fmt: skip
|
||||
if visit:
|
||||
if visit: # a study without a report (a consultation): the encounter its values are of
|
||||
if not observations:
|
||||
return []
|
||||
encounter = Encounter.model_validate({
|
||||
@@ -317,6 +331,9 @@ def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> l
|
||||
|
||||
|
||||
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"])
|
||||
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
|
||||
if row.get("icd10"):
|
||||
@@ -345,6 +362,8 @@ def condition(row: dict) -> Condition:
|
||||
|
||||
|
||||
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",
|
||||
@@ -356,10 +375,13 @@ def procedure(row: dict, domain: str = "cacu") -> Procedure:
|
||||
}) # fmt: skip
|
||||
|
||||
|
||||
SCENARIO_SEPARATOR = " | "
|
||||
SCENARIO_SEPARATOR = " | " # as models.survival joins them
|
||||
|
||||
|
||||
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"))
|
||||
@@ -372,11 +394,10 @@ def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
|
||||
**({"extension": interval} if interval else {}),
|
||||
}) # fmt: skip
|
||||
model = row["model"]
|
||||
scored_at = _moment(row["scored_at"])
|
||||
return RiskAssessment.model_validate({
|
||||
"resourceType": "RiskAssessment",
|
||||
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
|
||||
"meta": {"lastUpdated": scored_at.isoformat() if scored_at is not None else None},
|
||||
"meta": {"lastUpdated": _instant(row["scored_at"])},
|
||||
"status": "final",
|
||||
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
|
||||
"display": models.title(model)}],
|
||||
@@ -395,6 +416,7 @@ SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variab
|
||||
|
||||
|
||||
def measure_id(code: str) -> str:
|
||||
"""A measure's FHIR id (ids allow no underscore)."""
|
||||
return code.lower().replace("_", "-")
|
||||
|
||||
|
||||
@@ -402,6 +424,7 @@ 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
|
||||
@@ -409,6 +432,7 @@ 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", ())]
|
||||
|
||||
@@ -418,6 +442,8 @@ 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
|
||||
group: dict = {
|
||||
@@ -450,6 +476,9 @@ def measure(m, domain: str) -> Measure:
|
||||
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,
|
||||
@@ -464,14 +493,6 @@ def extensions() -> list[StructureDefinition]:
|
||||
found = []
|
||||
for name, (value_type, contexts) in EXTENSIONS.items():
|
||||
url = EXTENSION + name
|
||||
elements = [
|
||||
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
|
||||
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
|
||||
"type": [{"code": value_type}]},
|
||||
] if value_type else [
|
||||
{"id": "Extension.extension", "path": "Extension.extension", "min": 1},
|
||||
{"id": "Extension.value[x]", "path": "Extension.value[x]", "max": "0"},
|
||||
] # fmt: skip
|
||||
found.append(StructureDefinition.model_validate({
|
||||
"resourceType": "StructureDefinition", "id": name, "url": url,
|
||||
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
|
||||
@@ -482,14 +503,16 @@ def extensions() -> list[StructureDefinition]:
|
||||
"differential": {"element": [
|
||||
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
|
||||
else "1"},
|
||||
*elements[:-1],
|
||||
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
|
||||
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
|
||||
elements[-1],
|
||||
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
|
||||
"type": [{"code": value_type}]},
|
||||
]},
|
||||
})) # fmt: skip
|
||||
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"),
|
||||
@@ -516,4 +539,6 @@ def search_parameters() -> list[SearchParameter]:
|
||||
|
||||
|
||||
def conformance() -> list[Resource]:
|
||||
"""Everything our resources declare: what the validator loads, and what the
|
||||
CapabilityStatement points to."""
|
||||
return [*code_systems(), *extensions(), *search_parameters()]
|
||||
|
||||
+28
-3
@@ -1,3 +1,15 @@
|
||||
"""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
|
||||
@@ -14,10 +26,18 @@ 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 {}
|
||||
@@ -29,6 +49,7 @@ 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", ""))
|
||||
@@ -40,6 +61,7 @@ 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", []):
|
||||
@@ -64,7 +86,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
|
||||
return codings[0].get("code") if codings else None # kept as sent: held, saying why
|
||||
for key in ("valueBoolean", "valueString", "valueInteger"):
|
||||
if key in observation:
|
||||
return observation[key]
|
||||
@@ -76,9 +98,12 @@ 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)
|
||||
named = _entries(bundle)
|
||||
sent = {f"{r['resourceType']}/{r['id']}": r for r in named.values()}
|
||||
sent = resources(bundle)
|
||||
named = _entries(bundle) # what a reference may name
|
||||
|
||||
def subject(r: dict) -> dict | None:
|
||||
return named.get((r.get("subject") or {}).get("reference", ""))
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
"""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])
|
||||
|
||||
+160
-67
@@ -1,3 +1,18 @@
|
||||
"""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
|
||||
@@ -9,7 +24,7 @@ from typing import ClassVar
|
||||
|
||||
from fhir.resources.R4B.measurereport import MeasureReport
|
||||
|
||||
from core.fhir import EXTENSION, _moment, measure_url, stratifier_code
|
||||
from core.fhir import EXTENSION, measure_url, stratifier_code
|
||||
|
||||
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
|
||||
IMPROVEMENT = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
|
||||
@@ -21,10 +36,11 @@ NO_BIOPSY = "no_biopsy"
|
||||
@dataclass(frozen=True)
|
||||
class Period:
|
||||
start: date
|
||||
end: date
|
||||
end: date # exclusive
|
||||
|
||||
@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
|
||||
@@ -41,13 +57,14 @@ class Period:
|
||||
return self.start.isoformat(), self.end.isoformat()
|
||||
|
||||
def __contains__(self, day) -> bool:
|
||||
if isinstance(day, str):
|
||||
if isinstance(day, str): # ISO days sort as the days they name
|
||||
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):
|
||||
return value
|
||||
if isinstance(value, datetime):
|
||||
@@ -57,10 +74,20 @@ 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))
|
||||
return found if found.tzinfo else found.replace(tzinfo=UTC)
|
||||
|
||||
|
||||
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
|
||||
@@ -72,8 +99,13 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
|
||||
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
|
||||
|
||||
|
||||
Stratum = tuple[str, Callable[[dict, "Period"], str]]
|
||||
Overlap = tuple[str, dict[str, Callable[[dict], bool]]]
|
||||
# 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]"]]
|
||||
|
||||
|
||||
def groups(value: "str | list[str]") -> list[str]:
|
||||
return [value] if isinstance(value, str) else value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -83,9 +115,13 @@ 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]:
|
||||
@@ -97,17 +133,26 @@ def wilson(k: int, n: int) -> tuple[float, float]:
|
||||
|
||||
@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
|
||||
order: Callable[[dict], tuple] | None = None
|
||||
levels: tuple[tuple[str, Callable[[dict], bool]], ...] = ()
|
||||
unit: str = "person_id"
|
||||
date: str = "sample_date"
|
||||
overlaps: tuple[Overlap, ...] = ()
|
||||
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:
|
||||
mine = [r for r in rows if r[self.date] in period and self.denominator(r)]
|
||||
if self.order:
|
||||
mine = list({r[self.unit]: r for r in sorted(mine, key=self.order)}.values())
|
||||
den = {r[self.unit]: r for r in mine}
|
||||
num = {r[self.unit] for r in mine if self.numerator(r)}
|
||||
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
|
||||
@@ -115,18 +160,19 @@ class Proportion:
|
||||
for name, stratum in self.strata:
|
||||
values: dict[str, dict[str, int]] = {}
|
||||
for unit, row in den.items():
|
||||
cell = values.setdefault(
|
||||
stratum(row, period),
|
||||
{"initial-population": 0, "denominator": 0, "numerator": 0},
|
||||
)
|
||||
cell["initial-population"] += 1
|
||||
cell["denominator"] += 1
|
||||
cell["numerator"] += unit in num
|
||||
for value in groups(stratum(row, period)):
|
||||
cell = values.setdefault(
|
||||
value, {"initial-population": 0, "denominator": 0, "numerator": 0}
|
||||
)
|
||||
cell["initial-population"] += 1
|
||||
cell["denominator"] += 1
|
||||
cell["numerator"] += unit in num
|
||||
strata[name] = values
|
||||
for name, groups in self.overlaps:
|
||||
strata[name] = {value: {"initial-population": len(den), "denominator": len(den),
|
||||
"numerator": sum(belongs(row) for row in den.values())}
|
||||
for value, belongs in groups.items()} # fmt: skip
|
||||
if self.levels and den:
|
||||
strata["level"] = {
|
||||
level: {**found, "numerator": len({r[self.unit] for r in mine if meets(r)})}
|
||||
for level, meets in self.levels
|
||||
}
|
||||
if not den:
|
||||
return Result(found, strata=strata)
|
||||
low, high = wilson(len(num), len(den))
|
||||
@@ -134,11 +180,16 @@ 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
|
||||
@@ -147,6 +198,7 @@ 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:
|
||||
@@ -161,37 +213,53 @@ class Composition:
|
||||
for name, stratum in (("category", lambda row, p: self.category(row)), *self.strata):
|
||||
values: dict[str, dict[str, int]] = {}
|
||||
for row in chosen.values():
|
||||
value = stratum(row, period)
|
||||
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
|
||||
for value in groups(stratum(row, period)):
|
||||
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:
|
||||
for name, stratum in self.strata: # each also by category
|
||||
pairs: dict[tuple[str, str], dict[str, int]] = {}
|
||||
for row in chosen.values():
|
||||
key = (stratum(row, period), self.category(row))
|
||||
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
|
||||
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
|
||||
n = len(chosen)
|
||||
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
|
||||
crossed=crossed) # fmt: skip
|
||||
|
||||
|
||||
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]}
|
||||
q1, median, q3 = statistics.quantiles(values, n=4, method="inclusive")
|
||||
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
|
||||
horizon: int
|
||||
units: Callable[[dict], bool] = lambda row: True
|
||||
ended: str | None = None
|
||||
strata: tuple[Stratum, ...] = ()
|
||||
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
|
||||
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
|
||||
@@ -199,6 +267,9 @@ class Duration:
|
||||
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:
|
||||
for value in groups(stratum(row, period)):
|
||||
grouped[name].setdefault(value, []).append(measured[-1])
|
||||
stop = as_day(row.get(self.ended)) if self.ended else None
|
||||
done = has or (stop is not None and stop <= cutoff)
|
||||
pending = not done and (cutoff - as_day(row[self.start])).days < self.horizon
|
||||
@@ -206,15 +277,21 @@ class Duration:
|
||||
found = {"initial-population": initial, "measure-observation": len(measured)}
|
||||
if not measured:
|
||||
return Result(found)
|
||||
if len(measured) == 1:
|
||||
q1 = median = q3 = measured[0]
|
||||
else:
|
||||
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
|
||||
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
|
||||
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
|
||||
|
||||
|
||||
@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"
|
||||
|
||||
@@ -233,11 +310,14 @@ class RiskBand:
|
||||
|
||||
@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], ...]
|
||||
unit: str = "person_id"
|
||||
exit_inclusive: bool = True
|
||||
|
||||
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
|
||||
found = {}
|
||||
@@ -245,8 +325,6 @@ class AtEnd:
|
||||
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
|
||||
if gone == period.start and not self.exit_inclusive:
|
||||
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
|
||||
if reached:
|
||||
@@ -255,12 +333,17 @@ class AtEnd:
|
||||
|
||||
|
||||
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]
|
||||
@@ -290,38 +373,28 @@ 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
|
||||
strata: tuple[Stratum, ...] = ()
|
||||
kind: str = "composition"
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
units = [(r, s) for r, s in self.population.units(rows, period).values() if self.admit(s)]
|
||||
strata: dict[str, dict[str, dict[str, int]]] = {}
|
||||
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {
|
||||
(name, "category"): {} for name, _ in self.strata
|
||||
}
|
||||
strata["category"] = {}
|
||||
strata.update((name, {}) for name, _ in self.strata)
|
||||
for row, state in units:
|
||||
category = strata["category"].setdefault(state, {"initial-population": 0})
|
||||
category["initial-population"] += 1
|
||||
for name, stratum in self.strata:
|
||||
value = stratum(row, period)
|
||||
cell = strata[name].setdefault(value, {"initial-population": 0})
|
||||
cell["initial-population"] += 1
|
||||
pair = crossed[name, "category"].setdefault(
|
||||
(value, state), {"initial-population": 0}
|
||||
)
|
||||
pair["initial-population"] += 1
|
||||
n = len(units)
|
||||
return Result(
|
||||
{"initial-population": n, "measure-observation": n}, strata=strata, crossed=crossed
|
||||
)
|
||||
states = [s for _, s in self.population.units(rows, period).values() if self.admit(s)]
|
||||
categories: dict[str, dict[str, int]] = {}
|
||||
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
|
||||
|
||||
|
||||
@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
|
||||
@@ -350,15 +423,19 @@ Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | Stat
|
||||
class Measure:
|
||||
id: str
|
||||
title: str
|
||||
rows: str
|
||||
rows: str # which gold rows it reads (see persistance.measures)
|
||||
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)
|
||||
known: str = "known_at"
|
||||
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.
|
||||
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
|
||||
|
||||
|
||||
@@ -369,9 +446,15 @@ 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 as_of is None:
|
||||
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
|
||||
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
|
||||
|
||||
def known(column: str, row: dict) -> bool:
|
||||
@@ -392,11 +475,15 @@ 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):
|
||||
if getattr(rule, "one_per_unit", False): # the same for every period: done once
|
||||
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):
|
||||
@@ -413,27 +500,33 @@ def _population(code: str, count: int) -> dict:
|
||||
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
|
||||
|
||||
|
||||
def _score(value: float, extensions: dict[str, float], unit: str | None) -> dict:
|
||||
return {
|
||||
"value": value,
|
||||
**({"unit": unit} if unit else {}),
|
||||
"extension": [{"url": EXTENSION + k, "valueDecimal": v} for k, v in extensions.items()],
|
||||
}
|
||||
|
||||
|
||||
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"] = {
|
||||
"value": result.score,
|
||||
**({"unit": result.unit} if result.unit else {}),
|
||||
"extension": [{"url": EXTENSION + k, "valueDecimal": v}
|
||||
for k, v in result.score_extensions.items()],
|
||||
} # fmt: skip
|
||||
elif measure.rule.kind == "composition":
|
||||
group["measureScore"] = _score(result.score, result.score_extensions, result.unit)
|
||||
elif measure.rule.kind == "composition": # a cohort scores its count
|
||||
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()]}
|
||||
"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()
|
||||
] + [
|
||||
@@ -447,7 +540,7 @@ def report(
|
||||
found = {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"type": "summary", # with no score when nothing in the period could be measured
|
||||
"measure": f"{measure_url(measure.id)}|{measure.version}",
|
||||
"period": {"start": period.start.isoformat(),
|
||||
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
|
||||
|
||||
+5
-1
@@ -1,3 +1,6 @@
|
||||
"""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",
|
||||
@@ -14,9 +17,10 @@ TITLES: dict[str, str] = {
|
||||
"tea.eeg-spindles-n3": "Curva por edad: husos de sueño N3",
|
||||
"tea.eeg-spindle-topography-n2": "Curva por edad: topografía de husos N2",
|
||||
"tea.eeg-spindle-topography-n3": "Curva por edad: topografía de husos N3",
|
||||
"tea.ados2_association": "Relación del EEG con el ADOS-2",
|
||||
"tea.eeg-ados2": "Relación del EEG con el ADOS-2",
|
||||
}
|
||||
|
||||
|
||||
def title(model: str) -> str:
|
||||
"""`model` (`<domain>.<name>`) as the pages name it."""
|
||||
return TITLES.get(model, model.split(".", 1)[-1])
|
||||
|
||||
+95
-160
@@ -1,3 +1,11 @@
|
||||
"""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
|
||||
@@ -18,16 +26,21 @@ from pydantic import (
|
||||
from core import catalog, sources
|
||||
from core.schema import ENTITIES
|
||||
|
||||
ID_PATTERN = r"^[a-z][a-z0-9_]*$"
|
||||
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
|
||||
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
|
||||
|
||||
|
||||
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."""
|
||||
extra: dict[str, Any] = {}
|
||||
if options:
|
||||
listed = [{"value": k, "label": v} for k, v in options.items()]
|
||||
@@ -46,55 +59,41 @@ class Position(BaseModel):
|
||||
|
||||
class Node(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1)
|
||||
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
|
||||
|
||||
id: Id
|
||||
inputs: list[Id] = []
|
||||
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
|
||||
position: Position | None = None
|
||||
position: Position | None = None # where the canvas drew it
|
||||
|
||||
|
||||
class Guided(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"How the Conectar dialog drew a source: its type (core.sources) "
|
||||
"and the answers given.\n"
|
||||
"The node's dlt fields are made from them; drawn by hand "
|
||||
'("Avanzado"), a node has none.'
|
||||
)
|
||||
},
|
||||
)
|
||||
"""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):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"One table, file set or API resource, copied as it is (dlt). "
|
||||
"Merged on the source's\n"
|
||||
"own primary key or `primary_key`; replaced whole when it has "
|
||||
"none."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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[
|
||||
resource: Annotated[ # which resource, when the source has several
|
||||
str | None,
|
||||
_says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True),
|
||||
] = None
|
||||
then: Annotated[
|
||||
then: Annotated[ # a dlt transformer piped after (file contents, Excel)
|
||||
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
|
||||
] = None
|
||||
primary_key: Annotated[
|
||||
@@ -105,25 +104,21 @@ 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 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", {})):
|
||||
if MASK not in repr(guided.get("answers", {})): # masked: shown, not run
|
||||
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
|
||||
return data
|
||||
|
||||
|
||||
class Read(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
|
||||
|
||||
kind: Literal["read"] = "read"
|
||||
column: Annotated[
|
||||
@@ -149,18 +144,9 @@ class Condition(BaseModel):
|
||||
|
||||
|
||||
class Route(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Only the rows where every condition holds (e.g. reports titled "
|
||||
'"Citología"). An\n'
|
||||
"`otherwise` route takes the rows of its input that none of the "
|
||||
"other routes on that\n"
|
||||
"input take (documents nobody recognises, for a reviewer), then "
|
||||
"its own conditions."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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")] = []
|
||||
@@ -170,50 +156,37 @@ class Route(Node):
|
||||
|
||||
|
||||
class Map(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Columns to platform fields, the site's codes translated by its "
|
||||
"ConceptMap\n"
|
||||
"(core.concept_map), and its date formats."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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[
|
||||
fields: Annotated[ # platform field -> column
|
||||
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
|
||||
]
|
||||
concept_map: Annotated[
|
||||
concept_map: Annotated[ # the site's codes in platform terms
|
||||
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
|
||||
] = None
|
||||
formats: Annotated[
|
||||
formats: Annotated[ # platform field -> strptime format
|
||||
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):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Platform fields read from text, each kept with the text it was "
|
||||
"read from.\n"
|
||||
"\n"
|
||||
"`auto` asks the LLM when one is configured and answering, else "
|
||||
"applies `patterns`;\n"
|
||||
"with neither, the row is held. Patterns are regexes with one "
|
||||
"group, per field (the\n"
|
||||
"LLM can propose them from sample documents); their values go "
|
||||
"through the ConceptMap\n"
|
||||
"and `formats` as in `map`."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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)
|
||||
@@ -230,9 +203,11 @@ class Extract(Node):
|
||||
), # fmt: skip
|
||||
] = "auto"
|
||||
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
|
||||
patterns: Annotated[
|
||||
patterns: Annotated[ # platform field -> regex with one group
|
||||
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"),
|
||||
@@ -249,57 +224,15 @@ 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))
|
||||
|
||||
|
||||
class Edf(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"EDF files (a column of file hashes) to the facts their header holds: "
|
||||
"patient code, sex,\n"
|
||||
"birth date, recording date, record code, duration and channel count, as "
|
||||
"`edf_*` columns.\n"
|
||||
"An unreadable file keeps its row with `edf_error` set.\n"
|
||||
"\n"
|
||||
"Use a filesystem source (`dlt.sources.filesystem:filesystem`) with the "
|
||||
"uploads folder as\n"
|
||||
'`bucket_url`, `file_glob: "*.edf"`, and `then: '
|
||||
'"persistance.readers:read_bytes"`. Read its\n'
|
||||
"`content` column with this node. Map `edf_patient_code`, `edf_birth_date`, "
|
||||
"and `edf_sex` to\n"
|
||||
"identity's `record_number`, `birth_date`, and `sex`, using the site's "
|
||||
"formats and ConceptMap.\n"
|
||||
"\n"
|
||||
"The patient code must match the hospital's record number including its "
|
||||
"prefix. Feed the\n"
|
||||
"identity map into the pipeline's link node alongside the hospital identity "
|
||||
"source. Map\n"
|
||||
"`edf_study_date` to `study_date` (format `%Y-%m-%d`), `edf_record_code` to "
|
||||
"`lab_record_id`,\n"
|
||||
"and `content` to `edf`, then feed that map and the link into a target with "
|
||||
"entity `eeg`."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
kind: Literal["edf"] = "edf"
|
||||
column: str
|
||||
|
||||
|
||||
class Fhir(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"FHIR R4 Bundles a standard hospital sent (a column of their "
|
||||
"JSON) as rows of one\n"
|
||||
"entity: identity, death or a study (core.fhir_in). The sender's "
|
||||
"own codes go through\n"
|
||||
"its ConceptMap."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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"
|
||||
@@ -308,13 +241,11 @@ class Fhir(Node):
|
||||
|
||||
|
||||
class Join(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={"description": "Two inputs side by side where their columns match."}
|
||||
)
|
||||
"""Two inputs side by side where their columns match."""
|
||||
|
||||
inputs_allowed = (2, 2)
|
||||
kind: Literal["join"] = "join"
|
||||
on: Annotated[
|
||||
on: Annotated[ # (left column, right column)
|
||||
list[tuple[str, str]],
|
||||
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
|
||||
]
|
||||
@@ -331,28 +262,18 @@ IDENTIFIERS = ("record_number", "curp", "nss")
|
||||
|
||||
|
||||
class Link(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Identity rows from every input, grouped into persons (Splink).\n"
|
||||
"\n"
|
||||
"Two records are the same person when any rule holds (Splink's "
|
||||
"SQL rule syntax, `l.`\n"
|
||||
"and `r.` for the two records); persons are the connected "
|
||||
"groups. A person whose\n"
|
||||
"records disagree on birth date or sex is held for review as a "
|
||||
"whole. Pairs Splink\n"
|
||||
"scores above `review` that ended up apart are queued as "
|
||||
"possible matches."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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[
|
||||
rules: Annotated[ # empty: the defaults for `fields` (see default_rules)
|
||||
list[str],
|
||||
_says(
|
||||
"Reglas",
|
||||
@@ -366,6 +287,8 @@ 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"
|
||||
@@ -378,16 +301,8 @@ class Link(Node):
|
||||
|
||||
|
||||
class Target(Node):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Rows of platform fields into one platform entity, each row "
|
||||
"given its person by the\n"
|
||||
"one `link` node among the inputs. Rule breaks are held for "
|
||||
"review."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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"
|
||||
@@ -405,8 +320,7 @@ class Target(Node):
|
||||
|
||||
|
||||
AnyNode = Annotated[
|
||||
Source | Read | Route | Map | Extract | Edf | Fhir | Join | Link | Target,
|
||||
Field(discriminator="kind"),
|
||||
Source | Read | Route | Map | Extract | Fhir | Join | Link | Target, Field(discriminator="kind")
|
||||
]
|
||||
|
||||
|
||||
@@ -435,14 +349,15 @@ 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"
|
||||
HELD = "_held"
|
||||
QUOTES = "_quotes"
|
||||
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
|
||||
|
||||
|
||||
def matches(node: Route, row: dict[str, Any]) -> bool:
|
||||
@@ -461,6 +376,7 @@ 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)
|
||||
@@ -473,20 +389,25 @@ def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list
|
||||
return out
|
||||
|
||||
|
||||
Codes = dict[str, dict[str, str]]
|
||||
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
|
||||
|
||||
|
||||
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 = raw.strip()
|
||||
raw = _SPACE.sub(" ", raw.strip()) # a value read across a line break is one value
|
||||
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:
|
||||
if " " not in fmt: # OCR may split a number ("25/01/1 967")
|
||||
raw = "".join(raw.split())
|
||||
try:
|
||||
return datetime.strptime(raw, fmt).date()
|
||||
@@ -503,6 +424,7 @@ 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:
|
||||
@@ -514,6 +436,7 @@ _SPACE = re.compile(r"\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
|
||||
@@ -521,6 +444,8 @@ def grounded(quote: str | None, text: str) -> bool:
|
||||
|
||||
|
||||
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 = {}, {}, []
|
||||
@@ -536,6 +461,8 @@ 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 = {}, {}
|
||||
for field, pattern in node.patterns.items():
|
||||
if found := re.search(pattern, text, re.IGNORECASE):
|
||||
@@ -547,6 +474,8 @@ 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()
|
||||
@@ -574,6 +503,8 @@ 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"}
|
||||
|
||||
@@ -589,6 +520,8 @@ def _masked_source(n: "Source") -> "Source":
|
||||
|
||||
|
||||
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})
|
||||
|
||||
@@ -605,6 +538,8 @@ 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
|
||||
|
||||
+13
-8
@@ -1,3 +1,11 @@
|
||||
"""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
|
||||
@@ -13,6 +21,8 @@ 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",
|
||||
@@ -29,14 +39,7 @@ class Entity(BaseModel):
|
||||
|
||||
|
||||
class Identity(Entity):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"What a record says about whom it belongs to. "
|
||||
"Input to linkage, never trusted alone."
|
||||
)
|
||||
}
|
||||
)
|
||||
"""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")
|
||||
@@ -48,6 +51,8 @@ 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
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
"""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
|
||||
@@ -10,18 +25,18 @@ from pydantic import BaseModel, ConfigDict, model_validator
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
FieldType = Literal[
|
||||
"text",
|
||||
"text", # a line of text
|
||||
"number",
|
||||
"password",
|
||||
"select",
|
||||
"folder",
|
||||
"server_file",
|
||||
"upload",
|
||||
"url",
|
||||
"oauth",
|
||||
"table",
|
||||
"format",
|
||||
"columns",
|
||||
"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
|
||||
]
|
||||
|
||||
|
||||
@@ -39,9 +54,9 @@ class FieldSpec(BaseModel):
|
||||
placeholder: str = ""
|
||||
required: bool = True
|
||||
default: Any = None
|
||||
options: list[Option] = []
|
||||
provider: str | None = None
|
||||
advanced: bool = False
|
||||
options: list[Option] = [] # select
|
||||
provider: str | None = None # oauth: microsoft, google
|
||||
advanced: bool = False # shown under "Más opciones"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _complete(self):
|
||||
@@ -53,17 +68,10 @@ class FieldSpec(BaseModel):
|
||||
|
||||
|
||||
class Listing(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
'What "Probar conexión" shows: a database\'s tables (the '
|
||||
"resources of `source`, built\n"
|
||||
"from `args`), or the first rows the type's own node reads "
|
||||
"(files, records)."
|
||||
)
|
||||
},
|
||||
)
|
||||
"""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
|
||||
args: dict[str, Any] = {}
|
||||
@@ -76,7 +84,7 @@ class SourceType(BaseModel):
|
||||
description: str
|
||||
icon: str
|
||||
fields: dict[str, FieldSpec]
|
||||
source: str
|
||||
source: str # the dlt source or resource the node runs
|
||||
args: dict[str, Any] = {}
|
||||
resource: str | None = None
|
||||
then: str | None = None
|
||||
@@ -94,14 +102,11 @@ class SourceType(BaseModel):
|
||||
|
||||
|
||||
class Provider(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
json_schema_extra={
|
||||
"description": "A sign-in button's OAuth 2.0 provider (authorization code flow)."
|
||||
},
|
||||
)
|
||||
"""A sign-in button's OAuth 2.0 provider (authorization code flow)."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
env: str
|
||||
env: str # prefix of the server's settings for its app registration
|
||||
authorize_url: str
|
||||
token_url: str
|
||||
scope: str
|
||||
@@ -118,7 +123,7 @@ class Catalog(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
groups: dict[str, Group]
|
||||
providers: dict[str, Provider]
|
||||
formats: list[Option]
|
||||
formats: list[Option] # how a file is read: the `then` of a filesystem source
|
||||
types: dict[str, SourceType]
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -133,7 +138,7 @@ class Catalog(BaseModel):
|
||||
|
||||
|
||||
class MissingAnswer(ValueError):
|
||||
pass
|
||||
"""An answer the type needs was left empty; its message names it in plain words."""
|
||||
|
||||
|
||||
@cache
|
||||
@@ -175,7 +180,7 @@ _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
|
||||
return _DROP # a block whose every answer is empty (an optional token's auth)
|
||||
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}
|
||||
@@ -185,7 +190,7 @@ def _fill(template: Any, values: dict[str, Any]) -> Any:
|
||||
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]
|
||||
name = parts[0][1] # "{account}", or a part of it: "{account[drive_id]}"
|
||||
if values.get(_base(name)) in (None, ""):
|
||||
return _DROP
|
||||
value = _FORMAT.get_field(name, (), values)[0]
|
||||
@@ -194,6 +199,7 @@ 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):
|
||||
raise ValueError(f"{type_id}: no fields {sorted(unknown)}")
|
||||
@@ -209,6 +215,8 @@ 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 = {
|
||||
@@ -222,6 +230,8 @@ 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:
|
||||
return None
|
||||
@@ -238,13 +248,14 @@ 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):
|
||||
elif not _placeholders(part): # a fixed key the node lacks
|
||||
raise _NoMatch
|
||||
return
|
||||
if isinstance(template, list):
|
||||
@@ -259,9 +270,9 @@ def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
|
||||
return
|
||||
parts = list(_FORMAT.parse(template))
|
||||
if any(name and ("[" in name or "." in name) for _, name, _, _ in parts):
|
||||
raise _NoMatch
|
||||
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)
|
||||
_answer(found, parts[0][1], value) # the whole value, whatever its type
|
||||
return
|
||||
if not isinstance(value, str):
|
||||
raise _NoMatch
|
||||
@@ -286,6 +297,8 @@ 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,6 +325,9 @@ def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | 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:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# 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:
|
||||
title: Base de datos
|
||||
@@ -12,6 +15,9 @@ 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
|
||||
@@ -243,7 +249,7 @@ types:
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "persistance.readers:fsspec_files"
|
||||
args:
|
||||
args: # the signed-in user's own drive, by its id (msgraphfs single-drive mode)
|
||||
url: "msgd://{folder:path}"
|
||||
file_glob: "{pattern}"
|
||||
storage_options:
|
||||
|
||||
+22
-24
@@ -1,15 +1,18 @@
|
||||
from core import catalog
|
||||
"""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).
|
||||
CONFIRMING_ICD10 = ["F84.0"]
|
||||
NEUROLOGY = "pediatric_neurology"
|
||||
PREVALENCE_AGE = (16, 36)
|
||||
FOLLOW_UP_WINDOWS = (1, 3, 6, 12)
|
||||
|
||||
EEG_METRICS = ("posterior_rhythm", "spindles_n2", "spindles_n3", "paroxysmal_spikes",
|
||||
"anteroposterior_gradient") # fmt: skip
|
||||
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.
|
||||
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],
|
||||
@@ -19,26 +22,21 @@ 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"]
|
||||
|
||||
ADOS2_ITEMS: list[str] = [
|
||||
name for name, field in catalog.studies()["ados2"].fields.items()
|
||||
if field.type == "number" and not name.endswith("_total")
|
||||
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",
|
||||
"rapport_quality",
|
||||
] # fmt: skip
|
||||
RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_sensory_interest",
|
||||
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
return {
|
||||
k.lower(): v
|
||||
for k, v in globals().items()
|
||||
if k.isupper() and k not in ("ADOS2_CSS", "ASSOCIATION_BIOMARKERS")
|
||||
}
|
||||
|
||||
|
||||
ASSOCIATION_BIOMARKERS = {
|
||||
"spikes": "paroxysmal_spikes",
|
||||
"spindles": "spindles_n2",
|
||||
"posterior_rhythm": "posterior_rhythm",
|
||||
"gradient": "anteroposterior_gradient",
|
||||
}
|
||||
"""What dbt reads (`var('tea')`)."""
|
||||
return {k.lower(): v for k, v in globals().items() if k.isupper() and k != "ADOS2_CSS"}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
"""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
|
||||
from core.tea import ados2_items
|
||||
|
||||
TODDLER_BANDS = {True: (10, 16), False: (8, 14)}
|
||||
TODDLER_BANDS = {True: (10, 16), False: (8, 14)} # 20 months or younger: (mild, severe) totals
|
||||
|
||||
|
||||
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)
|
||||
@@ -17,13 +21,13 @@ 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]
|
||||
|
||||
module = row.get("module")
|
||||
social = domain(ados2_items.domain(module, "AS"))
|
||||
restricted = domain(ados2_items.domain(module, "CRR"))
|
||||
social = domain(tea.SOCIAL_AFFECT_ITEMS)
|
||||
restricted = domain(tea.RESTRICTED_REPETITIVE_ITEMS)
|
||||
return sum(social) + sum(restricted) if social and restricted else 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")
|
||||
if found is None or module is None:
|
||||
return None, None
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
import re
|
||||
from typing import NamedTuple
|
||||
|
||||
|
||||
class Item(NamedTuple):
|
||||
domain: str
|
||||
subdomain: str
|
||||
code: str
|
||||
title: str
|
||||
field: str
|
||||
|
||||
|
||||
DOMAINS = {
|
||||
"AS": "Afectación social (AS)",
|
||||
"CRR": "Comportamiento restringido y repetitivo (CRR)",
|
||||
}
|
||||
COMMUNICATION = "communication"
|
||||
RECIPROCAL = "reciprocal_social_interaction"
|
||||
RESTRICTED = "restricted_repetitive_behaviors"
|
||||
SUBDOMAINS = {
|
||||
COMMUNICATION: "Comunicación",
|
||||
RECIPROCAL: "Interacción social recíproca",
|
||||
RESTRICTED: "Comportamientos restringidos y repetitivos",
|
||||
}
|
||||
|
||||
ITEMS: dict[str, tuple[Item, ...]] = {
|
||||
"toddler": (
|
||||
Item(
|
||||
"AS",
|
||||
COMMUNICATION,
|
||||
"A-2",
|
||||
"Frecuencia de la vocalización espontánea dirigida a otros",
|
||||
"vocalization_directed",
|
||||
),
|
||||
Item("AS", COMMUNICATION, "A-7", "Señalar", "pointing"),
|
||||
Item("AS", COMMUNICATION, "A-8", "Gestos", "gestures"),
|
||||
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
|
||||
Item(
|
||||
"AS", RECIPROCAL, "B-4", "Expresiones faciales dirigidas a otros", "facial_expressions"
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-5",
|
||||
"Integración de la mirada y otras conductas durante las iniciaciones sociales",
|
||||
"gaze_integration",
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-6",
|
||||
"Disfrute compartido durante la interacción",
|
||||
"shared_enjoyment",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-7", "Respuesta al nombre", "response_to_name"),
|
||||
Item("AS", RECIPROCAL, "B-8", "Ignorar", "ignoring"),
|
||||
Item("AS", RECIPROCAL, "B-9", "Pedir", "requesting"),
|
||||
Item("AS", RECIPROCAL, "B-12", "Mostrar", "showing"),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-13",
|
||||
"Iniciación espontánea de la atención conjunta",
|
||||
"joint_attention_initiation",
|
||||
),
|
||||
Item(
|
||||
"AS", RECIPROCAL, "B-14", "Respuesta a la atención conjunta", "joint_attention_response"
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-15",
|
||||
"Características de las iniciaciones sociales",
|
||||
"social_overtures_quality",
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-16b",
|
||||
"Cantidad de las iniciaciones sociales/familiar o cuidador",
|
||||
"social_overtures_caregiver",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-18", "Calidad general de la relación", "rapport_quality"),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"A-3",
|
||||
"Entonación de las vocalizaciones o verbalizaciones",
|
||||
"intonation",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-1",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas",
|
||||
"unusual_sensory_interest",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-2",
|
||||
"Movimientos de manos y dedos / postura",
|
||||
"hand_finger_mannerisms",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-5",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados",
|
||||
"repetitive_interests",
|
||||
),
|
||||
),
|
||||
"module_1": (
|
||||
Item(
|
||||
"AS",
|
||||
COMMUNICATION,
|
||||
"A-2",
|
||||
"Frecuencia de la vocalización espontánea dirigida a otros",
|
||||
"vocalization_directed",
|
||||
),
|
||||
Item("AS", COMMUNICATION, "A-7", "Señalar", "pointing"),
|
||||
Item("AS", COMMUNICATION, "A-8", "Gestos", "gestures"),
|
||||
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
|
||||
Item(
|
||||
"AS", RECIPROCAL, "B-3", "Expresiones faciales dirigidas a otros", "facial_expressions"
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-4",
|
||||
"Integración de la mirada y otras conductas durante las iniciaciones sociales",
|
||||
"gaze_integration",
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-5",
|
||||
"Disfrute compartido durante la interacción",
|
||||
"shared_enjoyment",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-9", "Mostrar", "showing"),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-10",
|
||||
"Iniciación espontánea de la atención conjunta",
|
||||
"joint_attention_initiation",
|
||||
),
|
||||
Item(
|
||||
"AS", RECIPROCAL, "B-11", "Respuesta a la atención conjunta", "joint_attention_response"
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-12",
|
||||
"Características de las iniciaciones sociales",
|
||||
"social_overtures_quality",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"A-3",
|
||||
"Entonación de las vocalizaciones o verbalizaciones",
|
||||
"intonation",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"A-5",
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases",
|
||||
"stereotyped_language",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-1",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas",
|
||||
"unusual_sensory_interest",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-2",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos",
|
||||
"hand_finger_mannerisms",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-4",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados",
|
||||
"repetitive_interests",
|
||||
),
|
||||
),
|
||||
"module_2": (
|
||||
Item("AS", COMMUNICATION, "A-6", "Señalar", "pointing"),
|
||||
Item(
|
||||
"AS",
|
||||
COMMUNICATION,
|
||||
"A-7",
|
||||
"Gestos descriptivos, convencionales, instrumentales o informativos",
|
||||
"gestures",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-1", "Contacto visual inusual", "unusual_eye_contact"),
|
||||
Item(
|
||||
"AS", RECIPROCAL, "B-2", "Expresiones faciales dirigidas a otros", "facial_expressions"
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-3",
|
||||
"Disfrute compartido durante la interacción",
|
||||
"shared_enjoyment",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-5", "Mostrar", "showing"),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-6",
|
||||
"Iniciación espontánea de la atención conjunta",
|
||||
"joint_attention_initiation",
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-8",
|
||||
"Características de las iniciaciones sociales",
|
||||
"social_overtures_quality",
|
||||
),
|
||||
Item(
|
||||
"AS",
|
||||
RECIPROCAL,
|
||||
"B-11",
|
||||
"Cantidad de comunicación social recíproca",
|
||||
"reciprocal_communication",
|
||||
),
|
||||
Item("AS", RECIPROCAL, "B-12", "Calidad general de la relación", "rapport_quality"),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"A-4",
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases",
|
||||
"stereotyped_language",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-1",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas",
|
||||
"unusual_sensory_interest",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-2",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos",
|
||||
"hand_finger_mannerisms",
|
||||
),
|
||||
Item(
|
||||
"CRR",
|
||||
RESTRICTED,
|
||||
"D-4",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados",
|
||||
"repetitive_interests",
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def domain(module: str, name: str) -> list[str]:
|
||||
return [item.field for item in ITEMS.get(module, ()) if item.domain == name]
|
||||
|
||||
|
||||
def pattern(field: str) -> str:
|
||||
codes: dict[str, list[str]] = {}
|
||||
for items in ITEMS.values():
|
||||
for item in items:
|
||||
if item.field == field and item.code not in codes.setdefault(item.title, []):
|
||||
codes[item.title].append(item.code)
|
||||
alternatives = []
|
||||
for title, found in codes.items():
|
||||
code = found[0] if len(found) == 1 else f"(?:{'|'.join(found)})"
|
||||
words = r"\s+".join(re.escape(word) for word in title.split())
|
||||
alternatives.append(f"(?:{code}\\s+)?{words}")
|
||||
body = alternatives[0] if len(alternatives) == 1 else f"(?:{'|'.join(alternatives)})"
|
||||
return f"(?m)^{body}\\s+([0-3])\\s*$"
|
||||
|
||||
|
||||
def patterns() -> dict[str, str]:
|
||||
fields = dict.fromkeys(item.field for items in ITEMS.values() for item in items)
|
||||
return {field: pattern(field) for field in fields}
|
||||
@@ -0,0 +1,120 @@
|
||||
"""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")),
|
||||
3: ("gestures", ("toddler", "module_1", "module_2")),
|
||||
4: ("unusual_eye_contact", ("toddler", "module_1", "module_2")),
|
||||
5: ("facial_expressions", ("toddler", "module_1", "module_2")),
|
||||
6: ("gaze_integration", ("toddler", "module_1")),
|
||||
7: ("shared_enjoyment", ("toddler", "module_1", "module_2")),
|
||||
8: ("response_to_name", ("toddler",)),
|
||||
9: ("ignoring", ("toddler",)),
|
||||
10: ("requesting", ("toddler",)),
|
||||
11: ("showing", ("toddler", "module_1", "module_2")),
|
||||
12: ("joint_attention_initiation", ("toddler", "module_1", "module_2")),
|
||||
13: ("joint_attention_response", ("toddler", "module_1")),
|
||||
14: ("social_overtures_quality", ("toddler", "module_1", "module_2")),
|
||||
15: ("social_overtures_caregiver", ("toddler",)),
|
||||
16: ("reciprocal_communication", ("module_2",)),
|
||||
17: ("rapport_quality", ("toddler", "module_2")),
|
||||
18: ("intonation", ("toddler", "module_1")),
|
||||
19: ("stereotyped_language", ("module_1", "module_2")),
|
||||
20: ("unusual_sensory_interest", ("toddler", "module_1", "module_2")),
|
||||
21: ("hand_finger_mannerisms", ("toddler", "module_1", "module_2")),
|
||||
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),
|
||||
"frontal_midline": (6, 11, 12, 13, 14),
|
||||
"central": (21,),
|
||||
"parietal": (6, 13, 20),
|
||||
"temporal_left": (1, 16, 18, 19),
|
||||
"temporal_right": (4, 5, 8),
|
||||
"occipital": (4, 20),
|
||||
}
|
||||
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",
|
||||
"posterior_rhythm": "posterior_rhythm",
|
||||
"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")
|
||||
|
||||
|
||||
def item_code(n: int) -> str:
|
||||
return f"ados2_item_{n:02d}"
|
||||
|
||||
|
||||
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)]
|
||||
|
||||
out = [
|
||||
{
|
||||
"biomarker": "spikes",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spikes_{zone}",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for zone, numbers in ZONE_ITEMS.items()
|
||||
for k, o in outcomes(numbers)
|
||||
]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "spindles",
|
||||
"zone": zone,
|
||||
"predictor": f"z_spindles_{zone}",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
for zone in SPINDLE_ZONES
|
||||
]
|
||||
out += [
|
||||
{
|
||||
"biomarker": "posterior_rhythm",
|
||||
"zone": "posterior",
|
||||
"predictor": "z_posterior_rhythm",
|
||||
"kind": k,
|
||||
"outcome": o,
|
||||
}
|
||||
for k, o in outcomes(RHYTHM_ITEMS)
|
||||
]
|
||||
out.append(
|
||||
{
|
||||
"biomarker": "gradient",
|
||||
"zone": "global",
|
||||
"predictor": "z_gradient",
|
||||
"kind": "domain",
|
||||
"outcome": CSS,
|
||||
}
|
||||
)
|
||||
return out
|
||||
@@ -1,19 +0,0 @@
|
||||
import re
|
||||
|
||||
MIN_GROUP = 5
|
||||
FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/", re.IGNORECASE)
|
||||
|
||||
|
||||
def guard(version: dict) -> list[str]:
|
||||
problems = []
|
||||
n = version["metrics"].get("n_reference")
|
||||
if n is None:
|
||||
problems.append("cannot tell the reference group size (no n_reference metric)")
|
||||
elif n < MIN_GROUP:
|
||||
problems.append(f"reference group of {n:g} children is under {MIN_GROUP}")
|
||||
cutoff = version["params"].get("as_of", "")
|
||||
for field, label in (("params", "param"), ("tags", "tag"), ("reports", "report")):
|
||||
for key, value in version[field].items():
|
||||
if match := FORBIDDEN.search(value.replace(cutoff, "")):
|
||||
problems.append(f"{label} {key} holds a study code, date or path ({match[0]!r})")
|
||||
return problems
|
||||
@@ -1,212 +0,0 @@
|
||||
import hashlib
|
||||
|
||||
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
|
||||
from fhir.resources.R4B.observation import Observation
|
||||
from fhir.resources.R4B.riskassessment import RiskAssessment
|
||||
|
||||
from core import catalog, fhir, tea
|
||||
from core.measures import as_day
|
||||
from core.tea import ados2, ados2_items
|
||||
|
||||
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
|
||||
SITE_SYSTEMS = {"electrode": "eeg-electrode-10-20", "zone": "tea-eeg-zone"}
|
||||
BIOMARKER_METRIC = {
|
||||
"spikes": "paroxysmal_spikes",
|
||||
"spindles": "spindles_n2",
|
||||
"posterior_rhythm": "posterior_rhythm",
|
||||
"gradient": "anteroposterior_gradient",
|
||||
}
|
||||
|
||||
|
||||
def _interpretation(code):
|
||||
return [{"coding": [{"system": INTERPRETATION, "code": code}]}]
|
||||
|
||||
|
||||
def _extensions(row, fields):
|
||||
return [fhir.ext(name, kind, row[key]) for key, name, kind in fields
|
||||
if row.get(key) is not None] # fmt: skip
|
||||
|
||||
|
||||
def _ados2_id(person, day):
|
||||
return f"ados2-{person}-{fhir._day(day)}"
|
||||
|
||||
|
||||
def ados2_observation(row, birth):
|
||||
day = fhir._day(row["evaluation_date"])
|
||||
spec = catalog.studies()["ados2"]
|
||||
module = row.get("module")
|
||||
items = {item.field: item for item in ados2_items.ITEMS.get(module, ())}
|
||||
components = []
|
||||
for name in ("module", *items, *(i for i in tea.ADOS2_ITEMS if i not in items)):
|
||||
value = row.get(name)
|
||||
component = {"code": fhir.concept("catalog-field", f"ados2.{name}")}
|
||||
if item := items.get(name):
|
||||
component["code"]["coding"].append(fhir.coding(f"ados2-item-{module}", item.code))
|
||||
component["code"]["text"] = item.title
|
||||
component["extension"] = [
|
||||
fhir.ext("ados2-domain", "Coding", fhir.coding("ados2-domain", item.domain)),
|
||||
fhir.ext("ados2-subdomain", "Coding",
|
||||
fhir.coding("ados2-subdomain", item.subdomain)),
|
||||
] # fmt: skip
|
||||
if value is not None:
|
||||
component.update(fhir._value(spec.fields[name], value))
|
||||
components.append(component)
|
||||
css, classification = ados2.score(row, birth)
|
||||
return Observation(
|
||||
id=_ados2_id(row["person_id"], day),
|
||||
status="final",
|
||||
code=fhir.concept("study", "ados2"),
|
||||
subject=fhir.subject(row["person_id"]),
|
||||
effectiveDateTime=day,
|
||||
valueInteger=css,
|
||||
interpretation=[fhir.concept("tea-ados2-classification", classification)]
|
||||
if classification
|
||||
else None,
|
||||
component=components,
|
||||
)
|
||||
|
||||
|
||||
def eeg_study_id(person_id: str, study_date) -> str:
|
||||
return f"{person_id}|{as_day(study_date)}"
|
||||
|
||||
|
||||
def _eeg_report_id(person_id, study_date) -> str:
|
||||
key = eeg_study_id(person_id, study_date)
|
||||
return f"eeg-{hashlib.sha256(key.encode()).hexdigest()[:16]}"
|
||||
|
||||
|
||||
def eeg_report(row, results):
|
||||
valid = row["valid"]
|
||||
quality = "not_analyzed" if valid is None else "good" if valid else "bad"
|
||||
conclusions = [fhir.concept("tea-eeg-quality", quality)]
|
||||
if valid is not None:
|
||||
conclusions.append(fhir.concept("tea-eeg-validity", "valid" if valid else "not_valid"))
|
||||
extensions = _extensions(row, (
|
||||
("duration_min", "eeg-duration-min", "decimal"),
|
||||
("age_months", "eeg-age-months", "decimal"),
|
||||
("channels", "eeg-channels", "integer"),
|
||||
)) # fmt: skip
|
||||
return DiagnosticReport(
|
||||
id=_eeg_report_id(row["person_id"], row["study_date"]),
|
||||
status="registered" if valid is None else "final",
|
||||
code=fhir.concept("study", "eeg"),
|
||||
subject=fhir.subject(row["person_id"]),
|
||||
effectiveDateTime=fhir._day(row["study_date"]),
|
||||
conclusionCode=conclusions,
|
||||
extension=extensions or None,
|
||||
result=[{"reference": f"Observation/{r.id}"} for r in results] or None,
|
||||
)
|
||||
|
||||
|
||||
def _quantity(value, unit=None):
|
||||
return {"value": value, **({"unit": unit} if unit else {})}
|
||||
|
||||
|
||||
def _eeg_observation(row, system, *key, **fields):
|
||||
return Observation(
|
||||
id=fhir._id(system, row["person_id"], row["study_date"], row["edf"], *key),
|
||||
status="final",
|
||||
code=fhir.concept(system, row["code"]),
|
||||
subject=fhir.subject(row["person_id"]),
|
||||
effectiveDateTime=fhir._day(row["study_date"]),
|
||||
**fields,
|
||||
)
|
||||
|
||||
|
||||
def eeg_check(row):
|
||||
electrode = row.get("electrode")
|
||||
unit = row.get("unit")
|
||||
value = row.get("value")
|
||||
bounds = {key: _quantity(row[key], unit) for key in ("low", "high")
|
||||
if row.get(key) is not None} # fmt: skip
|
||||
return _eeg_observation(
|
||||
row, "tea-eeg-check", row["code"], electrode,
|
||||
valueQuantity=_quantity(value, unit) if value is not None else None,
|
||||
valueString=row.get("text") if value is None else None,
|
||||
referenceRange=[bounds] if bounds else None,
|
||||
interpretation=_interpretation("A" if row["abnormal"] else "N"),
|
||||
extension=[fhir.ext("eeg-check-decisive", "boolean", row["decisive"])],
|
||||
component=[{"code": fhir.concept(SITE_SYSTEMS["electrode"], electrode)}]
|
||||
if electrode else None,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _curve_extensions(row, *, centiles=False):
|
||||
if row.get("model") is None:
|
||||
return None
|
||||
extensions = _extensions(
|
||||
row, (("z", "eeg-z", "decimal"), ("outside", "eeg-outside", "integer"))
|
||||
)
|
||||
if centiles:
|
||||
extensions.append(fhir.ext("eeg-model", "string", row["model"]))
|
||||
parts = [{"url": key, "valueDecimal": row[key]} for key in ("p5", "median", "p95")
|
||||
if row.get(key) is not None] # fmt: skip
|
||||
if parts:
|
||||
extensions.append({"url": fhir.EXTENSION + "curve-centiles", "extension": parts})
|
||||
return extensions or None
|
||||
|
||||
|
||||
def eeg_metric(row, regions):
|
||||
components = [
|
||||
{
|
||||
"code": fhir.concept(SITE_SYSTEMS[site["kind"]], site["site"]),
|
||||
"valueQuantity": _quantity(site["value"]) if site["value"] is not None else None,
|
||||
"extension": _curve_extensions(site),
|
||||
}
|
||||
for site in regions
|
||||
]
|
||||
outside = row.get("outside") if row.get("model") is not None else None
|
||||
return _eeg_observation(
|
||||
row, "tea-eeg-metric", row["code"],
|
||||
valueQuantity=_quantity(row["value"]) if row["value"] is not None else None,
|
||||
component=components or None,
|
||||
extension=_curve_extensions(row, centiles=True),
|
||||
interpretation=_interpretation({-1: "L", 0: "N", 1: "H"}[outside])
|
||||
if outside is not None else None,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def association_risk(rows):
|
||||
def order(row):
|
||||
metric = BIOMARKER_METRIC[row["biomarker"]]
|
||||
q = row["q"]
|
||||
return not row.get(f"alt_{metric}"), q if q is not None else float("inf"), row["pair"]
|
||||
|
||||
head, *other = sorted(rows, key=order)
|
||||
predictions = []
|
||||
for index, row in enumerate((head, *other)):
|
||||
extensions = _extensions(row, (
|
||||
("odds_ratio", "association-odds-ratio", "decimal"),
|
||||
("ci_low", "association-ci-low", "decimal"),
|
||||
("ci_high", "association-ci-high", "decimal"),
|
||||
("q", "association-q", "decimal"),
|
||||
("reference_probability", "association-reference-probability", "decimal"),
|
||||
("same_direction", "association-same-direction", "boolean"),
|
||||
)) # fmt: skip
|
||||
extensions.append(fhir.ext("association-reliable", "boolean", row["n"] >= 20))
|
||||
if index == 0:
|
||||
extensions.append(fhir.ext("association-headline", "boolean", True))
|
||||
predictions.append(
|
||||
{
|
||||
"outcome": fhir.concept("tea-association", row["pair"]),
|
||||
"probabilityDecimal": row["probability"],
|
||||
"extension": extensions,
|
||||
}
|
||||
)
|
||||
person = head["person_id"]
|
||||
basis = [{"reference": f"DiagnosticReport/{_eeg_report_id(person, head['study_date'])}"}]
|
||||
if head["evaluation_date"] is not None:
|
||||
basis.append({"reference": f"Observation/{_ados2_id(person, head['evaluation_date'])}"})
|
||||
return RiskAssessment(
|
||||
id=f"tea-association-{person}",
|
||||
status="final",
|
||||
subject=fhir.subject(person),
|
||||
occurrenceDateTime=fhir._day(head["study_date"]),
|
||||
basis=basis,
|
||||
prediction=predictions,
|
||||
extension=_extensions(head, (
|
||||
("model", "association-model-version", "string"),
|
||||
("n_cohort", "association-cohort", "integer"),
|
||||
("level", "association-level", "string"),
|
||||
)),
|
||||
) # fmt: skip
|
||||
+81
-94
@@ -1,5 +1,15 @@
|
||||
"""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 decimal import Decimal, InvalidOperation
|
||||
|
||||
from core import tea
|
||||
from core.measures import as_day
|
||||
@@ -9,109 +19,86 @@ WINDOWS = tea.FOLLOW_UP_WINDOWS
|
||||
SORTS = ("-recent",)
|
||||
DEFAULT_HORIZON = None
|
||||
STATUS_SYSTEM = "tea-follow-up-status"
|
||||
PROCEDURES = ()
|
||||
REPORT_FACTS = {}
|
||||
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
|
||||
|
||||
FILTERS = {
|
||||
"tea-step": ("token", "step", ("eeg", "neurology", "psychology", "mchat_only")),
|
||||
"tea-case": ("token", "case", ("confirmed", "in_process", "not_confirmed")),
|
||||
"tea-eeg-result": ("token", "eeg_result", ("abnormal", "normal", "no_valid_eeg", "not_scored")),
|
||||
"tea-model": ("token", "eeg_scored", ("yes", "no")),
|
||||
"tea-age-group": ("token", "age_group", ("16-23", "24-29", "30-36", "no_data")),
|
||||
"tea-sex": ("token", "sex", ("female", "male")),
|
||||
"tea-alteration": ("token", None, tea.EEG_METRICS),
|
||||
"tea-mchat": ("number", "mchat_score", ()),
|
||||
"tea-css": ("number", "css", ()),
|
||||
}
|
||||
|
||||
def _by(day, cutoff: date) -> date | None:
|
||||
found = as_day(day)
|
||||
return found if found is not None and found <= cutoff else None
|
||||
|
||||
|
||||
def stage(row: dict, cutoff: date) -> str:
|
||||
reached = "mchat_only"
|
||||
for column, name in STEPS:
|
||||
if _by(row.get(column), cutoff):
|
||||
reached = name
|
||||
return reached
|
||||
|
||||
|
||||
def case(row: dict, cutoff: date) -> str:
|
||||
if _by(row.get("confirmed_date"), cutoff):
|
||||
return "confirmed"
|
||||
if _by(row.get("not_confirmed_date"), cutoff):
|
||||
return "not_confirmed"
|
||||
return "in_process"
|
||||
|
||||
|
||||
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
|
||||
out = []
|
||||
"""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:
|
||||
begins, ends = as_day(row["start_date"]), as_day(row["end_date"])
|
||||
if begins > cutoff or (ends is not None and ends < start):
|
||||
person = row["person_id"]
|
||||
if not _by(row.get("mchat_date"), cutoff):
|
||||
continue
|
||||
confirmed = as_day(row.get("confirmed_date"))
|
||||
not_confirmed = as_day(row.get("not_confirmed_date"))
|
||||
if confirmed is not None and confirmed <= cutoff:
|
||||
case = "confirmed"
|
||||
elif not_confirmed is not None and not_confirmed <= cutoff:
|
||||
case = "not_confirmed"
|
||||
children.setdefault(person, row)
|
||||
studied = _by(row.get("eeg_study_date"), cutoff)
|
||||
if row.get("eeg_id") and studied:
|
||||
eeg = eegs.setdefault(person, {}).setdefault(
|
||||
row["eeg_id"], {"date": studied, "valid": row.get("valid"), "altered": set()}
|
||||
)
|
||||
if row.get("metric") and row.get("outside"):
|
||||
side = "above" if row["outside"] > 0 else "below"
|
||||
eeg["altered"].add(f"{row['metric']}:{side}")
|
||||
out = []
|
||||
for person, row in children.items():
|
||||
steps = [d for c in DATES if (d := _by(row.get(c), cutoff))]
|
||||
recent = max(steps)
|
||||
if recent < start:
|
||||
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)
|
||||
if not valid:
|
||||
eeg_status, altered = "no_valid_eeg", []
|
||||
else:
|
||||
case = "in_process"
|
||||
css, classification = None, None
|
||||
if evaluated := as_day(row.get("ados2_date")):
|
||||
evaluation = {item: row.get(f"ados2_{item}") for item in tea.ADOS2_ITEMS}
|
||||
evaluation.update(module=row.get("ados2_module"), evaluation_date=evaluated)
|
||||
css, classification = ados2.score(evaluation, as_day(row["birth_date"]))
|
||||
out.append(
|
||||
{
|
||||
**row,
|
||||
"priority": None,
|
||||
"recent": row["step_date"],
|
||||
"case": case,
|
||||
"css": css,
|
||||
"classification": classification,
|
||||
"alterations": sum(bool(row.get(f"alt_{m}")) for m in tea.EEG_METRICS),
|
||||
}
|
||||
)
|
||||
return sorted(out, key=lambda row: (-as_day(row["recent"]).toordinal(), row["person_id"]))
|
||||
altered = sorted(study["altered"])
|
||||
eeg_status = "abnormal" if altered else "normal"
|
||||
css = None
|
||||
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
|
||||
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> str | None:
|
||||
return row.get("status")
|
||||
def status(row: dict, cutoff: date) -> None:
|
||||
"""A child's status exists only on the list."""
|
||||
return None
|
||||
|
||||
|
||||
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
|
||||
return rows
|
||||
|
||||
|
||||
def _limit(name: str, value: str) -> tuple[str, Decimal]:
|
||||
prefix = value[:2]
|
||||
try:
|
||||
limit = Decimal(value[2:])
|
||||
if prefix in ("ge", "le") and limit.is_finite():
|
||||
return prefix, limit
|
||||
except InvalidOperation:
|
||||
pass
|
||||
raise ValueError(f"invalid {name} value: {value}")
|
||||
|
||||
|
||||
def matches(row: dict, params: dict[str, list[str]]) -> bool:
|
||||
matched = True
|
||||
for name, values in params.items():
|
||||
kind, field, allowed = FILTERS[name]
|
||||
actual = row.get(field)
|
||||
if kind == "number":
|
||||
for value in values:
|
||||
prefix, limit = _limit(name, value)
|
||||
if actual is None or (actual < limit if prefix == "ge" else actual > limit):
|
||||
matched = False
|
||||
continue
|
||||
tokens = [token for value in values for token in value.split(",")]
|
||||
for token in tokens:
|
||||
if token not in allowed:
|
||||
raise ValueError(f"invalid {name} value: {token}")
|
||||
if name == "tea-alteration":
|
||||
actual = any(row.get(f"alt_{token}") for token in tokens)
|
||||
elif name == "tea-model":
|
||||
actual = ("yes" if actual else "no") in tokens
|
||||
else:
|
||||
actual = actual in tokens
|
||||
matched = matched and actual
|
||||
return matched
|
||||
|
||||
|
||||
def summary(rows: list[dict]) -> dict:
|
||||
valid = sum(row["eeg_id"] is not None for row in rows)
|
||||
return {
|
||||
"valid": valid,
|
||||
"not_valid": len(rows) - valid,
|
||||
"normal": sum(row["eeg_result"] == "normal" for row in rows),
|
||||
"abnormal": sum(row["eeg_result"] == "abnormal" for row in rows),
|
||||
"by_alteration": [
|
||||
{"alteration": metric, "patients": count}
|
||||
for metric in tea.EEG_METRICS
|
||||
if (count := sum(bool(row.get(f"alt_{metric}")) for row in rows))
|
||||
],
|
||||
}
|
||||
|
||||
+33
-139
@@ -1,16 +1,20 @@
|
||||
"""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 (
|
||||
NO_DATA,
|
||||
AtEnd,
|
||||
Composition,
|
||||
Measure,
|
||||
Proportion,
|
||||
StatusComposition,
|
||||
StatusDuration,
|
||||
StatusProportion,
|
||||
as_day,
|
||||
reached,
|
||||
)
|
||||
from core.tea import EEG_METRICS
|
||||
|
||||
DIAGNOSIS = AtEnd("mchat_date", "eeg_date", (
|
||||
("in_process", "mchat_date"), ("not_confirmed", "not_confirmed_date"),
|
||||
@@ -20,146 +24,36 @@ STEPS = AtEnd("mchat_date", "eeg_date", (
|
||||
("mchat_only", "mchat_date"), ("psychology", "psychology_date"),
|
||||
("neuropediatrics", "neuro_date"), ("eeg", "eeg_date"),
|
||||
)) # fmt: skip
|
||||
PREVALENCE = AtEnd("entry_date", "exit_date", (
|
||||
("in_population", "entry_date"), ("confirmed", "confirmed_date"),
|
||||
), exit_inclusive=False) # fmt: skip
|
||||
AGE = ("age_group", lambda row, p: row["age_group"])
|
||||
SEX = ("sex", lambda row, p: row.get("sex") or NO_DATA)
|
||||
AGE_SEX = ("age_sex", lambda row, p: f"{row['age_group']}|{row.get('sex') or NO_DATA}")
|
||||
ALTERATIONS = ("alteration", {m: lambda row, m=m: bool(row[f"alt_{m}"]) for m in EEG_METRICS})
|
||||
CONFIRMED = lambda row, state, p: state == "confirmed" # noqa: E731
|
||||
|
||||
MEASURES = {
|
||||
m.id: m
|
||||
for m in [
|
||||
Measure(
|
||||
"M21_DIAGNOSTICADOS_CON_EEG",
|
||||
"Porcentaje de pacientes con diagnóstico de TEA con EEG",
|
||||
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, AGE_SEX),
|
||||
),
|
||||
"increase",
|
||||
description=(
|
||||
"Of the children with a confirmed diagnosis at period end, how many already have a "
|
||||
"good-quality EEG. By age group at the first M-CHAT."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M22_DIAGNOSTICADOS_SIN_EEG",
|
||||
"Porcentaje de 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, AGE_SEX),
|
||||
),
|
||||
"decrease",
|
||||
description=("The complement of M21."),
|
||||
),
|
||||
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"), strata=(SEX,)
|
||||
),
|
||||
description=(
|
||||
"Children in the screening during the period by result: confirmed (a "
|
||||
"neuropediatrics note with F84.0) or in process."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M24_CONFIRMACION_DIAGNOSTICO",
|
||||
"Porcentaje de confirmación diagnóstica",
|
||||
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",
|
||||
"screening",
|
||||
StatusProportion(
|
||||
DIAGNOSIS,
|
||||
lambda row, s, p: s in ("confirmed", "in_process"),
|
||||
CONFIRMED,
|
||||
strata=(AGE, SEX, AGE_SEX),
|
||||
),
|
||||
"increase",
|
||||
description=(
|
||||
"Of the children confirmed or in process at period end, how many are confirmed."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M25_DIAS_MCHAT_DIAGNOSTICO",
|
||||
"Días de M-CHAT a diagnóstico positivo",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"),
|
||||
"decrease",
|
||||
description=(
|
||||
"Calendar days from the first M-CHAT to the neuropediatrics note with F84.0."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M26_DIAS_MCHAT_ADOS2",
|
||||
"Días de M-CHAT a ADOS-2",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"),
|
||||
"decrease",
|
||||
description=(
|
||||
"Calendar days from the first M-CHAT to the psychology note with the ADOS-2."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M27_DIAS_ADOS2_DIAGNOSTICO",
|
||||
"Días de ADOS-2 a diagnóstico",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"),
|
||||
"decrease",
|
||||
description=("Calendar days from the psychology note to the neuropediatrics note."),
|
||||
),
|
||||
Measure(
|
||||
"M28_CASOS_POR_ESTADO",
|
||||
"Casos por estatus",
|
||||
"screening",
|
||||
StatusComposition(STEPS),
|
||||
description=("Children in the screening during the period, by status."),
|
||||
),
|
||||
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",
|
||||
),
|
||||
description=(
|
||||
"EEGs done in the period for cohort children: good if the analysis found it valid, "
|
||||
"bad if not, and those not yet analysed."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M30_RESULTADO_EEG",
|
||||
"Porcentaje de EEG normal y anormal",
|
||||
"alterations",
|
||||
Proportion(
|
||||
lambda row: bool(row["altered"]), date="study_date", overlaps=(ALTERATIONS,)
|
||||
),
|
||||
"decrease",
|
||||
description=(
|
||||
"Of the children whose first good EEG falls in the period, how many have an "
|
||||
"alteration. One group per alteration. Hidden until the alterations are validated."
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"M31_PREVALENCIA",
|
||||
"Prevalencia registrada de TEA",
|
||||
"prevalence",
|
||||
StatusComposition(PREVALENCE, strata=(SEX,)),
|
||||
description=(
|
||||
"Every child loaded on the platform, with or without M-CHAT, aged 16 to 36 months "
|
||||
"during the period, by whether they were confirmed at its end."
|
||||
),
|
||||
),
|
||||
]
|
||||
}
|
||||
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
|
||||
|
||||
+22
-3
@@ -1,3 +1,4 @@
|
||||
# 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 \
|
||||
@@ -7,22 +8,40 @@ 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 . .
|
||||
RUN uv sync --frozen --no-dev
|
||||
# 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 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ADD --checksum=sha256:9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f \
|
||||
https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar \
|
||||
/opt/fhir/validator_cli.jar
|
||||
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
|
||||
CMD ["pytest", "-q", "-rs"]
|
||||
# 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 useradd --uid 10001 --create-home dask
|
||||
RUN uv sync --frozen --no-dev --extra dask \
|
||||
&& useradd --uid 10001 --create-home dask
|
||||
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1
|
||||
WORKDIR /home/dask
|
||||
USER dask
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
{# 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 %}
|
||||
@@ -10,18 +11,7 @@
|
||||
cast(julianday({{ b }}) - julianday({{ a }}) as integer)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro add_days(d, n) -%}
|
||||
{{ return(adapter.dispatch('add_days', 'isssteleon')(d, n)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__add_days(d, n) -%}
|
||||
(cast({{ d }} as date) + {{ n }})
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlite__add_days(d, n) -%}
|
||||
date({{ d }}, '+' || ({{ n }}) || ' days')
|
||||
{%- 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 %}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{# 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,3 +1,9 @@
|
||||
{#
|
||||
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,3 +1,4 @@
|
||||
{# 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,3 +1,4 @@
|
||||
{# 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
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
{#
|
||||
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] -%}
|
||||
(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
{#- 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) -%}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
{# 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,3 +1,14 @@
|
||||
{#
|
||||
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,3 +1,10 @@
|
||||
{#
|
||||
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,3 +1,8 @@
|
||||
{#
|
||||
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,2 +1,3 @@
|
||||
{# 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) }}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{# 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,
|
||||
row_number() over (partition by person_id order by date, source_table, source_id) as n
|
||||
from {{ ref('cacu_events') }}
|
||||
where date <= {{ as_of() }} and source_table <> 'person'
|
||||
)
|
||||
|
||||
select person_id, date as index_date, cast(null as {{ dbt.type_string() }}) as excluded_by
|
||||
from ranked
|
||||
where n = 1
|
||||
@@ -1,3 +1,18 @@
|
||||
{#
|
||||
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,3 +1,8 @@
|
||||
{#
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
{#
|
||||
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
|
||||
person_id, request_date as date, cytology_sample_date as recorded, report_date, histology,
|
||||
known_at, report_known_at,
|
||||
case
|
||||
{%- for grade in p.biopsy_severity %}
|
||||
when histology = '{{ grade }}' then {{ loop.index }}
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as severity
|
||||
from {{ ref('cervical_biopsy') }}
|
||||
),
|
||||
|
||||
colposcopy as (
|
||||
select person_id, date, min(known_at) as known_at
|
||||
from {{ ref('cacu_events') }}
|
||||
where type = 'colposcopy'
|
||||
and not (source_table = 'cervical_biopsy' and source_id <> cast(date as {{ dbt.type_string() }}))
|
||||
group by person_id, date
|
||||
),
|
||||
|
||||
answered as (
|
||||
select
|
||||
c.person_id, c.date, b.report_date, b.histology, b.report_known_at,
|
||||
row_number() over (partition by c.person_id, c.date
|
||||
order by b.severity desc, b.report_date, b.date) as n
|
||||
from colposcopy as c
|
||||
join biopsy as b on b.person_id = c.person_id and b.date >= c.date
|
||||
where b.histology is not null and b.report_date is not null
|
||||
and {{ days_between('c.date', 'b.date') }} <= {{ p.horizons.colposcopy_to_biopsy }}
|
||||
),
|
||||
|
||||
procedures as (
|
||||
select 'biopsy' as type, person_id, date, recorded, report_date, histology,
|
||||
known_at, report_known_at
|
||||
from biopsy
|
||||
union all
|
||||
select 'colposcopy', c.person_id, c.date, null, a.report_date, a.histology,
|
||||
c.known_at, a.report_known_at
|
||||
from colposcopy as c
|
||||
left join answered as a on a.person_id = c.person_id and a.date = c.date and a.n = 1
|
||||
),
|
||||
|
||||
referred as (
|
||||
select
|
||||
x.type, x.person_id, x.date, c.sample_date,
|
||||
row_number() over (partition by x.type, x.person_id, x.date
|
||||
order by c.sample_date desc, c.report_date desc) as n
|
||||
from procedures as x
|
||||
join {{ ref('cervical_cytology') }} as c on c.person_id = x.person_id
|
||||
where c.result is not null and coalesce(c.adequacy, '') <> 'unsatisfactory'
|
||||
and c.sample_date < x.date and c.report_date < x.date
|
||||
and {{ days_between('c.report_date', 'x.date') }} <= {{ p.cytology_before_days }}
|
||||
)
|
||||
|
||||
select
|
||||
{{ dbt.concat(['x.person_id', "'|'", 'cast(x.date as ' ~ dbt.type_string() ~ ')']) }} as procedure_id,
|
||||
x.type, x.person_id, x.date,
|
||||
coalesce(x.recorded, r.sample_date) as sample_date,
|
||||
case when x.recorded is not null then 'recorded'
|
||||
when r.sample_date is not null then 'inferred' end as link,
|
||||
x.report_date, x.histology, x.known_at, x.report_known_at
|
||||
from procedures as x
|
||||
left join referred as r
|
||||
on r.type = x.type and r.person_id = x.person_id and r.date = x.date and r.n = 1
|
||||
@@ -1,3 +1,6 @@
|
||||
{# 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,7 +1,9 @@
|
||||
{# 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.cytology_sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.request_date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
|
||||
b.report_date, b.histology, b.known_at,
|
||||
case
|
||||
when b.histology is null then -1
|
||||
@@ -10,5 +12,5 @@ select
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as severity
|
||||
from {{ ref('cervical_biopsy') }} as b
|
||||
where b.cytology_sample_date is not null
|
||||
from {{ ref('cacu_procedures') }} as b
|
||||
where b.type = 'biopsy' and b.sample_date is not null
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
{#
|
||||
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 (
|
||||
select
|
||||
c.person_id, c.sample_date, c.report_date, c.result, c.adequacy, c.known_at,
|
||||
c.report_known_at, c.screening_history, c.hpv, c.hpv_16, c.hpv_18,
|
||||
case when c.result is not null then c.report_date end as result_date,
|
||||
{{ dbt.concat(['c.person_id', "'|'", 'cast(c.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
p.birth_date
|
||||
@@ -20,13 +30,23 @@ events as (select * from {{ ref('cacu_events') }}),
|
||||
biopsy as (
|
||||
select s.sample_id, min(b.report_date) as date
|
||||
from sample as s
|
||||
join {{ ref('cervical_biopsy') }} as b
|
||||
on b.person_id = s.person_id and b.cytology_sample_date = s.sample_date
|
||||
join {{ ref('cacu_procedures') }} as b
|
||||
on b.type = 'biopsy' and b.person_id = s.person_id and b.sample_date = s.sample_date
|
||||
where b.report_date > s.sample_date
|
||||
and {{ days_between('s.sample_date', 'b.report_date') }} < {{ h.sample_to_biopsy }}
|
||||
group by s.sample_id
|
||||
),
|
||||
|
||||
diagnosis_code as ( -- the ICD-10 of the note that dates the diagnosis
|
||||
select d.sample_id, count(distinct n.value_code) as codes, min(n.value_code) as code
|
||||
from diagnosis as d
|
||||
join sample as s on s.sample_id = d.sample_id
|
||||
join events as e on e.person_id = s.person_id and e.type = 'diagnosis' and e.date = d.date
|
||||
join events as n on n.person_id = e.person_id and n.type = 'note' and n.date = e.date
|
||||
and n.source_id = e.source_id
|
||||
group by d.sample_id
|
||||
),
|
||||
|
||||
diagnosis_treatment as (
|
||||
select d.sample_id, min(e.date) as date
|
||||
from diagnosis as d
|
||||
@@ -53,6 +73,7 @@ select
|
||||
f.first_colposcopy,
|
||||
{{ days_between('s.sample_date', 's.result_date') }} as days_sample_result,
|
||||
dx.date as diagnosis_date,
|
||||
case when dc.codes > 1 then 'several' else dc.code end as diagnosis_code,
|
||||
{{ days_between('s.sample_date', 'dx.date') }} as days_sample_diagnosis,
|
||||
tx.date as treatment_date,
|
||||
{{ days_between('s.sample_date', 'tx.date') }} as days_sample_treatment,
|
||||
@@ -74,6 +95,7 @@ select
|
||||
from sample as s
|
||||
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
|
||||
left join diagnosis as dx on dx.sample_id = s.sample_id
|
||||
left join diagnosis_code as dc on dc.sample_id = s.sample_id
|
||||
left join treatment as tx on tx.sample_id = s.sample_id
|
||||
left join diagnosis_treatment as dt on dt.sample_id = s.sample_id
|
||||
left join colposcopy as col on col.sample_id = s.sample_id
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
{#
|
||||
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,2 +1,4 @@
|
||||
{# 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,2 +1,3 @@
|
||||
{# 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,3 +1,18 @@
|
||||
{#
|
||||
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,3 +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.
|
||||
#}
|
||||
select
|
||||
m.*,
|
||||
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
{#
|
||||
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,3 +1,5 @@
|
||||
{# 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,87 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_screening
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [unique, not_null]
|
||||
- name: tea_eegs
|
||||
columns:
|
||||
- name: eeg_id
|
||||
data_tests: [not_null]
|
||||
- name: tea_eeg_analyses
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [not_null]
|
||||
- name: tea_eeg_metrics
|
||||
columns:
|
||||
- name: eeg_id
|
||||
data_tests: [not_null]
|
||||
- name: code
|
||||
data_tests: [not_null]
|
||||
- name: tea_events
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [not_null]
|
||||
- name: tea_alterations
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [unique, not_null]
|
||||
- name: study_date
|
||||
data_tests: [not_null]
|
||||
- name: tea_prevalence
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [unique, not_null]
|
||||
- name: entry_date
|
||||
data_tests: [not_null]
|
||||
- name: tea_follow_up
|
||||
columns:
|
||||
- name: person_id
|
||||
data_tests: [unique, not_null]
|
||||
- name: step
|
||||
data_tests:
|
||||
- not_null
|
||||
- accepted_values:
|
||||
arguments:
|
||||
values: [eeg, neurology, psychology, mchat_only]
|
||||
- name: status
|
||||
data_tests:
|
||||
- not_null
|
||||
- accepted_values:
|
||||
arguments:
|
||||
values: [finished, active]
|
||||
- name: eeg_result
|
||||
data_tests:
|
||||
- not_null
|
||||
- accepted_values:
|
||||
arguments:
|
||||
values: [no_valid_eeg, abnormal, normal, not_scored]
|
||||
- name: tea_eeg_checks
|
||||
columns:
|
||||
- name: eeg_id
|
||||
data_tests: [not_null]
|
||||
- name: code
|
||||
data_tests: [not_null]
|
||||
- name: tea_eeg_regions
|
||||
columns:
|
||||
- name: eeg_id
|
||||
data_tests: [not_null]
|
||||
- name: code
|
||||
data_tests: [not_null]
|
||||
- name: kind
|
||||
data_tests:
|
||||
- not_null
|
||||
- accepted_values:
|
||||
arguments:
|
||||
values: [electrode, zone]
|
||||
- name: site
|
||||
data_tests: [not_null]
|
||||
- name: tea_associations
|
||||
columns:
|
||||
- name: key
|
||||
data_tests: [unique, not_null]
|
||||
- name: tea_association_scores
|
||||
columns:
|
||||
- name: key
|
||||
data_tests: [unique, not_null]
|
||||
@@ -1,25 +0,0 @@
|
||||
{% set p = var('tea') %}
|
||||
with first_good as (
|
||||
select person_id, min(study_date) as study_date
|
||||
from {{ ref('tea_eegs') }} where valid group by person_id
|
||||
),
|
||||
eeg as (
|
||||
select s.person_id, s.age_group, f.study_date, e.eeg_id, e.known_at
|
||||
from {{ ref('tea_screening') }} as s
|
||||
join first_good as f on f.person_id = s.person_id
|
||||
join {{ ref('tea_eegs') }} as e on e.person_id = f.person_id and e.study_date = f.study_date and e.valid
|
||||
where s.eeg_date is not null
|
||||
),
|
||||
scored as (
|
||||
select eeg_id, code, (outside is not null and outside <> 0 and model is not null) as altered
|
||||
from {{ ref('tea_eeg_metrics') }}
|
||||
)
|
||||
select
|
||||
eeg.person_id, eeg.age_group, eeg.study_date, eeg.eeg_id, eeg.known_at,
|
||||
coalesce(max(case when m.altered then 1 else 0 end), 0) = 1 as altered
|
||||
{%- for metric in p.eeg_metrics %},
|
||||
coalesce(max(case when m.code = '{{ metric }}' and m.altered then 1 else 0 end), 0) = 1 as alt_{{ metric }}
|
||||
{%- endfor %}
|
||||
from eeg
|
||||
left join scored as m on m.eeg_id = eeg.eeg_id
|
||||
group by eeg.person_id, eeg.age_group, eeg.study_date, eeg.eeg_id, eeg.known_at
|
||||
@@ -1,21 +0,0 @@
|
||||
-- depends_on: {{ ref('eeg') }}
|
||||
{% if staged_exists('eeg_association_scores') %}
|
||||
select
|
||||
a.key, a.model, a.eeg_id, a.pair, a.z, a.probability, a.reference_probability,
|
||||
e.person_id, e.study_date
|
||||
from {{ source('bronze', 'eeg_association_scores') }} as a
|
||||
join {{ ref('eeg') }} as e
|
||||
on a.eeg_id = {{ dbt.concat(['e.person_id', "'|'", 'cast(e.study_date as ' ~ dbt.type_string() ~ ')']) }}
|
||||
{% else %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as key,
|
||||
cast(null as {{ dbt.type_string() }}) as model,
|
||||
cast(null as {{ dbt.type_string() }}) as eeg_id,
|
||||
cast(null as {{ dbt.type_string() }}) as pair,
|
||||
cast(null as {{ dbt.type_float() }}) as z,
|
||||
cast(null as {{ dbt.type_float() }}) as probability,
|
||||
cast(null as {{ dbt.type_float() }}) as reference_probability,
|
||||
cast(null as {{ dbt.type_string() }}) as person_id,
|
||||
cast(null as date) as study_date
|
||||
where 1 = 0
|
||||
{% endif %}
|
||||
@@ -1,32 +0,0 @@
|
||||
{% if staged_exists('eeg_associations') %}
|
||||
select
|
||||
a.key, a.model, a.level, a.n_cohort, a.biomarker, a.zone, a.kind, a.outcome_code,
|
||||
a.event, a.method, a.n, a.odds_ratio, a.ci_low, a.ci_high, a.p, a.q,
|
||||
a.sens_model, a.sens_odds_ratio, a.same_direction, a.reason,
|
||||
cast(substr(a.model, 23) as integer) as champion_version
|
||||
from {{ source('bronze', 'eeg_associations') }} as a
|
||||
{% else %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as key,
|
||||
cast(null as {{ dbt.type_string() }}) as model,
|
||||
cast(null as {{ dbt.type_string() }}) as level,
|
||||
cast(null as bigint) as n_cohort,
|
||||
cast(null as {{ dbt.type_string() }}) as biomarker,
|
||||
cast(null as {{ dbt.type_string() }}) as zone,
|
||||
cast(null as {{ dbt.type_string() }}) as kind,
|
||||
cast(null as {{ dbt.type_string() }}) as outcome_code,
|
||||
cast(null as {{ dbt.type_string() }}) as event,
|
||||
cast(null as {{ dbt.type_string() }}) as method,
|
||||
cast(null as bigint) as n,
|
||||
cast(null as {{ dbt.type_float() }}) as odds_ratio,
|
||||
cast(null as {{ dbt.type_float() }}) as ci_low,
|
||||
cast(null as {{ dbt.type_float() }}) as ci_high,
|
||||
cast(null as {{ dbt.type_float() }}) as p,
|
||||
cast(null as {{ dbt.type_float() }}) as q,
|
||||
cast(null as {{ dbt.type_string() }}) as sens_model,
|
||||
cast(null as {{ dbt.type_float() }}) as sens_odds_ratio,
|
||||
cast(null as {{ dbt.type_boolean() }}) as same_direction,
|
||||
cast(null as {{ dbt.type_string() }}) as reason,
|
||||
cast(null as integer) as champion_version
|
||||
where 1 = 0
|
||||
{% endif %}
|
||||
@@ -1,3 +1,4 @@
|
||||
{# 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,24 +0,0 @@
|
||||
-- depends_on: {{ ref('tea_eegs') }}
|
||||
{%- if not staged_exists('eeg_checks') %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as person_id,
|
||||
cast(null as {{ dbt.type_string() }}) as eeg_id,
|
||||
cast(null as date) as study_date,
|
||||
cast(null as {{ dbt.type_string() }}) as edf,
|
||||
cast(null as {{ dbt.type_string() }}) as code,
|
||||
cast(null as {{ dbt.type_string() }}) as electrode,
|
||||
cast(null as {{ dbt.type_float() }}) as value,
|
||||
cast(null as {{ dbt.type_string() }}) as text,
|
||||
cast(null as {{ dbt.type_string() }}) as unit,
|
||||
cast(null as {{ dbt.type_float() }}) as low,
|
||||
cast(null as {{ dbt.type_float() }}) as high,
|
||||
cast(null as {{ dbt.type_boolean() }}) as decisive,
|
||||
cast(null as {{ dbt.type_boolean() }}) as abnormal
|
||||
where 1 = 0
|
||||
{%- else %}
|
||||
select
|
||||
e.person_id, e.eeg_id, e.study_date, c.edf,
|
||||
c.code, c.electrode, c.value, c.text, c.unit, c.low, c.high, c.decisive, c.abnormal
|
||||
from {{ source('bronze', 'eeg_checks') }} as c
|
||||
join {{ ref('tea_eegs') }} as e on e.edf = c.edf
|
||||
{%- endif %}
|
||||
@@ -1,4 +1,9 @@
|
||||
{%- 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,40 +0,0 @@
|
||||
-- depends_on: {{ ref('tea_eegs') }}
|
||||
{%- if not staged_exists('eeg_sites') %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as person_id,
|
||||
cast(null as {{ dbt.type_string() }}) as eeg_id,
|
||||
cast(null as date) as study_date,
|
||||
cast(null as {{ dbt.type_string() }}) as edf,
|
||||
cast(null as {{ dbt.type_string() }}) as code,
|
||||
cast(null as {{ dbt.type_string() }}) as kind,
|
||||
cast(null as {{ dbt.type_string() }}) as site,
|
||||
cast(null as {{ dbt.type_float() }}) as value,
|
||||
cast(null as {{ dbt.type_float() }}) as z,
|
||||
cast(null as {{ dbt.type_float() }}) as outside,
|
||||
cast(null as {{ dbt.type_float() }}) as p5,
|
||||
cast(null as {{ dbt.type_float() }}) as median,
|
||||
cast(null as {{ dbt.type_float() }}) as p95,
|
||||
cast(null as {{ dbt.type_string() }}) as model
|
||||
where 1 = 0
|
||||
{%- else %}
|
||||
select
|
||||
e.person_id, e.eeg_id, e.study_date, x.edf, x.code,
|
||||
case x.part when 'electrodes' then 'electrode' when 'zones' then 'zone' end as kind,
|
||||
x.site, x.value,
|
||||
{%- if staged_exists('eeg_scores') %}
|
||||
s.z, s.outside, s.p5, s.median, s.p95, s.model
|
||||
{%- else %}
|
||||
cast(null as {{ dbt.type_float() }}) as z,
|
||||
cast(null as {{ dbt.type_float() }}) as outside,
|
||||
cast(null as {{ dbt.type_float() }}) as p5,
|
||||
cast(null as {{ dbt.type_float() }}) as median,
|
||||
cast(null as {{ dbt.type_float() }}) as p95,
|
||||
cast(null as {{ dbt.type_string() }}) as model
|
||||
{%- endif %}
|
||||
from {{ source('bronze', 'eeg_sites') }} as x
|
||||
join {{ ref('tea_eegs') }} as e on e.edf = x.edf
|
||||
{%- if staged_exists('eeg_scores') %}
|
||||
left join {{ source('bronze', 'eeg_scores') }} as s
|
||||
on s.edf = x.edf and s.metric = x.code and s.part = x.part and s.site = x.site
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
@@ -1,3 +1,8 @@
|
||||
{#
|
||||
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,3 +1,4 @@
|
||||
{# 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,70 +0,0 @@
|
||||
{% set p = var('tea') %}
|
||||
with screening as (
|
||||
select *,
|
||||
case
|
||||
when eeg_date is not null then 'eeg'
|
||||
when neuro_date is not null then 'neurology'
|
||||
when psychology_date is not null then 'psychology'
|
||||
else 'mchat_only'
|
||||
end as step
|
||||
from {{ ref('tea_screening') }}
|
||||
),
|
||||
mchat_scores as (
|
||||
select person_id, screening_date, max(score) as score
|
||||
from {{ ref('mchat') }}
|
||||
group by person_id, screening_date
|
||||
),
|
||||
ranked_ados2 as (
|
||||
select *,
|
||||
row_number() over (partition by person_id order by evaluation_date desc, known_at desc) as rn
|
||||
from {{ ref('ados2') }}
|
||||
),
|
||||
first_good as (
|
||||
select person_id, min(study_date) as study_date
|
||||
from {{ ref('tea_eegs') }} where valid group by person_id
|
||||
),
|
||||
eeg as (
|
||||
select e.person_id, e.eeg_id,
|
||||
{%- if staged_exists('eeg_analysis') %}
|
||||
a.duration_min, a.channels,
|
||||
{%- else %}
|
||||
cast(null as {{ dbt.type_float() }}) as duration_min,
|
||||
cast(null as {{ dbt.type_float() }}) as channels,
|
||||
{%- endif %}
|
||||
exists (
|
||||
select 1 from {{ ref('tea_eeg_metrics') }} as m
|
||||
where m.eeg_id = e.eeg_id and m.model is not null
|
||||
) as scored
|
||||
from first_good as f
|
||||
join {{ ref('tea_eegs') }} as e on e.person_id = f.person_id and e.study_date = f.study_date and e.valid
|
||||
{%- if staged_exists('eeg_analysis') %}
|
||||
left join {{ source('bronze', 'eeg_analysis') }} as a on a.edf = e.edf
|
||||
{%- endif %}
|
||||
)
|
||||
select
|
||||
s.person_id, s.sex, s.birth_date, s.age_months, s.age_group, s.known_at,
|
||||
s.step, coalesce(s.eeg_date, s.neuro_date, s.psychology_date, s.mchat_date) as step_date,
|
||||
case when s.step = 'eeg' then 'finished' else 'active' end as status,
|
||||
s.mchat_date as start_date, s.eeg_date as end_date,
|
||||
s.mchat_date, m.score as mchat_score,
|
||||
s.psychology_date, s.neuro_date, s.confirmed_date, s.not_confirmed_date, s.eeg_date,
|
||||
a.evaluation_date as ados2_date, a.module as ados2_module,
|
||||
{%- for item in p.ados2_items %}
|
||||
a.{{ item }} as ados2_{{ item }},
|
||||
{%- endfor %}
|
||||
e.eeg_id, e.duration_min as eeg_duration_min, e.channels as eeg_channels, e.scored as eeg_scored,
|
||||
case
|
||||
when e.eeg_id is null then 'no_valid_eeg'
|
||||
when t.altered then 'abnormal'
|
||||
when e.scored then 'normal'
|
||||
else 'not_scored'
|
||||
end as eeg_result,
|
||||
t.altered
|
||||
{%- for metric in p.eeg_metrics %},
|
||||
t.alt_{{ metric }}
|
||||
{%- endfor %}
|
||||
from screening as s
|
||||
left join mchat_scores as m on m.person_id = s.person_id and m.screening_date = s.mchat_date
|
||||
left join ranked_ados2 as a on a.person_id = s.person_id and a.rn = 1
|
||||
left join eeg as e on e.person_id = s.person_id
|
||||
left join {{ ref('tea_alterations') }} as t on t.person_id = s.person_id
|
||||
@@ -1,17 +0,0 @@
|
||||
{% set p = var('tea') %}
|
||||
{% set entry = (p.prevalence_age[0] * p.days_per_month) | round | int %}
|
||||
{% set leave = ((p.prevalence_age[1] + 1) * p.days_per_month) | round | int %}
|
||||
with confirmed as (
|
||||
select person_id, min(note_date) as confirmed_date
|
||||
from {{ ref('clinical_note') }}
|
||||
where specialty = '{{ p.neurology }}' and icd10 in {{ sql_list(p.confirming_icd10) }}
|
||||
group by person_id
|
||||
)
|
||||
select
|
||||
pe.person_id, pe.sex, pe.birth_date, pe.known_at,
|
||||
{{ add_days('pe.birth_date', entry) }} as entry_date,
|
||||
{{ add_days('pe.birth_date', leave) }} as exit_date,
|
||||
s.confirmed_date
|
||||
from {{ ref('person') }} as pe
|
||||
left join confirmed as s on s.person_id = pe.person_id
|
||||
where pe.birth_date is not null
|
||||
@@ -1,3 +1,10 @@
|
||||
{#
|
||||
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 (
|
||||
@@ -7,7 +14,7 @@ with mchat as (
|
||||
|
||||
child as (
|
||||
select
|
||||
m.person_id, m.mchat_date, m.known_at, b.birth_date, b.sex,
|
||||
m.person_id, m.mchat_date, m.known_at, b.birth_date,
|
||||
cast(round({{ days_between('b.birth_date', 'm.mchat_date') }} / {{ p.days_per_month }}, 1) * 10
|
||||
as integer) / 10 as age_months
|
||||
from mchat as m
|
||||
@@ -61,7 +68,7 @@ steps as (
|
||||
)
|
||||
|
||||
select
|
||||
person_id, birth_date, sex, age_months, known_at,
|
||||
person_id, birth_date, age_months, known_at,
|
||||
case
|
||||
when age_months is null then 'no_data'
|
||||
{%- for low, high in p.age_groups %}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- ados2, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('ados2') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- breast_biopsy, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('breast_biopsy') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- breast_recurrence, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('breast_recurrence') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- breast_treatment, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('breast_treatment') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_biopsy') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_cytology') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('clinical_note') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- death, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('death') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- eeg, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('eeg') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- mammography, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('mammography') }} as p
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- mchat, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('mchat') }} as p
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
{#
|
||||
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,
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
{#
|
||||
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,3 +1,8 @@
|
||||
{#
|
||||
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') }}
|
||||
@@ -10,6 +15,6 @@ union
|
||||
{%- endfor %}
|
||||
select distinct
|
||||
person_id,
|
||||
'{{ var("record_number_system") }}' || _pipeline as system,
|
||||
{{ dbt.concat(["'" ~ var('record_number_system') ~ "'", '_pipeline', "':'", '_source']) }} as system,
|
||||
record_number as value
|
||||
from identity where record_number is not null
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
{#
|
||||
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,3 +1,4 @@
|
||||
{#- 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
|
||||
|
||||
@@ -6,10 +6,7 @@ sources:
|
||||
- name: model_scores
|
||||
- name: eeg_analysis
|
||||
- name: eeg_metrics
|
||||
- name: eeg_sites
|
||||
- name: eeg_scores
|
||||
- name: eeg_associations
|
||||
- name: eeg_association_scores
|
||||
- name: eeg_checks
|
||||
- name: review_log
|
||||
- name: staged__identity
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{#- 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,3 +1,4 @@
|
||||
{#- 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,3 +1,23 @@
|
||||
"""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
|
||||
@@ -69,6 +89,8 @@ 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()
|
||||
@@ -76,6 +98,7 @@ 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})")
|
||||
@@ -127,6 +150,7 @@ def _prune(root: Path) -> None:
|
||||
|
||||
|
||||
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():
|
||||
@@ -139,6 +163,7 @@ 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)
|
||||
from sqlalchemy import inspect
|
||||
@@ -150,6 +175,10 @@ 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())
|
||||
|
||||
@@ -1,349 +0,0 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import tempfile
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO, Literal
|
||||
|
||||
from core.domains import Domain
|
||||
from core.tea import bundle as tea_bundle
|
||||
from persistance import config, registry
|
||||
|
||||
FORMAT = 1
|
||||
MANIFEST = "manifest.json"
|
||||
EPOCH = (1980, 1, 1, 0, 0, 0)
|
||||
MAX_BYTES = 2 * 1024**3
|
||||
Selection = Literal["champion", "latest", "all"]
|
||||
|
||||
|
||||
class BundleError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class Empty(BundleError):
|
||||
pass
|
||||
|
||||
|
||||
class Conflict(BundleError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Exported:
|
||||
data: bytes
|
||||
sha256: str
|
||||
versions: list[tuple[str, int]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Imported:
|
||||
sha256: str
|
||||
imported: list[tuple[str, int]]
|
||||
skipped: list[tuple[str, int]]
|
||||
|
||||
|
||||
def _sha256(content: bytes) -> str:
|
||||
return hashlib.sha256(content).hexdigest()
|
||||
|
||||
|
||||
def content_sha256(files: dict[str, bytes]) -> str:
|
||||
return _sha256("".join(f"{path}\0{_sha256(files[path])}\n" for path in sorted(files)).encode())
|
||||
|
||||
|
||||
def guard(domain: Domain, snapshot: registry.Snapshot) -> list[str]:
|
||||
if domain != Domain.TEA:
|
||||
return []
|
||||
reports = {}
|
||||
for key in ("technical_validation", "interpretability"):
|
||||
if key in snapshot.reports:
|
||||
try:
|
||||
reports[key] = snapshot.reports[key][1].decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return tea_bundle.guard(
|
||||
{
|
||||
"name": snapshot.name,
|
||||
"version": snapshot.version,
|
||||
"params": snapshot.params,
|
||||
"metrics": snapshot.metrics,
|
||||
"tags": snapshot.tags,
|
||||
"reports": reports,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _check_guard(domain: Domain, snapshots: list[registry.Snapshot]) -> None:
|
||||
problems = [
|
||||
f"{snapshot.name} v{snapshot.version}: {problem}"
|
||||
for snapshot in snapshots
|
||||
for problem in guard(domain, snapshot)
|
||||
]
|
||||
if problems:
|
||||
raise BundleError("; ".join(problems))
|
||||
|
||||
|
||||
def _prefix(name: str, version: int) -> str:
|
||||
return f"models/{name}/v{version}/"
|
||||
|
||||
|
||||
def export(
|
||||
domain: Domain, names: list[str] | None = None, versions: Selection = "champion"
|
||||
) -> Exported:
|
||||
prefix = f"{domain.value}."
|
||||
available = registry.names(prefix)
|
||||
selected = available
|
||||
if names is not None:
|
||||
selected = []
|
||||
for short in names:
|
||||
name = prefix + short
|
||||
if name not in available:
|
||||
raise BundleError(f"no {domain.value} model {short}")
|
||||
selected.append(name)
|
||||
|
||||
pairs = []
|
||||
for name in sorted(set(selected)):
|
||||
if versions == "all":
|
||||
pairs.extend((name, item["version"]) for item in registry.versions(name))
|
||||
else:
|
||||
lookup = (
|
||||
registry.champion_version if versions == "champion" else registry.latest_version
|
||||
)
|
||||
if (version := lookup(name)) is not None:
|
||||
pairs.append((name, version))
|
||||
if not pairs:
|
||||
raise Empty("nothing to export: no version selected")
|
||||
|
||||
snapshots = [registry.snapshot(name, version) for name, version in pairs]
|
||||
_check_guard(domain, snapshots)
|
||||
entries = {}
|
||||
manifest_versions = []
|
||||
for snapshot in snapshots:
|
||||
files = {f"model/{path}": data for path, data in snapshot.model.items()}
|
||||
files.update({f"reports/{filename}": data for filename, data in snapshot.reports.values()})
|
||||
identity = {
|
||||
"name": snapshot.name,
|
||||
"version": snapshot.version,
|
||||
"content_sha256": content_sha256(files),
|
||||
}
|
||||
meta = {
|
||||
**identity,
|
||||
"created": snapshot.created,
|
||||
"params": snapshot.params,
|
||||
"metrics": snapshot.metrics,
|
||||
"tags": snapshot.tags,
|
||||
"reports": {key: filename for key, (filename, _) in snapshot.reports.items()},
|
||||
}
|
||||
files["meta.json"] = json.dumps(meta, sort_keys=True, indent=1, ensure_ascii=False).encode()
|
||||
folder = _prefix(snapshot.name, snapshot.version)
|
||||
entries.update({folder + path: data for path, data in files.items()})
|
||||
manifest_versions.append(
|
||||
{**identity, "files": {folder + path: _sha256(data) for path, data in files.items()}}
|
||||
)
|
||||
manifest = {"format": FORMAT, "domain": domain.value, "versions": manifest_versions}
|
||||
entries[MANIFEST] = json.dumps(manifest, sort_keys=True, indent=1).encode()
|
||||
output = io.BytesIO()
|
||||
with zipfile.ZipFile(output, "w") as archive:
|
||||
for path, data in sorted(entries.items()):
|
||||
info = zipfile.ZipInfo(path, EPOCH)
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.external_attr = 0o644 << 16
|
||||
info.create_system = 3
|
||||
archive.writestr(info, data, compresslevel=6)
|
||||
data = output.getvalue()
|
||||
return Exported(data, _sha256(data), pairs)
|
||||
|
||||
|
||||
def _safe_path(path: str) -> bool:
|
||||
return not any(part in ("", ".", "..") for part in path.split("/")) and not (
|
||||
"\\" in path or "\0" in path
|
||||
)
|
||||
|
||||
|
||||
def _read(domain: Domain, archive: zipfile.ZipFile) -> list[tuple[registry.Snapshot, str]]:
|
||||
paths = set()
|
||||
for entry in archive.infolist():
|
||||
path = entry.orig_filename
|
||||
if not _safe_path(path):
|
||||
raise BundleError(f"unsafe bundle path: {path}")
|
||||
if path in paths:
|
||||
raise BundleError(f"duplicate bundle path: {path}")
|
||||
paths.add(path)
|
||||
if sum(entry.file_size for entry in archive.infolist()) > MAX_BYTES:
|
||||
raise BundleError("bundle exceeds the uncompressed size limit")
|
||||
if MANIFEST not in paths:
|
||||
raise BundleError("bundle has no manifest.json")
|
||||
manifest = json.loads(archive.read(MANIFEST))
|
||||
if (format_ := manifest.get("format")) != FORMAT:
|
||||
raise BundleError(f"bundle format {format_}, this platform reads 1")
|
||||
if (source := manifest.get("domain")) != domain.value:
|
||||
raise BundleError(f"bundle is for {source}, not {domain.value}")
|
||||
versions = manifest["versions"]
|
||||
expected = {path for item in versions for path in item["files"]}
|
||||
if MANIFEST in expected or paths != expected | {MANIFEST}:
|
||||
raise BundleError("the files in the bundle do not match the manifest")
|
||||
files = {path: archive.read(path) for path in expected}
|
||||
for item in versions:
|
||||
for path, digest in item["files"].items():
|
||||
if _sha256(files[path]) != digest:
|
||||
raise BundleError(f"{path}: content does not match the manifest")
|
||||
snapshots = [_snapshot(domain, item, files) for item in versions]
|
||||
if len({(snapshot.name, snapshot.version) for snapshot, _ in snapshots}) != len(snapshots):
|
||||
raise BundleError("duplicate model version in the manifest")
|
||||
return snapshots
|
||||
|
||||
|
||||
def _snapshot(domain: Domain, item: dict, files: dict[str, bytes]) -> tuple[registry.Snapshot, str]:
|
||||
name, version, digest = item["name"], item["version"], item["content_sha256"]
|
||||
if (
|
||||
not name.startswith(f"{domain.value}.")
|
||||
or "/" in name
|
||||
or type(version) is not int
|
||||
or version < 1
|
||||
):
|
||||
raise BundleError("invalid model name or version in the manifest")
|
||||
prefix = _prefix(name, version)
|
||||
if any(not path.startswith(prefix) for path in item["files"]):
|
||||
raise BundleError(f"{name} v{version}: file outside version folder")
|
||||
relative = {path.removeprefix(prefix): files[path] for path in item["files"]}
|
||||
meta = json.loads(relative.pop("meta.json"))
|
||||
if any(meta[key] != item[key] for key in ("name", "version", "content_sha256")):
|
||||
raise BundleError(f"{name} v{version}: meta.json does not match the manifest")
|
||||
if content_sha256(relative) != digest:
|
||||
raise BundleError(f"{name} v{version}: content SHA-256 does not match")
|
||||
reports = {}
|
||||
for key, filename in meta["reports"].items():
|
||||
if key not in registry.REPORTS or "/" in filename:
|
||||
raise BundleError(f"{name} v{version}: invalid report {key}")
|
||||
reports[key] = (filename, relative.pop(f"reports/{filename}"))
|
||||
if any(not path.startswith("model/") for path in relative):
|
||||
raise BundleError(f"{name} v{version}: unexpected file in version folder")
|
||||
model = {path.removeprefix("model/"): data for path, data in relative.items()}
|
||||
return registry.Snapshot(
|
||||
name,
|
||||
version,
|
||||
meta["created"],
|
||||
meta["params"],
|
||||
meta["metrics"],
|
||||
meta["tags"],
|
||||
reports,
|
||||
model,
|
||||
), digest
|
||||
|
||||
|
||||
def import_(domain: Domain, data: bytes) -> Imported:
|
||||
sha256 = _sha256(data)
|
||||
if not trusted(sha256):
|
||||
raise BundleError(
|
||||
f"bundle {sha256} is not trusted on this server: "
|
||||
f"the operator adds its SHA-256 to {trusted_file()}"
|
||||
)
|
||||
try:
|
||||
archive = zipfile.ZipFile(io.BytesIO(data))
|
||||
except zipfile.BadZipFile:
|
||||
raise BundleError("not a bundle") from None
|
||||
try:
|
||||
with archive:
|
||||
versions = _read(domain, archive)
|
||||
versions.sort(key=lambda item: (item[0].name, item[0].version))
|
||||
_check_guard(domain, [snapshot for snapshot, _ in versions])
|
||||
except BundleError:
|
||||
raise
|
||||
except (
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
AttributeError,
|
||||
RuntimeError,
|
||||
OSError,
|
||||
zipfile.BadZipFile,
|
||||
) as e:
|
||||
raise BundleError(f"invalid bundle: {e}") from None
|
||||
|
||||
pending, skipped = [], []
|
||||
for snapshot, digest in versions:
|
||||
if digest in registry.content_hashes(snapshot.name):
|
||||
skipped.append((snapshot.name, snapshot.version))
|
||||
else:
|
||||
pending.append((snapshot, digest))
|
||||
if not pending:
|
||||
found = ", ".join(f"{name} v{version}" for name, version in skipped)
|
||||
raise Conflict(f"every version is already registered: {found}")
|
||||
|
||||
imported = []
|
||||
for snapshot, digest in pending:
|
||||
tags = {key: val for key, val in snapshot.tags.items() if not key.startswith("bundle.")}
|
||||
tags.update(
|
||||
{
|
||||
"bundle.sha256": sha256,
|
||||
"bundle.source_name": snapshot.name,
|
||||
"bundle.source_version": str(snapshot.version),
|
||||
"bundle.content_sha256": digest,
|
||||
}
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model_dir = Path(tmp)
|
||||
for path, content in snapshot.model.items():
|
||||
target = model_dir / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(content)
|
||||
try:
|
||||
version = registry.restore(
|
||||
snapshot.name,
|
||||
model_dir,
|
||||
snapshot.params,
|
||||
snapshot.metrics,
|
||||
snapshot.reports,
|
||||
tags,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise BundleError(str(e)) from None
|
||||
imported.append((snapshot.name, version))
|
||||
return Imported(sha256, imported, skipped)
|
||||
|
||||
|
||||
def staging() -> Path:
|
||||
path = config.DATA_DIR / "bundles"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def staged(sha256: str) -> Path:
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", sha256):
|
||||
raise ValueError("invalid bundle SHA-256")
|
||||
return staging() / f"{sha256}.zip"
|
||||
|
||||
|
||||
def stage(stream: BinaryIO) -> tuple[str, Path]:
|
||||
digest = hashlib.sha256()
|
||||
with tempfile.NamedTemporaryFile(dir=staging(), delete=False) as output:
|
||||
temp = Path(output.name)
|
||||
try:
|
||||
while chunk := stream.read(1024**2):
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
output.close()
|
||||
sha256 = digest.hexdigest()
|
||||
path = staged(sha256)
|
||||
temp.replace(path)
|
||||
finally:
|
||||
temp.unlink(missing_ok=True)
|
||||
return sha256, path
|
||||
|
||||
|
||||
def trusted_file() -> Path:
|
||||
return staging() / "trusted"
|
||||
|
||||
|
||||
def trusted(sha256: str) -> bool:
|
||||
try:
|
||||
with trusted_file().open(encoding="utf-8") as file:
|
||||
return any(
|
||||
line == sha256
|
||||
for raw in file
|
||||
if (line := raw.strip().lower()) and not line.startswith("#")
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
@@ -1,310 +0,0 @@
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import psutil
|
||||
from dask.utils import parse_bytes
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
Mode = Literal["sync", "local", "remote"]
|
||||
PROGRESS_TAG = "isssteleon/progress"
|
||||
CHECKED_PACKAGES = (
|
||||
"numpy",
|
||||
"scipy",
|
||||
"pandas",
|
||||
"scikit-learn",
|
||||
"mne",
|
||||
"edfio",
|
||||
"statsmodels",
|
||||
"cloudpickle",
|
||||
"joblib",
|
||||
)
|
||||
REFERENCE_NAME = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
|
||||
_SCHEDULER = re.compile(r"^(tcp|tls)://[A-Za-z0-9._-]+:\d{1,5}$")
|
||||
_MODES = ("sync", "local", "remote")
|
||||
|
||||
|
||||
class ExecutionError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class ClusterVersionError(ExecutionError):
|
||||
pass
|
||||
|
||||
|
||||
class Execution(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
title="Ejecución",
|
||||
json_schema_extra={
|
||||
"description": "What a request or a job config carries: "
|
||||
"None means the deployment's default."
|
||||
},
|
||||
)
|
||||
mode: Mode | None = Field(None, title="Modo")
|
||||
scheduler: str | None = Field(None, title="Planificador Dask")
|
||||
|
||||
|
||||
class SiteTrainingSource(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", title="Niños del sitio sin el diagnóstico")
|
||||
kind: Literal["site"] = Field(title="Origen")
|
||||
|
||||
|
||||
class FolderTrainingSource(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", title="Carpeta de EDF con edades")
|
||||
kind: Literal["folder"] = Field(title="Origen")
|
||||
folder: str = Field(
|
||||
pattern=r"^[A-Za-z0-9._-]{1,64}$",
|
||||
title="Carpeta",
|
||||
description="Carpeta dentro de TEA_REFERENCE_ROOT",
|
||||
)
|
||||
line_hz: Literal[50, 60] = Field(50, title="Frecuencia de la red eléctrica (Hz)")
|
||||
|
||||
|
||||
type TrainingSource = Annotated[
|
||||
SiteTrainingSource | FolderTrainingSource, Field(discriminator="kind")
|
||||
]
|
||||
|
||||
|
||||
class Resolved(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
mode: Mode
|
||||
scheduler: str | None
|
||||
|
||||
|
||||
class Worker(BaseModel):
|
||||
name: str
|
||||
cpu_pct: float
|
||||
memory_bytes: int
|
||||
memory_limit: int | None
|
||||
executing: int
|
||||
threads: int
|
||||
|
||||
|
||||
class Tasks(BaseModel):
|
||||
waiting: int = 0
|
||||
queued: int = 0
|
||||
processing: int = 0
|
||||
memory: int = 0
|
||||
erred: int = 0
|
||||
|
||||
|
||||
class Progress(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={"description": "The run tag's JSON; the API returns it as it is."}
|
||||
)
|
||||
|
||||
phase: str
|
||||
done: int
|
||||
total: int
|
||||
elapsed_s: float
|
||||
eta_s: float | None
|
||||
mode: Mode
|
||||
scheduler: str | None
|
||||
workers: list[Worker] = []
|
||||
tasks: Tasks | None = None
|
||||
updated_at: str
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
mode: Mode
|
||||
scheduler: str | None
|
||||
reachable: bool
|
||||
workers: int | None = None
|
||||
expected_workers: int | None = None
|
||||
threads: int | None = None
|
||||
versions_ok: bool | None = None
|
||||
version_error: str | None = None
|
||||
dashboard_url: str | None = None
|
||||
dashboard_ok: bool | None = None
|
||||
latency_ms: float | None = None
|
||||
reference: dict | None = None
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class Options(BaseModel):
|
||||
default_mode: Mode
|
||||
schedulers: list[str]
|
||||
|
||||
|
||||
def normalize(address: str) -> str:
|
||||
address = address.strip()
|
||||
full = address if "://" in address else f"tcp://{address}"
|
||||
if not _SCHEDULER.match(full):
|
||||
raise ExecutionError(f"scheduler {address!r} is not host:port")
|
||||
return full
|
||||
|
||||
|
||||
def schedulers() -> list[str]:
|
||||
found = [
|
||||
normalize(part) for part in os.environ.get("DASK_SCHEDULERS", "").split(",") if part.strip()
|
||||
]
|
||||
return list(dict.fromkeys(found))
|
||||
|
||||
|
||||
def default_mode() -> Mode:
|
||||
mode = os.environ.get("EXECUTION_MODE", "").strip() or "local"
|
||||
if mode not in _MODES:
|
||||
raise ExecutionError(f"EXECUTION_MODE {mode!r} is not one of {', '.join(_MODES)}")
|
||||
return mode # type: ignore[return-value]
|
||||
|
||||
|
||||
def options() -> Options:
|
||||
return Options(default_mode=default_mode(), schedulers=schedulers())
|
||||
|
||||
|
||||
def resolve(execution: Execution | None = None) -> Resolved:
|
||||
execution = execution or Execution()
|
||||
mode = execution.mode or default_mode()
|
||||
if mode != "remote":
|
||||
if execution.scheduler:
|
||||
raise ExecutionError("a scheduler only goes with remote mode")
|
||||
return Resolved(mode=mode, scheduler=None)
|
||||
allowed = schedulers()
|
||||
if execution.scheduler:
|
||||
scheduler = normalize(execution.scheduler)
|
||||
if scheduler not in allowed:
|
||||
raise ExecutionError(f"scheduler {scheduler} is not in DASK_SCHEDULERS")
|
||||
elif allowed:
|
||||
scheduler = allowed[0]
|
||||
else:
|
||||
raise ExecutionError(
|
||||
"remote execution needs a scheduler: none given and DASK_SCHEDULERS is empty"
|
||||
)
|
||||
return Resolved(mode=mode, scheduler=scheduler)
|
||||
|
||||
|
||||
def memory_per_worker() -> str:
|
||||
return os.environ.get("DASK_MEMORY_PER_WORKER") or "4GiB"
|
||||
|
||||
|
||||
def local_workers(n: int | None = None) -> int:
|
||||
if n is not None:
|
||||
return n
|
||||
given = os.environ.get("DASK_LOCAL_WORKERS")
|
||||
if given:
|
||||
value = int(given)
|
||||
if value < 1:
|
||||
raise ExecutionError("DASK_LOCAL_WORKERS must be at least 1")
|
||||
return value
|
||||
fits = psutil.virtual_memory().available // parse_bytes(memory_per_worker())
|
||||
return max(1, min(os.cpu_count() or 1, fits))
|
||||
|
||||
|
||||
def versions_error(client) -> str | None:
|
||||
try:
|
||||
from distributed.versions import error_message
|
||||
|
||||
v = client.get_versions(packages=list(CHECKED_PACKAGES))
|
||||
m = error_message(v["scheduler"], v["workers"], v["client"])
|
||||
return m["error"] or m["warning"] or None
|
||||
except Exception as e:
|
||||
return str(e) or type(e).__name__
|
||||
|
||||
|
||||
def dashboard_url(scheduler: str | None) -> str | None:
|
||||
given = os.environ.get("DASK_DASHBOARD_URL")
|
||||
if given:
|
||||
return given
|
||||
if scheduler:
|
||||
return f"http://{urlsplit(scheduler).hostname}:8787/status"
|
||||
return None
|
||||
|
||||
|
||||
def reference_dir(name: str) -> Path:
|
||||
root = os.environ.get("TEA_REFERENCE_ROOT")
|
||||
if not root:
|
||||
raise ValueError("TEA_REFERENCE_ROOT is not set")
|
||||
if not REFERENCE_NAME.match(name) or name in (".", ".."):
|
||||
raise ValueError(f"no reference cohort {name!r}")
|
||||
path = Path(root) / name
|
||||
if path.resolve().parent != Path(root).resolve() or not path.is_dir():
|
||||
raise ValueError(f"no reference cohort {name!r}")
|
||||
return path
|
||||
|
||||
|
||||
def reference_edfs(name: str) -> int:
|
||||
return sum(
|
||||
1 for p in reference_dir(name).rglob("*") if p.suffix.lower() == ".edf" and p.is_file()
|
||||
)
|
||||
|
||||
|
||||
def _dashboard_ok(url: str) -> bool:
|
||||
parts = urlsplit(url)
|
||||
try:
|
||||
with urllib.request.urlopen(f"{parts.scheme}://{parts.netloc}/health", timeout=3) as r:
|
||||
return 200 <= r.status < 300
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _expected_workers() -> int | None:
|
||||
try:
|
||||
return int(os.environ["DASK_EXPECTED_WORKERS"])
|
||||
except (KeyError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def health(execution: Execution | None = None, reference: str | None = None) -> Health:
|
||||
r = resolve(execution)
|
||||
if reference is not None and (not REFERENCE_NAME.match(reference) or reference in (".", "..")):
|
||||
raise ExecutionError(f"reference {reference!r} is not a cohort name")
|
||||
url = dashboard_url(r.scheduler)
|
||||
h = Health(
|
||||
mode=r.mode,
|
||||
scheduler=r.scheduler,
|
||||
reachable=False,
|
||||
expected_workers=_expected_workers(),
|
||||
dashboard_url=url,
|
||||
dashboard_ok=_dashboard_ok(url) if url else None,
|
||||
)
|
||||
|
||||
def count_here():
|
||||
try:
|
||||
return {"name": reference, "edfs": reference_edfs(reference)}
|
||||
except (OSError, ValueError):
|
||||
return {"name": reference, "edfs": None}
|
||||
|
||||
if r.mode != "remote":
|
||||
h.reachable = True
|
||||
h.workers = 1 if r.mode == "sync" else local_workers()
|
||||
h.threads = h.workers
|
||||
if reference is not None:
|
||||
h.reference = count_here()
|
||||
return h
|
||||
|
||||
from distributed import Client
|
||||
|
||||
client = None
|
||||
try:
|
||||
started = time.perf_counter()
|
||||
client = Client(r.scheduler, timeout=5)
|
||||
h.latency_ms = (time.perf_counter() - started) * 1000
|
||||
h.reachable = True
|
||||
info = client.scheduler_info()["workers"]
|
||||
h.workers = len(info)
|
||||
h.threads = sum(w["nthreads"] for w in info.values())
|
||||
h.version_error = versions_error(client)
|
||||
h.versions_ok = h.version_error is None
|
||||
if reference is not None and info:
|
||||
h.reference = {"name": reference, "edfs": None}
|
||||
try:
|
||||
h.reference["edfs"] = client.submit(
|
||||
reference_edfs, reference, pure=False, workers=[next(iter(info))]
|
||||
).result(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
elif reference is not None:
|
||||
h.reference = {"name": reference, "edfs": None}
|
||||
except Exception as e:
|
||||
if client is None:
|
||||
h.reachable = False
|
||||
h.error = str(e) or type(e).__name__
|
||||
finally:
|
||||
if client is not None:
|
||||
client.close()
|
||||
return h
|
||||
@@ -1,3 +1,5 @@
|
||||
"""Where the platform data lives. One env var per location; SQLite by default."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
"""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
|
||||
@@ -22,7 +26,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,
|
||||
"pipeline_id": item_id, # the item's id, whichever kind
|
||||
"version": version,
|
||||
"doc": doc.model_dump_json(exclude_none=True),
|
||||
"saved_at": datetime.now(UTC),
|
||||
@@ -33,13 +37,14 @@ def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
|
||||
return version
|
||||
|
||||
|
||||
def pipelines() -> list[dict]:
|
||||
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("pipelines", schema="config"):
|
||||
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 "
|
||||
"from config.pipelines group by pipeline_id order by pipeline_id"
|
||||
f"from config.{kind} group by pipeline_id order by pipeline_id"
|
||||
)
|
||||
return [dict(r) for r in con.execute(sql).mappings()]
|
||||
|
||||
@@ -52,11 +57,16 @@ def get(item_id: str, version: int | None = None, kind: str = "pipelines"):
|
||||
return version, KINDS[kind].model_validate_json(doc)
|
||||
|
||||
|
||||
def pipelines() -> list[dict]:
|
||||
return listing("pipelines")
|
||||
|
||||
|
||||
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__":
|
||||
if __name__ == "__main__": # python -m persistance.config_log <kind> <id> <doc.json>
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
"""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
|
||||
@@ -24,13 +31,14 @@ def _sqlite(attach: bool) -> Engine:
|
||||
|
||||
def platform():
|
||||
if platform_url().startswith("sqlite"):
|
||||
return dlt.destinations.sqlalchemy(_sqlite(attach=False))
|
||||
return dlt.destinations.sqlalchemy(_sqlite(attach=False)) # dlt attaches its own
|
||||
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"))
|
||||
return create_engine(make_url(url).set(drivername="postgresql+psycopg2")) # dlt's driver
|
||||
|
||||
+150
-248
@@ -1,24 +1,19 @@
|
||||
"""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
|
||||
import re
|
||||
from datetime import UTC, date, datetime
|
||||
from typing import Literal
|
||||
|
||||
import dlt
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from sqlalchemy import bindparam, inspect, text
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.measures import as_day
|
||||
from core.tea import ADOS2_ITEMS, ASSOCIATION_BIOMARKERS
|
||||
from core.tea.fhir import eeg_study_id
|
||||
from persistance import files
|
||||
from persistance.destination import engine, platform
|
||||
|
||||
_SCORE_JOIN = "left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code"
|
||||
VALUE_SCORE_JOIN = f"{_SCORE_JOIN} and s.part = 'value'"
|
||||
REGION_SCORE_JOIN = f"{_SCORE_JOIN} and s.part = m.part and s.site = m.site"
|
||||
|
||||
|
||||
def _text() -> dict:
|
||||
def _text() -> dict: # a new dict per column: dlt writes the column's name into it
|
||||
return {"data_type": "text", "nullable": True}
|
||||
|
||||
|
||||
@@ -57,13 +52,30 @@ METRICS = {
|
||||
"electrodes": _text(),
|
||||
"zones": _text(),
|
||||
}
|
||||
SITES = {
|
||||
ASSOCIATIONS = {
|
||||
"key": {"data_type": "text"},
|
||||
"edf": {"data_type": "text"},
|
||||
"code": _text(),
|
||||
"part": _text(),
|
||||
"site": _text(),
|
||||
"value": _number(),
|
||||
**{
|
||||
c: _text()
|
||||
for c in (
|
||||
"model",
|
||||
"biomarker",
|
||||
"metric",
|
||||
"zone",
|
||||
"kind",
|
||||
"outcome_code",
|
||||
"event",
|
||||
"principal",
|
||||
"sensitivity",
|
||||
"reason",
|
||||
)
|
||||
},
|
||||
**{c: _number() for c in ("n", "odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio")},
|
||||
"same_direction": {"data_type": "bool", "nullable": True},
|
||||
}
|
||||
ASSOCIATION_SCORES = {
|
||||
"key": {"data_type": "text"},
|
||||
**{c: _text() for c in ("edf", "model", "biomarker", "zone", "outcome_code")},
|
||||
**{c: _number() for c in ("z", "probability", "reference_probability", "observed")},
|
||||
}
|
||||
SCORES = {
|
||||
"key": {"data_type": "text"},
|
||||
@@ -80,95 +92,21 @@ def _write(name: str, rows: list[dict], columns: dict, key: str = "key") -> None
|
||||
dlt.pipeline(name, destination=platform(), dataset_name="bronze").run(resource)
|
||||
|
||||
|
||||
_ID = re.compile(r"^[^|]+\|\d{4}-\d{2}-\d{2}$")
|
||||
MAX_IDS = 500
|
||||
|
||||
|
||||
class Scope(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
extra="forbid",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Which EEGs an analysis takes: the pending ones, the first `n` of them, "
|
||||
"or the named\n"
|
||||
"ones (re-analysis), each named by the `id` that `/tea/eegs` shows."
|
||||
)
|
||||
},
|
||||
)
|
||||
mode: Literal["pending", "first_n", "ids"] = "pending"
|
||||
n: int | None = Field(None, ge=1)
|
||||
ids: list[str] = []
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _consistent(self):
|
||||
if self.mode == "first_n":
|
||||
if self.n is None:
|
||||
raise ValueError("first_n needs n")
|
||||
if self.ids:
|
||||
raise ValueError("first_n takes no ids")
|
||||
elif self.mode == "ids":
|
||||
if not self.ids:
|
||||
raise ValueError("ids needs a non-empty ids")
|
||||
if self.n is not None:
|
||||
raise ValueError("ids takes no n")
|
||||
if len(self.ids) > MAX_IDS:
|
||||
raise ValueError(f"ids takes at most {MAX_IDS} ids")
|
||||
bad = [i for i in self.ids if not _ID.match(i)]
|
||||
if bad:
|
||||
raise ValueError(f"ids must look like person|YYYY-MM-DD, not {bad[0]!r}")
|
||||
else:
|
||||
if self.n is not None:
|
||||
raise ValueError("pending takes no n")
|
||||
if self.ids:
|
||||
raise ValueError("pending takes no ids")
|
||||
return self
|
||||
|
||||
|
||||
def _with_dates(rows: list[dict]) -> list[dict]:
|
||||
for r in rows:
|
||||
if r["birth_date"] is not None and not isinstance(r["birth_date"], date):
|
||||
r["birth_date"] = as_day(r["birth_date"])
|
||||
return rows
|
||||
|
||||
|
||||
def pending() -> list[dict]:
|
||||
"""The hospital's EEG signals not analysed yet, each with the child's birth date."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("eeg", schema="silver"):
|
||||
return []
|
||||
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}
|
||||
order by e.edf
|
||||
""") # fmt: skip
|
||||
rows = [dict(r) for r in con.execute(sql).mappings()]
|
||||
return _with_dates(rows)
|
||||
|
||||
|
||||
def select(scope: Scope) -> list[dict]:
|
||||
if scope.mode == "pending":
|
||||
return pending()
|
||||
if scope.mode == "first_n":
|
||||
return pending()[: scope.n]
|
||||
found: dict[str, dict] = {}
|
||||
sql = text("""
|
||||
select 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.person_id = :p and cast(e.study_date as varchar(10)) = :d
|
||||
""") # fmt: skip
|
||||
with engine().connect() as con:
|
||||
for one in scope.ids:
|
||||
person, day = one.split("|")
|
||||
rows = con.execute(sql, {"p": person, "d": day}).mappings()
|
||||
row = next(iter(_with_dates([dict(r) for r in rows])), None)
|
||||
if row is None:
|
||||
raise LookupError(f"no EEG {one}")
|
||||
if row["edf"] is None:
|
||||
raise LookupError(f"EEG {one} has no signal")
|
||||
found.setdefault(row["edf"], row)
|
||||
return list(found.values())
|
||||
for r in rows: # SQLite gives dates as text
|
||||
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
|
||||
|
||||
|
||||
def signal(edf: str) -> bytes:
|
||||
@@ -179,8 +117,9 @@ 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, sites = [], [], [], []
|
||||
found, checks, metrics = [], [], []
|
||||
for edf, a in analyses.items():
|
||||
found.append({
|
||||
"edf": edf, "valid": a.valid, "level": a.level, "age_months": a.age_months,
|
||||
@@ -190,24 +129,16 @@ def save_analyses(analyses: dict[str, object]) -> None:
|
||||
"features": json.dumps(a.features), "error": a.error, "analysed_at": now,
|
||||
}) # fmt: skip
|
||||
checks += [{**c, "key": f"{edf}|{i}", "edf": edf} for i, c in enumerate(a.checks)]
|
||||
for m in a.metrics:
|
||||
metrics.append({
|
||||
"key": f"{edf}|{m.code}", "edf": edf, "code": m.code, "value": m.value,
|
||||
"electrodes": json.dumps(m.electrodes), "zones": json.dumps(m.zones),
|
||||
}) # fmt: skip
|
||||
for part in ("electrodes", "zones"):
|
||||
for site, value in getattr(m, part).items():
|
||||
sites.append({
|
||||
"key": f"{edf}|{m.code}|{part}|{site}", "edf": edf,
|
||||
"code": m.code, "part": part, "site": site, "value": value,
|
||||
}) # 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] # fmt: skip
|
||||
_write("eeg_analysis", found, ANALYSIS, key="edf")
|
||||
_write("eeg_checks", checks, CHECKS)
|
||||
_write("eeg_metrics", metrics, METRICS)
|
||||
_write("eeg_sites", sites, SITES)
|
||||
|
||||
|
||||
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 []
|
||||
@@ -228,12 +159,16 @@ def analysed() -> list[dict]:
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def without_diagnosis(as_of: date) -> list[dict]:
|
||||
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
|
||||
return []
|
||||
rows = con.execute(text("""
|
||||
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
|
||||
@@ -243,19 +178,96 @@ def without_diagnosis(as_of: date) -> list[dict]:
|
||||
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
|
||||
"""), {"as_of": as_of.isoformat()}).mappings() # fmt: skip
|
||||
""") # fmt: skip (ISO days compare as text on both engines)
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
b = codes.get(r["metric"])
|
||||
if b is not None:
|
||||
name = f"z_{b}" if r["part"] == "value" else f"z_{b}_{r['site']}"
|
||||
z.setdefault(r["edf"], {})[name] = r["z"]
|
||||
out = []
|
||||
for e in eegs:
|
||||
ados2 = first.get(e["person_id"])
|
||||
if ados2 is not None:
|
||||
out.append({**e, "ados2": ados2, **z.get(e["edf"], {})})
|
||||
return out
|
||||
|
||||
|
||||
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"):
|
||||
con.execute(text(f"delete from bronze.{table}"))
|
||||
_write("ados2_association", associations, ASSOCIATIONS)
|
||||
_write("ados2_association_scores", scores, ASSOCIATION_SCORES)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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})
|
||||
_write("eeg_scores", rows, SCORES)
|
||||
|
||||
|
||||
def _id(person_id: str, study_date) -> str:
|
||||
return f"{person_id}|{str(study_date)[:10]}"
|
||||
|
||||
|
||||
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 (
|
||||
@@ -267,61 +279,15 @@ def studies() -> list[dict]:
|
||||
order by e.study_date desc, e.person_id
|
||||
""") # fmt: skip
|
||||
rows = [dict(r) for r in con.execute(sql).mappings()]
|
||||
return [{"id": eeg_study_id(r["person_id"], r["study_date"]), "person_id": r["person_id"],
|
||||
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
|
||||
|
||||
|
||||
def summary() -> dict[str, int]:
|
||||
with engine().connect() as con:
|
||||
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
|
||||
join = "left join bronze.eeg_analysis as b on b.edf = a.edf" if has_analysis else ""
|
||||
analysed = "b.edf is not null" if has_analysis else "a.valid is not null"
|
||||
failed = "b.error is not null" if has_analysis else "false"
|
||||
studies = con.execute(text(f"""
|
||||
select
|
||||
count(*) as eegs,
|
||||
count(case when {analysed} then 1 end) as analysed,
|
||||
count(case when a.valid then 1 end) as valid,
|
||||
count(case when {analysed} and a.valid = false then 1 end) as not_valid,
|
||||
count(case when {analysed} and {failed} then 1 end) as failed
|
||||
from gold.tea_eeg_analyses as a {join}
|
||||
""")).mappings().one() # fmt: skip
|
||||
tables = inspect(con)
|
||||
if not tables.has_table("eeg_metrics", schema="bronze"):
|
||||
metrics = {"metrics": 0, "metrics_with_z": 0, "high": 0, "low": 0}
|
||||
else:
|
||||
scores = tables.has_table("eeg_scores", schema="bronze")
|
||||
join = VALUE_SCORE_JOIN if scores else ""
|
||||
z, outside = ("s.z", "s.outside") if scores else ("null", "null")
|
||||
metrics = con.execute(text(f"""
|
||||
select count(*) as metrics, count({z}) as metrics_with_z,
|
||||
count(case when {outside} > 0 then 1 end) as high,
|
||||
count(case when {outside} < 0 then 1 end) as low
|
||||
from bronze.eeg_metrics as m {join}
|
||||
where m.edf in (select edf from silver.eeg)
|
||||
""")).mappings().one() # fmt: skip
|
||||
served = """
|
||||
from silver.eeg as e
|
||||
join silver.person as p on p.person_id = e.person_id
|
||||
where e.edf is not null
|
||||
"""
|
||||
fhir_eegs = con.execute(text(f"select count(*) {served}")).scalar_one()
|
||||
fhir_metrics = 0
|
||||
if tables.has_table("eeg_metrics", schema="bronze"):
|
||||
fhir_metrics = con.execute(
|
||||
text(f"""
|
||||
select count(*) from bronze.eeg_metrics as m
|
||||
join (select e.edf {served}) as e on e.edf = m.edf
|
||||
""")
|
||||
).scalar_one()
|
||||
return {**studies, **metrics, "fhir_eegs": fhir_eegs, "fhir_metrics": fhir_metrics}
|
||||
|
||||
|
||||
def study(eeg_id: str) -> dict | None:
|
||||
if not _ID.fullmatch(eeg_id):
|
||||
return 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"):
|
||||
@@ -334,93 +300,29 @@ def study(eeg_id: str) -> dict | None:
|
||||
if head is None:
|
||||
return None
|
||||
scored = inspect(con).has_table("eeg_scores", schema="bronze")
|
||||
score = "s.z, s.outside, s.model" if scored else "null as z, null as outside, null as model"
|
||||
join = VALUE_SCORE_JOIN if scored else ""
|
||||
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, {score} from bronze.eeg_metrics as m {join}
|
||||
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
|
||||
found = [dict(m) for m in metrics]
|
||||
details = {}
|
||||
for kind in ("checks", "regions"):
|
||||
table = f"tea_eeg_{kind}"
|
||||
details[kind] = []
|
||||
if inspect(con).has_table(table, schema="gold"):
|
||||
rows = con.execute(
|
||||
text(f"select * from gold.{table} where eeg_id = :id"), {"id": eeg_id}
|
||||
).mappings()
|
||||
details[kind] = [
|
||||
{k: v for k, v in row.items() if k not in ("person_id", "eeg_id")}
|
||||
for row in rows
|
||||
]
|
||||
return {"id": eeg_id, "valid": head["valid"], "level": head["level"],
|
||||
"age_months": head["age_months"], "metrics": found, **details} # fmt: skip
|
||||
|
||||
|
||||
ASSOCIATIONS = {
|
||||
"key": {"data_type": "text"},
|
||||
"model": _text(),
|
||||
"level": _text(),
|
||||
"n_cohort": {"data_type": "bigint"},
|
||||
**{c: _text() for c in ("biomarker", "zone", "kind", "outcome_code", "event", "method")},
|
||||
"n": {"data_type": "bigint"},
|
||||
**{c: _number() for c in ("odds_ratio", "ci_low", "ci_high", "p", "q")},
|
||||
"sens_model": _text(),
|
||||
"sens_odds_ratio": _number(),
|
||||
"same_direction": {"data_type": "bool", "nullable": True},
|
||||
"reason": _text(),
|
||||
}
|
||||
ASSOCIATION_SCORES = {
|
||||
"key": {"data_type": "text"},
|
||||
**{c: _text() for c in ("model", "eeg_id", "pair")},
|
||||
**{c: _number() for c in ("z", "probability", "reference_probability")},
|
||||
}
|
||||
|
||||
|
||||
def _save_association(name: str, version: int, rows: list[dict], columns: dict) -> None:
|
||||
with engine().begin() as con:
|
||||
if inspect(con).has_table(name, schema="bronze"):
|
||||
con.execute(text(f"delete from bronze.{name}"))
|
||||
_write(name, [{**row, "model": f"tea.ados2_association/{version}"} for row in rows], columns)
|
||||
|
||||
|
||||
def save_associations(version: int, rows: list[dict]) -> None:
|
||||
_save_association("eeg_associations", version, rows, ASSOCIATIONS)
|
||||
|
||||
|
||||
def save_association_scores(version: int, rows: list[dict]) -> None:
|
||||
_save_association("eeg_association_scores", version, rows, ASSOCIATION_SCORES)
|
||||
|
||||
|
||||
def association_cohort_rows() -> tuple[list[dict], list[dict]]:
|
||||
studies, scores = [], []
|
||||
with engine().connect() as con:
|
||||
tables = inspect(con)
|
||||
if tables.has_table("eeg_analysis", schema="bronze"):
|
||||
items = ", ".join(ADOS2_ITEMS)
|
||||
selected_items = ", ".join(f"t.{i}" for i in ADOS2_ITEMS)
|
||||
query = text(f"""
|
||||
with first_ados as (
|
||||
select person_id, module, evaluation_date, {items},
|
||||
row_number() over (
|
||||
partition by person_id order by evaluation_date nulls last, known_at
|
||||
) as rn
|
||||
from silver.ados2
|
||||
)
|
||||
select e.person_id, e.study_date, e.edf, a.age_months,
|
||||
t.module, t.evaluation_date, p.birth_date, {selected_items}
|
||||
from silver.eeg as e
|
||||
join bronze.eeg_analysis as a on a.edf = e.edf
|
||||
join first_ados as t on t.person_id = e.person_id and t.rn = 1
|
||||
left join silver.person as p on p.person_id = e.person_id
|
||||
where a.valid and a.age_months is not null
|
||||
""")
|
||||
studies = [dict(row) for row in con.execute(query).mappings()]
|
||||
if studies and tables.has_table("eeg_scores", schema="bronze"):
|
||||
query = text("""
|
||||
select edf, metric, part, site, z from bronze.eeg_scores
|
||||
where metric in :metrics and z is not null
|
||||
""").bindparams(bindparam("metrics", expanding=True))
|
||||
metrics = list(ASSOCIATION_BIOMARKERS.values())
|
||||
scores = [dict(row) for row in con.execute(query, {"metrics": metrics}).mappings()]
|
||||
return studies, scores
|
||||
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 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
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""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, tea
|
||||
from core.measures import as_day
|
||||
from core import catalog
|
||||
from persistance.destination import engine
|
||||
from persistance.eeg import REGION_SCORE_JOIN, VALUE_SCORE_JOIN
|
||||
|
||||
PERSONS = """
|
||||
select p.person_id, p.birth_date, p.sex, d.death_date{extra}
|
||||
@@ -18,10 +19,6 @@ CACU_PERSONS = PERSONS.format(
|
||||
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
|
||||
)
|
||||
CAMA_PERSONS = PERSONS.format(extra="", join="")
|
||||
TEA_PERSONS = PERSONS.format(
|
||||
extra=", f.status, f.step, f.age_group",
|
||||
join=" left join gold.tea_follow_up as f on f.person_id = p.person_id",
|
||||
)
|
||||
|
||||
COMMON = {
|
||||
"names": "select person_id, text from silver.person_name where person_id in :persons",
|
||||
@@ -40,6 +37,7 @@ COMMON = {
|
||||
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
|
||||
@@ -54,62 +52,13 @@ COMMON = {
|
||||
""",
|
||||
}
|
||||
|
||||
_TEA_EEG_SCOPE = "e.edf is not null and e.person_id in :persons and e.study_date <= :cutoff"
|
||||
_TEA_EEG_SOURCE = "from silver.eeg as e join silver.person as p on p.person_id = e.person_id"
|
||||
_TEA_SCORE_FIELDS = "z, outside, p5, median, p95, model"
|
||||
_TEA_ALTERATIONS = ", ".join(f"f.alt_{metric}" for metric in tea.EEG_METRICS)
|
||||
|
||||
TEA_PERSONS = PERSONS.format(extra="", join="")
|
||||
|
||||
READS = {
|
||||
"tea": {
|
||||
"births": "select person_id, birth_date from silver.person where person_id in :persons",
|
||||
"person": TEA_PERSONS + " where p.person_id = :id",
|
||||
"persons": TEA_PERSONS + " order by p.person_id",
|
||||
"follow_up": "select * from gold.tea_follow_up where start_date <= :cutoff",
|
||||
"eegs": f"""
|
||||
select e.person_id, e.study_date, e.edf, {{analysis_fields}}
|
||||
{_TEA_EEG_SOURCE} {{analysis_join}}
|
||||
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, e.edf
|
||||
""",
|
||||
"checks": f"""
|
||||
select e.person_id, e.study_date, c.*
|
||||
{_TEA_EEG_SOURCE} join bronze.eeg_checks as c on c.edf = e.edf
|
||||
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, c.code, c.electrode
|
||||
""",
|
||||
"metrics": f"""
|
||||
select e.person_id, e.study_date, m.edf, m.code, m.value, {{score_fields}}
|
||||
{_TEA_EEG_SOURCE} join bronze.eeg_metrics as m on m.edf = e.edf
|
||||
{{score_join}}
|
||||
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, m.code
|
||||
""",
|
||||
"regions": f"""
|
||||
select e.person_id, e.study_date, m.edf, m.code, m.site, m.value,
|
||||
case m.part when 'electrodes' then 'electrode' when 'zones' then 'zone' end as kind,
|
||||
{{score_fields}}
|
||||
{_TEA_EEG_SOURCE} join bronze.eeg_sites as m on m.edf = e.edf
|
||||
{{score_join}}
|
||||
where {_TEA_EEG_SCOPE} order by e.person_id, e.study_date, m.code, m.part, m.site
|
||||
""",
|
||||
"association_scores": f"""
|
||||
select s.person_id, s.study_date, s.pair, s.model, s.probability,
|
||||
s.reference_probability, e.edf,
|
||||
a.biomarker, a.n, a.n_cohort, a.level, a.q, a.odds_ratio,
|
||||
a.ci_low, a.ci_high, a.same_direction, {_TEA_ALTERATIONS},
|
||||
(select min(t.evaluation_date) from silver.ados2 as t
|
||||
where t.person_id = s.person_id and t.evaluation_date <= :cutoff
|
||||
) as evaluation_date
|
||||
from gold.tea_association_scores as s
|
||||
join gold.tea_associations as a on a.key = s.pair and a.model = s.model
|
||||
join silver.eeg as e on e.person_id = s.person_id and e.study_date = s.study_date
|
||||
join silver.person as p on p.person_id = e.person_id
|
||||
left join gold.tea_follow_up as f on f.person_id = s.person_id
|
||||
where {_TEA_EEG_SCOPE}
|
||||
order by s.person_id, s.study_date, e.edf, s.pair
|
||||
""",
|
||||
},
|
||||
"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
|
||||
@@ -117,21 +66,62 @@ READS = {
|
||||
group by person_id) as w on w.person_id = x.person_id
|
||||
order by w.recent desc, x.person_id
|
||||
""",
|
||||
"diagnosis_days": """
|
||||
select person_id, sample_date, days_sample_diagnosis as days
|
||||
from gold.cacu_samples
|
||||
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
|
||||
# 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
|
||||
""",
|
||||
},
|
||||
"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)),
|
||||
},
|
||||
"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
|
||||
@@ -144,11 +134,15 @@ READS = {
|
||||
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
|
||||
@@ -157,50 +151,24 @@ READS = {
|
||||
}
|
||||
|
||||
|
||||
_TEA_OPTIONAL = {"checks": "eeg_checks", "metrics": "eeg_metrics", "regions": "eeg_sites"}
|
||||
|
||||
|
||||
def _tea_sql(query, kind, tables):
|
||||
if kind == "eegs":
|
||||
fields = ("valid", "duration_min", "age_months", "channels")
|
||||
analysed = tables.has_table("eeg_analysis", schema="bronze")
|
||||
return query.format(
|
||||
analysis_fields=", ".join(f"a.{f}" if analysed else f"null as {f}" for f in fields),
|
||||
analysis_join="left join bronze.eeg_analysis as a on a.edf = e.edf" if analysed else "",
|
||||
)
|
||||
if kind in _TEA_OPTIONAL and not tables.has_table(_TEA_OPTIONAL[kind], schema="bronze"):
|
||||
return None
|
||||
if kind in ("metrics", "regions"):
|
||||
scored = tables.has_table("eeg_scores", schema="bronze")
|
||||
score_join = REGION_SCORE_JOIN if kind == "regions" else VALUE_SCORE_JOIN
|
||||
return query.format(
|
||||
score_fields=", ".join(
|
||||
f"s.{f}" if scored else f"null as {f}" for f in _TEA_SCORE_FIELDS.split(", ")
|
||||
),
|
||||
score_join=score_join if scored else "",
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def rows(domain: str, kind: str, **params) -> list[dict]:
|
||||
if any(many in params and not params[many] for many in ("persons", "types")):
|
||||
return []
|
||||
query = (READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain)
|
||||
"""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:
|
||||
sql = sql.bindparams(bindparam(many, expanding=True))
|
||||
if not params[many]:
|
||||
return []
|
||||
with engine().connect() as con:
|
||||
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
|
||||
return []
|
||||
if domain == "tea":
|
||||
query = _tea_sql(query, kind, inspect(con))
|
||||
if query is None:
|
||||
return []
|
||||
sql = text(query)
|
||||
for many in ("persons", "types"):
|
||||
if many in params:
|
||||
sql = sql.bindparams(bindparam(many, expanding=True))
|
||||
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)
|
||||
sql = text(
|
||||
@@ -216,9 +184,11 @@ 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"):
|
||||
return None
|
||||
found = con.execute(sql, {"today": date.today().isoformat()}).scalar()
|
||||
return as_day(found)
|
||||
return None if found is None else date.fromisoformat(str(found)[:10])
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
"""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
|
||||
@@ -10,7 +15,7 @@ from sqlalchemy.types import TypeEngine
|
||||
from persistance.destination import engine
|
||||
|
||||
TABLE = "files"
|
||||
INSERT_BYTES = 32_000_000
|
||||
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
|
||||
|
||||
@@ -19,10 +24,15 @@ def key(content: bytes) -> str:
|
||||
return hashlib.sha256(content).hexdigest()
|
||||
|
||||
|
||||
FLUSH_BYTES = 256_000_000
|
||||
FLUSH_BYTES = 256_000_000 # file contents stored per load
|
||||
|
||||
|
||||
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] = []
|
||||
@@ -57,10 +67,13 @@ 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()
|
||||
@@ -69,6 +82,8 @@ 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:
|
||||
@@ -80,7 +95,7 @@ def keep(contents: dict[str, bytes]) -> None:
|
||||
if k in have:
|
||||
continue
|
||||
row = {"key": k, "content": c}
|
||||
if "_dlt_id" in columns:
|
||||
if "_dlt_id" in columns: # a table an earlier platform made through dlt
|
||||
row |= {"_dlt_load_id": "files", "_dlt_id": k[:14]}
|
||||
batch.append(row)
|
||||
size += len(c)
|
||||
@@ -98,6 +113,7 @@ def _with_dlt():
|
||||
|
||||
|
||||
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
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user