Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b9ed108855 |
@@ -1,106 +0,0 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [rebuild]
|
||||
pull_request:
|
||||
branches: [rebuild]
|
||||
|
||||
env:
|
||||
# Submodule URLs are SSH; the runner reaches the same repos over the server's HTTP.
|
||||
GIT_CONFIG_COUNT: 1
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
|
||||
jobs:
|
||||
python: # the whole suite, nothing skipped: SQLite and PostgreSQL, OCR included
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: platform
|
||||
options: >-
|
||||
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
|
||||
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
|
||||
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
|
||||
env:
|
||||
ACCEPT_EULA: "Y"
|
||||
MSSQL_PID: Developer
|
||||
MSSQL_SA_PASSWORD: Test-only-Site-1
|
||||
options: >-
|
||||
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
|
||||
--health-interval 5s --health-timeout 10s --health-retries 30
|
||||
env:
|
||||
POSTGRES_TEST_URL: postgresql://postgres:postgres@postgres:5432/platform
|
||||
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
|
||||
PGHOST: postgres
|
||||
FHIR_VALIDATOR_JAR: /opt/fhir/validator_cli.jar
|
||||
SYNTHEA_JAR: /opt/synthea/synthea.jar
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: git submodule update --init
|
||||
- run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
|
||||
default-jre-headless
|
||||
- name: HL7 validator, pinned
|
||||
run: |
|
||||
mkdir -p /opt/fhir
|
||||
curl -sLo /opt/fhir/validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar
|
||||
echo "9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f /opt/fhir/validator_cli.jar" | sha256sum -c
|
||||
- name: Synthea, pinned
|
||||
run: |
|
||||
mkdir -p /opt/synthea
|
||||
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
|
||||
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
- run: uv sync --locked
|
||||
- run: uv run ruff check
|
||||
- run: uv run ruff format --check
|
||||
- run: uv run lint-imports
|
||||
- run: uv run pytest -q -rs -m "not webapp" # the pages run in the web job
|
||||
|
||||
web:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
|
||||
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
|
||||
env:
|
||||
ACCEPT_EULA: "Y"
|
||||
MSSQL_PID: Developer
|
||||
MSSQL_SA_PASSWORD: Test-only-Site-1
|
||||
options: >-
|
||||
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
|
||||
--health-interval 5s --health-timeout 10s --health-retries 30
|
||||
env:
|
||||
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
|
||||
SYNTHEA_JAR: /opt/synthea/synthea.jar
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: git submodule update --init
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
- name: Generated API client matches the API
|
||||
run: |
|
||||
uv sync --locked
|
||||
uv run python -m webapi.openapi > WebApp/openapi.json
|
||||
cd WebApp && npm ci && npm run api
|
||||
git diff --exit-code -- . || { echo 'Run: npm run api (after exporting openapi.json)'; exit 1; }
|
||||
- working-directory: WebApp
|
||||
run: npx ng build
|
||||
- working-directory: WebApp
|
||||
run: npx ng test --watch=false
|
||||
- name: Every page loads from the API (Playwright over a loaded platform)
|
||||
run: |
|
||||
apt-get update
|
||||
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
|
||||
+4
-7
@@ -1,10 +1,7 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
deploy/.env
|
||||
data/
|
||||
*.db
|
||||
.dlt/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
compose.override.yml
|
||||
!tests/fixtures/**/*.db
|
||||
.env
|
||||
WebApp/node_modules/
|
||||
WebApp/dist/
|
||||
WebApp/.angular/
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
[submodule "WebApi"]
|
||||
path = WebApi
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
||||
branch = rebuild
|
||||
[submodule "WebApp"]
|
||||
path = WebApp
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
||||
branch = rebuild
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
branch = rebuild
|
||||
@@ -1,26 +0,0 @@
|
||||
[importlinter]
|
||||
root_packages =
|
||||
core
|
||||
persistance
|
||||
models
|
||||
webapi
|
||||
synthetic
|
||||
|
||||
[importlinter:contract:layers]
|
||||
name = WebApi and models sit on Persistance, which sits on Core
|
||||
type = layers
|
||||
layers =
|
||||
webapi | models
|
||||
persistance
|
||||
core
|
||||
|
||||
[importlinter:contract:synthetic]
|
||||
name = Product packages never import the synthetic hospital
|
||||
type = forbidden
|
||||
source_modules =
|
||||
core
|
||||
persistance
|
||||
models
|
||||
webapi
|
||||
forbidden_modules =
|
||||
synthetic
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
|
||||
+45
-57
@@ -1,16 +1,8 @@
|
||||
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
|
||||
import them. Codes are the platform's (core.schema)."""
|
||||
|
||||
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
|
||||
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
|
||||
CANCER = ["carcinoma"]
|
||||
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
|
||||
|
||||
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
|
||||
CASE = ["CIS", "carcinoma"]
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
|
||||
FOLLOW_UP_WINDOW = 3
|
||||
|
||||
# Index cytology in the six KPNC categories, least to most severe.
|
||||
KPNC = {
|
||||
"NILM": ["NILM"],
|
||||
"ASC-US": ["ASC-US"],
|
||||
@@ -19,74 +11,70 @@ 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"],
|
||||
}
|
||||
|
||||
# The referral PPVs (core.cacu.measures.ReferralPPV). Cytology groups overlap: each holds its
|
||||
# grade and every more severe squamous one. Histology levels are numerators over one
|
||||
# denominator; the first is the measure's score.
|
||||
PPV_CYTOLOGY = {
|
||||
"ASCUS+": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
|
||||
"LSIL+": ["LSIL", "ASC-H", "HSIL", "CIS"],
|
||||
"HSIL+": ["HSIL", "CIS"],
|
||||
}
|
||||
PPV_HISTOLOGY = {"LIEBG+": ["LSIL", *CIN2_PLUS], "LIEAG+": CIN2_PLUS, "invasive": CANCER}
|
||||
PREVIOUS_SCREENING = ["1_year_or_less", "2_years", "3_years_or_more"] # screening_history
|
||||
REFERRAL_CYTOLOGY_DAYS = 365 # the referring cytology's report is at most this old
|
||||
|
||||
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
|
||||
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
|
||||
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
|
||||
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
|
||||
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
|
||||
INDEX_SAMPLE_DAYS = 30
|
||||
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12
|
||||
DAYS_PER_YEAR = 365.25
|
||||
|
||||
# Recruitment windows (start inclusive, end exclusive).
|
||||
RECRUITMENT = ("2018-01-01", "2027-01-01")
|
||||
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
|
||||
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
|
||||
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
|
||||
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
|
||||
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
|
||||
POST_TREATMENT_INDEX_AFTER_DAYS = 90
|
||||
POST_TREATMENT_LOOKBACK_DAYS = 365
|
||||
POST_COLPOSCOPY_VISIT = 1
|
||||
REFERRAL_LOOKBACK_DAYS = 365
|
||||
HYSTERECTOMY_ICD10 = ["Z907"]
|
||||
|
||||
# Inferred procedures, from clinical notes (ICD-10 without the dot).
|
||||
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
|
||||
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
|
||||
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
|
||||
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
|
||||
SAMPLE_TO_DIAGNOSIS_DAYS = 120
|
||||
DIAGNOSIS_ICD10 = [
|
||||
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
|
||||
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
|
||||
] # fmt: skip
|
||||
"Z014",
|
||||
"Z124",
|
||||
"B977",
|
||||
"R876",
|
||||
"N87",
|
||||
"N870",
|
||||
"N871",
|
||||
"N872",
|
||||
"N879",
|
||||
"D06",
|
||||
"D060",
|
||||
"D061",
|
||||
"D067",
|
||||
"D069",
|
||||
"C53",
|
||||
"C530",
|
||||
"C531",
|
||||
"C538",
|
||||
"C539",
|
||||
]
|
||||
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
|
||||
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
|
||||
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
|
||||
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
|
||||
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
|
||||
|
||||
|
||||
# Measures (core.measures): the horizons of the screening route, in days; an interval
|
||||
# that hasn't ended after its horizon counts as not ended.
|
||||
HORIZONS = {
|
||||
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
|
||||
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
|
||||
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
|
||||
} # fmt: skip
|
||||
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
|
||||
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
|
||||
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
|
||||
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
|
||||
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
|
||||
"sample_to_report": 60,
|
||||
"sample_to_treatment": 180,
|
||||
"diagnosis_to_treatment": 60,
|
||||
"sample_to_colposcopy": 60,
|
||||
"sample_to_biopsy": 60,
|
||||
"result_to_colposcopy": 60,
|
||||
"colposcopy_to_biopsy": 60,
|
||||
"biopsy_to_diagnosis": 60,
|
||||
}
|
||||
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"]
|
||||
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"]
|
||||
DETECTION = ["HSIL", "CIS", "carcinoma"]
|
||||
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"]
|
||||
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)]
|
||||
RISK_BAND_MODEL = "cacu.cin2_pim"
|
||||
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)]
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
"""What dbt reads (`var('cacu')`)."""
|
||||
return {k.lower(): v for k, v in globals().items() if k.isupper()}
|
||||
|
||||
@@ -1,49 +1,37 @@
|
||||
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
|
||||
it is read in. The list holds every patient with a cytology sampled within the window
|
||||
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import date
|
||||
|
||||
from core import cacu
|
||||
from core.cacu.measures import follow_up_status
|
||||
|
||||
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
|
||||
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
|
||||
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
|
||||
DEFAULT_HORIZON = 5.0
|
||||
WINDOWS = cacu.FOLLOW_UP_WINDOWS
|
||||
STATUS_SYSTEM = "cacu-follow-up-status"
|
||||
PROCEDURES = ("colposcopy", "treatment")
|
||||
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"} # days from the sample to its diagnosis
|
||||
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"}
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> str:
|
||||
"""Her follow-up status by the end of the cut-off day."""
|
||||
return follow_up_status(row, cutoff, through=True)
|
||||
|
||||
|
||||
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
|
||||
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
|
||||
her status."""
|
||||
return [{**r, "status": status(r, cutoff)} for r in rows]
|
||||
|
||||
|
||||
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
|
||||
"""Her current risk of an outcome at a horizon (years): from the latest index date any
|
||||
of the outcome's models scored her at; the highest when several did."""
|
||||
prefix = OUTCOMES[outcome]
|
||||
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
|
||||
if not mine:
|
||||
return None
|
||||
latest = max(str(r["index_date"]) for r in mine)
|
||||
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
|
||||
latest = max((str(r["index_date"]) for r in mine))
|
||||
return max((r["probability"] for r in mine if str(r["index_date"]) == latest))
|
||||
|
||||
|
||||
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
|
||||
horizon: float) -> list[dict]: # fmt: skip
|
||||
"""The list in reading order. `rows` come most recent first; by risk, highest first,
|
||||
unscored patients last, ties kept most recent first."""
|
||||
def ordered(
|
||||
rows: list[dict], sort: str, risks: dict[str, list[dict]], horizon: float
|
||||
) -> list[dict]:
|
||||
if sort == "-recent":
|
||||
return rows
|
||||
outcome = sort.removeprefix("-risk-")
|
||||
|
||||
+180
-331
@@ -1,9 +1,4 @@
|
||||
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
import statistics
|
||||
|
||||
from core import cacu
|
||||
from core.measures import (
|
||||
NO_BIOPSY,
|
||||
@@ -11,49 +6,47 @@ from core.measures import (
|
||||
Composition,
|
||||
Duration,
|
||||
Measure,
|
||||
Period,
|
||||
Proportion,
|
||||
Result,
|
||||
RiskBand,
|
||||
Result,
|
||||
age_group,
|
||||
as_day,
|
||||
desc,
|
||||
wilson,
|
||||
)
|
||||
|
||||
|
||||
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
|
||||
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
|
||||
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
|
||||
cancer; what follows her is survival."""
|
||||
|
||||
def by(first: str) -> bool:
|
||||
day = as_day(row.get(first))
|
||||
return day is not None and (day <= at if through else day < at)
|
||||
|
||||
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
|
||||
("first_colposcopy", "post_colposcopy")): # fmt: skip
|
||||
for first, status in (
|
||||
("first_case", "case"),
|
||||
("first_treatment", "post_treatment"),
|
||||
("first_colposcopy", "post_colposcopy"),
|
||||
):
|
||||
if by(first):
|
||||
return status
|
||||
return "pre_colposcopy"
|
||||
|
||||
|
||||
def valid(row: dict) -> bool:
|
||||
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
|
||||
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
|
||||
|
||||
|
||||
def latest(row: dict) -> tuple:
|
||||
"""A patient's latest valid sample ranks highest."""
|
||||
return valid(row), as_day(row["sample_date"]), row["sample_id"]
|
||||
return (valid(row), as_day(row["sample_date"]), row["sample_id"])
|
||||
|
||||
|
||||
def latest_most_severe_biopsy(row: dict) -> tuple:
|
||||
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
|
||||
reported = row.get("biopsy_report_date") is not None
|
||||
return (*latest(row), reported, row.get("severity") or 0,
|
||||
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
|
||||
return (
|
||||
*latest(row),
|
||||
reported,
|
||||
row.get("severity") or 0,
|
||||
desc(as_day(row.get("biopsy_report_date"))),
|
||||
desc(row.get("biopsy_id")),
|
||||
)
|
||||
|
||||
|
||||
def result(row: dict) -> str:
|
||||
@@ -61,7 +54,6 @@ def result(row: dict) -> str:
|
||||
|
||||
|
||||
def histology(row: dict) -> str:
|
||||
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
|
||||
if not valid(row):
|
||||
return NO_DATA
|
||||
if row.get("biopsy_report_date") is None:
|
||||
@@ -69,318 +61,175 @@ def histology(row: dict) -> str:
|
||||
return row.get("histology") or NO_DATA
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BiopsyRequests:
|
||||
"""Recorded request units, classified at the event cutoff, not all HIS referrals."""
|
||||
kind: str = "composition"
|
||||
|
||||
def evaluate(self, rows, period, cutoff):
|
||||
chosen = {}
|
||||
severity = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY, 1)}
|
||||
for row in rows:
|
||||
request = as_day(row.get("request_date"))
|
||||
if request not in period or request > cutoff:
|
||||
continue
|
||||
reported = as_day(row.get("report_date"))
|
||||
if (row.get("rows_merged") or 0) > 1:
|
||||
category, rank = "ambiguous", (4, 0, date.min)
|
||||
elif reported is None or reported > cutoff:
|
||||
category, rank = "pending", (0, 0, date.min)
|
||||
elif reported < request:
|
||||
category, rank = "inconsistent", (1, 0, reported)
|
||||
elif row.get("histology") is None:
|
||||
category, rank = "no_grade", (2, 0, reported)
|
||||
elif row["histology"] not in severity:
|
||||
category, rank = "unclassified", (2, 0, reported)
|
||||
else:
|
||||
grade = row["histology"]
|
||||
category = "high_grade" if grade in cacu.CIN2_PLUS else "below_high_grade"
|
||||
rank = (3, severity[grade], reported)
|
||||
key = row["request_id"]
|
||||
if key not in chosen or rank > chosen[key][0]:
|
||||
chosen[key] = (rank, category)
|
||||
categories = {}
|
||||
for _, category in chosen.values():
|
||||
cell = categories.setdefault(category, {"initial-population": 0})
|
||||
cell["initial-population"] += 1
|
||||
count = len(chosen)
|
||||
return Result({"initial-population": count, "measure-observation": count},
|
||||
strata={"category": categories})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiagnosisDurations:
|
||||
kind: str = "continuous-variable"
|
||||
strata: tuple = (("diagnosis_code", None),)
|
||||
|
||||
def evaluate(self, rows, period, cutoff):
|
||||
rule = Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
|
||||
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0)
|
||||
overall = rule.evaluate(rows, period, cutoff)
|
||||
grouped = {}
|
||||
for row in {r["sample_id"]: r for r in rows}.values():
|
||||
if (row["sample_date"] not in period or row["history"] != 0
|
||||
or row.get("days_sample_diagnosis") is None
|
||||
or as_day(row.get("diagnosis_date")) is None
|
||||
or as_day(row["diagnosis_date"]) > cutoff):
|
||||
continue
|
||||
code = row.get("diagnosis_code") or "sin_codigo"
|
||||
grouped.setdefault(code, []).append(row)
|
||||
cells, scores = {}, {}
|
||||
for code, group in grouped.items():
|
||||
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
|
||||
median = statistics.median(values)
|
||||
q1, q3 = (values[0], values[0]) if len(values) == 1 else (statistics.quantiles(values, n=4, method="inclusive")[0], statistics.quantiles(values, n=4, method="inclusive")[2])
|
||||
descriptions = {r.get("diagnosis_description") for r in group if r.get("diagnosis_description")}
|
||||
label = code + (" | " + next(iter(descriptions)) if len(descriptions) == 1 else "")
|
||||
cells[label] = {"measure-observation": len(values)}
|
||||
scores[label] = {"value": median, "unit": "d", "extension": [
|
||||
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
|
||||
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3}]}
|
||||
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
|
||||
{"diagnosis_code": cells}, {"diagnosis_code": scores})
|
||||
|
||||
|
||||
def referring_cytology(cytologies: list[dict], day: date) -> dict | None:
|
||||
"""Her latest valid cytology sampled and reported before `day` (a result of that same
|
||||
day doesn't count: dates can't say which came first), its report at most
|
||||
REFERRAL_CYTOLOGY_DAYS old."""
|
||||
found = [
|
||||
c for c in cytologies
|
||||
if valid(c) and c.get("result") is not None
|
||||
and as_day(c["date"]) < day and as_day(c["result_date"]) < day
|
||||
and (day - as_day(c["result_date"])).days <= cacu.REFERRAL_CYTOLOGY_DAYS
|
||||
] # fmt: skip
|
||||
return max(found, key=lambda c: (as_day(c["date"]), as_day(c["result_date"]),
|
||||
c["sample_id"]), default=None) # fmt: skip
|
||||
|
||||
|
||||
def screening_round(cytology: dict | None) -> str:
|
||||
"""`subsequent`: screened before (as her form says) or already past colposcopy or
|
||||
treatment at the sample; `initial`: the first screening of her life, before colposcopy."""
|
||||
if cytology is None:
|
||||
return NO_DATA
|
||||
# a referral fact is dated `date`; a gold sample `sample_date`
|
||||
status = follow_up_status(cytology, as_day(cytology.get("date") or cytology["sample_date"]))
|
||||
history = cytology.get("screening_history")
|
||||
if history in cacu.PREVIOUS_SCREENING or status in ("post_colposcopy", "post_treatment"):
|
||||
return "subsequent"
|
||||
return "initial" if history == "first_time" else NO_DATA
|
||||
|
||||
|
||||
def hpv_result(row: dict) -> str | None:
|
||||
"""Her high-risk HPV result on a sample; none when it has none."""
|
||||
return None if row.get("hpv") is None else "positive" if row["hpv"] else "negative"
|
||||
|
||||
|
||||
def hpv_groups(cytology: dict | None) -> list[str]:
|
||||
"""The referral PPVs' HPV groups of a referring cytology: its result and, apart, each
|
||||
genotype it was positive for (they overlap with `positive`, and may with each other)."""
|
||||
row = cytology or {}
|
||||
found = [name for name in (hpv_result(row),) if name]
|
||||
found += [name for name in ("hpv_16", "hpv_18") if row.get(name)]
|
||||
return found or [NO_DATA]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReferralPPV:
|
||||
"""Of the patients with a procedure in the period, those whose histology confirms the
|
||||
first level of PPV_HISTOLOGY. Rows are facts (`gold.cacu_referral_facts`: `fact` is
|
||||
cytology, colposcopy or biopsy, each dated `date`), so the referring cytology is chosen
|
||||
among those known at the evaluation's `as_of`.
|
||||
|
||||
A patient counts once, with her first procedure of the period that qualifies: she wasn't
|
||||
a case already (at her referring sample, or at the procedure without one) and, for the
|
||||
biopsy PPV, a biopsy requested that day has a histology. Its histology is that of the
|
||||
biopsies requested that day and reported by the cut-off; with none, not confirmed."""
|
||||
|
||||
procedure: str # "colposcopy" or "biopsy"
|
||||
kind: str = "proportion"
|
||||
strata: tuple[tuple[str, None], ...] = (
|
||||
("referral_cytology", None), ("referral_hpv", None), ("histology_level", None),
|
||||
("screening_round", None),
|
||||
) # fmt: skip
|
||||
|
||||
def _units(self, rows: list[dict], period: Period, cutoff: date):
|
||||
"""Per patient counted: the histologies of her procedure and its referring cytology."""
|
||||
mine: dict[str, dict[str, list[dict]]] = {}
|
||||
for row in rows:
|
||||
mine.setdefault(row["person_id"], {}).setdefault(row["fact"], []).append(row)
|
||||
for facts in mine.values():
|
||||
procedures: dict[date, list[dict]] = {}
|
||||
for row in facts.get(self.procedure, []):
|
||||
day = as_day(row["date"])
|
||||
if day in period and day <= cutoff:
|
||||
procedures.setdefault(day, []).append(row)
|
||||
for day in sorted(procedures):
|
||||
found = {
|
||||
b["histology"] for b in facts.get("biopsy", [])
|
||||
if as_day(b["date"]) == day and b.get("histology") is not None
|
||||
and b.get("report_date") is not None
|
||||
and day <= as_day(b["report_date"]) <= cutoff
|
||||
} # fmt: skip
|
||||
if self.procedure == "biopsy" and not found:
|
||||
continue
|
||||
cytology = referring_cytology(facts.get("cytology", []), day)
|
||||
at = day if cytology is None else as_day(cytology["date"])
|
||||
if follow_up_status(cytology or procedures[day][0], at) == "case":
|
||||
continue
|
||||
yield found, cytology
|
||||
break
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
units = list(self._units(rows, period, cutoff))
|
||||
|
||||
def cell(members: list, level: list[str]) -> dict[str, int]:
|
||||
n = len(members)
|
||||
return {"initial-population": n, "denominator": n,
|
||||
"numerator": sum(bool(found & set(level)) for found, _ in members)} # fmt: skip
|
||||
|
||||
score_level = next(iter(cacu.PPV_HISTOLOGY.values()))
|
||||
total = cell(units, score_level)
|
||||
strata: dict[str, dict] = {name: {} for name, _ in self.strata}
|
||||
if not units:
|
||||
return Result(total, strata=strata)
|
||||
groups: dict[str, list] = {}
|
||||
for unit in units:
|
||||
cytology = unit[1]
|
||||
names = (
|
||||
[NO_DATA]
|
||||
if cytology is None
|
||||
else [g for g, codes in cacu.PPV_CYTOLOGY.items() if cytology["result"] in codes]
|
||||
)
|
||||
for name in names:
|
||||
groups.setdefault(name, []).append(unit)
|
||||
strata["referral_cytology"] = {g: cell(u, score_level) for g, u in groups.items()}
|
||||
by_hpv: dict[str, list] = {}
|
||||
for unit in units:
|
||||
for name in hpv_groups(unit[1]):
|
||||
by_hpv.setdefault(name, []).append(unit)
|
||||
strata["referral_hpv"] = {g: cell(u, score_level) for g, u in by_hpv.items()}
|
||||
strata["histology_level"] = {
|
||||
name: cell(units, level) for name, level in cacu.PPV_HISTOLOGY.items()
|
||||
}
|
||||
rounds: dict[str, list] = {}
|
||||
for unit in units:
|
||||
rounds.setdefault(screening_round(unit[1]), []).append(unit)
|
||||
strata["screening_round"] = {g: cell(u, score_level) for g, u in rounds.items()}
|
||||
k, n = total["numerator"], total["denominator"]
|
||||
low, high = wilson(k, n)
|
||||
return Result(total, k / n, {"ic-bajo": low, "ic-alto": high}, strata=strata)
|
||||
|
||||
|
||||
H = cacu.HORIZONS
|
||||
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
|
||||
NO_HISTORY = lambda row: row["history"] == 0
|
||||
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
|
||||
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
|
||||
RESULT = ("result", lambda row, p: row["result"])
|
||||
SCREENING = ("screening_round", lambda row, p: screening_round(row))
|
||||
|
||||
|
||||
def results_of(wanted: str):
|
||||
"""The results of the patients in one screening round (the others are in no group)."""
|
||||
return (f"result_{wanted}",
|
||||
lambda row, p: result(row) if screening_round(row) == wanted else None) # fmt: skip
|
||||
|
||||
|
||||
def genotype(name: str):
|
||||
"""A genotype's result on the chosen sample (in no group when not reported)."""
|
||||
return (name, lambda row, p: None if row.get(name) is None
|
||||
else "positive" if row[name] else "negative") # fmt: skip
|
||||
|
||||
|
||||
def hpv_of(wanted: str):
|
||||
"""The HPV results of the patients in one screening round."""
|
||||
return (f"hpv_{wanted}",
|
||||
lambda row, p: hpv_result(row) if screening_round(row) == wanted else None) # fmt: skip
|
||||
|
||||
|
||||
MEASURES = {m.id: m for m in [
|
||||
Measure("IND1", "Pacientes con citología anormal", "samples",
|
||||
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
|
||||
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
|
||||
Proportion(lambda r: r.get("histology") in cacu.DETECTION
|
||||
and r.get("biopsy_report_date") is not None,
|
||||
strata=(AGE, STATUS)), group="principal"),
|
||||
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
|
||||
Composition(latest, result, strata=(
|
||||
AGE, STATUS, SCREENING, results_of("initial"), results_of("subsequent")))),
|
||||
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "hpv_reports",
|
||||
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
|
||||
unit="sample_id", date="sample_date"),
|
||||
description="Reportes VPH con fecha de reporte y algún resultado VPH, por paciente y "
|
||||
"fecha de toma; periodo por toma. Los nulos no son negativos; el contrato "
|
||||
"booleano actual no representa resultados indeterminados."),
|
||||
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "biopsy_reports",
|
||||
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
|
||||
unit="biopsy_id", date="report_date"),
|
||||
description="Reportes de biopsia por paciente y fecha de solicitud, incluidos los no "
|
||||
"vinculados a una toma; periodo por fecha de reporte. El estrato no_data "
|
||||
"identifica reportes sin grado; la distribución clasificable lo excluye."),
|
||||
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", "Resultados por solicitudes de biopsia registradas",
|
||||
"biopsy_requests", BiopsyRequests(), known="order_known_at", supports_as_of=False,
|
||||
description="Solicitudes de biopsia registradas por persona y fecha de solicitud, "
|
||||
"según fecha de solicitud; resultados hasta el corte. La clave puede "
|
||||
"agrupar órdenes y no se conocen cancelaciones ni cobertura de referencias. "
|
||||
"No admite corte histórico de conocimiento as-of."),
|
||||
# Her latest sample with an HPV result in the period, whatever its cytology says.
|
||||
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
|
||||
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]), hpv_result,
|
||||
where=lambda r: r.get("hpv") is not None,
|
||||
strata=(AGE, STATUS, genotype("hpv_16"), genotype("hpv_18"), SCREENING,
|
||||
hpv_of("initial"), hpv_of("subsequent"))),
|
||||
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
|
||||
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
|
||||
Composition(latest_most_severe_biopsy, histology,
|
||||
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
|
||||
strata=(RESULT,))),
|
||||
# Rows become known with `known_at`; a report's values only with `report_known_at`.
|
||||
*(Measure(f"CACU_VPP_{name}", f"VPP de la referencia a {title}", "referral_facts",
|
||||
ReferralPPV(procedure),
|
||||
facts={"report_known_at": ("result", "result_date", "adequacy",
|
||||
"histology", "report_date",
|
||||
"hpv", "hpv_16", "hpv_18")})
|
||||
for name, title, procedure in (("COLPOSCOPIA", "colposcopía", "colposcopy"),
|
||||
("BIOPSIA", "biopsia", "biopsy"))),
|
||||
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
|
||||
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
|
||||
ended="report_date"), "decrease"),
|
||||
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
|
||||
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
|
||||
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
|
||||
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo a diagnóstico por CIE-10 (exploratorio)",
|
||||
"diagnosis_codes", DiagnosisDurations(),
|
||||
description="Agrupa la fecha diagnóstica ya seleccionada por asociación temporal; no confirma vínculo clínico."),
|
||||
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
|
||||
Duration("days_sample_treatment", "treatment_date", "sample_date",
|
||||
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
|
||||
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
|
||||
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
|
||||
H["diagnosis_to_treatment"],
|
||||
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
|
||||
"decrease"),
|
||||
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
|
||||
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
|
||||
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
|
||||
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
|
||||
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
|
||||
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
|
||||
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
|
||||
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
|
||||
H["result_to_colposcopy"],
|
||||
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
|
||||
"decrease"),
|
||||
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
|
||||
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
|
||||
H["colposcopy_to_biopsy"],
|
||||
units=lambda r: r["history"] == 0
|
||||
and r["result_colposcopy_date"] is not None), "decrease"),
|
||||
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
|
||||
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
|
||||
H["biopsy_to_diagnosis"],
|
||||
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
|
||||
"decrease"),
|
||||
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
|
||||
MEASURES = {
|
||||
m.id: m
|
||||
for m in [
|
||||
Measure(
|
||||
"IND1",
|
||||
"Pacientes con citología anormal",
|
||||
"samples",
|
||||
Proportion(lambda r: r["result"] in cacu.ABNORMAL),
|
||||
"decrease",
|
||||
group="principal",
|
||||
),
|
||||
Measure(
|
||||
"CACU_EU13",
|
||||
"Tasa de detección histopatológica",
|
||||
"sample_biopsies",
|
||||
Proportion(
|
||||
lambda r: (
|
||||
r.get("histology") in cacu.DETECTION and r.get("biopsy_report_date") is not None
|
||||
),
|
||||
strata=(AGE, STATUS),
|
||||
),
|
||||
group="principal",
|
||||
),
|
||||
Measure(
|
||||
"CACU_EU7",
|
||||
"Pacientes evaluadas por resultado de citología",
|
||||
"samples",
|
||||
Composition(latest, result, strata=(AGE, STATUS)),
|
||||
),
|
||||
Measure(
|
||||
"CACU_CONFIRMACION_CITOLOGIA",
|
||||
"Confirmación histopatológica",
|
||||
"sample_biopsies",
|
||||
Composition(
|
||||
latest_most_severe_biopsy,
|
||||
histology,
|
||||
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
|
||||
strata=(RESULT,),
|
||||
),
|
||||
),
|
||||
Measure(
|
||||
"CACU_EU_TIEMPO_REPORTE",
|
||||
"Tiempo de toma a resultado de citología",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_sample_result",
|
||||
"result_date",
|
||||
"sample_date",
|
||||
H["sample_to_report"],
|
||||
ended="report_date",
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"Tiempo de tamizaje a diagnóstico",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_sample_diagnosis",
|
||||
"diagnosis_date",
|
||||
"sample_date",
|
||||
cacu.SAMPLE_TO_DIAGNOSIS_DAYS,
|
||||
units=NO_HISTORY,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_TOMA_TRATAMIENTO",
|
||||
"Tiempo de tamizaje a tratamiento",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_sample_treatment",
|
||||
"treatment_date",
|
||||
"sample_date",
|
||||
H["sample_to_treatment"],
|
||||
units=NO_HISTORY,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
|
||||
"Tiempo de diagnóstico a tratamiento",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_diagnosis_treatment",
|
||||
"diagnosis_treatment_date",
|
||||
"diagnosis_date",
|
||||
H["diagnosis_to_treatment"],
|
||||
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_TOMA_COLPOSCOPIA",
|
||||
"Tiempo de toma de muestra a colposcopía",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_sample_colposcopy",
|
||||
"colposcopy_date",
|
||||
"sample_date",
|
||||
H["sample_to_colposcopy"],
|
||||
units=NO_HISTORY,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_TOMA_BIOPSIA",
|
||||
"Tiempo de toma de muestra a resultado de biopsia",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_sample_biopsy",
|
||||
"biopsy_date",
|
||||
"sample_date",
|
||||
H["sample_to_biopsy"],
|
||||
units=NO_HISTORY,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_RESULTADO_COLPOSCOPIA",
|
||||
"Tiempo de resultado a colposcopía",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_result_colposcopy",
|
||||
"result_colposcopy_date",
|
||||
"result_date",
|
||||
H["result_to_colposcopy"],
|
||||
units=lambda r: r["history"] == 0 and r["result_date"] is not None,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_COLPOSCOPIA_BIOPSIA",
|
||||
"Tiempo de colposcopía a biopsia",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_colposcopy_biopsy",
|
||||
"biopsy_date",
|
||||
"result_colposcopy_date",
|
||||
H["colposcopy_to_biopsy"],
|
||||
units=lambda r: r["history"] == 0 and r["result_colposcopy_date"] is not None,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_DIAS_BIOPSIA_DIAGNOSTICO",
|
||||
"Tiempo de biopsia a diagnóstico",
|
||||
"samples",
|
||||
Duration(
|
||||
"days_biopsy_diagnosis",
|
||||
"biopsy_diagnosis_date",
|
||||
"biopsy_date",
|
||||
H["biopsy_to_diagnosis"],
|
||||
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None,
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"CACU_RIESGO_BANDA",
|
||||
"Banda de riesgo de CIN2+ en vigilancia",
|
||||
"risk",
|
||||
RiskBand(tuple(cacu.RISK_BANDS)),
|
||||
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
|
||||
]} # fmt: skip
|
||||
periods=("semester",),
|
||||
params={"model": cacu.RISK_BAND_MODEL},
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
"""Stage facts for a sample, using gold's dates and explicit biopsy links."""
|
||||
|
||||
def stage_facts(sample, biopsies, events, cutoff):
|
||||
def day(value):
|
||||
return str(value)[:10] if value is not None else None
|
||||
start, end = day(sample['sample_date']), str(cutoff)[:10]
|
||||
out = {}
|
||||
for kind, column in [('colposcopy', 'colposcopy_date'), ('diagnosis', 'diagnosis_date')]:
|
||||
selected = day(sample.get(column))
|
||||
if selected and start < selected <= end:
|
||||
matches = {(e['source_table'], e['source_id']) for e in events
|
||||
if e['type'] == kind and day(e['date']) == selected}
|
||||
out[kind] = ('inferred', selected) if len(matches) == 1 else ('ambiguous', None)
|
||||
linked = [b for b in biopsies if day(b.get('cytology_sample_date')) == start
|
||||
and day(b.get('request_date')) and start <= day(b['request_date']) <= end]
|
||||
if len(linked) > 1 or any((b.get('rows_merged') or 0) > 1 for b in linked):
|
||||
out['biopsy'] = ('ambiguous', None)
|
||||
elif linked:
|
||||
b = linked[0]
|
||||
reported = day(b.get('report_date'))
|
||||
if reported and reported < day(b['request_date']):
|
||||
out['biopsy'] = ('ambiguous', None)
|
||||
elif reported and reported <= end:
|
||||
out['biopsy'] = ('structured', reported)
|
||||
else:
|
||||
out['biopsy'] = ('pending', None)
|
||||
return out
|
||||
+44
-32
@@ -1,48 +1,60 @@
|
||||
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
|
||||
and models import them. Codes are the platform's (core.catalog)."""
|
||||
|
||||
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
|
||||
# benign one; a 4 without subcategory weighs less than 4A.
|
||||
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
|
||||
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
|
||||
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
|
||||
|
||||
# Biopsy grades, least to most severe.
|
||||
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"]
|
||||
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
|
||||
CANCER = ["in_situ", "invasive"] # detected (detection rate)
|
||||
CANCER = ["in_situ", "invasive"]
|
||||
INVASIVE = ["invasive"]
|
||||
|
||||
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
|
||||
# window (start inclusive, end exclusive).
|
||||
SURVIVAL_GRADES = ["invasive"]
|
||||
RECRUITMENT = ("2018-01-01", "2027-01-01")
|
||||
|
||||
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
|
||||
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
|
||||
# specialty;
|
||||
# - history: a breast cancer note, whoever wrote it.
|
||||
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
|
||||
HISTORY_ICD10 = [
|
||||
"D05", "D050", "D051", "D057", "D059",
|
||||
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
|
||||
] # fmt: skip
|
||||
"D05",
|
||||
"D050",
|
||||
"D051",
|
||||
"D057",
|
||||
"D059",
|
||||
"C50",
|
||||
"C500",
|
||||
"C501",
|
||||
"C502",
|
||||
"C503",
|
||||
"C504",
|
||||
"C505",
|
||||
"C506",
|
||||
"C508",
|
||||
"C509",
|
||||
]
|
||||
DIAGNOSIS_ICD10 = [
|
||||
"Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
|
||||
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92",
|
||||
"Z123",
|
||||
"N60",
|
||||
"N600",
|
||||
"N601",
|
||||
"N602",
|
||||
"N603",
|
||||
"N604",
|
||||
"N608",
|
||||
"N609",
|
||||
"N61",
|
||||
"N62",
|
||||
"N63",
|
||||
"N64",
|
||||
"N640",
|
||||
"N641",
|
||||
"N642",
|
||||
"N643",
|
||||
"N644",
|
||||
"N645",
|
||||
"N648",
|
||||
"N649",
|
||||
"D24",
|
||||
"R92",
|
||||
*HISTORY_ICD10,
|
||||
] # fmt: skip
|
||||
|
||||
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
|
||||
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
|
||||
]
|
||||
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
|
||||
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
|
||||
|
||||
# The follow-up list: patients whose latest mammogram, taken within the window before the
|
||||
# cut-off, is BI-RADS 4 to 6.
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
|
||||
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)]
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
|
||||
FOLLOW_UP_WINDOW = 3
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
"""What dbt reads (`var('cama')`)."""
|
||||
return {k.lower(): v for k, v in globals().items() if k.isupper()}
|
||||
|
||||
+22
-32
@@ -1,17 +1,4 @@
|
||||
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
|
||||
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
|
||||
she should be seen.
|
||||
|
||||
Status, from the biopsies that mammogram led to, reported by the cut-off:
|
||||
- cancer: one found cancer (in situ or invasive);
|
||||
- pending_biopsy: none reported;
|
||||
- biopsy_no_result: the latest has no grade;
|
||||
- benign_biopsy: otherwise.
|
||||
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
|
||||
pending biopsy or one without result; low otherwise."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core import cama
|
||||
from core.measures import as_day
|
||||
|
||||
@@ -19,23 +6,21 @@ WINDOWS = cama.FOLLOW_UP_WINDOWS
|
||||
SORTS = ("-recent",)
|
||||
DEFAULT_HORIZON = None
|
||||
STATUS_SYSTEM = "cama-follow-up-status"
|
||||
PROCEDURES: tuple[str, ...] = ()
|
||||
REPORT_FACTS: dict[str, str] = {}
|
||||
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
|
||||
PROCEDURES = ("treatment",)
|
||||
REPORT_FACTS = {"mammography": "diagnosis_days"}
|
||||
URGENT = ["5", "6"]
|
||||
|
||||
|
||||
def _ranked(row: dict) -> tuple:
|
||||
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
|
||||
return (as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0)
|
||||
|
||||
|
||||
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
|
||||
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
|
||||
who is on the list, most recent mammogram first."""
|
||||
latest: dict[str, dict] = {}
|
||||
biopsies: dict[str, list[dict]] = {}
|
||||
for row in rows:
|
||||
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
|
||||
if row["birads"] is None or report is None or not exam <= report <= cutoff:
|
||||
exam, report = (as_day(row["exam_date"]), as_day(row["report_date"]))
|
||||
if row["birads"] is None or report is None or (not exam <= report <= cutoff):
|
||||
continue
|
||||
person = row["person_id"]
|
||||
if person not in latest or _ranked(row) > _ranked(latest[person]):
|
||||
@@ -48,28 +33,33 @@ def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
|
||||
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
|
||||
continue
|
||||
mine = biopsies.get(row["mammogram_id"], [])
|
||||
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
|
||||
default=None) # fmt: skip
|
||||
shown = max(
|
||||
mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]), default=None
|
||||
)
|
||||
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
|
||||
if cancers:
|
||||
status, priority = "cancer", "high"
|
||||
status, priority = ("cancer", "high")
|
||||
elif shown is None:
|
||||
status = "pending_biopsy"
|
||||
priority = "high" if row["birads"] in URGENT else "medium"
|
||||
elif shown["histology"] is None:
|
||||
status, priority = "biopsy_no_result", "medium"
|
||||
status, priority = ("biopsy_no_result", "medium")
|
||||
else:
|
||||
status, priority = "benign_biopsy", "low"
|
||||
out.append({
|
||||
"person_id": person, "birth_date": row["birth_date"], "status": status,
|
||||
"priority": priority, "recent": as_day(row["exam_date"]),
|
||||
"first_cancer": min(cancers, default=None),
|
||||
}) # fmt: skip
|
||||
status, priority = ("benign_biopsy", "low")
|
||||
out.append(
|
||||
{
|
||||
"person_id": person,
|
||||
"birth_date": row["birth_date"],
|
||||
"status": status,
|
||||
"priority": priority,
|
||||
"recent": as_day(row["exam_date"]),
|
||||
"first_cancer": min(cancers, default=None),
|
||||
}
|
||||
)
|
||||
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> None:
|
||||
"""A patient's status exists only on the list."""
|
||||
return None
|
||||
|
||||
|
||||
|
||||
+158
-69
@@ -1,10 +1,3 @@
|
||||
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
|
||||
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
|
||||
|
||||
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
|
||||
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
|
||||
with no data instead of being left out."""
|
||||
|
||||
from core import cama
|
||||
from core.measures import (
|
||||
NO_BIOPSY,
|
||||
@@ -18,27 +11,37 @@ from core.measures import (
|
||||
)
|
||||
|
||||
H = cama.HORIZONS
|
||||
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
|
||||
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
|
||||
REPORT = {
|
||||
"report_known_at": (
|
||||
"report_date",
|
||||
"birads",
|
||||
"birads_rank",
|
||||
"days_sample_report",
|
||||
"report_diagnosis_date",
|
||||
"days_report_diagnosis",
|
||||
)
|
||||
}
|
||||
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
|
||||
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
|
||||
|
||||
|
||||
def reported(row: dict) -> bool:
|
||||
"""A mammogram with a reported BI-RADS."""
|
||||
return row["birads"] is not None and row["report_date"] is not None
|
||||
|
||||
|
||||
def most_severe(row: dict) -> tuple:
|
||||
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
|
||||
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
|
||||
return (reported(row), row["birads_rank"] or 0, as_day(row["exam_date"]))
|
||||
|
||||
|
||||
def then_its_most_severe_biopsy(row: dict) -> tuple:
|
||||
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
|
||||
counted = row["biopsy_report_date"] is not None
|
||||
return (*most_severe(row), counted, desc(row["histology_rank"]),
|
||||
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
|
||||
return (
|
||||
*most_severe(row),
|
||||
counted,
|
||||
desc(row["histology_rank"]),
|
||||
desc(as_day(row["biopsy_report_date"])),
|
||||
desc(row["biopsy_id"]),
|
||||
)
|
||||
|
||||
|
||||
def birads(row: dict) -> str:
|
||||
@@ -46,7 +49,6 @@ 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
|
||||
@@ -56,59 +58,146 @@ def four_to_six(row: dict) -> bool:
|
||||
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
|
||||
|
||||
|
||||
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
|
||||
NO_HISTORY = lambda row: row["history"] == 0
|
||||
BIRADS = ("birads", lambda row, p: row["birads"])
|
||||
|
||||
MEASURES = {m.id: m for m in [
|
||||
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
|
||||
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
|
||||
Measure("CAMA_BIRADS456_PACIENTE",
|
||||
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
|
||||
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
|
||||
Measure("CAMA_BIRADS456_MASTOGRAFIA",
|
||||
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
|
||||
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
|
||||
date="exam_date"), facts=REPORT),
|
||||
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
|
||||
MEASURES = {
|
||||
m.id: m
|
||||
for m in [
|
||||
Measure(
|
||||
"CAMA_BIRADS",
|
||||
"Distribución de BI-RADS",
|
||||
"mammograms",
|
||||
Composition(most_severe, birads, date="exam_date"),
|
||||
facts=REPORT,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_BIRADS456_PACIENTE",
|
||||
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
|
||||
"mammograms",
|
||||
Composition(most_severe, birads, admit=four_to_six, date="exam_date"),
|
||||
facts=REPORT,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_BIRADS456_MASTOGRAFIA",
|
||||
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6",
|
||||
"mammograms",
|
||||
Composition(
|
||||
most_severe, birads, where=four_to_six, unit="mammogram_id", date="exam_date"
|
||||
),
|
||||
facts=REPORT,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_BIRADS_CANCER_INVASOR",
|
||||
"BI-RADS de la mastografía previa a un cáncer invasor",
|
||||
"biopsies",
|
||||
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
|
||||
r["biopsy_id"]),
|
||||
lambda r: r["birads"] or NO_DATA,
|
||||
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
|
||||
known="report_known_at"),
|
||||
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
|
||||
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
|
||||
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
|
||||
date="report_date"),
|
||||
known="report_known_at"),
|
||||
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
|
||||
"mammogram_biopsies",
|
||||
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
|
||||
strata=(BIRADS,), date="exam_date"),
|
||||
facts=REPORT | BIOPSY),
|
||||
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
|
||||
"mammogram_biopsies",
|
||||
Proportion(lambda r: r["biopsy_report_date"] is not None,
|
||||
denominator=lambda r: r["report_date"] is not None
|
||||
and r["birads"] in cama.SUSPICIOUS,
|
||||
unit="mammogram_id", date="exam_date"),
|
||||
"increase", group="principal", facts=REPORT | BIOPSY),
|
||||
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
|
||||
Composition(
|
||||
lambda r: (r["birads"] is not None, as_day(r["report_date"]), r["biopsy_id"]),
|
||||
lambda r: r["birads"] or NO_DATA,
|
||||
where=lambda r: r["histology"] in cama.INVASIVE,
|
||||
date="report_date",
|
||||
),
|
||||
known="report_known_at",
|
||||
),
|
||||
Measure(
|
||||
"CAMA_BIOPSIAS",
|
||||
"Distribución de resultados de biopsia",
|
||||
"biopsies",
|
||||
Proportion(lambda r: r["histology"] in cama.CANCER,
|
||||
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
|
||||
unit="biopsy_id", date="report_date"),
|
||||
group="principal", known="report_known_at"),
|
||||
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
|
||||
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
|
||||
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
|
||||
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
|
||||
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
|
||||
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
|
||||
"decrease", facts=DIAGNOSIS),
|
||||
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
|
||||
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
|
||||
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
|
||||
date="report_date"),
|
||||
"decrease", known="report_known_at"),
|
||||
]} # fmt: skip
|
||||
Composition(
|
||||
lambda r: (r["histology"] is not None, as_day(r["report_date"])),
|
||||
lambda r: r["histology"] or NO_DATA,
|
||||
unit="biopsy_id",
|
||||
date="report_date",
|
||||
),
|
||||
known="report_known_at",
|
||||
),
|
||||
Measure(
|
||||
"CAMA_HISTOPATOLOGIA_BIRADS",
|
||||
"Resultado histopatológico por categoría BI-RADS",
|
||||
"mammogram_biopsies",
|
||||
Composition(
|
||||
then_its_most_severe_biopsy,
|
||||
biopsy_histology,
|
||||
admit=four_to_six,
|
||||
strata=(BIRADS,),
|
||||
date="exam_date",
|
||||
),
|
||||
facts=REPORT | BIOPSY,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_CONFIRMACION_BIRADS45",
|
||||
"Tasa de confirmación histopatológica",
|
||||
"mammogram_biopsies",
|
||||
Proportion(
|
||||
lambda r: r["biopsy_report_date"] is not None,
|
||||
denominator=lambda r: (
|
||||
r["report_date"] is not None and r["birads"] in cama.SUSPICIOUS
|
||||
),
|
||||
unit="mammogram_id",
|
||||
date="exam_date",
|
||||
),
|
||||
"increase",
|
||||
group="principal",
|
||||
facts=REPORT | BIOPSY,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_TASA_DETECCION_HISTOPATOLOGICA",
|
||||
"Tasa de detección histopatológica",
|
||||
"biopsies",
|
||||
Proportion(
|
||||
lambda r: r["histology"] in cama.CANCER,
|
||||
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
|
||||
unit="biopsy_id",
|
||||
date="report_date",
|
||||
),
|
||||
group="principal",
|
||||
known="report_known_at",
|
||||
),
|
||||
Measure(
|
||||
"CAMA_EU38A",
|
||||
"Días de la toma de la mastografía a su resultado",
|
||||
"mammograms",
|
||||
Duration(
|
||||
"days_sample_report",
|
||||
"report_date",
|
||||
"exam_date",
|
||||
H["sample_to_report"],
|
||||
unit="mammogram_id",
|
||||
date="exam_date",
|
||||
),
|
||||
"decrease",
|
||||
facts=REPORT,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_DIAS_TOMA_DIAGNOSTICO",
|
||||
"Tiempo de tamizaje a diagnóstico",
|
||||
"mammograms",
|
||||
Duration(
|
||||
"days_sample_diagnosis",
|
||||
"diagnosis_date",
|
||||
"exam_date",
|
||||
H["to_diagnosis"],
|
||||
units=NO_HISTORY,
|
||||
unit="mammogram_id",
|
||||
date="exam_date",
|
||||
),
|
||||
"decrease",
|
||||
facts=DIAGNOSIS,
|
||||
),
|
||||
Measure(
|
||||
"CAMA_DIAS_RESULTADO_DIAGNOSTICO",
|
||||
"Tiempo de resultado a diagnóstico",
|
||||
"mammograms",
|
||||
Duration(
|
||||
"days_report_diagnosis",
|
||||
"report_diagnosis_date",
|
||||
"report_date",
|
||||
H["to_diagnosis"],
|
||||
units=NO_HISTORY,
|
||||
unit="mammogram_id",
|
||||
date="report_date",
|
||||
),
|
||||
"decrease",
|
||||
known="report_known_at",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +1,12 @@
|
||||
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
|
||||
code systems their values come from. It is data (the YAML files beside this module) and
|
||||
changes only by a reviewed commit; nothing ships that it doesn't name.
|
||||
|
||||
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
|
||||
each study (what a pipeline's target checks rows against), the long silver tables and their
|
||||
wide views (dbt), and the FHIR conformance resources the API serves.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, ClassVar, Literal
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
EventClass = Literal["order", "encounter", "sample", "report", "part"]
|
||||
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
|
||||
# platform keeps the content once (persistance.files).
|
||||
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
|
||||
|
||||
|
||||
@@ -26,12 +14,12 @@ class System(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
url: str
|
||||
title: str
|
||||
external: bool = False # a standard system we name but don't publish
|
||||
external: bool = False
|
||||
|
||||
|
||||
class Event(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
date: str # the field that dates it
|
||||
date: str
|
||||
parent: EventClass | None = None
|
||||
|
||||
|
||||
@@ -41,7 +29,7 @@ class FieldDef(BaseModel):
|
||||
event: EventClass
|
||||
title: str
|
||||
system: str | None = None
|
||||
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
|
||||
codes: dict[str, str] = {}
|
||||
pattern: str | None = None
|
||||
unit: str | None = None
|
||||
required: bool = False
|
||||
@@ -58,7 +46,7 @@ class FieldDef(BaseModel):
|
||||
class Study(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
key: list[str] # fields that, with the person, identify one study instance
|
||||
key: list[str]
|
||||
events: dict[EventClass, Event]
|
||||
fields: dict[str, FieldDef]
|
||||
|
||||
@@ -89,7 +77,6 @@ def systems() -> dict[str, System]:
|
||||
|
||||
@cache
|
||||
def files() -> dict[str, list[str]]:
|
||||
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
|
||||
return {
|
||||
path.stem: list(_load(path.stem))
|
||||
for path in sorted(HERE.glob("*.yaml"))
|
||||
@@ -98,13 +85,11 @@ def files() -> dict[str, list[str]]:
|
||||
|
||||
|
||||
def of_domain(domain: str) -> list[str]:
|
||||
"""The studies a domain serves: its own and the common ones."""
|
||||
return [*files().get(domain, []), *files().get("common", [])]
|
||||
|
||||
|
||||
@cache
|
||||
def studies() -> dict[str, Study]:
|
||||
"""Every study of every catalog file, by name (names are unique across files)."""
|
||||
found: dict[str, Study] = {}
|
||||
for path in sorted(HERE.glob("*.yaml")):
|
||||
if path.stem == "systems":
|
||||
@@ -121,25 +106,17 @@ def studies() -> dict[str, Study]:
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
"""One row of a study, as a pipeline's target receives it."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
key: ClassVar[tuple[str, ...]] = ()
|
||||
study: ClassVar[str] = ""
|
||||
|
||||
|
||||
_TYPES: dict[str, Any] = {
|
||||
"boolean": bool,
|
||||
"number": float,
|
||||
"date": date,
|
||||
"text": str,
|
||||
"file": str,
|
||||
} # fmt: skip (a file field holds its content hash)
|
||||
_TYPES: dict[str, Any] = {"boolean": bool, "number": float, "date": date, "text": str, "file": str}
|
||||
|
||||
|
||||
def _annotation(f: FieldDef) -> Any:
|
||||
if f.type == "code" and f.codes:
|
||||
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
|
||||
kind: Any = Literal[tuple(f.codes)]
|
||||
elif f.type == "code":
|
||||
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
|
||||
else:
|
||||
@@ -149,26 +126,24 @@ def _annotation(f: FieldDef) -> Any:
|
||||
|
||||
@cache
|
||||
def model(study: str) -> type[Record]:
|
||||
"""The pydantic model a row of this study is checked against."""
|
||||
spec = studies()[study]
|
||||
fields = {
|
||||
name: (_annotation(f), ... if f.required else None) for name, f in spec.fields.items()
|
||||
name: (_annotation(f), Field(... if f.required else None, title=f.title))
|
||||
for name, f in spec.fields.items()
|
||||
}
|
||||
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
|
||||
found = create_model(study, __base__=Record, **fields)
|
||||
found.key = tuple(spec.key)
|
||||
found.study = study
|
||||
return found
|
||||
|
||||
|
||||
def value_column(f: FieldDef) -> str:
|
||||
"""The typed column of the long observation table a field's value is stored in."""
|
||||
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
|
||||
f.type, "value_text"
|
||||
)
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
|
||||
return {
|
||||
name: {
|
||||
"key": s.key,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Cervical cancer screening.
|
||||
cervical_cytology:
|
||||
title: Citología cervical
|
||||
key: [sample_date]
|
||||
@@ -7,40 +6,6 @@ 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:
|
||||
first_time: Primera vez en la vida
|
||||
1_year_or_less: Un año o menos
|
||||
2_years: 2 años
|
||||
3_years_or_more: 3 o más años
|
||||
# Condiciones ginecoobstétricas a la detección, as recorded at the sample: true when the
|
||||
# form says it; otherwise unknown, never false (the source records only one of them).
|
||||
gyn_puerperium: {type: boolean, event: sample, title: "Puerperio postparto o postaborto"}
|
||||
gyn_pregnancy: {type: boolean, event: sample, title: "Embarazo actual"}
|
||||
gyn_iud: {type: boolean, event: sample, title: "DIU in situ"}
|
||||
gyn_hormonal_treatment: {type: boolean, event: sample, title: "Tratamiento hormonal"}
|
||||
gyn_other_treatment: {type: boolean, event: sample, title: "Otro tratamiento ginecológico"}
|
||||
gyn_postmenopause: {type: boolean, event: sample, title: "Posmenopausia"}
|
||||
gyn_hysterectomy: {type: boolean, event: sample, title: "Histerectomía"}
|
||||
gyn_not_applicable: {type: boolean, event: sample, title: "Condiciones ginecoobstétricas: no aplica"}
|
||||
# Actualmente presenta, recorded like the conditions above: true or unknown, never false.
|
||||
presents_discharge: {type: boolean, event: sample, title: "Actualmente presenta: flujo"}
|
||||
presents_vulvar_pruritus: {type: boolean, event: sample, title: "Actualmente presenta: prurito o ardor vulvar"}
|
||||
presents_abnormal_bleeding: {type: boolean, event: sample, title: "Actualmente presenta: sangrado anormal"}
|
||||
presents_none: {type: boolean, event: sample, title: "Actualmente presenta: ninguno"}
|
||||
cervix_exam:
|
||||
type: code
|
||||
event: sample
|
||||
title: A la exploración se observa
|
||||
system: cervix-exam
|
||||
codes:
|
||||
healthy: Cuello sano
|
||||
abnormal_with_lesion: Cuello anormal con lesión
|
||||
not_visible: No se observa cuello
|
||||
report_date: {type: date, event: report, title: Fecha de reporte}
|
||||
adequacy:
|
||||
type: code
|
||||
@@ -63,36 +28,6 @@ cervical_cytology:
|
||||
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
|
||||
hpv_16: {type: boolean, event: report, title: VPH 16}
|
||||
hpv_18: {type: boolean, event: report, title: VPH 18}
|
||||
# The cytologist's additional findings, free text on the form (known with the report).
|
||||
# A finding is true when the text states it; otherwise unknown, never false.
|
||||
cyto_findings_text: {type: text, event: report, title: Hallazgos adicionales}
|
||||
cyto_inflammation: {type: boolean, event: report, title: "Inflamación"}
|
||||
cyto_reactive_changes: {type: boolean, event: report, title: "Cambios reactivos"}
|
||||
cyto_bacterial_vaginosis_flora: {type: boolean, event: report, title: "Flora sugestiva de vaginosis bacteriana"}
|
||||
cyto_candida: {type: boolean, event: report, title: "Microorganismos compatibles con Candida sp"}
|
||||
cyto_bacillary_flora_cytolysis: {type: boolean, event: report, title: "Aumento de la flora bacilar con citólisis"}
|
||||
cyto_intermediate_cytolysis: {type: boolean, event: report, title: "Citólisis de las células intermedias"}
|
||||
cyto_trichomonas: {type: boolean, event: report, title: "Trichomonas vaginalis"}
|
||||
cyto_leptothrix: {type: boolean, event: report, title: "Microorganismos compatibles con Leptothrix"}
|
||||
cyto_actinomyces_organisms: {type: boolean, event: report, title: "Microorganismos compatibles con Actinomyces sp"}
|
||||
cyto_actinomyces_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con Actinomyces sp"}
|
||||
cyto_herpes_simplex_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con virus herpes simple"}
|
||||
cyto_squamous_tubular_metaplasia: {type: boolean, event: report, title: "Metaplasia escamosa tubular"}
|
||||
cyto_keratotic_changes: {type: boolean, event: report, title: "Cambios queratósicos"}
|
||||
cyto_pregnancy_changes: {type: boolean, event: report, title: "Cambios asociados al embarazo"}
|
||||
cyto_atrophy: {type: boolean, event: report, title: "Atrofia"}
|
||||
cyto_hypoestrogenism: {type: boolean, event: report, title: "Hipoestrogenismo"}
|
||||
cyto_radiotherapy_effect: {type: boolean, event: report, title: "Efecto de radioterapia"}
|
||||
cyto_iud_changes: {type: boolean, event: report, title: "Cambios compatibles con dispositivo intrauterino"}
|
||||
cyto_post_hysterectomy_glandular_cells: {type: boolean, event: report, title: "Células glandulares post-histerectomía"}
|
||||
cyto_bacteria: {type: boolean, event: report, title: "Bacterias"}
|
||||
cyto_herpes_image: {type: boolean, event: report, title: "Imagen del virus del herpes"}
|
||||
cyto_fungi: {type: boolean, event: report, title: "Hongos"}
|
||||
cyto_radiation: {type: boolean, event: report, title: "Cambios reactivos: radiación"}
|
||||
cyto_repair: {type: boolean, event: report, title: "Cambios reactivos: reparación"}
|
||||
cyto_iud_effect: {type: boolean, event: report, title: "Efecto del DIU"}
|
||||
cyto_endometrial_cells_40_plus: {type: boolean, event: report, title: "Células endometriales, 40 años o más"}
|
||||
cyto_findings_none: {type: boolean, event: report, title: "Hallazgos adicionales: ninguno"}
|
||||
|
||||
cervical_biopsy:
|
||||
title: Biopsia cervical
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Breast cancer screening.
|
||||
mammography:
|
||||
title: Mastografía
|
||||
key: [exam_date]
|
||||
@@ -78,6 +77,7 @@ breast_biopsy:
|
||||
codes: *receptor
|
||||
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
|
||||
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
|
||||
positive_nodes: {type: number, event: report, title: Ganglios linfáticos positivos}
|
||||
stage:
|
||||
type: code
|
||||
event: report
|
||||
@@ -117,3 +117,17 @@ breast_treatment:
|
||||
radiotherapy: Radioterapia
|
||||
hormone_therapy: Hormonoterapia
|
||||
anti_her2: Terapia anti-HER2
|
||||
|
||||
breast_recurrence:
|
||||
title: Recurrencia de cáncer de mama
|
||||
key: [diagnosis_date]
|
||||
events:
|
||||
encounter: {date: diagnosis_date}
|
||||
fields:
|
||||
diagnosis_date: {type: date, event: encounter, title: Fecha de diagnóstico, required: true}
|
||||
site:
|
||||
type: code
|
||||
event: encounter
|
||||
title: Sitio de la recurrencia
|
||||
system: breast-recurrence-site
|
||||
codes: {local: Local, regional: Regional, distant: A distancia}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# Studies every domain shares.
|
||||
clinical_note:
|
||||
title: Nota médica
|
||||
key: [note_date, specialty]
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
# 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: Antecedente de detección de cáncer de cérvix
|
||||
cervix-exam:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/cervix-exam
|
||||
title: Exploración del cuello uterino
|
||||
bi-rads:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
|
||||
title: BI-RADS
|
||||
@@ -47,3 +39,6 @@ ajcc-stage:
|
||||
breast-treatment:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
|
||||
title: Tratamientos de cáncer de mama
|
||||
breast-recurrence-site:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/breast-recurrence-site
|
||||
title: Sitio de la recurrencia de cáncer de mama
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
|
||||
# is the common clinical note (specialty pediatric_neurology).
|
||||
mchat:
|
||||
title: M-CHAT-R/F
|
||||
key: [screening_date]
|
||||
@@ -22,7 +20,6 @@ ados2:
|
||||
title: Módulo
|
||||
system: ados2-module
|
||||
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
|
||||
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
|
||||
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
|
||||
pointing: {type: number, event: encounter, title: Señalar}
|
||||
gestures: {type: number, event: encounter, title: Gestos}
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
"""A site's codes in platform terms: FHIR ConceptMaps (R4B), as data a site's configuration
|
||||
holds, never code. A new laboratory that writes "Negativo para lesión" for NILM, or "F" for
|
||||
female, is one more element in its ConceptMap.
|
||||
|
||||
Each group maps the site's codes (`source`, any URI the site uses) onto one system the
|
||||
platform's fields take their codes from (`target`): a catalog system (core.catalog), FHIR's
|
||||
administrative gender (identity `sex`), or the platform's yes/no system (boolean fields).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
|
||||
from core import catalog
|
||||
|
||||
GENDER = "http://hl7.org/fhir/administrative-gender"
|
||||
@@ -20,8 +9,6 @@ _BOOLEAN_CODES = {"true", "false"}
|
||||
|
||||
|
||||
def systems(field: str) -> dict[str, set[str] | None]:
|
||||
"""The systems a field of this name takes codes from, each with its allowed codes
|
||||
(None: any code of the system)."""
|
||||
found: dict[str, set[str] | None] = {}
|
||||
if field == "sex":
|
||||
found[GENDER] = _GENDER_CODES
|
||||
@@ -40,8 +27,6 @@ def systems(field: str) -> dict[str, set[str] | None]:
|
||||
|
||||
|
||||
def problems(cm: ConceptMap) -> list[str]:
|
||||
"""Why this map can't be used: a group onto a system no field takes, or a target code
|
||||
its field doesn't allow."""
|
||||
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
|
||||
for study in catalog.studies().values():
|
||||
for name in study.fields:
|
||||
@@ -60,8 +45,6 @@ def problems(cm: ConceptMap) -> list[str]:
|
||||
|
||||
|
||||
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
|
||||
"""A field's translations, site code (case ignored) -> platform code, from the groups
|
||||
of these maps that target a system the field takes."""
|
||||
targets = systems(field)
|
||||
found = {}
|
||||
for cm in maps:
|
||||
@@ -76,7 +59,6 @@ def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
|
||||
|
||||
|
||||
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
|
||||
"""A sender's coding (system, code) as (platform system, code), when a map knows it."""
|
||||
for cm in maps:
|
||||
for group in cm.group or []:
|
||||
if group.source != source:
|
||||
@@ -84,5 +66,5 @@ def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str,
|
||||
for element in group.element:
|
||||
if element.code.casefold() == code.casefold():
|
||||
for target in element.target or []:
|
||||
return group.target, target.code
|
||||
return (group.target, target.code)
|
||||
return None
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
|
||||
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
|
||||
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
|
||||
|
||||
import importlib
|
||||
from enum import StrEnum
|
||||
from types import ModuleType
|
||||
@@ -14,7 +10,6 @@ class Domain(StrEnum):
|
||||
|
||||
|
||||
def part(domain: Domain, name: str = "") -> ModuleType | None:
|
||||
"""The domain's module `name` (its package without one), or None while it has none."""
|
||||
path = f"core.{domain.value}" + (f".{name}" if name else "")
|
||||
try:
|
||||
return importlib.import_module(path)
|
||||
@@ -25,6 +20,5 @@ def part(domain: Domain, name: str = "") -> ModuleType | None:
|
||||
|
||||
|
||||
def measures(domain: Domain) -> dict:
|
||||
"""The domain's measures by id (none for a domain without them yet)."""
|
||||
found = part(domain, "measures")
|
||||
return found.MEASURES if found else {}
|
||||
|
||||
+362
-225
@@ -1,15 +1,6 @@
|
||||
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
|
||||
declare what ours are: the local code systems, our extensions and our search parameters.
|
||||
|
||||
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
|
||||
fails here, before it is served. Clinical resources other than Patient are found by search
|
||||
only; their ids are stable (a UUID of their natural key), not addresses.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from fhir.resources.R4B.codesystem import CodeSystem
|
||||
from fhir.resources.R4B.condition import Condition
|
||||
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
|
||||
@@ -22,8 +13,7 @@ from fhir.resources.R4B.resource import Resource
|
||||
from fhir.resources.R4B.riskassessment import RiskAssessment
|
||||
from fhir.resources.R4B.searchparameter import SearchParameter
|
||||
from fhir.resources.R4B.structuredefinition import StructureDefinition
|
||||
|
||||
from core import catalog
|
||||
from core import catalog, models
|
||||
|
||||
FHIR_VERSION = "4.3.0"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
@@ -32,60 +22,91 @@ CODES = f"{BASE}/CodeSystem/"
|
||||
ICD10 = "http://hl7.org/fhir/sid/icd-10"
|
||||
UCUM = "http://unitsofmeasure.org"
|
||||
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
|
||||
|
||||
|
||||
# Local code systems: code -> display (Spanish, as the screens show them).
|
||||
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
|
||||
"cacu-procedure": ("Procedimientos de CaCu", {
|
||||
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
|
||||
}),
|
||||
"cacu-follow-up-status": ("Estatus de seguimiento", {
|
||||
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
|
||||
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
|
||||
}),
|
||||
"cama-follow-up-status": ("Estatus de seguimiento", {
|
||||
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
|
||||
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
|
||||
}),
|
||||
"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",
|
||||
"diagnosis_code": "Diagnóstico CIE-10",
|
||||
"birads": "BI-RADS de la mastografía",
|
||||
"referral_cytology": "Citología previa", "histology_level": "Histología",
|
||||
"screening_round": "Tamizaje inicial o subsecuente",
|
||||
"result_initial": "Resultado en tamizaje inicial",
|
||||
"result_subsequent": "Resultado en tamizaje subsecuente",
|
||||
"referral_hpv": "VPH de la citología previa", "hpv_16": "VPH 16", "hpv_18": "VPH 18",
|
||||
"hpv_initial": "VPH en tamizaje inicial",
|
||||
"hpv_subsequent": "VPH en tamizaje subsecuente",
|
||||
}),
|
||||
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
|
||||
} # fmt: skip
|
||||
"cacu-procedure": (
|
||||
"Procedimientos de CaCu",
|
||||
{"colposcopy": "Colposcopia", "treatment": "Tratamiento"},
|
||||
),
|
||||
"cacu-follow-up-status": (
|
||||
"Estatus de seguimiento",
|
||||
{
|
||||
"case": "Caso (cáncer)",
|
||||
"pre_colposcopy": "Pre colposcopia",
|
||||
"post_colposcopy": "Post colposcopia",
|
||||
"post_treatment": "Post tratamiento",
|
||||
},
|
||||
),
|
||||
"cama-follow-up-status": (
|
||||
"Estatus de seguimiento",
|
||||
{
|
||||
"cancer": "Diagnóstico confirmado",
|
||||
"pending_biopsy": "Pendiente de biopsia",
|
||||
"biopsy_no_result": "Biopsia sin resultado",
|
||||
"benign_biopsy": "Biopsia benigna",
|
||||
},
|
||||
),
|
||||
"tea-follow-up-status": (
|
||||
"Estatus de seguimiento",
|
||||
{
|
||||
"mchat_only": "Solo M-CHAT",
|
||||
"psychology": "Hasta evaluación psicológica",
|
||||
"neuropediatrics": "Hasta evaluación neuropediátrica",
|
||||
"eeg": "Con EEG",
|
||||
},
|
||||
),
|
||||
"tea-case": (
|
||||
"Estado del caso",
|
||||
{
|
||||
"confirmed": "Diagnóstico confirmado",
|
||||
"in_process": "En proceso",
|
||||
"not_confirmed": "Sin TEA",
|
||||
},
|
||||
),
|
||||
"tea-eeg-status": (
|
||||
"Estatus de EEG",
|
||||
{"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido"},
|
||||
),
|
||||
"tea-eeg-alteration": ("Alteración del EEG", {}),
|
||||
"follow-up-priority": (
|
||||
"Prioridad de seguimiento",
|
||||
{"high": "Alta", "medium": "Media", "low": "Baja"},
|
||||
),
|
||||
"measure-stratifier": (
|
||||
"Estratos de indicadores",
|
||||
{
|
||||
"category": "Categoría",
|
||||
"age_group": "Grupo de edad",
|
||||
"follow_up_status": "Estatus de seguimiento",
|
||||
"result": "Citología de alto grado",
|
||||
"birads": "BI-RADS de la mastografía",
|
||||
},
|
||||
),
|
||||
"risk-model": ("Modelos de riesgo", {}),
|
||||
}
|
||||
|
||||
|
||||
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
|
||||
"""The catalog's own code systems, with every code some field allows."""
|
||||
found: dict[str, tuple[str, dict[str, str]]] = {}
|
||||
for name, system in catalog.systems().items():
|
||||
if not system.external:
|
||||
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
|
||||
if f.system == name for c, d in f.codes.items()} # fmt: skip
|
||||
codes = {
|
||||
c: d
|
||||
for s in catalog.studies().values()
|
||||
for f in s.fields.values()
|
||||
if f.system == name
|
||||
for c, d in f.codes.items()
|
||||
}
|
||||
found[name] = (system.title, codes)
|
||||
return found
|
||||
|
||||
|
||||
CODE_SYSTEMS |= _catalog_systems()
|
||||
# What the catalog names: its studies, and every field as `<study>.<field>`.
|
||||
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
|
||||
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
|
||||
|
||||
# Our extensions: name -> (value type, the elements they extend).
|
||||
CODE_SYSTEMS["catalog-field"] = (
|
||||
"Campos de los estudios",
|
||||
{f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()},
|
||||
)
|
||||
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
|
||||
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
@@ -97,22 +118,23 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
|
||||
"follow-up-priority": ("Coding", ["Patient"]),
|
||||
"report-date": ("date", ["DiagnosticReport"]),
|
||||
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
|
||||
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-colposcopy-date": ("date", ["DiagnosticReport"]),
|
||||
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-biopsy-date": ("date", ["DiagnosticReport"]),
|
||||
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-diagnosis-date": ("date", ["DiagnosticReport"]),
|
||||
} # fmt: skip
|
||||
"escenario-clinico": ("string", ["RiskAssessment"]),
|
||||
"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"]),
|
||||
}
|
||||
|
||||
|
||||
def _name(code: str) -> str:
|
||||
"""A conformance resource's computable name (CamelCase)."""
|
||||
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
|
||||
return "".join((part.capitalize() for part in code.replace("_", "-").split("-")))
|
||||
|
||||
|
||||
def _id(*key) -> str:
|
||||
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
|
||||
return str(uuid.uuid5(_IDS, "|".join((str(k) for k in key))))
|
||||
|
||||
|
||||
def _day(value) -> str | None:
|
||||
@@ -122,7 +144,6 @@ def _day(value) -> str | None:
|
||||
|
||||
|
||||
def _instant(value) -> str | None:
|
||||
"""A stored moment as an instant; one stored without an offset is UTC."""
|
||||
if value is None:
|
||||
return None
|
||||
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
|
||||
@@ -147,12 +168,7 @@ def subject(person_id: str) -> dict:
|
||||
return {"reference": f"Patient/{person_id}"}
|
||||
|
||||
|
||||
# --- clinical resources ----------------------------------------------------------------
|
||||
|
||||
|
||||
def patient(row: dict, status_system: str | None = None) -> Patient:
|
||||
"""A person: what her records agree on, her names and identifiers, the ids she
|
||||
replaced; on a follow-up list, her status there (`status_system`) and priority."""
|
||||
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
|
||||
if row.get("sex"):
|
||||
found["gender"] = row["sex"]
|
||||
@@ -161,37 +177,65 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
|
||||
if row.get("death_date"):
|
||||
found["deceasedDateTime"] = _day(row["death_date"])
|
||||
if row.get("status") and status_system:
|
||||
found["extension"] = [ext("follow-up-status", "Coding",
|
||||
coding(status_system, row["status"]))] # fmt: skip
|
||||
found["extension"] = [
|
||||
ext("follow-up-status", "Coding", coding(status_system, row["status"]))
|
||||
]
|
||||
if row.get("priority"):
|
||||
priority = coding("follow-up-priority", row["priority"])
|
||||
found["extension"].append(ext("follow-up-priority", "Coding", priority))
|
||||
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"):
|
||||
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
|
||||
if row.get("replaces"):
|
||||
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
|
||||
for old in row["replaces"]] # fmt: skip
|
||||
found["link"] = [
|
||||
{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
|
||||
for old in row["replaces"]
|
||||
]
|
||||
return Patient.model_validate(found)
|
||||
|
||||
|
||||
def _tea_listed(row: dict) -> list[dict]:
|
||||
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"}],
|
||||
}) # fmt: skip
|
||||
return Patient.model_validate(
|
||||
{
|
||||
"resourceType": "Patient",
|
||||
"id": person_id,
|
||||
"active": False,
|
||||
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _value(f: catalog.FieldDef, value) -> dict:
|
||||
"""A field's value as the Observation value of its type."""
|
||||
if f.type == "code":
|
||||
system = catalog.systems()[f.system]
|
||||
if system.external:
|
||||
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
|
||||
"text": value}} # fmt: skip
|
||||
return {
|
||||
"valueCodeableConcept": {
|
||||
"coding": [{"system": system.url, "code": value}],
|
||||
"text": value,
|
||||
}
|
||||
}
|
||||
return {"valueCodeableConcept": concept(f.system, value)}
|
||||
if f.type == "boolean":
|
||||
return {"valueBoolean": bool(value)}
|
||||
@@ -203,8 +247,6 @@ def _value(f: catalog.FieldDef, value) -> dict:
|
||||
|
||||
|
||||
def known(study: str, row: dict, cutoff) -> dict:
|
||||
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
|
||||
event that has no date yet, or a later one, are not known."""
|
||||
spec = catalog.studies()[study]
|
||||
out = dict(row)
|
||||
for cls, event in spec.events.items():
|
||||
@@ -217,128 +259,173 @@ def known(study: str, row: dict, cutoff) -> dict:
|
||||
|
||||
|
||||
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
|
||||
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
|
||||
Observation per field that is not an event's date, and, when the study has a report,
|
||||
the DiagnosticReport that gathers them."""
|
||||
spec = catalog.studies()[study]
|
||||
person = row["person_id"]
|
||||
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
|
||||
dates = {e.date for e in spec.events.values()}
|
||||
root = next(e for e in spec.events.values() if e.parent is None)
|
||||
root = next((e for e in spec.events.values() if e.parent is None))
|
||||
effective = _day(row.get(root.date))
|
||||
container = _id(study, person, *key) # its report, or the encounter its notes are of
|
||||
container = _id(study, person, *key)
|
||||
visit = "report" not in spec.events
|
||||
observations = []
|
||||
for name, f in spec.fields.items():
|
||||
if name in dates or row.get(name) is None or f.type == "file":
|
||||
continue
|
||||
observations.append(Observation.model_validate({
|
||||
"resourceType": "Observation",
|
||||
"id": _id(study, name, person, *key),
|
||||
"status": "final",
|
||||
"code": concept("catalog-field", f"{study}.{name}"),
|
||||
"subject": subject(person),
|
||||
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
|
||||
**({"effectiveDateTime": effective} if effective else {}),
|
||||
**_value(f, row[name]),
|
||||
})) # fmt: skip
|
||||
if visit: # a study without a report (a consultation): the encounter its values are of
|
||||
observations.append(
|
||||
Observation.model_validate(
|
||||
{
|
||||
"resourceType": "Observation",
|
||||
"id": _id(study, name, person, *key),
|
||||
"status": "final",
|
||||
"code": concept("catalog-field", f"{study}.{name}"),
|
||||
"subject": subject(person),
|
||||
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
|
||||
**({"effectiveDateTime": effective} if effective else {}),
|
||||
**_value(f, row[name]),
|
||||
}
|
||||
)
|
||||
)
|
||||
if visit:
|
||||
if not observations:
|
||||
return []
|
||||
encounter = Encounter.model_validate({
|
||||
"resourceType": "Encounter", "id": container, "status": "finished",
|
||||
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
|
||||
"code": "AMB"},
|
||||
"type": [concept("study", study)],
|
||||
"subject": subject(person),
|
||||
**({"period": {"start": effective}} if effective else {}),
|
||||
}) # fmt: skip
|
||||
encounter = Encounter.model_validate(
|
||||
{
|
||||
"resourceType": "Encounter",
|
||||
"id": container,
|
||||
"status": "finished",
|
||||
"class": {
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
|
||||
"code": "AMB",
|
||||
},
|
||||
"type": [concept("study", study)],
|
||||
"subject": subject(person),
|
||||
**({"period": {"start": effective}} if effective else {}),
|
||||
}
|
||||
)
|
||||
return [encounter, *observations]
|
||||
reported = _day(row.get(spec.events["report"].date))
|
||||
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
|
||||
report_extensions
|
||||
)
|
||||
report = DiagnosticReport.model_validate({
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": container,
|
||||
"status": "final" if reported else "registered",
|
||||
"code": concept("study", study),
|
||||
"subject": subject(person),
|
||||
**({"effectiveDateTime": effective} if effective else {}),
|
||||
**({"extension": extensions} if extensions else {}),
|
||||
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
|
||||
}) # fmt: skip
|
||||
report = DiagnosticReport.model_validate(
|
||||
{
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": container,
|
||||
"status": "final" if reported else "registered",
|
||||
"code": concept("study", study),
|
||||
"subject": subject(person),
|
||||
**({"effectiveDateTime": effective} if effective else {}),
|
||||
**({"extension": extensions} if extensions else {}),
|
||||
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
|
||||
}
|
||||
)
|
||||
return [report, *observations]
|
||||
|
||||
|
||||
def condition(row: dict) -> Condition:
|
||||
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written."""
|
||||
person, day = row["person_id"], _day(row["note_date"])
|
||||
person, day = (row["person_id"], _day(row["note_date"]))
|
||||
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
|
||||
if row.get("icd10"):
|
||||
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
|
||||
if study := row.get("study"):
|
||||
code = concept("study", study)
|
||||
system = next(
|
||||
(f.system for f in catalog.studies()[study].fields.values() if f.type == "code"), None
|
||||
)
|
||||
if system and row.get("code"):
|
||||
where = coding(system, row["code"])
|
||||
code["coding"].append(where)
|
||||
code["text"] += f" ({where.get('display', row['code']).lower()})"
|
||||
found: dict = {
|
||||
"resourceType": "Condition",
|
||||
"id": _id("condition", person, day, row.get("specialty")),
|
||||
"category": [{"coding": [{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
|
||||
"code": "encounter-diagnosis"}]}],
|
||||
"id": _id("condition", person, day, row.get("specialty") or study),
|
||||
"category": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
|
||||
"code": "encounter-diagnosis",
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"code": code,
|
||||
"subject": subject(person),
|
||||
"recordedDate": day,
|
||||
} # fmt: skip
|
||||
}
|
||||
if row.get("reason"):
|
||||
found["note"] = [{"text": row["reason"]}]
|
||||
return Condition.model_validate(found)
|
||||
|
||||
|
||||
def procedure(row: dict) -> Procedure:
|
||||
"""A procedure the timeline inferred (`gold.cacu_events`: colposcopy, treatment)."""
|
||||
person, day = row["person_id"], _day(row["date"])
|
||||
return Procedure.model_validate({
|
||||
"resourceType": "Procedure",
|
||||
"id": _id("procedure", row["type"], person, day),
|
||||
"status": "completed",
|
||||
"code": concept("cacu-procedure", row["type"]),
|
||||
"subject": subject(person),
|
||||
"performedDateTime": day,
|
||||
}) # fmt: skip
|
||||
def procedure(row: dict, domain: str = "cacu") -> Procedure:
|
||||
person, day = (row["person_id"], _day(row["date"]))
|
||||
return Procedure.model_validate(
|
||||
{
|
||||
"resourceType": "Procedure",
|
||||
"id": _id("procedure", row["type"], person, day),
|
||||
"status": "completed",
|
||||
"code": concept(f"{domain}-procedure", row["type"]),
|
||||
"subject": subject(person),
|
||||
"performedDateTime": day,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
SCENARIO_SEPARATOR = " | "
|
||||
|
||||
|
||||
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
|
||||
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
|
||||
per horizon, in years, with its 95% interval."""
|
||||
predictions = []
|
||||
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
|
||||
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
|
||||
interval = [ext(name, "decimal", h[key]) for name, key in bounds
|
||||
if h.get(key) is not None] # fmt: skip
|
||||
predictions.append({
|
||||
"probabilityDecimal": h["probability"],
|
||||
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
|
||||
"code": "a"}},
|
||||
**({"extension": interval} if interval else {}),
|
||||
}) # fmt: skip
|
||||
interval = [ext(name, "decimal", h[key]) for name, key in bounds if h.get(key) is not None]
|
||||
predictions.append(
|
||||
{
|
||||
"probabilityDecimal": h["probability"],
|
||||
"whenRange": {
|
||||
"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM, "code": "a"}
|
||||
},
|
||||
**({"extension": interval} if interval else {}),
|
||||
}
|
||||
)
|
||||
model = row["model"]
|
||||
return RiskAssessment.model_validate({
|
||||
"resourceType": "RiskAssessment",
|
||||
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
|
||||
"meta": {"lastUpdated": _instant(row["scored_at"])},
|
||||
"status": "final",
|
||||
"method": {"coding": [{"system": CODES + "risk-model", "code": model}],
|
||||
"text": f"{model} v{row['version']}"},
|
||||
"subject": subject(row["person_id"]),
|
||||
"occurrenceDateTime": _day(row["index_date"]),
|
||||
"prediction": predictions,
|
||||
}) # fmt: skip
|
||||
return RiskAssessment.model_validate(
|
||||
{
|
||||
"resourceType": "RiskAssessment",
|
||||
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
|
||||
"meta": {"lastUpdated": _instant(row["scored_at"])},
|
||||
"status": "final",
|
||||
"method": {
|
||||
"coding": [
|
||||
{"system": CODES + "risk-model", "code": model, "display": models.title(model)}
|
||||
],
|
||||
"text": f"{models.title(model)} v{row['version']}",
|
||||
},
|
||||
"subject": subject(row["person_id"]),
|
||||
"occurrenceDateTime": _day(row["index_date"]),
|
||||
"prediction": predictions,
|
||||
**(
|
||||
{"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
|
||||
if (
|
||||
scenarios := [
|
||||
n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR) if n
|
||||
]
|
||||
)
|
||||
else {}
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
|
||||
"composition": "cohort"} # fmt: skip
|
||||
SCORING = {
|
||||
"proportion": "proportion",
|
||||
"continuous-variable": "continuous-variable",
|
||||
"composition": "cohort",
|
||||
}
|
||||
|
||||
|
||||
def measure_id(code: str) -> str:
|
||||
"""A measure's FHIR id (ids allow no underscore)."""
|
||||
return code.lower().replace("_", "-")
|
||||
|
||||
|
||||
@@ -346,15 +433,15 @@ def measure_url(code: str) -> str:
|
||||
return f"{BASE}/Measure/{code}"
|
||||
|
||||
|
||||
# The populations each kind of measure counts (core.measures emits exactly these).
|
||||
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
|
||||
"continuous-variable": ["initial-population", "measure-observation"],
|
||||
"composition": ["initial-population", "measure-observation"]} # fmt: skip
|
||||
POPULATIONS = {
|
||||
"proportion": ["initial-population", "denominator", "numerator"],
|
||||
"continuous-variable": ["initial-population", "measure-observation"],
|
||||
"composition": ["initial-population", "measure-observation"],
|
||||
}
|
||||
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
|
||||
|
||||
|
||||
def stratifiers(m) -> list[str]:
|
||||
"""A measure's strata: a composition's categories first, then its declared strata."""
|
||||
first = ["category"] if m.rule.kind == "composition" else []
|
||||
return first + [name for name, _ in getattr(m.rule, "strata", ())]
|
||||
|
||||
@@ -364,18 +451,21 @@ def stratifier_code(name: str) -> dict:
|
||||
|
||||
|
||||
def measure(m, domain: str) -> Measure:
|
||||
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
|
||||
which `criteria` points to."""
|
||||
criteria = {"language": "text/x-python",
|
||||
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
|
||||
criteria = {
|
||||
"language": "text/x-python",
|
||||
"expression": f"core.{domain}.measures.MEASURES['{m.id}']",
|
||||
}
|
||||
group: dict = {
|
||||
"id": m.group,
|
||||
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
|
||||
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
|
||||
} # fmt: skip
|
||||
"population": [
|
||||
{"code": {"coding": [{"system": POPULATION, "code": c}]}, "criteria": criteria}
|
||||
for c in POPULATIONS[m.rule.kind]
|
||||
],
|
||||
}
|
||||
if strata := stratifiers(m):
|
||||
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
|
||||
for s in strata] # fmt: skip
|
||||
group["stratifier"] = [
|
||||
{"id": s, "code": stratifier_code(s), "criteria": criteria} for s in strata
|
||||
]
|
||||
found: dict = {
|
||||
"resourceType": "Measure",
|
||||
"id": measure_id(m.id),
|
||||
@@ -384,87 +474,134 @@ def measure(m, domain: str) -> Measure:
|
||||
"name": m.id,
|
||||
"title": m.title,
|
||||
"status": "active",
|
||||
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": SCORING[m.rule.kind]}]},
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": SCORING[m.rule.kind],
|
||||
}
|
||||
]
|
||||
},
|
||||
"extension": [ext("period-type", "code", p) for p in m.periods],
|
||||
"group": [group],
|
||||
} # fmt: skip
|
||||
}
|
||||
if m.improvement:
|
||||
found["improvementNotation"] = {"coding": [{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": m.improvement}]} # fmt: skip
|
||||
if m.description:
|
||||
found["description"] = m.description
|
||||
found["improvementNotation"] = {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": m.improvement,
|
||||
}
|
||||
]
|
||||
}
|
||||
return Measure.model_validate(found)
|
||||
|
||||
|
||||
# --- conformance: what our resources declare ---------------------------------------------
|
||||
|
||||
|
||||
def code_systems() -> list[CodeSystem]:
|
||||
return [CodeSystem.model_validate({
|
||||
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
|
||||
"name": _name(name),
|
||||
"title": title, "status": "active", "caseSensitive": True,
|
||||
"content": "complete" if concepts else "not-present",
|
||||
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
|
||||
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
|
||||
return [
|
||||
CodeSystem.model_validate(
|
||||
{
|
||||
"resourceType": "CodeSystem",
|
||||
"id": name,
|
||||
"url": CODES + name,
|
||||
"name": _name(name),
|
||||
"title": title,
|
||||
"status": "active",
|
||||
"caseSensitive": True,
|
||||
"content": "complete" if concepts else "not-present",
|
||||
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
|
||||
}
|
||||
)
|
||||
for name, (title, concepts) in CODE_SYSTEMS.items()
|
||||
]
|
||||
|
||||
|
||||
def extensions() -> list[StructureDefinition]:
|
||||
found = []
|
||||
for name, (value_type, contexts) in EXTENSIONS.items():
|
||||
url = EXTENSION + name
|
||||
found.append(StructureDefinition.model_validate({
|
||||
"resourceType": "StructureDefinition", "id": name, "url": url,
|
||||
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
|
||||
"kind": "complex-type", "abstract": False, "type": "Extension",
|
||||
"context": [{"type": "element", "expression": c} for c in contexts],
|
||||
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
|
||||
"derivation": "constraint",
|
||||
"differential": {"element": [
|
||||
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
|
||||
else "1"},
|
||||
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
|
||||
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
|
||||
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
|
||||
"type": [{"code": value_type}]},
|
||||
]},
|
||||
})) # fmt: skip
|
||||
found.append(
|
||||
StructureDefinition.model_validate(
|
||||
{
|
||||
"resourceType": "StructureDefinition",
|
||||
"id": name,
|
||||
"url": url,
|
||||
"name": _name(name),
|
||||
"status": "active",
|
||||
"fhirVersion": FHIR_VERSION,
|
||||
"kind": "complex-type",
|
||||
"abstract": False,
|
||||
"type": "Extension",
|
||||
"context": [{"type": "element", "expression": c} for c in contexts],
|
||||
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
|
||||
"derivation": "constraint",
|
||||
"differential": {
|
||||
"element": [
|
||||
{
|
||||
"id": "Extension",
|
||||
"path": "Extension",
|
||||
"max": "*" if name == "period-type" else "1",
|
||||
},
|
||||
{
|
||||
"id": "Extension.extension",
|
||||
"path": "Extension.extension",
|
||||
"max": "0",
|
||||
},
|
||||
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
|
||||
{
|
||||
"id": "Extension.value[x]",
|
||||
"path": "Extension.value[x]",
|
||||
"min": 1,
|
||||
"type": [{"code": value_type}],
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
# Our search parameters: code -> (resource, type, description).
|
||||
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
|
||||
"stage-cutoff": ("DiagnosticReport", "date", "Cutoff for sample-linked stages"),
|
||||
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cutoff"),
|
||||
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cutoff"),
|
||||
"follow-up-search": ("Patient", "string", "Partial name or identifier"),
|
||||
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
|
||||
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
|
||||
"follow-up-window": ("Patient", "number",
|
||||
"Months before the cut-off a cytology puts a patient on the list"),
|
||||
"follow-up-window": (
|
||||
"Patient",
|
||||
"number",
|
||||
"Months before the cut-off a cytology puts a patient on the list",
|
||||
),
|
||||
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
|
||||
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
|
||||
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
|
||||
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
|
||||
"reporting-period": ("MeasureReport", "token",
|
||||
"A semester (2025-S1) or a month (2025-03) the report covers"),
|
||||
"reporting-period": (
|
||||
"MeasureReport",
|
||||
"token",
|
||||
"A semester (2025-S1) or a month (2025-03) the report covers",
|
||||
),
|
||||
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
|
||||
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
|
||||
} # fmt: skip
|
||||
}
|
||||
|
||||
|
||||
def search_parameters() -> list[SearchParameter]:
|
||||
return [SearchParameter.model_validate({
|
||||
"resourceType": "SearchParameter", "id": code,
|
||||
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
|
||||
"status": "active", "description": description, "code": code, "base": [base],
|
||||
"type": kind,
|
||||
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
|
||||
return [
|
||||
SearchParameter.model_validate(
|
||||
{
|
||||
"resourceType": "SearchParameter",
|
||||
"id": code,
|
||||
"url": f"{BASE}/SearchParameter/{code}",
|
||||
"name": _name(code),
|
||||
"status": "active",
|
||||
"description": description,
|
||||
"code": code,
|
||||
"base": [base],
|
||||
"type": kind,
|
||||
}
|
||||
)
|
||||
for code, (base, kind, description) in SEARCH_PARAMETERS.items()
|
||||
]
|
||||
|
||||
|
||||
def conformance() -> list[Resource]:
|
||||
"""Everything our resources declare: what the validator loads, and what the
|
||||
CapabilityStatement points to."""
|
||||
return [*code_systems(), *extensions(), *search_parameters()]
|
||||
|
||||
+33
-39
@@ -1,21 +1,7 @@
|
||||
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
|
||||
target nodes take, the same rows a site's map and extract nodes give. One silver,
|
||||
two doors.
|
||||
|
||||
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
|
||||
Encounter (one study instance). Every report also gives an identity row, its subject's, so
|
||||
the link node joins it to its person the way it joins any document: by identifiers, name and
|
||||
birth date. Codes in the platform's own systems pass as they are; any other code goes through
|
||||
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
|
||||
target holds the row saying why.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
|
||||
from core import catalog, concept_map
|
||||
from core.fhir import CODES
|
||||
from core.pipeline import RECORD
|
||||
@@ -26,18 +12,14 @@ FIELD = CODES + "catalog-field"
|
||||
|
||||
|
||||
def record(sender: str, reference: str) -> str:
|
||||
"""A sent resource's record id: stable across resends of the same resource."""
|
||||
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
|
||||
|
||||
|
||||
def resources(bundle: dict) -> dict[str, dict]:
|
||||
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
|
||||
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
|
||||
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
|
||||
|
||||
|
||||
def _entries(bundle: dict) -> dict[str, dict]:
|
||||
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
|
||||
found = {}
|
||||
for entry in bundle.get("entry", []):
|
||||
r = entry.get("resource") or {}
|
||||
@@ -49,7 +31,6 @@ def _entries(bundle: dict) -> dict[str, dict]:
|
||||
|
||||
|
||||
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
|
||||
"""A coding as a code of `system`: as it is when already there, else through the maps."""
|
||||
if coding.get("system") == system:
|
||||
return coding.get("code")
|
||||
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
|
||||
@@ -61,7 +42,6 @@ def _codings(concept: dict | None) -> list[dict]:
|
||||
|
||||
|
||||
def identity(patient: dict) -> dict[str, Any]:
|
||||
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
|
||||
found: dict[str, Any] = {}
|
||||
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
|
||||
for i in patient.get("identifier", []):
|
||||
@@ -86,7 +66,7 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
|
||||
for coding in codings:
|
||||
if url and (code := _translated(maps, coding, url)) is not None:
|
||||
return code
|
||||
return codings[0].get("code") if codings else None # kept as sent: held, saying why
|
||||
return codings[0].get("code") if codings else None
|
||||
for key in ("valueBoolean", "valueString", "valueInteger"):
|
||||
if key in observation:
|
||||
return observation[key]
|
||||
@@ -98,54 +78,68 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
|
||||
|
||||
|
||||
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
|
||||
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
|
||||
subject), `death` (Patients who died), or a study of the catalog (each report or
|
||||
encounter of it, with its results as fields)."""
|
||||
maps = list(maps)
|
||||
sent = resources(bundle)
|
||||
named = _entries(bundle) # what a reference may name
|
||||
named = _entries(bundle)
|
||||
|
||||
def subject(r: dict) -> dict | None:
|
||||
return named.get((r.get("subject") or {}).get("reference", ""))
|
||||
|
||||
if entity == "identity":
|
||||
out = [{**identity(r), RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
|
||||
out = [
|
||||
{**identity(r), RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items()
|
||||
if r["resourceType"] == "Patient"
|
||||
]
|
||||
for ref, r in sent.items():
|
||||
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
|
||||
out.append({**identity(p), RECORD: record(sender, ref)})
|
||||
return out
|
||||
if entity == "death":
|
||||
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items()
|
||||
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
|
||||
|
||||
return [
|
||||
{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items()
|
||||
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")
|
||||
]
|
||||
spec = catalog.studies()[entity]
|
||||
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
|
||||
root = next(e for e in spec.events.values() if e.parent is None)
|
||||
root = next((e for e in spec.events.values() if e.parent is None))
|
||||
out = []
|
||||
for ref, r in sent.items():
|
||||
if r["resourceType"] != kind:
|
||||
continue
|
||||
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
|
||||
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
|
||||
if not any((_translated(maps, c, STUDY) == entity for c in _codings(code))):
|
||||
continue
|
||||
row: dict[str, Any] = {RECORD: record(sender, ref)}
|
||||
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
|
||||
(r.get("period") or {}).get("start")) # fmt: skip
|
||||
start = (
|
||||
r.get("effectiveDateTime")
|
||||
if kind == "DiagnosticReport"
|
||||
else (r.get("period") or {}).get("start")
|
||||
)
|
||||
if start:
|
||||
row[root.date] = start[:10]
|
||||
if kind == "DiagnosticReport":
|
||||
reported = next((x.get("valueDate") for x in r.get("extension", [])
|
||||
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
|
||||
reported = next(
|
||||
(
|
||||
x.get("valueDate")
|
||||
for x in r.get("extension", [])
|
||||
if x.get("url", "").endswith("/report-date")
|
||||
),
|
||||
None,
|
||||
)
|
||||
reported = reported or (r.get("issued") or "")[:10] or None
|
||||
if reported:
|
||||
row[spec.events["report"].date] = reported
|
||||
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
|
||||
else:
|
||||
mine = {ref, *(k for k, v in named.items() if v is r)}
|
||||
results = [o for o in sent.values() if o["resourceType"] == "Observation"
|
||||
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
|
||||
results = [
|
||||
o
|
||||
for o in sent.values()
|
||||
if o["resourceType"] == "Observation"
|
||||
and (o.get("encounter") or {}).get("reference") in mine
|
||||
]
|
||||
for o in filter(None, results):
|
||||
for coding in _codings(o.get("code")):
|
||||
name = _translated(maps, coding, FIELD) or ""
|
||||
|
||||
@@ -1,25 +1,8 @@
|
||||
"""What every domain's follow-up list shares (pure). A domain with a list has a module
|
||||
`core.<domain>.follow_up` with:
|
||||
|
||||
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
|
||||
(years, for orders by risk; None without one);
|
||||
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
|
||||
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
|
||||
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
|
||||
`follow_up` read (persistance.fhir);
|
||||
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
|
||||
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
|
||||
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
|
||||
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
|
||||
"""
|
||||
|
||||
import calendar
|
||||
from datetime import date
|
||||
|
||||
|
||||
def window_start(cutoff: date, months: int) -> date:
|
||||
"""The first day of the window: `months` before the cut-off (the month's last day when
|
||||
shorter), plus one day."""
|
||||
total = cutoff.year * 12 + cutoff.month - 1 - months
|
||||
year, month = divmod(total, 12)
|
||||
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
|
||||
|
||||
+152
-115
@@ -1,26 +1,12 @@
|
||||
"""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
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from typing import ClassVar
|
||||
from fhir.resources.R4B.measurereport import MeasureReport
|
||||
|
||||
from core.fhir import EXTENSION, measure_url, stratifier_code
|
||||
|
||||
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
|
||||
@@ -33,11 +19,10 @@ NO_BIOPSY = "no_biopsy"
|
||||
@dataclass(frozen=True)
|
||||
class Period:
|
||||
start: date
|
||||
end: date # exclusive
|
||||
end: date
|
||||
|
||||
@classmethod
|
||||
def parse(cls, text: str) -> "Period":
|
||||
"""A semester (`2025-S1`) or a month (`2025-03`)."""
|
||||
year, part = text.split("-")
|
||||
if part.startswith("S"):
|
||||
first = 1 if part == "S1" else 7
|
||||
@@ -46,24 +31,33 @@ class Period:
|
||||
date(int(year), 7, 1) if first == 1 else date(int(year) + 1, 1, 1),
|
||||
)
|
||||
month = int(part)
|
||||
return cls(date(int(year), month, 1),
|
||||
date(int(year) + month // 12, month % 12 + 1, 1)) # fmt: skip
|
||||
return cls(date(int(year), month, 1), date(int(year) + month // 12, month % 12 + 1, 1))
|
||||
|
||||
@functools.cached_property
|
||||
def _iso(self) -> tuple[str, str]:
|
||||
return (self.start.isoformat(), self.end.isoformat())
|
||||
|
||||
def __contains__(self, day) -> bool:
|
||||
if isinstance(day, str):
|
||||
start, end = self._iso
|
||||
return start <= day[:10] < end
|
||||
return day is not None and self.start <= as_day(day) < self.end
|
||||
|
||||
|
||||
def as_day(value) -> date | None:
|
||||
"""A day, from a date, a datetime or ISO text."""
|
||||
if value is None or isinstance(value, date) and not isinstance(value, datetime):
|
||||
if value is None or (isinstance(value, date) and (not isinstance(value, datetime))):
|
||||
return value
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
return _iso_day(str(value)[:10])
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=65536)
|
||||
def _iso_day(text: str) -> date:
|
||||
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))
|
||||
@@ -71,7 +65,6 @@ def _moment(value) -> datetime | None:
|
||||
|
||||
|
||||
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
|
||||
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
|
||||
birth = as_day(birth)
|
||||
if birth is None:
|
||||
return NO_DATA
|
||||
@@ -79,11 +72,10 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
|
||||
for low, high in groups:
|
||||
if low <= age <= high:
|
||||
return f"{low}-{high}"
|
||||
lowest, highest = groups[0][0], groups[-1][1]
|
||||
lowest, highest = (groups[0][0], groups[-1][1])
|
||||
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
|
||||
|
||||
|
||||
# A stratum: its name and the value a row takes in a period.
|
||||
Stratum = tuple[str, Callable[[dict, "Period"], str]]
|
||||
|
||||
|
||||
@@ -94,27 +86,27 @@ 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)
|
||||
stratum_scores: dict[str, dict[str, dict]] = field(default_factory=dict)
|
||||
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
|
||||
default_factory=dict
|
||||
)
|
||||
|
||||
|
||||
def wilson(k: int, n: int) -> tuple[float, float]:
|
||||
p = k / n
|
||||
centre, half = p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n))
|
||||
low, high = (centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n)
|
||||
return round(max(low, 0.0), 12), round(min(high, 1.0), 12)
|
||||
centre, half = (p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)))
|
||||
low, high = ((centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n))
|
||||
return (round(max(low, 0.0), 12), round(min(high, 1.0), 12))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Proportion:
|
||||
"""Units with a row dated in the period that meets `denominator` and, of them, those
|
||||
with such a row that also meets `numerator`; with a Wilson 95% interval."""
|
||||
|
||||
numerator: Callable[[dict], bool]
|
||||
strata: tuple[Stratum, ...] = ()
|
||||
denominator: Callable[[dict], bool] = lambda row: True
|
||||
unit: str = "person_id"
|
||||
date: str = "sample_date"
|
||||
kind: str = "proportion"
|
||||
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)]
|
||||
@@ -140,16 +132,11 @@ class Proportion:
|
||||
|
||||
|
||||
def desc(value) -> tuple:
|
||||
"""A sort key on which a value ranks above a missing one."""
|
||||
return (value is not None, value)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Composition:
|
||||
"""Units by the category of one row each: of a unit's rows dated in the period (that meet
|
||||
`where`), the one `order` ranks highest. Only units whose chosen row is `admit`ted count.
|
||||
The chosen row's `category` is the first stratifier; `strata` add others."""
|
||||
|
||||
order: Callable[[dict], tuple]
|
||||
category: Callable[[dict], str]
|
||||
admit: Callable[[dict], bool] = lambda row: True
|
||||
@@ -158,6 +145,7 @@ class Composition:
|
||||
unit: str = "person_id"
|
||||
date: str = "sample_date"
|
||||
kind: str = "composition"
|
||||
dated_only: ClassVar[bool] = True
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
chosen: dict[str, dict] = {}
|
||||
@@ -171,20 +159,24 @@ 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():
|
||||
if (value := stratum(row, period)) is None: # in no group of this stratum
|
||||
continue
|
||||
value = 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:
|
||||
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
|
||||
crossed[name, "category"] = pairs
|
||||
n = len(chosen)
|
||||
return Result({"initial-population": n, "measure-observation": n}, strata=strata)
|
||||
return Result(
|
||||
{"initial-population": n, "measure-observation": n}, strata=strata, crossed=crossed
|
||||
)
|
||||
|
||||
|
||||
@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
|
||||
@@ -194,14 +186,16 @@ class Duration:
|
||||
unit: str = "sample_id"
|
||||
date: str = "sample_date"
|
||||
kind: str = "continuous-variable"
|
||||
dated_only: ClassVar[bool] = True
|
||||
one_per_unit: ClassVar[bool] = True
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
measured, initial = [], 0
|
||||
measured, initial = ([], 0)
|
||||
for row in {r[self.unit]: r for r in rows}.values():
|
||||
if row[self.date] not in period or not self.units(row):
|
||||
continue
|
||||
end = as_day(row.get(self.end))
|
||||
has = row.get(self.value) is not None and end is not None and end <= cutoff
|
||||
has = row.get(self.value) is not None and end is not None and (end <= cutoff)
|
||||
if has:
|
||||
measured.append(float(row[self.value]))
|
||||
stop = as_day(row.get(self.ended)) if self.ended else None
|
||||
@@ -220,9 +214,6 @@ class Duration:
|
||||
|
||||
@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"
|
||||
|
||||
@@ -232,19 +223,16 @@ class RiskBand:
|
||||
for row in mine:
|
||||
band = NO_DATA
|
||||
if (p := row.get("probability")) is not None:
|
||||
band = next(name for name, cut in self.bands if cut is None or p < cut)
|
||||
band = next((name for name, cut in self.bands if cut is None or p < cut))
|
||||
bands.setdefault(band, {"initial-population": 0})["initial-population"] += 1
|
||||
n = len(mine)
|
||||
return Result({"initial-population": n, "measure-observation": n},
|
||||
strata={"category": bands}) # fmt: skip
|
||||
return Result(
|
||||
{"initial-population": n, "measure-observation": n}, strata={"category": bands}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AtEnd:
|
||||
"""The units on the books at a period's end: entered (`entry`) before it ended and not
|
||||
gone (`exit`) before it began. Each is in the latest of `states` (name, date column, in
|
||||
order) it reached before the end."""
|
||||
|
||||
entry: str
|
||||
exit: str
|
||||
states: tuple[tuple[str, str], ...]
|
||||
@@ -253,28 +241,26 @@ class AtEnd:
|
||||
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
|
||||
found = {}
|
||||
for row in rows:
|
||||
entry, gone = as_day(row.get(self.entry)), as_day(row.get(self.exit))
|
||||
entry, gone = (as_day(row.get(self.entry)), as_day(row.get(self.exit)))
|
||||
if entry is None or entry >= period.end or (gone is not None and gone < period.start):
|
||||
continue
|
||||
reached = [n for n, c in self.states
|
||||
if (d := as_day(row.get(c))) is not None and d < period.end] # fmt: skip
|
||||
reached = [
|
||||
n
|
||||
for n, c in self.states
|
||||
if (d := as_day(row.get(c))) is not None and d < period.end
|
||||
]
|
||||
if reached:
|
||||
found[row[self.unit]] = (row, reached[-1])
|
||||
return found
|
||||
|
||||
|
||||
def reached(row: dict, column: str, period: Period) -> bool:
|
||||
"""A date reached by the period's end."""
|
||||
day = as_day(row.get(column))
|
||||
return day is not None and day < period.end
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StatusProportion:
|
||||
"""Of the units on the books at the end (`population`) that meet `denominator`, those
|
||||
that meet `numerator`; both see the unit's row, its state and the period. Strata count
|
||||
every unit on the books, so a stratum with none in the denominator still shows."""
|
||||
|
||||
population: AtEnd
|
||||
denominator: Callable[[dict, str, Period], bool]
|
||||
numerator: Callable[[dict, str, Period], bool]
|
||||
@@ -290,8 +276,10 @@ class StatusProportion:
|
||||
for name, stratum in self.strata:
|
||||
values: dict[str, dict[str, int]] = {}
|
||||
for unit, (row, _) in units.items():
|
||||
cell = values.setdefault(stratum(row, period), {
|
||||
"initial-population": 0, "denominator": 0, "numerator": 0}) # fmt: skip
|
||||
cell = values.setdefault(
|
||||
stratum(row, period),
|
||||
{"initial-population": 0, "denominator": 0, "numerator": 0},
|
||||
)
|
||||
cell["initial-population"] += unit in den
|
||||
cell["denominator"] += unit in den
|
||||
cell["numerator"] += unit in num
|
||||
@@ -304,8 +292,6 @@ class StatusProportion:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StatusComposition:
|
||||
"""The units on the books at the end, by their state; only `admit`ted states count."""
|
||||
|
||||
population: AtEnd
|
||||
admit: Callable[[str], bool] = lambda state: True
|
||||
kind: str = "composition"
|
||||
@@ -316,16 +302,13 @@ class StatusComposition:
|
||||
for state in states:
|
||||
categories.setdefault(state, {"initial-population": 0})["initial-population"] += 1
|
||||
n = len(states)
|
||||
return Result({"initial-population": n, "measure-observation": n},
|
||||
strata={"category": categories}) # fmt: skip
|
||||
return Result(
|
||||
{"initial-population": n, "measure-observation": n}, strata={"category": categories}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StatusDuration:
|
||||
"""Days (`value`) per unit on the books at the end, for those whose interval ended
|
||||
(`end`) before the period's end and by the cut-off; every unit on the books is in the
|
||||
initial population."""
|
||||
|
||||
population: AtEnd
|
||||
value: str
|
||||
end: str
|
||||
@@ -333,9 +316,13 @@ class StatusDuration:
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
units = self.population.units(rows, period)
|
||||
measured = [float(r[self.value]) for r, _ in units.values()
|
||||
if r.get(self.value) is not None and reached(r, self.end, period)
|
||||
and as_day(r[self.end]) <= cutoff] # fmt: skip
|
||||
measured = [
|
||||
float(r[self.value])
|
||||
for r, _ in units.values()
|
||||
if r.get(self.value) is not None
|
||||
and reached(r, self.end, period)
|
||||
and (as_day(r[self.end]) <= cutoff)
|
||||
]
|
||||
found = {"initial-population": len(units), "measure-observation": len(measured)}
|
||||
if not measured:
|
||||
return Result(found)
|
||||
@@ -346,28 +333,30 @@ class StatusDuration:
|
||||
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
|
||||
|
||||
|
||||
Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | StatusComposition
|
||||
| StatusDuration) # fmt: skip
|
||||
Rule = (
|
||||
Proportion
|
||||
| Composition
|
||||
| Duration
|
||||
| RiskBand
|
||||
| StatusProportion
|
||||
| StatusComposition
|
||||
| StatusDuration
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Measure:
|
||||
id: str
|
||||
title: str
|
||||
rows: str # which gold rows it reads (see persistance.measures)
|
||||
rows: str
|
||||
rule: Rule
|
||||
improvement: str | None = None
|
||||
version: str = "1.0.0"
|
||||
periods: tuple[str, ...] = ("semester", "month")
|
||||
group: str = "TOTAL"
|
||||
params: dict = field(default_factory=dict) # bound into the read of its rows
|
||||
known: str = "known_at" # when a row's unit became known: before then it isn't counted
|
||||
# Facts a row carries that became known apart from the row itself: their `known_at`
|
||||
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
|
||||
params: dict = field(default_factory=dict)
|
||||
known: str = "known_at"
|
||||
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
description: str | None = None
|
||||
# Some sources only retain an instance's first-known time, not each event's history.
|
||||
supports_as_of: bool = True
|
||||
|
||||
|
||||
def evaluate(
|
||||
@@ -377,11 +366,10 @@ 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)."""
|
||||
if as_of is not None and not measure.supports_as_of:
|
||||
raise ValueError("This measure cannot reconstruct knowledge at a historical as-of time")
|
||||
as_of = _moment(as_of)
|
||||
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
|
||||
if as_of is None:
|
||||
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
|
||||
|
||||
def known(column: str, row: dict) -> bool:
|
||||
return as_of is None or (_moment(row.get(column)) or as_of) <= as_of
|
||||
@@ -391,10 +379,33 @@ def evaluate(
|
||||
if known(measure.known, row):
|
||||
unknown = [c for k, cols in measure.facts.items() if not known(k, row) for c in cols]
|
||||
found.append({**row, **dict.fromkeys(unknown)} if unknown else row)
|
||||
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
|
||||
return measure.rule.evaluate(found, period, cutoff)
|
||||
|
||||
|
||||
def evaluate_periods(
|
||||
measure: Measure,
|
||||
rows: Iterable[dict],
|
||||
periods: list[Period],
|
||||
as_of: datetime | None = None,
|
||||
event_cutoff: date | None = None,
|
||||
) -> list[Result]:
|
||||
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):
|
||||
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):
|
||||
if (day := as_day(row[rule.date])) is not None:
|
||||
months[day.year, day.month].append(i)
|
||||
found = []
|
||||
for period in periods:
|
||||
mine = sorted((i for (y, m), ids in months.items() if date(y, m, 1) in period for i in ids))
|
||||
found.append(evaluate(measure, [rows[i] for i in mine], period, None, event_cutoff))
|
||||
return found
|
||||
|
||||
|
||||
def _population(code: str, count: int) -> dict:
|
||||
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
|
||||
|
||||
@@ -402,7 +413,6 @@ def _population(code: str, count: int) -> dict:
|
||||
def report(
|
||||
measure: Measure, period: Period, result: Result, as_of: datetime | None
|
||||
) -> MeasureReport:
|
||||
"""The evaluation as a FHIR R4B MeasureReport (validated when built)."""
|
||||
group: dict = {
|
||||
"id": measure.group,
|
||||
"population": [_population(c, n) for c, n in result.populations.items()],
|
||||
@@ -411,35 +421,62 @@ def report(
|
||||
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": # a cohort scores its count
|
||||
"extension": [
|
||||
{"url": EXTENSION + k, "valueDecimal": v}
|
||||
for k, v in result.score_extensions.items()
|
||||
],
|
||||
}
|
||||
elif measure.rule.kind == "composition":
|
||||
group["measureScore"] = {"value": result.populations["initial-population"]}
|
||||
if result.strata:
|
||||
group["stratifier"] = [
|
||||
{"id": name, "code": [stratifier_code(name)],
|
||||
"stratum": [{"value": {"text": value},
|
||||
"population": [_population(c, n) for c, n in cells.items()],
|
||||
**({"measureScore": result.stratum_scores[name][value]}
|
||||
if value in result.stratum_scores.get(name, {}) else {})}
|
||||
for value, cells in sorted(values.items())]}
|
||||
{
|
||||
"id": name,
|
||||
"code": [stratifier_code(name)],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {"text": value},
|
||||
"population": [_population(c, n) for c, n in cells.items()],
|
||||
}
|
||||
for value, cells in sorted(values.items())
|
||||
],
|
||||
}
|
||||
for name, values in result.strata.items()
|
||||
] # fmt: skip
|
||||
] + [
|
||||
{
|
||||
"id": f"{a}-{b}",
|
||||
"code": [stratifier_code(a), stratifier_code(b)],
|
||||
"stratum": [
|
||||
{
|
||||
"component": [
|
||||
{"code": stratifier_code(a), "value": {"text": va}},
|
||||
{"code": stratifier_code(b), "value": {"text": vb}},
|
||||
],
|
||||
"population": [_population(c, n) for c, n in cells.items()],
|
||||
}
|
||||
for (va, vb), cells in sorted(values.items())
|
||||
],
|
||||
}
|
||||
for (a, b), values in result.crossed.items()
|
||||
]
|
||||
found = {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary", # with no score when nothing in the period could be measured
|
||||
"type": "summary",
|
||||
"measure": f"{measure_url(measure.id)}|{measure.version}",
|
||||
"period": {"start": period.start.isoformat(),
|
||||
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
|
||||
"period": {
|
||||
"start": period.start.isoformat(),
|
||||
"end": date.fromordinal(period.end.toordinal() - 1).isoformat(),
|
||||
},
|
||||
"date": datetime.now().astimezone().isoformat(),
|
||||
"group": [group],
|
||||
} # fmt: skip
|
||||
}
|
||||
if as_of is not None:
|
||||
found["extension"] = [{"url": EXTENSION + "corte-conocimiento",
|
||||
"valueDateTime": as_of.isoformat()}] # fmt: skip
|
||||
found["extension"] = [
|
||||
{"url": EXTENSION + "corte-conocimiento", "valueDateTime": as_of.isoformat()}
|
||||
]
|
||||
if measure.improvement:
|
||||
found["improvementNotation"] = {"coding": [{"system": IMPROVEMENT,
|
||||
"code": measure.improvement}]} # fmt: skip
|
||||
found["improvementNotation"] = {
|
||||
"coding": [{"system": IMPROVEMENT, "code": measure.improvement}]
|
||||
}
|
||||
return MeasureReport.model_validate(found)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
TITLES: dict[str, str] = {
|
||||
"cacu.cin2_logistic": "Riesgo de LIEAG+ (regresión logística)",
|
||||
"cacu.cin2_pim": "Riesgo de LIEAG+ en vigilancia",
|
||||
"cacu.cancer_pim": "Riesgo de cáncer en vigilancia",
|
||||
"cacu.cin2_pim_post_colposcopy": "Riesgo de LIEAG+ tras colposcopía",
|
||||
"cacu.cin2_pim_post_treatment": "Riesgo de LIEAG+ tras tratamiento",
|
||||
"cacu.survival": "Supervivencia",
|
||||
"cama.survival": "Supervivencia",
|
||||
"cama.recurrence": "Recurrencia",
|
||||
"tea.eeg-gradient": "Curva por edad: gradiente anteroposterior",
|
||||
"tea.eeg-posterior-rhythm": "Curva por edad: ritmo posterior",
|
||||
"tea.eeg-spikes": "Curva por edad: picos paroxísticos",
|
||||
"tea.eeg-spindles-n2": "Curva por edad: husos de sueño N2",
|
||||
"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.eeg-ados2": "Relación del EEG con el ADOS-2",
|
||||
}
|
||||
|
||||
|
||||
def title(model: str) -> str:
|
||||
return TITLES.get(model, model.split(".", 1)[-1])
|
||||
+218
-136
@@ -1,17 +1,8 @@
|
||||
"""The ingestion DSL: a graph an operator draws, and the pure steps it needs. No IO here.
|
||||
|
||||
A pipeline is one versioned JSON document of nodes; each node names its inputs (the edges).
|
||||
Every node kind wraps one library operation and outputs one table, so any node's output can
|
||||
be previewed and a run can restart from the node that changed. Each kind's JSON Schema is
|
||||
the form the canvas shows for it. Nothing in a graph is specific to one hospital in code.
|
||||
"""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from graphlib import CycleError, TopologicalSorter
|
||||
from typing import Annotated, Any, ClassVar, Literal
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
import dateparser
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
@@ -22,13 +13,35 @@ from pydantic import (
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
|
||||
from core import catalog, sources
|
||||
from core.schema import ENTITIES
|
||||
|
||||
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
|
||||
ID_PATTERN = "^[a-z][a-z0-9_]*$"
|
||||
Id = Annotated[str, Field(pattern=ID_PATTERN, max_length=40)]
|
||||
ImportPath = Annotated[str, Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")]
|
||||
EntityName = Literal[tuple(ENTITIES)] # type: ignore[valid-type]
|
||||
ImportPath = Annotated[str, Field(pattern="^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$")]
|
||||
EntityName = Literal[tuple(ENTITIES)]
|
||||
ENTITY_TITLES = {
|
||||
"identity": "Identidad de la persona",
|
||||
**{name: spec.title for name, spec in catalog.studies().items()},
|
||||
}
|
||||
|
||||
|
||||
def _says(
|
||||
title: str,
|
||||
description: str = "",
|
||||
options: dict[str, str] | None = None,
|
||||
advanced: bool = False,
|
||||
keys: Literal["field"] | None = None,
|
||||
) -> Any:
|
||||
extra: dict[str, Any] = {}
|
||||
if options:
|
||||
listed = [{"value": k, "label": v} for k, v in options.items()]
|
||||
extra["widget"] = {"formlyConfig": {"props": {"options": listed}}}
|
||||
if advanced:
|
||||
extra["advanced"] = True
|
||||
if keys:
|
||||
extra["keys"] = keys
|
||||
return Field(title=title, description=description or None, json_schema_extra=extra or None)
|
||||
|
||||
|
||||
class Position(BaseModel):
|
||||
@@ -38,78 +51,128 @@ class Position(BaseModel):
|
||||
|
||||
class Node(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
|
||||
|
||||
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1)
|
||||
id: Id
|
||||
inputs: list[Id] = []
|
||||
label: str = "" # what the canvas shows
|
||||
position: Position | None = None # where the canvas drew it
|
||||
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
|
||||
position: Position | None = None
|
||||
|
||||
|
||||
class Guided(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
type: str
|
||||
answers: dict[str, Any] = {}
|
||||
|
||||
|
||||
class Source(Node):
|
||||
"""One table, file set or API resource, copied as it is (dlt). Merged on the source's
|
||||
own primary key or `primary_key`; replaced whole when it has none."""
|
||||
|
||||
inputs_allowed = (0, 0)
|
||||
kind: Literal["source"] = "source"
|
||||
source: ImportPath # any dlt source or resource, e.g. dlt.sources.sql_database:sql_table
|
||||
args: dict[str, Any] = {}
|
||||
resource: str | None = None # which resource, when the source has several
|
||||
then: ImportPath | None = None # a dlt transformer piped after (file contents, Excel)
|
||||
primary_key: list[str] = []
|
||||
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[
|
||||
str | None, _says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True)
|
||||
] = None
|
||||
then: Annotated[
|
||||
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
|
||||
] = None
|
||||
primary_key: Annotated[
|
||||
list[str], _says("Llave", "Columnas que identifican una fila.", advanced=True)
|
||||
] = []
|
||||
guided: Annotated[Guided | None, _says("Asistente", advanced=True)] = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _made_from_answers(cls, data: Any) -> Any:
|
||||
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", {})):
|
||||
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
|
||||
return data
|
||||
|
||||
|
||||
class Read(Node):
|
||||
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
|
||||
|
||||
kind: Literal["read"] = "read"
|
||||
column: str
|
||||
column: Annotated[
|
||||
str, _says("Columna con los archivos", "Donde la entrada trae cada documento.")
|
||||
]
|
||||
|
||||
|
||||
class Condition(BaseModel):
|
||||
column: str
|
||||
op: Literal["equals", "contains", "matches", "present"]
|
||||
value: str = ""
|
||||
column: Annotated[str, _says("Columna", "Por ejemplo «text», el texto leído del documento.")]
|
||||
op: Annotated[
|
||||
Literal["equals", "contains", "matches", "present"],
|
||||
_says(
|
||||
"Condición",
|
||||
options={
|
||||
"equals": "es igual a",
|
||||
"contains": "contiene",
|
||||
"matches": "coincide con la expresión",
|
||||
"present": "tiene algún valor",
|
||||
},
|
||||
),
|
||||
]
|
||||
value: Annotated[str, _says("Valor", "Lo que se busca; por ejemplo «citología».")] = ""
|
||||
|
||||
|
||||
class Route(Node):
|
||||
"""Only the rows where every condition holds (e.g. reports titled "Citología")."""
|
||||
|
||||
kind: Literal["route"] = "route"
|
||||
when: list[Condition]
|
||||
when: Annotated[list[Condition], _says("Pasan las filas donde")] = []
|
||||
otherwise: Annotated[
|
||||
bool, _says("Lo que ningún otro tome", "Recoge lo que nadie reconoce, para revisarlo.")
|
||||
] = False
|
||||
|
||||
|
||||
class Map(Node):
|
||||
"""Columns to platform fields, the site's codes translated by its ConceptMap
|
||||
(core.concept_map), and its date formats."""
|
||||
|
||||
kind: Literal["map"] = "map"
|
||||
fields: dict[str, str] # platform field -> column
|
||||
concept_map: Id | None = None # the site's codes in platform terms
|
||||
formats: dict[str, str] = {} # platform field -> strptime format
|
||||
# platform field -> a value in platform terms that every row has, though no column says
|
||||
# it (a table of neurology notes: their specialty)
|
||||
values: dict[str, str] = {}
|
||||
fields: Annotated[
|
||||
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
|
||||
]
|
||||
concept_map: Annotated[
|
||||
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
|
||||
] = None
|
||||
formats: Annotated[
|
||||
dict[str, str], _says("Formatos de fecha", "Por ejemplo %d/%m/%Y.", keys="field")
|
||||
] = {}
|
||||
values: Annotated[
|
||||
dict[str, str], _says("Valores fijos", "Un dato igual para todas las filas.", keys="field")
|
||||
] = {}
|
||||
|
||||
|
||||
class Extract(Node):
|
||||
"""Platform fields read from text, each kept with the text it was read from.
|
||||
|
||||
`auto` asks the LLM when one is configured and answering, else applies `patterns`;
|
||||
with neither, the row is held. Patterns are regexes with one group, per field (the
|
||||
LLM can propose them from sample documents); their values go through the ConceptMap
|
||||
and `formats` as in `map`."""
|
||||
|
||||
kind: Literal["extract"] = "extract"
|
||||
# the text to read; several columns are read as one document, in their order (an
|
||||
# outsourced result joined to the order it answers)
|
||||
column: str | list[str]
|
||||
entity: EntityName
|
||||
method: Literal["auto", "llm", "patterns"] = "auto"
|
||||
hints: str = "" # for the LLM
|
||||
patterns: dict[str, str] = {} # platform field -> regex with one group
|
||||
concept_map: Id | None = None
|
||||
formats: dict[str, str] = {}
|
||||
column: Annotated[str | list[str], _says("Columna con el texto")]
|
||||
entity: Annotated[
|
||||
EntityName, _says("Estudio", "Qué estudio se saca del documento.", ENTITY_TITLES)
|
||||
]
|
||||
method: Annotated[
|
||||
Literal["auto", "llm", "patterns"],
|
||||
_says(
|
||||
"Cómo leer",
|
||||
options={
|
||||
"auto": "Automático",
|
||||
"llm": "Con el modelo de lenguaje",
|
||||
"patterns": "Con patrones",
|
||||
},
|
||||
),
|
||||
] = "auto"
|
||||
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
|
||||
patterns: Annotated[
|
||||
dict[str, str], _says("Patrones", "Dato → expresión con un grupo ( ).", keys="field")
|
||||
] = {}
|
||||
columns: Annotated[
|
||||
dict[str, str],
|
||||
_says("Datos tomados de columnas", "Dato → columna, sin leer el texto.", keys="field"),
|
||||
] = {}
|
||||
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
|
||||
formats: Annotated[dict[str, str], _says("Formatos de fecha", keys="field")] = {}
|
||||
|
||||
@field_validator("patterns")
|
||||
@classmethod
|
||||
@@ -120,56 +183,67 @@ class Extract(Node):
|
||||
return v
|
||||
|
||||
def text(self, row: dict[str, Any]) -> str:
|
||||
"""The row's text this node reads."""
|
||||
columns = [self.column] if isinstance(self.column, str) else self.column
|
||||
return "\n".join(str(row[c]) for c in columns if row.get(c))
|
||||
return "\n".join((str(row[c]) for c in columns if row.get(c)))
|
||||
|
||||
|
||||
class Fhir(Node):
|
||||
"""FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
|
||||
entity: identity, death or a study (core.fhir_in). The sender's own codes go through
|
||||
its ConceptMap."""
|
||||
|
||||
kind: Literal["fhir"] = "fhir"
|
||||
column: str = "doc"
|
||||
entity: EntityName
|
||||
concept_map: Id | None = None
|
||||
column: Annotated[str, _says("Columna con el FHIR")] = "doc"
|
||||
entity: Annotated[EntityName, _says("Estudio", options=ENTITY_TITLES)]
|
||||
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
|
||||
|
||||
|
||||
class Join(Node):
|
||||
"""Two inputs side by side where their columns match."""
|
||||
|
||||
inputs_allowed = (2, 2)
|
||||
kind: Literal["join"] = "join"
|
||||
on: list[tuple[str, str]] # (left column, right column)
|
||||
how: Literal["inner", "left"] = "inner"
|
||||
on: Annotated[
|
||||
list[tuple[str, str]],
|
||||
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
|
||||
]
|
||||
how: Annotated[
|
||||
Literal["inner", "left"],
|
||||
_says(
|
||||
"Cuáles quedan",
|
||||
options={"inner": "Solo las que tienen pareja", "left": "Todas las de la izquierda"},
|
||||
),
|
||||
] = "inner"
|
||||
|
||||
|
||||
IDENTIFIERS = ("record_number", "curp", "nss")
|
||||
|
||||
|
||||
class Link(Node):
|
||||
"""Identity rows from every input, grouped into persons (Splink).
|
||||
|
||||
Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
|
||||
and `r.` for the two records); persons are the connected groups. A person whose
|
||||
records disagree on birth date or sex is held for review as a whole. Pairs Splink
|
||||
scores above `review` that ended up apart are queued as possible matches."""
|
||||
|
||||
inputs_allowed = (1, None)
|
||||
kind: Literal["link"] = "link"
|
||||
fields: list[str] = ["record_number", "full_name", "curp", "nss", "birth_date", "sex"]
|
||||
rules: list[str] = [] # empty: the defaults for `fields` (see default_rules)
|
||||
review: float = Field(0.5, gt=0, le=1)
|
||||
fields: Annotated[list[str], _says("Datos que comparar")] = [
|
||||
"record_number",
|
||||
"full_name",
|
||||
"curp",
|
||||
"nss",
|
||||
"birth_date",
|
||||
"sex",
|
||||
]
|
||||
rules: Annotated[
|
||||
list[str],
|
||||
_says(
|
||||
"Reglas",
|
||||
"Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).",
|
||||
),
|
||||
] = []
|
||||
review: Annotated[
|
||||
float,
|
||||
Field(gt=0, le=1),
|
||||
_says("Umbral para revisar", "Parecidos por encima de esto los ve un revisor."),
|
||||
] = 0.5
|
||||
|
||||
def default_rules(self) -> list[str]:
|
||||
"""The same identifier, unless the birth dates differ; or the same birth date and
|
||||
the same name (as compared: upper case, no accents, single spaces)."""
|
||||
dob = "birth_date" in self.fields
|
||||
same_dob = (
|
||||
" and (l.birth_date is null or r.birth_date is null"
|
||||
" or l.birth_date = r.birth_date)" if dob else ""
|
||||
) # fmt: skip
|
||||
" and (l.birth_date is null or r.birth_date is null or l.birth_date = r.birth_date)"
|
||||
if dob
|
||||
else ""
|
||||
)
|
||||
rules = [f"l.{f} = r.{f}{same_dob}" for f in IDENTIFIERS if f in self.fields]
|
||||
if dob and "full_name" in self.fields:
|
||||
rules.append("l.birth_date = r.birth_date and l.full_name = r.full_name")
|
||||
@@ -177,12 +251,11 @@ class Link(Node):
|
||||
|
||||
|
||||
class Target(Node):
|
||||
"""Rows of platform fields into one platform entity, each row given its person by the
|
||||
one `link` node among the inputs. Rule breaks are held for review."""
|
||||
|
||||
inputs_allowed = (2, None)
|
||||
kind: Literal["target"] = "target"
|
||||
entity: EntityName
|
||||
entity: Annotated[
|
||||
EntityName, _says("Estudio", "En qué estudio de la plataforma se guarda.", ENTITY_TITLES)
|
||||
]
|
||||
|
||||
@field_validator("entity")
|
||||
@classmethod
|
||||
@@ -209,7 +282,7 @@ class Pipeline(BaseModel):
|
||||
lo, hi = n.inputs_allowed
|
||||
if not lo <= len(n.inputs) <= (hi if hi is not None else len(n.inputs)):
|
||||
raise ValueError(f"{n.id}: {n.kind} takes {lo}..{hi} inputs")
|
||||
if missing := set(n.inputs) - set(ids):
|
||||
if missing := (set(n.inputs) - set(ids)):
|
||||
raise ValueError(f"{n.id}: no node {sorted(missing)}")
|
||||
kinds = {n.id: n.kind for n in self.nodes}
|
||||
for n in self.nodes:
|
||||
@@ -222,15 +295,14 @@ class Pipeline(BaseModel):
|
||||
return self
|
||||
|
||||
def order(self) -> list[AnyNode]:
|
||||
"""Nodes in an order where every input runs before the nodes that read it."""
|
||||
by_id = {n.id: n for n in self.nodes}
|
||||
graph = TopologicalSorter({n.id: n.inputs for n in self.nodes})
|
||||
return [by_id[i] for i in graph.static_order()]
|
||||
|
||||
|
||||
RECORD = "_record" # the source row every row comes from (hash of that row)
|
||||
HELD = "_held" # why a row may not reach silver (list of reasons) or None
|
||||
QUOTES = "_quotes" # what text each LLM value was read from
|
||||
RECORD = "_record"
|
||||
HELD = "_held"
|
||||
QUOTES = "_quotes"
|
||||
|
||||
|
||||
def matches(node: Route, row: dict[str, Any]) -> bool:
|
||||
@@ -249,38 +321,32 @@ def matches(node: Route, row: dict[str, Any]) -> bool:
|
||||
|
||||
|
||||
def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list[dict]:
|
||||
"""Left rows with the matching right rows' columns (a clashing name gets `__<right>`)."""
|
||||
index: dict[tuple, list[dict]] = {}
|
||||
for r in right:
|
||||
index.setdefault(tuple(r.get(b) for _, b in node.on), []).append(r)
|
||||
index.setdefault(tuple((r.get(b) for _, b in node.on)), []).append(r)
|
||||
out = []
|
||||
for row in left:
|
||||
found = index.get(tuple(row.get(a) for a, _ in node.on), [])
|
||||
found = index.get(tuple((row.get(a) for a, _ in node.on)), [])
|
||||
for r in found or ([{}] if node.how == "left" else []):
|
||||
extra = {(k if k not in row else f"{k}__{right_id}"): v for k, v in r.items()}
|
||||
extra = {k if k not in row else f"{k}__{right_id}": v for k, v in r.items()}
|
||||
out.append({**row, **extra, RECORD: row[RECORD]})
|
||||
return out
|
||||
|
||||
|
||||
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
|
||||
Codes = dict[str, dict[str, str]]
|
||||
|
||||
|
||||
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
|
||||
"""A raw value as the platform field expects it: the site's code translated (its
|
||||
ConceptMap; case, line breaks and repeated spaces 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 = codes.get(field, {}).get(" ".join(raw.split()).casefold(), raw)
|
||||
raw = codes.get(field, {}).get(raw.casefold(), raw)
|
||||
fmt = node.formats.get(field)
|
||||
if fmt and fmt.startswith("dateparser:"):
|
||||
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
|
||||
return found.date() if found else raw
|
||||
if fmt:
|
||||
if " " not in fmt: # OCR may split a number ("25/01/1 967")
|
||||
if " " not in fmt:
|
||||
raw = "".join(raw.split())
|
||||
try:
|
||||
return datetime.strptime(raw, fmt).date()
|
||||
@@ -297,7 +363,6 @@ def map_row(node: Map, row: dict[str, Any], codes: Codes) -> dict[str, Any]:
|
||||
|
||||
|
||||
def validate(entity: str, values: dict[str, Any]) -> list[str]:
|
||||
"""Why these values break the platform schema; empty if they don't."""
|
||||
try:
|
||||
ENTITIES[entity].model_validate(values)
|
||||
except ValidationError as e:
|
||||
@@ -305,28 +370,25 @@ def validate(entity: str, values: dict[str, Any]) -> list[str]:
|
||||
return []
|
||||
|
||||
|
||||
_SPACE = re.compile(r"\s+")
|
||||
_SPACE = re.compile("\\s+")
|
||||
|
||||
|
||||
def grounded(quote: str | None, text: str) -> bool:
|
||||
"""An LLM value counts only if the text it says it read is really in the document."""
|
||||
if not quote:
|
||||
return False
|
||||
norm = lambda s: _SPACE.sub(" ", s).strip().casefold() # noqa: E731
|
||||
norm = lambda s: _SPACE.sub(" ", s).strip().casefold()
|
||||
return norm(quote) in norm(text)
|
||||
|
||||
|
||||
def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
|
||||
"""Each record of an LLM answer as (values, quotes, reasons to hold it). A value whose
|
||||
quote is not in the text is dropped, and the record is held saying so."""
|
||||
out = []
|
||||
for record in answer.get("records", []):
|
||||
values, quotes, held = {}, {}, []
|
||||
values, quotes, held = ({}, {}, [])
|
||||
for field, got in record.items():
|
||||
if not got or got.get("value") is None:
|
||||
continue
|
||||
if grounded(got.get("quote"), text):
|
||||
values[field], quotes[field] = got["value"], got["quote"]
|
||||
values[field], quotes[field] = (got["value"], got["quote"])
|
||||
else:
|
||||
held.append(f"{field}: not found in the document as quoted")
|
||||
out.append((values, quotes, held))
|
||||
@@ -334,9 +396,7 @@ def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
|
||||
|
||||
|
||||
def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, dict, list[str]]]:
|
||||
"""One record from the node's patterns: (values, quotes, reasons to hold it). A value
|
||||
found this way is grounded by construction: the quote is the matched text."""
|
||||
values, quotes = {}, {}
|
||||
values, quotes = ({}, {})
|
||||
for field, pattern in node.patterns.items():
|
||||
if found := re.search(pattern, text, re.IGNORECASE):
|
||||
values[field] = convert(node, field, found.group(1), codes)
|
||||
@@ -347,8 +407,6 @@ def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, d
|
||||
|
||||
|
||||
def answer_schema(entity: str) -> dict:
|
||||
"""JSON Schema for an LLM answer: every record of `entity` found, each field with the
|
||||
quote it was read from."""
|
||||
fields = {
|
||||
f: (create_model(f"{entity}_{f}", value=(info.annotation, None), quote=(str, "")), None)
|
||||
for f, info in ENTITIES[entity].model_fields.items()
|
||||
@@ -358,7 +416,7 @@ def answer_schema(entity: str) -> dict:
|
||||
|
||||
|
||||
MASK = "********"
|
||||
_SECRET_KEY = re.compile(r"pass|secret|token|key", re.IGNORECASE)
|
||||
_SECRET_KEY = re.compile("pass|secret|token|key", re.IGNORECASE)
|
||||
|
||||
|
||||
def _mask(key: str, value: Any) -> Any:
|
||||
@@ -375,12 +433,25 @@ def _mask(key: str, value: Any) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
def _secret_answers(guided: "Guided") -> set[str]:
|
||||
fields = sources.catalog().types[guided.type].fields
|
||||
return {k for k, f in fields.items() if f.type == "password"}
|
||||
|
||||
|
||||
def _masked_source(n: "Source") -> "Source":
|
||||
update: dict[str, Any] = {"args": _mask("", n.args)}
|
||||
if n.guided:
|
||||
secret = _secret_answers(n.guided)
|
||||
answers = {
|
||||
k: MASK if k in secret and v not in (None, "") else _mask(k, v)
|
||||
for k, v in n.guided.answers.items()
|
||||
}
|
||||
update["guided"] = n.guided.model_copy(update={"answers": answers})
|
||||
return n.model_copy(update=update)
|
||||
|
||||
|
||||
def redacted(pipeline: Pipeline) -> Pipeline:
|
||||
"""The pipeline with every secret in its sources' arguments masked, as the API shows it."""
|
||||
nodes = [
|
||||
n.model_copy(update={"args": _mask("", n.args)}) if n.kind == "source" else n
|
||||
for n in pipeline.nodes
|
||||
]
|
||||
nodes = [_masked_source(n) if n.kind == "source" else n for n in pipeline.nodes]
|
||||
return pipeline.model_copy(update={"nodes": nodes})
|
||||
|
||||
|
||||
@@ -396,13 +467,24 @@ 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.args for n in old.nodes if n.kind == "source"} if old else {}
|
||||
nodes = [
|
||||
n.model_copy(update={"args": _restore(n.args, saved.get(n.id), n.id)})
|
||||
if n.kind == "source"
|
||||
else n
|
||||
for n in new.nodes
|
||||
]
|
||||
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]
|
||||
return new.model_copy(update={"nodes": nodes})
|
||||
|
||||
|
||||
def _restored_source(new: "Source", old: "Source | None") -> "Source":
|
||||
if not new.guided:
|
||||
return new.model_copy(update={"args": _restore(new.args, old and old.args, new.id)})
|
||||
kept = old.guided.answers if old and old.guided and (old.guided.type == new.guided.type) else {}
|
||||
secret = _secret_answers(new.guided)
|
||||
answers = {}
|
||||
for k, v in new.guided.answers.items():
|
||||
if k in secret and v == MASK:
|
||||
if kept.get(k) in (None, ""):
|
||||
raise ValueError(f"{new.id}.{k}: masked, but no saved secret to keep there")
|
||||
answers[k] = kept[k]
|
||||
else:
|
||||
answers[k] = _restore(v, kept.get(k), f"{new.id}.{k}")
|
||||
guided = new.guided.model_copy(update={"answers": answers})
|
||||
drawn = new.model_dump(exclude={"guided"})
|
||||
return Source.model_validate({**drawn, "guided": guided.model_dump()})
|
||||
|
||||
+15
-20
@@ -1,17 +1,8 @@
|
||||
"""The platform schema: the only fixed shape in ingestion. Every source is mapped onto it.
|
||||
|
||||
`identity` is what a record says about whom it belongs to; every other entity is a study of
|
||||
the clinical catalog (core.catalog), whose natural key and fields the catalog declares. Two
|
||||
values for one key that disagree are a conflict. `person` is never a field: record linkage
|
||||
over `identity` values assigns it.
|
||||
"""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from core import catalog
|
||||
|
||||
|
||||
@@ -20,13 +11,12 @@ class Sex(StrEnum):
|
||||
MALE = "male"
|
||||
|
||||
|
||||
# Systems of the identifiers a person carries. A record number's system is where it came
|
||||
# from (`urn:isssteleon:<pipeline>:<node>`): a hospital has as many as it has sources.
|
||||
IDENTIFIER_SYSTEMS = {
|
||||
"curp": "https://isssteleon.org/fhir/sid/curp",
|
||||
"nss": "https://isssteleon.org/fhir/sid/nss",
|
||||
}
|
||||
RECORD_NUMBER_SYSTEM = "urn:isssteleon:"
|
||||
_DATE = re.compile("\\d{1,4}[/.-]\\d{1,2}[/.-]\\d{1,4}")
|
||||
|
||||
|
||||
class Entity(BaseModel):
|
||||
@@ -35,14 +25,19 @@ class Entity(BaseModel):
|
||||
|
||||
|
||||
class Identity(Entity):
|
||||
"""What a record says about whom it belongs to. Input to linkage, never trusted alone."""
|
||||
record_number: str | None = Field(None, title="Número de expediente")
|
||||
full_name: str | None = Field(None, title="Nombre completo")
|
||||
curp: str | None = Field(None, title="CURP")
|
||||
nss: str | None = Field(None, title="NSS")
|
||||
birth_date: date | None = Field(None, title="Fecha de nacimiento")
|
||||
sex: Sex | None = Field(None, title="Sexo")
|
||||
|
||||
record_number: str | None = None
|
||||
full_name: str | None = None
|
||||
curp: str | None = None
|
||||
nss: str | None = None
|
||||
birth_date: date | None = None
|
||||
sex: Sex | None = None
|
||||
@field_validator("record_number")
|
||||
@classmethod
|
||||
def _not_a_date(cls, v: str | None) -> str | None:
|
||||
if v is not None and _DATE.fullmatch(v.strip()):
|
||||
raise ValueError("a date is not a record number")
|
||||
return v
|
||||
|
||||
|
||||
ENTITIES: dict[str, type[BaseModel]] = {
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
import re
|
||||
import string
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from urllib.parse import quote, unquote
|
||||
import yaml
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
FieldType = Literal[
|
||||
"text",
|
||||
"number",
|
||||
"password",
|
||||
"select",
|
||||
"folder",
|
||||
"server_file",
|
||||
"upload",
|
||||
"url",
|
||||
"oauth",
|
||||
"table",
|
||||
"format",
|
||||
"columns",
|
||||
]
|
||||
|
||||
|
||||
class Option(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
value: Any
|
||||
label: str
|
||||
|
||||
|
||||
class FieldSpec(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
label: str
|
||||
type: FieldType = "text"
|
||||
help: str = ""
|
||||
placeholder: str = ""
|
||||
required: bool = True
|
||||
default: Any = None
|
||||
options: list[Option] = []
|
||||
provider: str | None = None
|
||||
advanced: bool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _complete(self):
|
||||
if self.type == "select" and (not self.options):
|
||||
raise ValueError("a select field lists its options")
|
||||
if self.type == "oauth" and (not self.provider):
|
||||
raise ValueError("an oauth field names its provider")
|
||||
return self
|
||||
|
||||
|
||||
class Listing(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
kind: Literal["tables", "rows"]
|
||||
source: str | None = None
|
||||
args: dict[str, Any] = {}
|
||||
|
||||
|
||||
class SourceType(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
group: str
|
||||
title: str
|
||||
description: str
|
||||
icon: str
|
||||
fields: dict[str, FieldSpec]
|
||||
source: str
|
||||
args: dict[str, Any] = {}
|
||||
resource: str | None = None
|
||||
then: str | None = None
|
||||
primary_key: list[str] = []
|
||||
listing: Listing | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _templates_name_fields(self):
|
||||
named = _placeholders([self.source, self.args, self.resource, self.then])
|
||||
if self.listing:
|
||||
named |= _placeholders([self.listing.source, self.listing.args])
|
||||
if unknown := (named - set(self.fields)):
|
||||
raise ValueError(f"templates name unknown fields {sorted(unknown)}")
|
||||
return self
|
||||
|
||||
|
||||
class Provider(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
env: str
|
||||
authorize_url: str
|
||||
token_url: str
|
||||
scope: str
|
||||
authorize_params: dict[str, str] = {}
|
||||
|
||||
|
||||
class Group(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str
|
||||
description: str
|
||||
|
||||
|
||||
class Catalog(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
groups: dict[str, Group]
|
||||
providers: dict[str, Provider]
|
||||
formats: list[Option]
|
||||
types: dict[str, SourceType]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _groups_exist(self):
|
||||
for name, t in self.types.items():
|
||||
if t.group not in self.groups:
|
||||
raise ValueError(f"{name}: no group {t.group}")
|
||||
for field in t.fields.values():
|
||||
if field.type == "oauth" and field.provider not in self.providers:
|
||||
raise ValueError(f"{name}: no provider {field.provider}")
|
||||
return self
|
||||
|
||||
|
||||
class MissingAnswer(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@cache
|
||||
def catalog() -> Catalog:
|
||||
return Catalog.model_validate(yaml.safe_load((HERE / "types.yaml").read_text("utf-8")))
|
||||
|
||||
|
||||
class _Formatter(string.Formatter):
|
||||
def format_field(self, value: Any, format_spec: str) -> str:
|
||||
if format_spec == "url":
|
||||
return quote(str(value), safe="")
|
||||
if format_spec == "path":
|
||||
return quote(str(value), safe="/")
|
||||
if format_spec == "last":
|
||||
return str(value).split("?")[0].rstrip("/").rsplit("/", 1)[-1]
|
||||
return super().format_field(value, format_spec)
|
||||
|
||||
|
||||
_FORMAT = _Formatter()
|
||||
|
||||
|
||||
def _base(name: str) -> str:
|
||||
return name.split("[", 1)[0].split(".", 1)[0]
|
||||
|
||||
|
||||
def _placeholders(template: Any) -> set[str]:
|
||||
if isinstance(template, str):
|
||||
return {_base(name) for _, name, _, _ in _FORMAT.parse(template) if name}
|
||||
if isinstance(template, dict):
|
||||
return set().union(*(_placeholders(v) for v in template.values()))
|
||||
if isinstance(template, list):
|
||||
return set().union(*(_placeholders(v) for v in template))
|
||||
return set()
|
||||
|
||||
|
||||
_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
|
||||
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}
|
||||
if isinstance(template, list):
|
||||
return [v for v in (_fill(t, values) for t in template) if v is not _DROP]
|
||||
if not isinstance(template, str):
|
||||
return template
|
||||
parts = list(_FORMAT.parse(template))
|
||||
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and (not parts[0][2]):
|
||||
name = parts[0][1]
|
||||
if values.get(_base(name)) in (None, ""):
|
||||
return _DROP
|
||||
value = _FORMAT.get_field(name, (), values)[0]
|
||||
return _DROP if value in (None, "") else value
|
||||
return _FORMAT.vformat(template, (), {k: "" if v is None else v for k, v in values.items()})
|
||||
|
||||
|
||||
def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
|
||||
spec = catalog().types[type_id]
|
||||
if unknown := (set(given) - set(spec.fields)):
|
||||
raise ValueError(f"{type_id}: no fields {sorted(unknown)}")
|
||||
out = {}
|
||||
for name, field in spec.fields.items():
|
||||
value = given.get(name)
|
||||
if value in (None, ""):
|
||||
value = field.default
|
||||
if value in (None, "") and field.required:
|
||||
raise MissingAnswer(f"falta «{field.label}»")
|
||||
out[name] = value
|
||||
return out
|
||||
|
||||
|
||||
def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
|
||||
spec = catalog().types[type_id]
|
||||
values = answers(type_id, given)
|
||||
made = {
|
||||
"source": _fill(spec.source, values),
|
||||
"args": _fill(spec.args, values),
|
||||
"resource": _fill(spec.resource, values),
|
||||
"then": _fill(spec.then, values),
|
||||
"primary_key": spec.primary_key,
|
||||
}
|
||||
return {k: None if v is _DROP else v for k, v in made.items()}
|
||||
|
||||
|
||||
def listing(type_id: str, given: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
|
||||
spec = catalog().types[type_id]
|
||||
if not spec.listing or spec.listing.kind != "tables" or (not spec.listing.source):
|
||||
return None
|
||||
relaxed = {n: given.get(n) or f.default for n, f in spec.fields.items()}
|
||||
missing = [
|
||||
f.label
|
||||
for n, f in spec.fields.items()
|
||||
if f.required and f.type != "table" and (relaxed[n] in (None, ""))
|
||||
]
|
||||
if missing:
|
||||
raise MissingAnswer("falta " + ", ".join((f"«{m}»" for m in missing)))
|
||||
return (_fill(spec.listing.source, relaxed), _fill(spec.listing.args, relaxed))
|
||||
|
||||
|
||||
class _NoMatch(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _take(template: Any, value: Any, found: dict[str, Any]) -> 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):
|
||||
raise _NoMatch
|
||||
return
|
||||
if isinstance(template, list):
|
||||
if not isinstance(value, list) or len(value) != len(template):
|
||||
raise _NoMatch
|
||||
for part, item in zip(template, value, strict=True):
|
||||
_take(part, item, found)
|
||||
return
|
||||
if not isinstance(template, str):
|
||||
if template != value:
|
||||
raise _NoMatch
|
||||
return
|
||||
parts = list(_FORMAT.parse(template))
|
||||
if any((name and ("[" in name or "." in name) for _, name, _, _ in parts)):
|
||||
raise _NoMatch
|
||||
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and (not parts[0][2]):
|
||||
_answer(found, parts[0][1], value)
|
||||
return
|
||||
if not isinstance(value, str):
|
||||
raise _NoMatch
|
||||
pattern, names = ("", [])
|
||||
for literal, name, spec, _ in parts:
|
||||
pattern += re.escape(literal)
|
||||
if name:
|
||||
pattern += f"(?P<g{len(names)}>.*?)"
|
||||
names.append((name, spec))
|
||||
matched = re.fullmatch(pattern, value, re.DOTALL)
|
||||
if not matched:
|
||||
raise _NoMatch
|
||||
for i, (name, spec) in enumerate(names):
|
||||
text = matched.group(f"g{i}")
|
||||
_answer(found, name, unquote(text) if spec in ("url", "path") else text)
|
||||
|
||||
|
||||
def _answer(found: dict[str, Any], name: str, value: Any) -> None:
|
||||
if name in found and found[name] != value:
|
||||
raise _NoMatch
|
||||
found[name] = value
|
||||
|
||||
|
||||
def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
|
||||
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():
|
||||
found: dict[str, Any] = {}
|
||||
try:
|
||||
for key in made:
|
||||
template = getattr(spec, key)
|
||||
if template is None:
|
||||
if made[key] not in (None, {}):
|
||||
raise _NoMatch
|
||||
continue
|
||||
_take(template, made[key], found)
|
||||
numbers = {n for n, f in spec.fields.items() if f.type == "number"}
|
||||
given = {
|
||||
n: int(v) if n in numbers and isinstance(v, str) and v.isdigit() else v
|
||||
for n, v in found.items()
|
||||
if n in spec.fields
|
||||
}
|
||||
rendered = render(type_id, given)
|
||||
except (_NoMatch, ValueError):
|
||||
continue
|
||||
if all((rendered[k] == made[k] for k in ("source", "resource", "then"))) and _same_args(
|
||||
rendered["args"] or {}, made["args"], spec
|
||||
):
|
||||
return (type_id, given)
|
||||
return None
|
||||
|
||||
|
||||
def _same_args(rendered: dict, drawn: dict, spec: "SourceType") -> bool:
|
||||
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:
|
||||
if drawn[key] != value:
|
||||
return False
|
||||
elif defaults.get(spec.args.get(key)) != value:
|
||||
return False
|
||||
return set(drawn) <= set(rendered)
|
||||
@@ -0,0 +1,379 @@
|
||||
|
||||
groups:
|
||||
database:
|
||||
title: Base de datos
|
||||
description: Tablas de un sistema del hospital (expediente, laboratorio, archivo de PDFs).
|
||||
files:
|
||||
title: Archivos
|
||||
description: PDFs, escaneos, EEGs, hojas de cálculo o textos, en su computadora o en el servidor.
|
||||
cloud:
|
||||
title: Nube
|
||||
description: Carpetas en OneDrive, SharePoint, Google Drive u otro almacenamiento en línea.
|
||||
web:
|
||||
title: Web
|
||||
description: Un sistema que entrega sus datos por internet (una API) o envía FHIR.
|
||||
|
||||
providers:
|
||||
microsoft:
|
||||
title: Microsoft
|
||||
env: MICROSOFT
|
||||
authorize_url: "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize"
|
||||
token_url: "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
|
||||
scope: "offline_access User.Read Files.Read.All Sites.Read.All"
|
||||
google:
|
||||
title: Google
|
||||
env: GOOGLE
|
||||
authorize_url: "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
token_url: "https://oauth2.googleapis.com/token"
|
||||
scope: "https://www.googleapis.com/auth/drive.readonly"
|
||||
authorize_params: {access_type: offline, prompt: consent}
|
||||
|
||||
formats:
|
||||
- {value: "persistance.readers:read_bytes", label: "Documentos (PDF, Word, escaneos, EEG): cada archivo completo"}
|
||||
- {value: "persistance.readers:read_excel", label: "Hojas de Excel: cada fila de cada hoja"}
|
||||
- {value: "dlt.sources.filesystem:read_csv", label: "CSV (separado por comas): cada fila"}
|
||||
- {value: "persistance.readers:read_tsv", label: "Texto separado por tabuladores: cada fila"}
|
||||
- {value: "dlt.sources.filesystem:read_jsonl", label: "JSON por líneas: cada línea"}
|
||||
- {value: "dlt.sources.filesystem:read_parquet", label: "Parquet: cada fila"}
|
||||
|
||||
types:
|
||||
sqlserver:
|
||||
group: database
|
||||
title: SQL Server
|
||||
description: Una tabla de Microsoft SQL Server.
|
||||
icon: database
|
||||
fields: &sql_fields
|
||||
host: {label: Servidor, placeholder: "10.0.0.5 o servidor.hospital.local", help: "Nombre o dirección del equipo donde está la base de datos."}
|
||||
port: {label: Puerto, type: number, default: 1433, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
|
||||
database: {label: Base de datos, placeholder: "Pruebas"}
|
||||
user: {label: Usuario}
|
||||
password: {label: Contraseña, type: password}
|
||||
schema: {label: Esquema, default: dbo, advanced: true, help: "El grupo de tablas; valor habitual."}
|
||||
table: {label: Tabla, type: table, help: "Pulse «Probar conexión» para ver las tablas."}
|
||||
chunk_size: {label: Filas por lote, type: number, default: 100, advanced: true, help: "Menos filas por lote usan menos memoria cuando cada fila guarda un archivo."}
|
||||
columns: {label: Columnas, type: columns, required: false, advanced: true, help: "Solo estas columnas; vacío: todas."}
|
||||
source: "dlt.sources.sql_database:sql_table"
|
||||
args: &sql_args
|
||||
credentials: "mssql+pymssql://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
schema: "{schema}"
|
||||
table: "{table}"
|
||||
chunk_size: "{chunk_size}"
|
||||
included_columns: "{columns}"
|
||||
listing: &sql_listing
|
||||
kind: tables
|
||||
source: "dlt.sources.sql_database:sql_database"
|
||||
args:
|
||||
credentials: "mssql+pymssql://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
schema: "{schema}"
|
||||
reflection_level: minimal
|
||||
|
||||
postgresql:
|
||||
group: database
|
||||
title: PostgreSQL
|
||||
description: Una tabla de PostgreSQL.
|
||||
icon: database
|
||||
fields:
|
||||
<<: *sql_fields
|
||||
port: {label: Puerto, type: number, default: 5432, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
|
||||
schema: {label: Esquema, default: public, advanced: true, help: "El grupo de tablas; valor habitual."}
|
||||
source: "dlt.sources.sql_database:sql_table"
|
||||
args:
|
||||
<<: *sql_args
|
||||
credentials: "postgresql+psycopg2://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
listing:
|
||||
<<: *sql_listing
|
||||
args:
|
||||
credentials: "postgresql+psycopg2://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
schema: "{schema}"
|
||||
reflection_level: minimal
|
||||
|
||||
mysql:
|
||||
group: database
|
||||
title: MySQL o MariaDB
|
||||
description: Una tabla de MySQL o MariaDB.
|
||||
icon: database
|
||||
fields:
|
||||
<<: *sql_fields
|
||||
port: {label: Puerto, type: number, default: 3306, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
|
||||
schema: {label: Esquema, required: false, advanced: true, help: "En MySQL suele quedar vacío."}
|
||||
source: "dlt.sources.sql_database:sql_table"
|
||||
args:
|
||||
<<: *sql_args
|
||||
credentials: "mysql+pymysql://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
listing:
|
||||
<<: *sql_listing
|
||||
args:
|
||||
credentials: "mysql+pymysql://{user:url}:{password:url}@{host}:{port}/{database:path}"
|
||||
schema: "{schema}"
|
||||
reflection_level: minimal
|
||||
|
||||
oracle:
|
||||
group: database
|
||||
title: Oracle
|
||||
description: Una tabla de Oracle.
|
||||
icon: database
|
||||
fields:
|
||||
<<: *sql_fields
|
||||
port: {label: Puerto, type: number, default: 1521, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
|
||||
database: {label: Servicio, placeholder: "ORCLPDB1", help: "El nombre de servicio de la base de datos."}
|
||||
schema: {label: Esquema, required: false, advanced: true, help: "El dueño de las tablas; vacío: el del usuario."}
|
||||
source: "dlt.sources.sql_database:sql_table"
|
||||
args:
|
||||
<<: *sql_args
|
||||
credentials: "oracle+oracledb://{user:url}:{password:url}@{host}:{port}/?service_name={database:url}"
|
||||
listing:
|
||||
<<: *sql_listing
|
||||
args:
|
||||
credentials: "oracle+oracledb://{user:url}:{password:url}@{host}:{port}/?service_name={database:url}"
|
||||
schema: "{schema}"
|
||||
reflection_level: minimal
|
||||
|
||||
sqlite:
|
||||
group: database
|
||||
title: Archivo SQLite
|
||||
description: Una tabla de un archivo .db o .sqlite en el servidor.
|
||||
icon: database
|
||||
fields:
|
||||
path: {label: Archivo, type: server_file, placeholder: "/datos/hospital.db", help: "Pulse «Examinar…» o escriba la ruta del archivo en el servidor."}
|
||||
table: {label: Tabla, type: table, help: "Pulse «Probar conexión» para ver las tablas."}
|
||||
chunk_size: {label: Filas por lote, type: number, default: 100, advanced: true}
|
||||
columns: {label: Columnas, type: columns, required: false, advanced: true, help: "Solo estas columnas; vacío: todas."}
|
||||
source: "dlt.sources.sql_database:sql_table"
|
||||
args:
|
||||
credentials: "sqlite:///{path:path}"
|
||||
table: "{table}"
|
||||
chunk_size: "{chunk_size}"
|
||||
included_columns: "{columns}"
|
||||
listing:
|
||||
kind: tables
|
||||
source: "dlt.sources.sql_database:sql_database"
|
||||
args: {credentials: "sqlite:///{path:path}", reflection_level: minimal}
|
||||
|
||||
upload:
|
||||
group: files
|
||||
title: Desde mi computadora
|
||||
description: Suba archivos o una carpeta completa; quedan guardados en el servidor.
|
||||
icon: upload
|
||||
fields: &file_fields
|
||||
folder: {label: Archivos, type: upload, help: "Arrastre aquí los archivos o elija una carpeta."}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true, help: "Por ejemplo *.pdf para solo los PDF; **/* toma todos, también en subcarpetas."}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args: &file_args
|
||||
bucket_url: "{folder}"
|
||||
file_glob: "{pattern}"
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
server_folder:
|
||||
group: files
|
||||
title: Carpeta del servidor
|
||||
description: Una carpeta que el servidor ya tiene (una unidad compartida montada).
|
||||
icon: folder
|
||||
fields:
|
||||
<<: *file_fields
|
||||
folder: {label: Carpeta, type: folder, help: "Elija la carpeta; solo se muestran las que el administrador habilitó."}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args: *file_args
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
path_or_url:
|
||||
group: files
|
||||
title: Ruta o enlace
|
||||
description: Escriba la ruta de una carpeta o el enlace a un archivo en internet.
|
||||
icon: link
|
||||
fields:
|
||||
<<: *file_fields
|
||||
folder: {label: Ruta o enlace, type: url, placeholder: "/datos/reportes o https://sitio/archivo.csv", help: "Una carpeta del servidor, o la dirección de un archivo."}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args: *file_args
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
network_share:
|
||||
group: files
|
||||
title: Carpeta compartida de la red
|
||||
description: Una carpeta de Windows compartida en la red del hospital (\\servidor\carpeta).
|
||||
icon: folder-network
|
||||
fields:
|
||||
host: {label: Servidor, placeholder: "archivo.hospital.local"}
|
||||
share: {label: Carpeta compartida, placeholder: "Reportes", help: "Lo que va después del nombre del servidor: \\\\servidor\\Reportes."}
|
||||
path: {label: Subcarpeta, required: false, placeholder: "2026/citologias"}
|
||||
user: {label: Usuario, help: "Con dominio si lo pide: HOSPITAL\\usuario."}
|
||||
password: {label: Contraseña, type: password}
|
||||
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:
|
||||
url: "smb://{host}/{share:path}/{path:path}"
|
||||
file_glob: "{pattern}"
|
||||
storage_options: {username: "{user}", password: "{password}"}
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
sftp:
|
||||
group: files
|
||||
title: Servidor SFTP
|
||||
description: Archivos en otro equipo por SFTP (SSH).
|
||||
icon: server
|
||||
fields:
|
||||
host: {label: Servidor}
|
||||
port: {label: Puerto, type: number, default: 22, advanced: true}
|
||||
path: {label: Carpeta, placeholder: "/reportes"}
|
||||
user: {label: Usuario}
|
||||
password: {label: Contraseña, type: password}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args:
|
||||
bucket_url: "sftp://{host}/{path:path}"
|
||||
file_glob: "{pattern}"
|
||||
credentials: {sftp_port: "{port}", sftp_username: "{user}", sftp_password: "{password}"}
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
onedrive:
|
||||
group: cloud
|
||||
title: OneDrive
|
||||
description: Una carpeta de su OneDrive (Microsoft 365).
|
||||
icon: onedrive
|
||||
fields:
|
||||
account: {label: Cuenta de Microsoft, type: oauth, provider: microsoft, help: "Inicie sesión con la cuenta que tiene la carpeta."}
|
||||
folder: {label: Carpeta, required: false, placeholder: "Reportes/2026", help: "La ruta dentro de su OneDrive; vacío: todo."}
|
||||
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: # the signed-in user's own drive, by its id (msgraphfs single-drive mode)
|
||||
url: "msgd://{folder:path}"
|
||||
file_glob: "{pattern}"
|
||||
storage_options:
|
||||
drive_id: "{account[drive_id]}"
|
||||
oauth2_client_params: "{account[oauth2_client_params]}"
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
sharepoint:
|
||||
group: cloud
|
||||
title: SharePoint
|
||||
description: Una biblioteca de documentos de un sitio de SharePoint.
|
||||
icon: sharepoint
|
||||
fields:
|
||||
account: {label: Cuenta de Microsoft, type: oauth, provider: microsoft}
|
||||
site: {label: Sitio, placeholder: "Laboratorio", help: "El nombre del sitio, como aparece en su dirección."}
|
||||
library: {label: Biblioteca, default: Documentos compartidos, help: "Por lo general, «Documentos compartidos»."}
|
||||
folder: {label: Carpeta, required: false, placeholder: "Reportes/2026"}
|
||||
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:
|
||||
url: "msgd://{site:url}/{library:url}/{folder:path}"
|
||||
file_glob: "{pattern}"
|
||||
storage_options: {oauth2_client_params: "{account[oauth2_client_params]}"}
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
google_drive:
|
||||
group: cloud
|
||||
title: Google Drive
|
||||
description: Una carpeta de Google Drive.
|
||||
icon: google-drive
|
||||
fields:
|
||||
account: {label: Cuenta de Google, type: oauth, provider: google, help: "Inicie sesión con la cuenta que tiene la carpeta."}
|
||||
folder: {label: Enlace a la carpeta, type: url, default: root, placeholder: "https://drive.google.com/drive/folders/…", help: "Abra la carpeta en Drive y copie la dirección; vacío: Mi unidad."}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args:
|
||||
bucket_url: "gdrive://{folder:last}"
|
||||
file_glob: "{pattern}"
|
||||
credentials: "{account[credentials]}"
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
s3:
|
||||
group: cloud
|
||||
title: Amazon S3 o compatible
|
||||
description: Un bucket de S3, MinIO u otro almacenamiento compatible con S3.
|
||||
icon: cloud
|
||||
fields:
|
||||
bucket: {label: Bucket y carpeta, placeholder: "mi-bucket/reportes"}
|
||||
access_key: {label: Clave de acceso (Access key ID)}
|
||||
secret_key: {label: Clave secreta, type: password}
|
||||
endpoint: {label: Dirección del servicio, required: false, advanced: true, placeholder: "https://minio.hospital.local", help: "Solo si no es Amazon (MinIO y similares)."}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args:
|
||||
bucket_url: "s3://{bucket:path}"
|
||||
file_glob: "{pattern}"
|
||||
credentials: {aws_access_key_id: "{access_key}", aws_secret_access_key: "{secret_key}", endpoint_url: "{endpoint}"}
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
azure_blob:
|
||||
group: cloud
|
||||
title: Azure Blob Storage
|
||||
description: Un contenedor de Azure Storage.
|
||||
icon: cloud
|
||||
fields:
|
||||
account: {label: Cuenta de almacenamiento}
|
||||
key: {label: Clave de la cuenta, type: password}
|
||||
container: {label: Contenedor y carpeta, placeholder: "reportes/2026"}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args:
|
||||
bucket_url: "az://{container:path}"
|
||||
file_glob: "{pattern}"
|
||||
credentials: {azure_storage_account_name: "{account}", azure_storage_account_key: "{key}"}
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
gcs:
|
||||
group: cloud
|
||||
title: Google Cloud Storage
|
||||
description: Un bucket de Google Cloud Storage, con una cuenta de servicio.
|
||||
icon: cloud
|
||||
fields:
|
||||
bucket: {label: Bucket y carpeta, placeholder: "mi-bucket/reportes"}
|
||||
service_account: {label: Cuenta de servicio (JSON), type: password, help: "Pegue el contenido del archivo JSON de la cuenta de servicio."}
|
||||
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
|
||||
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
|
||||
source: "dlt.sources.filesystem:filesystem"
|
||||
args:
|
||||
bucket_url: "gs://{bucket:path}"
|
||||
file_glob: "{pattern}"
|
||||
credentials: "{service_account}"
|
||||
then: "{read_as}"
|
||||
listing: {kind: rows}
|
||||
|
||||
rest_api:
|
||||
group: web
|
||||
title: API web
|
||||
description: Un sistema que entrega sus datos en JSON por internet.
|
||||
icon: web
|
||||
fields:
|
||||
base_url: {label: Dirección base, type: url, placeholder: "https://laboratorio.example/api/"}
|
||||
path: {label: Recurso, placeholder: "resultados", help: "La parte de la dirección que entrega los datos."}
|
||||
token: {label: Token de acceso, type: password, required: false, help: "Si el sistema pide un token (Bearer)."}
|
||||
source: "dlt.sources.rest_api:rest_api_source"
|
||||
args:
|
||||
config:
|
||||
client:
|
||||
base_url: "{base_url}"
|
||||
auth: {type: bearer, token: "{token}"}
|
||||
resources: ["{path}"]
|
||||
listing: {kind: rows}
|
||||
|
||||
fhir_door:
|
||||
group: web
|
||||
title: Envío FHIR
|
||||
description: Un sistema que envía paquetes FHIR a la plataforma (POST /{dominio}/fhir).
|
||||
icon: fhir
|
||||
fields:
|
||||
sender: {label: Quién envía, placeholder: "synthea", help: "El nombre con que el sistema se identifica al enviar."}
|
||||
source: "persistance.readers:fhir_inbox"
|
||||
args: {sender: "{sender}"}
|
||||
primary_key: [id]
|
||||
listing: {kind: rows}
|
||||
+26
-21
@@ -1,17 +1,8 @@
|
||||
"""TEA clinical parameters: the one place they are set. dbt reads them as vars, the measures
|
||||
import them. Codes are the platform's (core.catalog)."""
|
||||
|
||||
# The screening cohort: children whose first M-CHAT is at this age (completed months, from
|
||||
# the age in months rounded to one decimal), in these windows.
|
||||
AGE_GROUPS = [(16, 23), (24, 29), (30, 36)]
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
# A neurology note with one of these confirms the diagnosis (ICD-10, with the dot).
|
||||
FOLLOW_UP_WINDOWS = [1, 3, 6, 12]
|
||||
CONFIRMING_ICD10 = ["F84.0"]
|
||||
NEUROLOGY = "pediatric_neurology" # the specialty of the notes the screening counts
|
||||
|
||||
# ADOS-2 calibrated severity (CSS): the lowest total reaching CSS 2..10, by module and
|
||||
# algorithm (Module 1) and whether the child is under five. Items score 0 to 3; a 3 counts
|
||||
# as 2. The values are approximate published ones, kept as data.
|
||||
NEUROLOGY = "pediatric_neurology"
|
||||
ADOS2_CSS = {
|
||||
("module_1", "few_to_no_words", True): [4, 7, 11, 14, 16, 18, 20, 22, 24],
|
||||
("module_1", "few_to_no_words", False): [6, 9, 12, 15, 17, 19, 21, 23, 25],
|
||||
@@ -21,21 +12,35 @@ ADOS2_CSS = {
|
||||
("module_2", None, False): [3, 6, 8, 10, 11, 13, 15, 17, 19],
|
||||
("module_3", None, None): [2, 4, 7, 8, 9, 11, 13, 15, 17],
|
||||
}
|
||||
# Classification by CSS: below 3 no spectrum, 3-4 autism spectrum, 5 or more autism.
|
||||
ADOS2_CLASSIFICATION = [("non_spectrum", 3), ("autism_spectrum", 5), ("autism", None)]
|
||||
# The Module 1 items that only the "few to no words" algorithm prints.
|
||||
FEW_TO_NO_WORDS_ITEMS = ["joint_attention_response", "intonation"]
|
||||
SOCIAL_AFFECT_ITEMS = [
|
||||
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact", "facial_expressions",
|
||||
"gaze_integration", "shared_enjoyment", "response_to_name", "ignoring", "requesting",
|
||||
"showing", "joint_attention_initiation", "joint_attention_response",
|
||||
"social_overtures_quality", "social_overtures_caregiver", "reciprocal_communication",
|
||||
"vocalization_directed",
|
||||
"pointing",
|
||||
"gestures",
|
||||
"unusual_eye_contact",
|
||||
"facial_expressions",
|
||||
"gaze_integration",
|
||||
"shared_enjoyment",
|
||||
"response_to_name",
|
||||
"ignoring",
|
||||
"requesting",
|
||||
"showing",
|
||||
"joint_attention_initiation",
|
||||
"joint_attention_response",
|
||||
"social_overtures_quality",
|
||||
"social_overtures_caregiver",
|
||||
"reciprocal_communication",
|
||||
"rapport_quality",
|
||||
] # fmt: skip
|
||||
RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_sensory_interest",
|
||||
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
|
||||
]
|
||||
RESTRICTED_REPETITIVE_ITEMS = [
|
||||
"intonation",
|
||||
"stereotyped_language",
|
||||
"unusual_sensory_interest",
|
||||
"hand_finger_mannerisms",
|
||||
"repetitive_interests",
|
||||
]
|
||||
|
||||
|
||||
def dbt_vars() -> dict:
|
||||
"""What dbt reads (`var('tea')`)."""
|
||||
return {k.lower(): v for k, v in globals().items() if k.isupper() and k != "ADOS2_CSS"}
|
||||
|
||||
+23
-20
@@ -1,23 +1,18 @@
|
||||
"""ADOS-2 scoring (pure): the calibrated severity score (CSS) and classification of one
|
||||
evaluation from its items (core.tea). The total is the sum of the items given, a 3 counting
|
||||
as 2; an evaluation without items in either domain is not scored."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core import tea
|
||||
|
||||
TODDLER_BANDS = {True: (10, 16), False: (8, 14)} # 20 months or younger: (mild, severe) totals
|
||||
TODDLER_BANDS = {True: (10, 16), False: (8, 14)}
|
||||
|
||||
|
||||
def algorithm(row: dict) -> str | None:
|
||||
"""Module 1's algorithm, from the items its report prints."""
|
||||
if row.get("module") != "module_1":
|
||||
return None
|
||||
printed = any(row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS)
|
||||
printed = any((row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS))
|
||||
return "few_to_no_words" if printed else "some_words"
|
||||
|
||||
|
||||
def total(row: dict) -> int | None:
|
||||
|
||||
def domain(items: list[str]) -> list[int]:
|
||||
return [min(int(row[i]), 2) for i in items if row.get(i) is not None]
|
||||
|
||||
@@ -27,22 +22,30 @@ def total(row: dict) -> int | None:
|
||||
|
||||
|
||||
def score(row: dict, birth: date | None) -> tuple[int | None, str | None]:
|
||||
"""(CSS, classification); (None, None) when it can't be scored."""
|
||||
found, module = total(row), row.get("module")
|
||||
found, module = (total(row), row.get("module"))
|
||||
if found is None or module is None:
|
||||
return None, None
|
||||
return (None, None)
|
||||
months = (row["evaluation_date"] - birth).days / tea.DAYS_PER_MONTH if birth else None
|
||||
if module == "toddler":
|
||||
mild, severe = TODDLER_BANDS[months is not None and months <= 20]
|
||||
band = "severe_concern" if found >= severe else (
|
||||
"mild_to_moderate_concern" if found >= mild else "non_spectrum") # fmt: skip
|
||||
return None, band
|
||||
band = (
|
||||
"severe_concern"
|
||||
if found >= severe
|
||||
else "mild_to_moderate_concern"
|
||||
if found >= mild
|
||||
else "non_spectrum"
|
||||
)
|
||||
return (None, band)
|
||||
under_five = months is not None and months < 60
|
||||
keys = [(module, algorithm(row), under_five), (module, algorithm(row), None),
|
||||
(module, None, under_five), (module, None, None)] # fmt: skip
|
||||
keys = [
|
||||
(module, algorithm(row), under_five),
|
||||
(module, algorithm(row), None),
|
||||
(module, None, under_five),
|
||||
(module, None, None),
|
||||
]
|
||||
cuts = next((tea.ADOS2_CSS[k] for k in keys if k in tea.ADOS2_CSS), None)
|
||||
if cuts is None:
|
||||
return None, None
|
||||
css = 1 + sum(c <= found for c in cuts)
|
||||
label = next(n for n, below in tea.ADOS2_CLASSIFICATION if below is None or css < below)
|
||||
return css, label
|
||||
return (None, None)
|
||||
css = 1 + sum((c <= found for c in cuts))
|
||||
label = next((n for n, below in tea.ADOS2_CLASSIFICATION if below is None or css < below))
|
||||
return (css, label)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
from core import tea
|
||||
|
||||
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
|
||||
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)
|
||||
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)
|
||||
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]:
|
||||
|
||||
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
|
||||
@@ -0,0 +1,102 @@
|
||||
from datetime import date
|
||||
from core import tea
|
||||
from core.measures import as_day
|
||||
from core.tea import ados2
|
||||
|
||||
WINDOWS = tea.FOLLOW_UP_WINDOWS
|
||||
SORTS = ("-recent",)
|
||||
DEFAULT_HORIZON = None
|
||||
STATUS_SYSTEM = "tea-follow-up-status"
|
||||
PROCEDURES: tuple[str, ...] = ()
|
||||
REPORT_FACTS: dict[str, str] = {}
|
||||
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"), ("eeg_date", "eeg"))
|
||||
DATES = (
|
||||
"mchat_date",
|
||||
"psychology_date",
|
||||
"neuro_date",
|
||||
"confirmed_date",
|
||||
"not_confirmed_date",
|
||||
"eeg_date",
|
||||
)
|
||||
|
||||
|
||||
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]:
|
||||
children: dict[str, dict] = {}
|
||||
eegs: dict[str, dict[str, dict]] = {}
|
||||
for row in rows:
|
||||
person = row["person_id"]
|
||||
if not _by(row.get("mchat_date"), cutoff):
|
||||
continue
|
||||
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:
|
||||
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,
|
||||
}
|
||||
)
|
||||
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
|
||||
return rows
|
||||
+93
-43
@@ -1,10 +1,3 @@
|
||||
"""TEA's measures (`core.measures` evaluates them), over gold's screening chain: one row per
|
||||
child of the cohort (`gold.tea_screening`) with the day she reached each step, and her EEGs
|
||||
(`gold.tea_eegs`).
|
||||
|
||||
A child is on the books from her first M-CHAT until the period after her chain ended with a
|
||||
good EEG; in a period she is in the latest step, and diagnosis state, reached by its end."""
|
||||
|
||||
from core.measures import (
|
||||
AtEnd,
|
||||
Composition,
|
||||
@@ -16,44 +9,101 @@ from core.measures import (
|
||||
reached,
|
||||
)
|
||||
|
||||
DIAGNOSIS = AtEnd("mchat_date", "eeg_date", (
|
||||
("in_process", "mchat_date"), ("not_confirmed", "not_confirmed_date"),
|
||||
("confirmed", "confirmed_date"),
|
||||
)) # fmt: skip
|
||||
STEPS = AtEnd("mchat_date", "eeg_date", (
|
||||
("mchat_only", "mchat_date"), ("psychology", "psychology_date"),
|
||||
("neuropediatrics", "neuro_date"), ("eeg", "eeg_date"),
|
||||
)) # fmt: skip
|
||||
DIAGNOSIS = AtEnd(
|
||||
"mchat_date",
|
||||
"eeg_date",
|
||||
(
|
||||
("in_process", "mchat_date"),
|
||||
("not_confirmed", "not_confirmed_date"),
|
||||
("confirmed", "confirmed_date"),
|
||||
),
|
||||
)
|
||||
STEPS = AtEnd(
|
||||
"mchat_date",
|
||||
"eeg_date",
|
||||
(
|
||||
("mchat_only", "mchat_date"),
|
||||
("psychology", "psychology_date"),
|
||||
("neuropediatrics", "neuro_date"),
|
||||
("eeg", "eeg_date"),
|
||||
),
|
||||
)
|
||||
AGE = ("age_group", lambda row, p: row["age_group"])
|
||||
CONFIRMED = lambda row, state, p: state == "confirmed" # noqa: E731
|
||||
|
||||
MEASURES = {m.id: m for m in [
|
||||
Measure("M21_DIAGNOSTICADOS_CON_EEG", "Pacientes con diagnóstico de TEA con EEG",
|
||||
CONFIRMED = lambda row, state, p: state == "confirmed"
|
||||
MEASURES = {
|
||||
m.id: m
|
||||
for m in [
|
||||
Measure(
|
||||
"M21_DIAGNOSTICADOS_CON_EEG",
|
||||
"Pacientes con diagnóstico de TEA con EEG",
|
||||
"screening",
|
||||
StatusProportion(DIAGNOSIS, CONFIRMED,
|
||||
lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)),
|
||||
"increase"),
|
||||
Measure("M22_DIAGNOSTICADOS_SIN_EEG", "Pacientes con diagnóstico de TEA sin EEG",
|
||||
StatusProportion(
|
||||
DIAGNOSIS, CONFIRMED, lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)
|
||||
),
|
||||
"increase",
|
||||
),
|
||||
Measure(
|
||||
"M22_DIAGNOSTICADOS_SIN_EEG",
|
||||
"Pacientes con diagnóstico de TEA sin EEG",
|
||||
"screening",
|
||||
StatusProportion(DIAGNOSIS, CONFIRMED,
|
||||
lambda row, s, p: not reached(row, "eeg_date", p), strata=(AGE,)),
|
||||
"decrease"),
|
||||
Measure("M23_PACIENTES_EVALUADOS", "Pacientes evaluados por resultado diagnóstico",
|
||||
StatusProportion(
|
||||
DIAGNOSIS,
|
||||
CONFIRMED,
|
||||
lambda row, s, p: not reached(row, "eeg_date", p),
|
||||
strata=(AGE,),
|
||||
),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"M23_PACIENTES_EVALUADOS",
|
||||
"Pacientes evaluados por resultado diagnóstico",
|
||||
"screening",
|
||||
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process"))),
|
||||
Measure("M24_CONFIRMACION_DIAGNOSTICO", "Confirmación diagnóstica", "screening",
|
||||
StatusProportion(DIAGNOSIS, lambda row, s, p: s in ("confirmed", "in_process"),
|
||||
CONFIRMED, strata=(AGE,)),
|
||||
"increase"),
|
||||
Measure("M25_DIAS_MCHAT_DIAGNOSTICO", "Días de M-CHAT a diagnóstico positivo", "screening",
|
||||
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"), "decrease"),
|
||||
Measure("M26_DIAS_MCHAT_ADOS2", "Días de M-CHAT a ADOS-2", "screening",
|
||||
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"), "decrease"),
|
||||
Measure("M27_DIAS_ADOS2_DIAGNOSTICO", "Días de ADOS-2 a valoración neuropediátrica",
|
||||
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process")),
|
||||
),
|
||||
Measure(
|
||||
"M24_CONFIRMACION_DIAGNOSTICO",
|
||||
"Confirmación diagnóstica",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"), "decrease"),
|
||||
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
|
||||
Measure("M29_CALIDAD_EEG", "Calidad del EEG", "eegs",
|
||||
Composition(lambda r: (as_day(r["study_date"]),), lambda r: r["quality"],
|
||||
unit="eeg_id", date="study_date")),
|
||||
]} # fmt: skip
|
||||
StatusProportion(
|
||||
DIAGNOSIS,
|
||||
lambda row, s, p: s in ("confirmed", "in_process"),
|
||||
CONFIRMED,
|
||||
strata=(AGE,),
|
||||
),
|
||||
"increase",
|
||||
),
|
||||
Measure(
|
||||
"M25_DIAS_MCHAT_DIAGNOSTICO",
|
||||
"Días de M-CHAT a diagnóstico positivo",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"M26_DIAS_MCHAT_ADOS2",
|
||||
"Días de M-CHAT a ADOS-2",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"),
|
||||
"decrease",
|
||||
),
|
||||
Measure(
|
||||
"M27_DIAS_ADOS2_DIAGNOSTICO",
|
||||
"Días de ADOS-2 a valoración neuropediátrica",
|
||||
"screening",
|
||||
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"),
|
||||
"decrease",
|
||||
),
|
||||
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
|
||||
Measure(
|
||||
"M29_CALIDAD_EEG",
|
||||
"Calidad del EEG",
|
||||
"eegs",
|
||||
Composition(
|
||||
lambda r: (as_day(r["study_date"]),),
|
||||
lambda r: r["quality"],
|
||||
unit="eeg_id",
|
||||
date="study_date",
|
||||
),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
+11
-7
@@ -1,18 +1,16 @@
|
||||
# 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 \
|
||||
postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
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
|
||||
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 \
|
||||
@@ -24,11 +22,17 @@ RUN echo '{"resourceType":"Basic","code":{"text":"warm-up"}}' > /tmp/warm.json \
|
||||
&& java -jar /opt/fhir/validator_cli.jar /tmp/warm.json -version 4.3.0 -tx n/a > /dev/null \
|
||||
&& rm /tmp/warm.json
|
||||
ENV FHIR_VALIDATOR_JAR=/opt/fhir/validator_cli.jar
|
||||
# Synthea, pinned: seeded synthetic patients sent through the FHIR door in tests.
|
||||
ADD --checksum=sha256:ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 \
|
||||
https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar \
|
||||
/opt/synthea/synthea.jar
|
||||
ENV SYNTHEA_JAR=/opt/synthea/synthea.jar
|
||||
RUN uv sync --frozen
|
||||
# The pages (-m webapp) run in CI's web job, which has Node and a browser.
|
||||
CMD ["pytest", "-q", "-rs", "-m", "not webapp"]
|
||||
|
||||
FROM app AS dask-worker
|
||||
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
|
||||
CMD ["dask", "worker", "--help"]
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{# Whole days from `a` to `b` (dates), on every engine the platform runs on. #}
|
||||
{% macro days_between(a, b) -%}
|
||||
{{ return(adapter.dispatch('days_between', 'isssteleon')(a, b)) }}
|
||||
{%- endmacro %}
|
||||
@@ -11,7 +10,6 @@
|
||||
cast(julianday({{ b }}) - julianday({{ a }}) as integer)
|
||||
{%- endmacro %}
|
||||
|
||||
{# The run's as-of date: `var('as_of')` when given, else the day dbt runs. #}
|
||||
{% macro as_of() -%}
|
||||
'{{ var("as_of", run_started_at.strftime("%Y-%m-%d")) }}'
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
{# The first event of `kind` after each unit's `start` (on that day too when not `strict`),
|
||||
fewer than `days` later: one row per unit that has one. Units are the CTE `units`, keyed
|
||||
by `key`, with the person's `person_id`. #}
|
||||
{% macro first_after(name, start, kind, days, strict=true, units='sample', key='sample_id') %}
|
||||
{{ name }} as (
|
||||
select s.{{ key }}, min(e.date) as date
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
{#
|
||||
A survival cohort over a domain's timeline (`<domain>_events`): every patient indexed at her
|
||||
first biopsy reported with one of `grades`, within the recruitment window (start inclusive,
|
||||
end exclusive), up to the as-of date. Out (`excluded_by`): no birth date (no age at the
|
||||
index), a death on or before the index.
|
||||
#}
|
||||
{% macro first_biopsy_cohort(events, grades, recruitment) %}
|
||||
with timeline as (
|
||||
select * from {{ ref(events) }} where date <= {{ as_of() }}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{# Use the declared schema as is (bronze, silver, gold), on SQLite and PostgreSQL alike. #}
|
||||
{% macro generate_schema_name(custom_schema_name, node) -%}
|
||||
{{ custom_schema_name if custom_schema_name else target.schema }}
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{# The later of two dates; empty when either is (a step counts once the previous one was reached). #}
|
||||
{% macro later(a, b) -%}
|
||||
case when {{ a }} is null or {{ b }} is null then null
|
||||
when {{ b }} > {{ a }} then {{ b }} else {{ a }} end
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
{#
|
||||
One study, wide: one row per study instance (person and the study's key), one column per
|
||||
field of the catalog (core.catalog), from the long `silver.observation`. `known_at` is when
|
||||
anything of the instance was first known, `<event>_known_at` when its event was (a report can
|
||||
arrive loads after its sample). A subquery, for
|
||||
`from {{ pivot('cervical_cytology') }} as c`, or a whole model.
|
||||
#}
|
||||
{% macro pivot(study) -%}
|
||||
{%- set s = var('catalog')[study] -%}
|
||||
(
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
{#- 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 %}
|
||||
|
||||
|
||||
{% macro staged_has_column(name, column) -%}
|
||||
{%- if not execute -%}{{ return(false) }}{%- endif -%}
|
||||
{%- set relation = adapter.get_relation(this.database, 'bronze', name) -%}
|
||||
{%- if relation is none -%}{{ return(false) }}{%- endif -%}
|
||||
{{ return(column in adapter.get_columns_in_relation(relation) | map(attribute='name') | list) }}
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
{# A list of values as a SQL list: ('a', 'b'). #}
|
||||
{% macro sql_list(values) -%}
|
||||
({% for v in values %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
{%- endmacro %}
|
||||
|
||||
{# Upper case without Spanish accents, so free text compares with written patterns. #}
|
||||
{% macro plain_upper(column) -%}
|
||||
{%- set pairs = [('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u'),
|
||||
('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U')] -%}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
{# A biopsy report belongs to the person/request-date study, linked sample optional. #}
|
||||
select
|
||||
{{ dbt.concat(['person_id', "'|'", 'cast(request_date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
|
||||
person_id, request_date, report_date, histology, known_at,
|
||||
case
|
||||
when histology is null then 'no_data'
|
||||
when histology in ('normal', 'LSIL', 'HSIL', 'CIS', 'carcinoma') then histology
|
||||
else 'unclassified'
|
||||
end as category
|
||||
from {{ ref('cervical_biopsy') }}
|
||||
where report_date is not null
|
||||
@@ -1,7 +0,0 @@
|
||||
{# Recorded biopsy studies, including orders with no report. The silver study key is
|
||||
person plus request date; it does not preserve an independent HIS order identifier. #}
|
||||
select
|
||||
{{ dbt.concat(['person_id', "'|'", 'cast(request_date as ' ~ dbt.type_string() ~ ')']) }} as request_id,
|
||||
person_id, request_date, report_date, histology, order_known_at, report_known_at, rows_merged
|
||||
from {{ ref('cervical_biopsy') }}
|
||||
where request_date is not null
|
||||
@@ -1,14 +1,3 @@
|
||||
{#
|
||||
After colposcopy (KPNC's post-colposcopy tables): the patient's first colposcopy is an
|
||||
episode whose result is known at the last report of the biopsies ordered that day (at the
|
||||
colposcopy itself when none were); indexed at the POST_COLPOSCOPY_VISIT-th cytology sample
|
||||
after that result and before any later colposcopy, in the recruitment window. Out, in
|
||||
order: a biopsy ordered that day without a report (unreported_biopsy); an outcome biopsy
|
||||
up to the index (outcome_by_index); a cervical cancer history (cancer_history); a
|
||||
hysterectomy (hysterectomy); a treatment (prior_treatment), each up to the index; no
|
||||
cytology or HPV result in the REFERRAL_LOOKBACK_DAYS before the colposcopy (no_referral);
|
||||
an index sample without both a cytology and an HPV result (no_cotest).
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
{#
|
||||
After treatment: indexed at the first cytology sample more than
|
||||
POST_TREATMENT_INDEX_AFTER_DAYS after the patient's first treatment, in the recruitment
|
||||
window. Out, in order: no biopsy result in the POST_TREATMENT_LOOKBACK_DAYS up to the
|
||||
treatment (no_pretreatment_biopsy); an outcome biopsy between treatment and index
|
||||
(outcome_before_index); an index sample with no cytology or HPV result (no_index_result).
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
Screening surveillance: indexed at the patient's first cytology sample, when it falls in
|
||||
the recruitment window. Out, in order: an outcome biopsy (CIN2+) before the index
|
||||
(prior_outcome); an index sample with no cytology or HPV result (no_index_result).
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{# Survival: indexed at the first biopsy reported as carcinoma or carcinoma in situ (core.cacu CASE). #}
|
||||
{% set p = var('cacu') %}
|
||||
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment) }}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
{# Every patient with a clinical event up to the as-of date, indexed at her first one. No
|
||||
window and no rules: models that set their own index start from here. #}
|
||||
with ranked as (
|
||||
select
|
||||
person_id, date,
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
{% set p = var('cacu') %}
|
||||
with candidates as (
|
||||
select s.sample_id, replace(n.icd10, '.', '') as code, n.diagnosis_text
|
||||
from {{ ref('cacu_samples') }} s
|
||||
join {{ ref('clinical_note') }} n on n.person_id = s.person_id and n.note_date = s.diagnosis_date
|
||||
where replace(n.icd10, '.', '') in {{ sql_list(p.diagnosis_icd10) }}
|
||||
and n.specialty in {{ sql_list(p.diagnosis_specialties) }}
|
||||
), grouped as (
|
||||
select sample_id, count(distinct code) as codes, min(code) as code,
|
||||
count(distinct nullif(trim(diagnosis_text), '')) as descriptions,
|
||||
min(nullif(trim(diagnosis_text), '')) as description
|
||||
from candidates group by sample_id
|
||||
)
|
||||
select s.*, case when coalesce(g.codes, 0) = 0 then 'sin_codigo'
|
||||
when g.codes > 1 then 'ambiguo' else g.code end as diagnosis_code,
|
||||
case when g.codes = 1 and g.descriptions = 1 then g.description end as diagnosis_description
|
||||
from {{ ref('cacu_samples') }} s left join grouped g on g.sample_id = s.sample_id
|
||||
@@ -1,18 +1,3 @@
|
||||
{#
|
||||
Every CaCu patient's timeline: one row per event, in one shape, from silver. Results are
|
||||
dated when they were reported; a cytology's results and a biopsy's order and report share
|
||||
their source (`source_table`, `source_id`), so a model can tell which sample a result
|
||||
belongs to.
|
||||
|
||||
Procedures silver has no record of are inferred from notes and biopsies (core.cacu):
|
||||
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
|
||||
- colposcopy: once a patient has been assessed (a diagnosis note within
|
||||
SAMPLE_TO_DIAGNOSIS_DAYS after a cytology sample), a later colposcopy-clinic note that
|
||||
says so (reason, ICD-10 or diagnosis text), and the biopsies ordered on such a day (at
|
||||
their order and at their report);
|
||||
- treatment: a note with a treatment ICD-10 after the first colposcopy;
|
||||
- history: a note with a cervical cancer ICD-10.
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
|
||||
with cytology as (
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
One row per CaCu patient: the first day of each follow-up step, from her timeline. Her
|
||||
status at any day follows from them (core.measures.follow_up_status): a case (a biopsy
|
||||
reported CASE grade), after treatment, after colposcopy, or before colposcopy.
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
select
|
||||
p.person_id,
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
{# One reported HPV result per person and sample date, the silver study key. #}
|
||||
select
|
||||
{{ dbt.concat(['person_id', "'|'", 'cast(sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
person_id, sample_date, report_date, known_at, hpv, hpv_16, hpv_18,
|
||||
case
|
||||
when hpv = false and (hpv_16 = true or hpv_18 = true) then 'inconsistent'
|
||||
when hpv = false then 'negative'
|
||||
when hpv = true and (hpv_16 is null or hpv_18 is null) then 'positive_incomplete'
|
||||
when hpv = true and hpv_16 = true and hpv_18 = true then 'positive_16_18'
|
||||
when hpv = true and hpv_16 = true and hpv_18 = false then 'positive_16'
|
||||
when hpv = true and hpv_16 = false and hpv_18 = true then 'positive_18'
|
||||
when hpv = true and hpv_16 = false and hpv_18 = false then 'positive_other'
|
||||
else 'inconsistent'
|
||||
end as category
|
||||
from {{ ref('cervical_cytology') }}
|
||||
where report_date is not null and (hpv is not null or hpv_16 is not null or hpv_18 is not null)
|
||||
@@ -1,40 +0,0 @@
|
||||
{#
|
||||
What the referral PPVs (core.cacu.measures.ReferralPPV) count over: one row per fact of a
|
||||
patient's route, in one shape, each dated `date`:
|
||||
- cytology: a sample, with its results (cytology and HPV) and the screening history her
|
||||
form says;
|
||||
- colposcopy: a day she had one (cacu_events, which infers it). cacu_events also dates one
|
||||
at the report of a biopsy taken at it; that day is not another colposcopy;
|
||||
- biopsy: a biopsy, dated its request, with its histology once reported.
|
||||
Every row carries the first day of her follow-up steps, for her status at any day.
|
||||
`report_known_at`: when a report's values were first known (`known_at`: the row).
|
||||
#}
|
||||
with facts as (
|
||||
select
|
||||
'cytology' as fact, person_id, sample_date as date, sample_id, result, adequacy,
|
||||
result_date, screening_history, hpv, hpv_16, hpv_18,
|
||||
cast(null as {{ dbt.type_string() }}) as histology,
|
||||
cast(null as date) as report_date,
|
||||
known_at, report_known_at
|
||||
from {{ ref('cacu_samples') }}
|
||||
|
||||
union all
|
||||
select
|
||||
'colposcopy', person_id, date, null, null, null, null, null, null, null, null, null, null,
|
||||
min(known_at), null
|
||||
from {{ ref('cacu_events') }}
|
||||
where type = 'colposcopy'
|
||||
and (source_table <> 'cervical_biopsy' or cast(date as {{ dbt.type_string() }}) = source_id)
|
||||
group by person_id, date
|
||||
|
||||
union all
|
||||
select
|
||||
'biopsy', person_id, request_date, null, null, null, null, null, null, null, null,
|
||||
histology, report_date,
|
||||
known_at, report_known_at
|
||||
from {{ ref('cervical_biopsy') }}
|
||||
)
|
||||
|
||||
select t.*, f.first_case, f.first_treatment, f.first_colposcopy
|
||||
from facts as t
|
||||
left join {{ ref('cacu_follow_up') }} as f on f.person_id = t.person_id
|
||||
@@ -1,6 +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). #}
|
||||
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 %},
|
||||
scored_at
|
||||
from {{ source('bronze', 'model_scores') }}
|
||||
where model like 'cacu.%'
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
{# The biopsies each cytology sample led to, with the grade's severity (core.cacu
|
||||
BIOPSY_SEVERITY, from 1; -1 a report without a grade, 0 a grade outside it). #}
|
||||
{% set p = var('cacu') %}
|
||||
select
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.cytology_sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
{#
|
||||
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
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
version: 2
|
||||
models:
|
||||
- name: cacu_biopsy_requests
|
||||
columns:
|
||||
- name: request_id
|
||||
data_tests: [not_null, unique]
|
||||
- name: cacu_hpv_reports
|
||||
columns:
|
||||
- name: sample_id
|
||||
data_tests: [not_null, unique]
|
||||
- name: cacu_biopsy_reports
|
||||
columns:
|
||||
- name: biopsy_id
|
||||
data_tests: [not_null, unique]
|
||||
unit_tests:
|
||||
- name: hpv_classification_preserves_unknowns
|
||||
model: cacu_hpv_reports
|
||||
given:
|
||||
- input: ref('cervical_cytology')
|
||||
format: sql
|
||||
rows: |
|
||||
select 'a' as person_id, '2026-01-01' as sample_date, '2026-01-02' as report_date, null as known_at, false as hpv, null as hpv_16, null as hpv_18
|
||||
union all select 'b','2026-01-01','2026-01-02',null,true,true,false
|
||||
union all select 'c','2026-01-01','2026-01-02',null,true,false,true
|
||||
union all select 'd','2026-01-01','2026-01-02',null,true,true,true
|
||||
union all select 'e','2026-01-01','2026-01-02',null,true,false,false
|
||||
union all select 'f','2026-01-01','2026-01-02',null,true,true,null
|
||||
union all select 'g','2026-01-01','2026-01-02',null,true,null,null
|
||||
union all select 'h','2026-01-01','2026-01-02',null,false,true,false
|
||||
union all select 'i','2026-01-01','2026-01-02',null,null,false,null
|
||||
union all select 'j','2026-01-01','2026-01-02',null,null,null,null
|
||||
union all select 'k','2026-01-01',null,null,true,true,true
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select person_id || '|2026-01-01' as sample_id, person_id, '2026-01-01' as sample_date,
|
||||
'2026-01-02' as report_date, null as known_at, hpv, hpv_16, hpv_18, category
|
||||
from (
|
||||
select 'a' as person_id, false as hpv, null as hpv_16, null as hpv_18, 'negative' as category
|
||||
union all select 'b',true,true,false,'positive_16'
|
||||
union all select 'c',true,false,true,'positive_18'
|
||||
union all select 'd',true,true,true,'positive_16_18'
|
||||
union all select 'e',true,false,false,'positive_other'
|
||||
union all select 'f',true,true,null,'positive_incomplete'
|
||||
union all select 'g',true,null,null,'positive_incomplete'
|
||||
union all select 'h',false,true,false,'inconsistent'
|
||||
union all select 'i',null,false,null,'inconsistent'
|
||||
)
|
||||
- name: biopsy_reports_include_unlinked_and_missing_grades
|
||||
model: cacu_biopsy_reports
|
||||
given:
|
||||
- input: ref('cervical_biopsy')
|
||||
format: sql
|
||||
rows: |
|
||||
select 'a' as person_id, '2026-01-01' as request_date, '2026-01-02' as report_date, 'normal' as histology, null as known_at
|
||||
union all select 'b','2026-01-01','2026-01-02','LSIL',null
|
||||
union all select 'c','2026-01-01','2026-01-02','HSIL',null
|
||||
union all select 'd','2026-01-01','2026-01-02','CIS',null
|
||||
union all select 'e','2026-01-01','2026-01-02','carcinoma',null
|
||||
union all select 'f','2026-01-01','2026-01-02',null,null
|
||||
union all select 'g','2026-01-01','2026-01-02','unknown',null
|
||||
union all select 'h','2026-01-01',null,null,null
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select person_id || '|2026-01-01' as biopsy_id, person_id, '2026-01-01' as request_date,
|
||||
'2026-01-02' as report_date, histology, null as known_at, category
|
||||
from (
|
||||
select 'a' as person_id, 'normal' as histology, 'normal' as category
|
||||
union all select 'b','LSIL','LSIL'
|
||||
union all select 'c','HSIL','HSIL'
|
||||
union all select 'd','CIS','CIS'
|
||||
union all select 'e','carcinoma','carcinoma'
|
||||
union all select 'f',null,'no_data'
|
||||
union all select 'g','unknown','unclassified'
|
||||
)
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
One row per breast biopsy, with the mammogram that led to it (the patient's, taken on
|
||||
`mammogram_exam_date`) and that mammogram's BI-RADS. `histology_rank` orders grades from
|
||||
least to most severe (core.cama): -1 for a report without one.
|
||||
#}
|
||||
{% set p = var('cama') %}
|
||||
select
|
||||
b.person_id,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
{% set p = var('cama') %}
|
||||
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
|
||||
@@ -1,3 +1,2 @@
|
||||
{# Survival: indexed at the first invasive biopsy report (core.cama SURVIVAL_GRADES). #}
|
||||
{% set p = var('cama') %}
|
||||
{{ first_biopsy_cohort('cama_events', p.survival_grades, p.recruitment) }}
|
||||
|
||||
@@ -1,17 +1,3 @@
|
||||
{#
|
||||
Every CaMa patient's timeline (whoever has a mammogram or a breast biopsy): one row per
|
||||
event, in the shape of the other domains' timelines. Results are dated when they were
|
||||
reported; a mammogram's report and a biopsy's order and report share their source
|
||||
(`source_table`, `source_id`), and a biopsy names the mammogram that led to it
|
||||
(`value_code` of `biopsy_order`).
|
||||
|
||||
A biopsy report's results (histologic type, grade, receptors, Ki-67, size, stage) are one
|
||||
event each, dated with the report; each treatment is an event at its start.
|
||||
|
||||
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 (
|
||||
@@ -26,6 +12,10 @@ treatment as (
|
||||
select * from {{ ref('breast_treatment') }}
|
||||
),
|
||||
|
||||
recurrence as (
|
||||
select * from {{ ref('breast_recurrence') }}
|
||||
),
|
||||
|
||||
patient as (
|
||||
select person_id from mammogram
|
||||
union
|
||||
@@ -78,7 +68,7 @@ events as (
|
||||
'breast_biopsy', cast(request_date as {{ dbt.type_string() }})
|
||||
from biopsy where {{ field }} is not null and report_date is not null
|
||||
{%- endfor %}
|
||||
{%- for field in ['ki67_pct', 'size_mm'] %}
|
||||
{%- for field in ['ki67_pct', 'size_mm', 'positive_nodes'] %}
|
||||
union all
|
||||
select person_id, report_date, report_known_at, '{{ field }}', null,
|
||||
cast({{ field }} as {{ dbt.type_float() }}),
|
||||
@@ -92,6 +82,12 @@ events as (
|
||||
from treatment as t
|
||||
join patient as p on p.person_id = t.person_id
|
||||
|
||||
union all
|
||||
select r.person_id, r.diagnosis_date, r.encounter_known_at, 'recurrence', r.site, null,
|
||||
'breast_recurrence', cast(r.diagnosis_date as {{ dbt.type_string() }})
|
||||
from recurrence as r
|
||||
join patient as p on p.person_id = r.person_id
|
||||
|
||||
union all
|
||||
select person_id, note_date, known_at, 'note', icd10, null, 'clinical_note', source_id
|
||||
from note
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
{#
|
||||
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,10 +1,3 @@
|
||||
{#
|
||||
One row per mammogram: the unit CaMa's mammography measures count over, with the intervals
|
||||
they measure. A diagnosis resolves a mammogram when it is the patient's first diagnosis note
|
||||
after it (on the report's day too, counted from the report), within the horizon (core.cama).
|
||||
`history`: a breast cancer note before the mammogram. Each fact keeps when it became known:
|
||||
the sample, its report, and the diagnosis note.
|
||||
#}
|
||||
{% set p = var('cama') %}
|
||||
with sample as (
|
||||
select
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{# The latest risk batch of each CaMa model: from its champion version, one row per patient
|
||||
and horizon (years from her index date). #}
|
||||
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 %},
|
||||
scored_at
|
||||
from {{ source('bronze', 'model_scores') }}
|
||||
where model like 'cama.%'
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{# Every EEG with its analysis verdict (the EEG job's `bronze.eeg_analysis`, by signal hash). #}
|
||||
select e.person_id, e.study_date, e.edf,
|
||||
{%- if staged_exists('eeg_analysis') %}
|
||||
a.valid
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
-- depends_on: {{ ref('tea_eegs') }}
|
||||
{#
|
||||
One row per EEG metric (the EEG job's `bronze.eeg_metrics`), with the age curve's score of
|
||||
its value (`bronze.eeg_scores`, when a curve in production scored it): what the EEG pages
|
||||
and FHIR read.
|
||||
#}
|
||||
{%- if not staged_exists('eeg_metrics') %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as person_id, cast(null as {{ dbt.type_string() }}) as eeg_id,
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
One row per EEG of a child of the screening cohort, with its analysis (the EEG job's
|
||||
`bronze.eeg_analysis`, by the signal's hash): `quality` good (valid), bad (not valid) or
|
||||
not_analyzed (no analysis yet, or no signal).
|
||||
#}
|
||||
select
|
||||
e.person_id,
|
||||
{{ dbt.concat(['e.person_id', "'|'", 'cast(e.study_date as ' ~ dbt.type_string() ~ ')']) }} as eeg_id,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{# Every TEA child's timeline, in the shape of the other domains' (the default cut-off reads it). #}
|
||||
select person_id, screening_date as date, known_at, 'mchat' as type,
|
||||
cast(null as {{ dbt.type_string() }}) as value_code,
|
||||
cast(score as {{ dbt.type_float() }}) as value_num,
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
{#
|
||||
One row per child of the screening cohort (her first M-CHAT at 16 to 36 months, or with no
|
||||
birth date), with the day she reached each step. A step counts once the previous one was
|
||||
reached: its day is the later of the two (core.tea):
|
||||
psychology (first ADOS-2) <- M-CHAT; neurology (first note) and its confirming or
|
||||
non-confirming verdict <- psychology; EEG (first good one) <- neurology.
|
||||
#}
|
||||
{% set p = var('tea') %}
|
||||
|
||||
with mchat as (
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- ados2, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('ados2') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- breast_biopsy, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('breast_biopsy') }} as p
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
select * from {{ pivot('breast_recurrence') }} as p
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- breast_treatment, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('breast_treatment') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_biopsy') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_cytology') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('clinical_note') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- death, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('death') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- eeg, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('eeg') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- mammography, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('mammography') }} as p
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- mchat, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('mchat') }} as p
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
{#
|
||||
Silver: every clinical value, long. One row per field of one study instance (a person and
|
||||
the study's key, e.g. her cytology sampled on a day), from what targets staged:
|
||||
- rows a reviewer rejected (review_log) stay out; rows a rule held never got here;
|
||||
- rows of one instance are one record: values that complement each other are merged; a
|
||||
field with two different values is a conflict, and the whole instance stays out until a
|
||||
reviewer rejects the wrong row;
|
||||
- an instance is known from when its first row was (`known_at`).
|
||||
#}
|
||||
{%- if not staged_exists('staged__observation') %}
|
||||
select
|
||||
cast(null as {{ dbt.type_string() }}) as person_id,
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
One row per person the link nodes found, with what her records agree on. A person whose
|
||||
records disagree on birth date or sex is held whole by the link node, so what is left
|
||||
agrees and min() only picks the one value.
|
||||
#}
|
||||
select
|
||||
person_id,
|
||||
min(birth_date) as birth_date,
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
{#
|
||||
Every identifier a person carries: CURP and NSS under their own systems, and each record
|
||||
number under the system of the source it came from (a site has as many as it has
|
||||
sources). Records held by the link node (a torn person) give none until reviewed.
|
||||
#}
|
||||
{%- set ids = var('identifiers') %}
|
||||
with identity as (
|
||||
select * from {{ source('bronze', 'staged__identity') }}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
{#
|
||||
Persons a review merged into another: the replaced id and the one that replaced it (the
|
||||
latest decision). A replaced id keeps resolving, to its survivor.
|
||||
#}
|
||||
{%- if not staged_exists('person_link') %}
|
||||
select cast(null as {{ dbt.type_string() }}) as person_id,
|
||||
cast(null as {{ dbt.type_string() }}) as replaced_by
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{#- Every name a person's records give (as the link node compared them). -#}
|
||||
select distinct person_id, full_name as text
|
||||
from {{ source('bronze', 'staged__identity') }}
|
||||
where _held is null and person_id is not null and full_name is not null
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
{#- Every value silver holds is a field of its study, and a code is one its field allows
|
||||
(core.catalog). -#}
|
||||
select o.study, o.field, o.value_text
|
||||
from {{ ref('observation') }} as o
|
||||
where not (
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{#- Silver holds one value per field of a study instance. -#}
|
||||
select person_id, study, instance, field
|
||||
from {{ ref('observation') }}
|
||||
group by person_id, study, instance, field
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
from persistance.config import DATA_DIR, platform_url
|
||||
|
||||
MANIFEST = "manifest.json"
|
||||
PG_DUMP = "platform.pgdump"
|
||||
SQLITE_MAGIC = b"SQLite format 3\x00"
|
||||
SKIPPED = (
|
||||
"*-wal",
|
||||
"*-shm",
|
||||
"*-journal",
|
||||
"startup.lock",
|
||||
"files-*",
|
||||
"oauth_pending",
|
||||
".before-restore-*",
|
||||
)
|
||||
|
||||
|
||||
def backup_dir() -> Path:
|
||||
return Path(os.environ.get("BACKUP_DIR", DATA_DIR.parent / "backups")).resolve()
|
||||
|
||||
|
||||
def keep() -> int:
|
||||
return int(os.environ.get("BACKUP_KEEP", "14"))
|
||||
|
||||
|
||||
def excluded() -> list[str]:
|
||||
return [p for p in os.environ.get("BACKUP_EXCLUDE", "ollama").split(",") if p]
|
||||
|
||||
|
||||
def _skipped(rel: Path) -> bool:
|
||||
return any((fnmatch(part, p) for part in rel.parts for p in (*SKIPPED, *excluded())))
|
||||
|
||||
|
||||
def _is_sqlite(path: Path) -> bool:
|
||||
with path.open("rb") as f:
|
||||
return f.read(len(SQLITE_MAGIC)) == SQLITE_MAGIC
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _tables(path: Path) -> dict[str, int]:
|
||||
con = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
||||
try:
|
||||
names = [r[0] for r in con.execute("select name from sqlite_master where type='table'")]
|
||||
return {n: con.execute(f'select count(*) from "{n}"').fetchone()[0] for n in names}
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _copy_sqlite(source: Path, target: Path) -> None:
|
||||
src = sqlite3.connect(f"file:{source}?mode=ro", uri=True)
|
||||
dst = sqlite3.connect(target)
|
||||
try:
|
||||
src.backup(dst)
|
||||
dst.execute("PRAGMA journal_mode=DELETE")
|
||||
finally:
|
||||
dst.close()
|
||||
src.close()
|
||||
|
||||
|
||||
def create(to: Path | None = None, data: Path = DATA_DIR) -> Path:
|
||||
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})")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
partial = root / f".{stamp}.partial"
|
||||
partial.mkdir(parents=True)
|
||||
files: dict[str, dict] = {}
|
||||
try:
|
||||
for source in sorted((p for p in data.rglob("*") if p.is_file())):
|
||||
rel = source.relative_to(data)
|
||||
if _skipped(rel):
|
||||
continue
|
||||
target = partial / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if _is_sqlite(source):
|
||||
_copy_sqlite(source, target)
|
||||
entry = {"kind": "sqlite", "tables": _tables(target)}
|
||||
else:
|
||||
shutil.copy2(source, target)
|
||||
entry = {"kind": "file"}
|
||||
files[rel.as_posix()] = {
|
||||
**entry,
|
||||
"bytes": target.stat().st_size,
|
||||
"sha256": _sha256(target),
|
||||
}
|
||||
url = platform_url()
|
||||
if not url.startswith("sqlite"):
|
||||
subprocess.run(
|
||||
["pg_dump", "--format=custom", f"--file={partial / PG_DUMP}", "--dbname", url],
|
||||
check=True,
|
||||
)
|
||||
files[PG_DUMP] = {
|
||||
"kind": "pg_dump",
|
||||
"bytes": (partial / PG_DUMP).stat().st_size,
|
||||
"sha256": _sha256(partial / PG_DUMP),
|
||||
}
|
||||
manifest = {
|
||||
"created": stamp,
|
||||
"version": os.environ.get("ISSSTELEON_VERSION", "dev"),
|
||||
"data": str(data),
|
||||
"files": files,
|
||||
}
|
||||
(partial / MANIFEST).write_text(json.dumps(manifest, indent=1, sort_keys=True))
|
||||
final = root / stamp
|
||||
partial.rename(final)
|
||||
except BaseException:
|
||||
shutil.rmtree(partial, ignore_errors=True)
|
||||
raise
|
||||
_prune(root)
|
||||
return final
|
||||
|
||||
|
||||
def _prune(root: Path) -> None:
|
||||
done = sorted((p for p in root.iterdir() if p.is_dir() and (p / MANIFEST).exists()))
|
||||
for old in done[: max(0, len(done) - keep())]:
|
||||
shutil.rmtree(old)
|
||||
|
||||
|
||||
def verify(folder: Path) -> list[str]:
|
||||
manifest = json.loads((folder / MANIFEST).read_text())
|
||||
problems = []
|
||||
for rel, entry in manifest["files"].items():
|
||||
path = folder / rel
|
||||
if not path.is_file():
|
||||
problems.append(f"{rel}: missing")
|
||||
elif _sha256(path) != entry["sha256"]:
|
||||
problems.append(f"{rel}: changed since the backup")
|
||||
return problems
|
||||
|
||||
|
||||
def _holds_platform(held: list[Path]) -> bool:
|
||||
if platform_url().startswith("sqlite"):
|
||||
return any((p.name.startswith("platform") for p in held))
|
||||
from sqlalchemy import inspect
|
||||
from persistance.destination import engine
|
||||
|
||||
with engine().connect() as con:
|
||||
return "config" in inspect(con).get_schema_names()
|
||||
|
||||
|
||||
def restore(folder: Path, data: Path = DATA_DIR, force: bool = False) -> None:
|
||||
if problems := verify(folder):
|
||||
raise ValueError("the backup is damaged: " + "; ".join(problems))
|
||||
manifest = json.loads((folder / MANIFEST).read_text())
|
||||
data.mkdir(parents=True, exist_ok=True)
|
||||
held = [p for p in data.iterdir() if not p.name.startswith(".before-restore-")]
|
||||
if _holds_platform(held):
|
||||
if not force:
|
||||
raise FileExistsError(f"{data} already holds a platform; restore with --force")
|
||||
aside = data / f".before-restore-{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}"
|
||||
aside.mkdir()
|
||||
for p in held:
|
||||
p.rename(aside / p.name)
|
||||
for rel, entry in manifest["files"].items():
|
||||
if entry["kind"] == "pg_dump":
|
||||
continue
|
||||
target = data / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = target.with_name(target.name + ".restoring")
|
||||
shutil.copy2(folder / rel, temporary)
|
||||
temporary.replace(target)
|
||||
if PG_DUMP in manifest["files"]:
|
||||
subprocess.run(
|
||||
[
|
||||
"pg_restore",
|
||||
"--clean",
|
||||
"--if-exists",
|
||||
"--no-owner",
|
||||
"--dbname",
|
||||
platform_url(),
|
||||
str(folder / PG_DUMP),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Backups of the platform's data folder.")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
made = sub.add_parser("create", help="make a backup (default under BACKUP_DIR)")
|
||||
made.add_argument("--to", type=Path)
|
||||
checked = sub.add_parser("verify", help="check a backup's files against its manifest")
|
||||
checked.add_argument("folder", type=Path)
|
||||
back = sub.add_parser("restore", help="put a backup back (stop the stack first)")
|
||||
back.add_argument("folder", type=Path)
|
||||
back.add_argument("--force", action="store_true", help="over an existing platform")
|
||||
args = parser.parse_args()
|
||||
if args.command == "create":
|
||||
print(create(args.to))
|
||||
elif args.command == "verify":
|
||||
problems = verify(args.folder)
|
||||
print("\n".join(problems) or "ok")
|
||||
sys.exit(1 if problems else 0)
|
||||
else:
|
||||
restore(args.folder, force=args.force)
|
||||
print(f"restored {args.folder} into {DATA_DIR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Where the platform data lives. One env var per location; SQLite by default."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
"""A site's configuration, append-only: every save is a new version; runs name the one they
|
||||
used. Two kinds: pipelines (the drawn graphs) and concept maps (the site's codes in
|
||||
platform terms, FHIR ConceptMaps)."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import dlt
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.pipeline import Pipeline
|
||||
from persistance.destination import engine, platform
|
||||
|
||||
@@ -26,7 +20,7 @@ def latest_version(item_id: str, kind: str = "pipelines") -> int:
|
||||
def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
|
||||
version = latest_version(item_id, kind) + 1
|
||||
row = {
|
||||
"pipeline_id": item_id, # the item's id, whichever kind
|
||||
"pipeline_id": item_id,
|
||||
"version": version,
|
||||
"doc": doc.model_dump_json(exclude_none=True),
|
||||
"saved_at": datetime.now(UTC),
|
||||
@@ -38,13 +32,11 @@ def save(item_id: str, doc: BaseModel, kind: str = "pipelines") -> int:
|
||||
|
||||
|
||||
def listing(kind: str = "pipelines") -> list[dict]:
|
||||
"""Every item's id with its latest version and when it was saved."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table(kind, schema="config"):
|
||||
return []
|
||||
sql = text(
|
||||
"select pipeline_id, max(version) as version, max(saved_at) as saved_at "
|
||||
f"from config.{kind} group by pipeline_id order by pipeline_id"
|
||||
f"select pipeline_id, max(version) as version, max(saved_at) as saved_at from config.{kind} group by pipeline_id order by pipeline_id"
|
||||
)
|
||||
return [dict(r) for r in con.execute(sql).mappings()]
|
||||
|
||||
@@ -54,7 +46,7 @@ def get(item_id: str, version: int | None = None, kind: str = "pipelines"):
|
||||
sql = text(f"select doc from config.{kind} where pipeline_id = :id and version = :v")
|
||||
with engine().connect() as con:
|
||||
doc = con.execute(sql, {"id": item_id, "v": version}).scalar_one()
|
||||
return version, KINDS[kind].model_validate_json(doc)
|
||||
return (version, KINDS[kind].model_validate_json(doc))
|
||||
|
||||
|
||||
def pipelines() -> list[dict]:
|
||||
@@ -62,11 +54,10 @@ def pipelines() -> list[dict]:
|
||||
|
||||
|
||||
def concept_map(item_id: str) -> ConceptMap:
|
||||
"""The latest version of a concept map."""
|
||||
return get(item_id, kind="concept_maps")[1]
|
||||
|
||||
|
||||
if __name__ == "__main__": # python -m persistance.config_log <kind> <id> <doc.json>
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
"""The platform database (SQLite now, PostgreSQL later): the dlt destination that writes it
|
||||
and the engine that reads it.
|
||||
|
||||
On SQLite each schema is its own file (`platform__<schema>.db`, as dlt lays it out),
|
||||
attached under its name, so the same SQL (`bronze.raw__...`) runs on both engines.
|
||||
"""
|
||||
|
||||
from functools import cache
|
||||
|
||||
import dlt
|
||||
from sqlalchemy import Engine, create_engine, event, make_url
|
||||
|
||||
from persistance.config import DATA_DIR, platform_url
|
||||
|
||||
SCHEMAS = ("bronze", "silver", "gold", "config")
|
||||
@@ -31,14 +22,13 @@ def _sqlite(attach: bool) -> Engine:
|
||||
|
||||
def platform():
|
||||
if platform_url().startswith("sqlite"):
|
||||
return dlt.destinations.sqlalchemy(_sqlite(attach=False)) # dlt attaches its own
|
||||
return dlt.destinations.sqlalchemy(_sqlite(attach=False))
|
||||
return dlt.destinations.postgres(platform_url())
|
||||
|
||||
|
||||
@cache
|
||||
def engine() -> Engine:
|
||||
"""For reading: every platform schema reachable by name."""
|
||||
url = platform_url()
|
||||
if url.startswith("sqlite"):
|
||||
return _sqlite(attach=True)
|
||||
return create_engine(make_url(url).set(drivername="postgresql+psycopg2")) # dlt's driver
|
||||
return create_engine(make_url(url).set(drivername="postgresql+psycopg2"))
|
||||
|
||||
+238
-69
@@ -1,19 +1,12 @@
|
||||
"""The EEG analysis as the platform keeps it, by signal (the EDF's content hash, silver's
|
||||
`eeg.edf`): its verdict and measures (`bronze.eeg_analysis`), its checks (`bronze.eeg_checks`)
|
||||
and its metrics (`bronze.eeg_metrics`), written by the analysis job; the age curves' scores of
|
||||
each metric (`bronze.eeg_scores`), by the scoring job. dbt places them in gold (tea)."""
|
||||
|
||||
import json
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import dlt
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from persistance import files
|
||||
from persistance.destination import engine, platform
|
||||
|
||||
|
||||
def _text() -> dict: # a new dict per column: dlt writes the column's name into it
|
||||
def _text() -> dict:
|
||||
return {"data_type": "text", "nullable": True}
|
||||
|
||||
|
||||
@@ -52,6 +45,31 @@ METRICS = {
|
||||
"electrodes": _text(),
|
||||
"zones": _text(),
|
||||
}
|
||||
ASSOCIATIONS = {
|
||||
"key": {"data_type": "text"},
|
||||
**{
|
||||
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"},
|
||||
"edf": {"data_type": "text"},
|
||||
@@ -62,24 +80,22 @@ SCORES = {
|
||||
|
||||
def _write(name: str, rows: list[dict], columns: dict, key: str = "key") -> None:
|
||||
if rows:
|
||||
resource = dlt.resource(rows, name=name, primary_key=key, columns=columns,
|
||||
write_disposition="merge") # fmt: skip
|
||||
resource = dlt.resource(
|
||||
rows, name=name, primary_key=key, columns=columns, write_disposition="merge"
|
||||
)
|
||||
dlt.pipeline(name, destination=platform(), dataset_name="bronze").run(resource)
|
||||
|
||||
|
||||
def pending() -> list[dict]:
|
||||
"""The hospital's EEG signals not analysed yet, each with the child's birth date."""
|
||||
with engine().connect() as con:
|
||||
done = inspect(con).has_table("eeg_analysis", schema="bronze")
|
||||
where = "and e.edf not in (select edf from bronze.eeg_analysis)" if done else ""
|
||||
sql = text(f"""
|
||||
select distinct e.edf, p.birth_date from silver.eeg as e
|
||||
left join silver.person as p on p.person_id = e.person_id
|
||||
where e.edf is not null {where}
|
||||
""") # fmt: skip
|
||||
sql = text(
|
||||
f"\n select distinct e.edf, p.birth_date from silver.eeg as e\n left join silver.person as p on p.person_id = e.person_id\n where e.edf is not null {where}\n "
|
||||
)
|
||||
rows = [dict(r) for r in con.execute(sql).mappings()]
|
||||
for r in rows: # SQLite gives dates as text
|
||||
if r["birth_date"] is not None and not isinstance(r["birth_date"], date):
|
||||
for r in rows:
|
||||
if r["birth_date"] is not None and (not isinstance(r["birth_date"], date)):
|
||||
r["birth_date"] = date.fromisoformat(str(r["birth_date"])[:10])
|
||||
return rows
|
||||
|
||||
@@ -92,50 +108,159 @@ def signal(edf: str) -> bytes:
|
||||
|
||||
|
||||
def save_analyses(analyses: dict[str, object]) -> None:
|
||||
"""Analyses by signal hash (models.tea.eeg.analysis.Analysis)."""
|
||||
now = datetime.now(UTC)
|
||||
found, checks, metrics = [], [], []
|
||||
found, checks, metrics = ([], [], [])
|
||||
for edf, a in analyses.items():
|
||||
found.append({
|
||||
"edf": edf, "valid": a.valid, "level": a.level, "age_months": a.age_months,
|
||||
"clean_fraction": a.clean_fraction, "bad_channels": a.bad_channels,
|
||||
"channels": a.channels, "duration_min": a.duration_min,
|
||||
"line_noise_db": a.line_noise_db, "sleep": a.sleep,
|
||||
"features": json.dumps(a.features), "error": a.error, "analysed_at": now,
|
||||
}) # fmt: skip
|
||||
found.append(
|
||||
{
|
||||
"edf": edf,
|
||||
"valid": a.valid,
|
||||
"level": a.level,
|
||||
"age_months": a.age_months,
|
||||
"clean_fraction": a.clean_fraction,
|
||||
"bad_channels": a.bad_channels,
|
||||
"channels": a.channels,
|
||||
"duration_min": a.duration_min,
|
||||
"line_noise_db": a.line_noise_db,
|
||||
"sleep": a.sleep,
|
||||
"features": json.dumps(a.features),
|
||||
"error": a.error,
|
||||
"analysed_at": now,
|
||||
}
|
||||
)
|
||||
checks += [{**c, "key": f"{edf}|{i}", "edf": edf} for i, c in enumerate(a.checks)]
|
||||
metrics += [{"key": f"{edf}|{m.code}", "edf": edf, "code": m.code, "value": m.value,
|
||||
"electrodes": json.dumps(m.electrodes), "zones": json.dumps(m.zones)}
|
||||
for m in a.metrics] # fmt: skip
|
||||
metrics += [
|
||||
{
|
||||
"key": f"{edf}|{m.code}",
|
||||
"edf": edf,
|
||||
"code": m.code,
|
||||
"value": m.value,
|
||||
"electrodes": json.dumps(m.electrodes),
|
||||
"zones": json.dumps(m.zones),
|
||||
}
|
||||
for m in a.metrics
|
||||
]
|
||||
_write("eeg_analysis", found, ANALYSIS, key="edf")
|
||||
_write("eeg_checks", checks, CHECKS)
|
||||
_write("eeg_metrics", metrics, METRICS)
|
||||
|
||||
|
||||
def analysed() -> list[dict]:
|
||||
"""Every valid analysis with its metrics: what the age curves score."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("eeg_metrics", schema="bronze"):
|
||||
return []
|
||||
sql = text("""
|
||||
select a.edf, a.age_months, a.features, m.code, m.value, m.electrodes, m.zones
|
||||
from bronze.eeg_analysis as a join bronze.eeg_metrics as m on m.edf = a.edf
|
||||
where a.valid
|
||||
""") # fmt: skip
|
||||
sql = text(
|
||||
"\n select a.edf, a.age_months, a.features, m.code, m.value, m.electrodes, m.zones\n from bronze.eeg_analysis as a join bronze.eeg_metrics as m on m.edf = a.edf\n where a.valid\n "
|
||||
)
|
||||
rows = [dict(r) for r in con.execute(sql).mappings()]
|
||||
out: dict[str, dict] = {}
|
||||
for r in rows:
|
||||
first = {"edf": r["edf"], "age_months": r["age_months"],
|
||||
"features": json.loads(r["features"]), "metrics": []} # fmt: skip
|
||||
first = {
|
||||
"edf": r["edf"],
|
||||
"age_months": r["age_months"],
|
||||
"features": json.loads(r["features"]),
|
||||
"metrics": [],
|
||||
}
|
||||
one = out.setdefault(r["edf"], first)
|
||||
one["metrics"].append({"code": r["code"], "value": r["value"],
|
||||
"electrodes": json.loads(r["electrodes"]),
|
||||
"zones": json.loads(r["zones"])}) # fmt: skip
|
||||
one["metrics"].append(
|
||||
{
|
||||
"code": r["code"],
|
||||
"value": r["value"],
|
||||
"electrodes": json.loads(r["electrodes"]),
|
||||
"zones": json.loads(r["zones"]),
|
||||
}
|
||||
)
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def ruled_out(as_of: date) -> list[dict]:
|
||||
with engine().connect() as con:
|
||||
if not (
|
||||
inspect(con).has_table("eeg_analysis", schema="bronze")
|
||||
and inspect(con).has_table("tea_screening", schema="gold")
|
||||
):
|
||||
return []
|
||||
sql = text(
|
||||
"\n select a.edf, a.age_months, a.features\n from bronze.eeg_analysis as a\n join silver.eeg as e on e.edf = a.edf\n join gold.tea_screening as s on s.person_id = e.person_id\n where a.valid and a.error is null\n and cast(e.study_date as varchar(10)) <= :as_of\n and cast(s.not_confirmed_date as varchar(10)) <= :as_of\n and (s.confirmed_date is null or cast(s.confirmed_date as varchar(10)) > :as_of)\n order by a.edf\n "
|
||||
)
|
||||
rows = con.execute(sql, {"as_of": as_of.isoformat()}).mappings()
|
||||
return [
|
||||
{
|
||||
"key": r["edf"],
|
||||
"age_months": r["age_months"],
|
||||
"valid": True,
|
||||
"error": None,
|
||||
"features": json.loads(r["features"]),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def association_inputs(metrics: dict[str, str]) -> list[dict]:
|
||||
with engine().connect() as con:
|
||||
has = lambda t, s: inspect(con).has_table(t, schema=s)
|
||||
if not (has("eeg_analysis", "bronze") and has("ados2", "silver")):
|
||||
return []
|
||||
eegs = [
|
||||
dict(r)
|
||||
for r in con.execute(
|
||||
text(
|
||||
"\n select e.person_id, cast(e.study_date as varchar(10)) as study_date, a.edf,\n a.age_months, cast(p.birth_date as varchar(10)) as birth_date\n from bronze.eeg_analysis as a join silver.eeg as e on e.edf = a.edf\n left join silver.person as p on p.person_id = e.person_id\n where a.valid and a.age_months is not null\n order by e.person_id, e.study_date, a.edf\n "
|
||||
)
|
||||
).mappings()
|
||||
]
|
||||
first: dict[str, dict] = {}
|
||||
for r in con.execute(
|
||||
text(
|
||||
"\n select * from silver.ados2\n order by person_id, case when evaluation_date is null then 1 else 0 end,\n evaluation_date\n "
|
||||
)
|
||||
).mappings():
|
||||
first.setdefault(r["person_id"], dict(r))
|
||||
z: dict[str, dict[str, float]] = {}
|
||||
if has("eeg_scores", "bronze"):
|
||||
codes = {code: b for b, code in metrics.items()}
|
||||
for r in con.execute(
|
||||
text(
|
||||
"\n select edf, metric, part, site, z from bronze.eeg_scores\n where part in ('value', 'zones') and z is not null\n "
|
||||
)
|
||||
).mappings():
|
||||
b = codes.get(r["metric"])
|
||||
if b is not None:
|
||||
name = f"z_{b}" if r["part"] == "value" else f"z_{b}_{r['site']}"
|
||||
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:
|
||||
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]:
|
||||
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(
|
||||
"\n select s.biomarker, a.metric, s.zone, s.outcome_code, a.kind, a.event, s.z,\n s.probability, s.reference_probability, s.observed, a.odds_ratio,\n a.ci_low, a.ci_high, a.q, a.n, s.model\n from bronze.ados2_association_scores as s\n join bronze.ados2_association as a\n on a.model = s.model and a.biomarker = s.biomarker and a.zone = s.zone\n and a.outcome_code = s.outcome_code\n where s.edf = :e order by a.q, s.biomarker, s.zone\n "
|
||||
),
|
||||
{"e": edf},
|
||||
).mappings()
|
||||
]
|
||||
|
||||
|
||||
def save_scores(scenario: str, rows: list[dict]) -> None:
|
||||
"""One age curve's scores of every EEG, replacing what it scored before."""
|
||||
with engine().begin() as con:
|
||||
if inspect(con).has_table("eeg_scores", schema="bronze"):
|
||||
con.execute(text("delete from bronze.eeg_scores where scenario = :s"), {"s": scenario})
|
||||
@@ -147,45 +272,89 @@ def _id(person_id: str, study_date) -> str:
|
||||
|
||||
|
||||
def studies() -> list[dict]:
|
||||
"""Every EEG with its analysis verdict (none while not analysed), newest first."""
|
||||
with engine().connect() as con:
|
||||
analysed = inspect(con).has_table("eeg_analysis", schema="bronze")
|
||||
verdict = "a.valid, a.level, a.error, a.edf as analysed" if analysed else (
|
||||
"null as valid, null as level, null as error, null as analysed") # fmt: skip
|
||||
verdict = (
|
||||
"a.valid, a.level, a.error, a.edf as analysed"
|
||||
if analysed
|
||||
else "null as valid, null as level, null as error, null as analysed"
|
||||
)
|
||||
join = "left join bronze.eeg_analysis as a on a.edf = e.edf" if analysed else ""
|
||||
sql = text(f"""
|
||||
select e.person_id, e.study_date, e.lab_record_id, {verdict}
|
||||
from silver.eeg as e {join}
|
||||
order by e.study_date desc, e.person_id
|
||||
""") # fmt: skip
|
||||
sql = text(
|
||||
f"\n select e.person_id, e.study_date, e.lab_record_id, {verdict}\n from silver.eeg as e {join}\n order by e.study_date desc, e.person_id\n "
|
||||
)
|
||||
rows = [dict(r) for r in con.execute(sql).mappings()]
|
||||
return [{"id": _id(r["person_id"], r["study_date"]), "person_id": r["person_id"],
|
||||
"study_date": str(r["study_date"])[:10], "lab_record_id": r["lab_record_id"],
|
||||
"analysed": r["analysed"] is not None or r["error"] is not None,
|
||||
"valid": r["valid"], "level": r["level"]} for r in rows] # fmt: skip
|
||||
return [
|
||||
{
|
||||
"id": _id(r["person_id"], r["study_date"]),
|
||||
"person_id": r["person_id"],
|
||||
"study_date": str(r["study_date"])[:10],
|
||||
"lab_record_id": r["lab_record_id"],
|
||||
"analysed": r["analysed"] is not None or r["error"] is not None,
|
||||
"valid": r["valid"],
|
||||
"level": r["level"],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def study(eeg_id: str) -> dict | None:
|
||||
"""One EEG's verdict, age and metrics, each with its age curve's score when scored."""
|
||||
person, day = eeg_id.split("|")
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("eeg_analysis", schema="bronze"):
|
||||
return None
|
||||
head = con.execute(text("""
|
||||
select a.edf, a.valid, a.level, a.age_months from silver.eeg as e
|
||||
join bronze.eeg_analysis as a on a.edf = e.edf
|
||||
where e.person_id = :p and cast(e.study_date as varchar(10)) = :d
|
||||
"""), {"p": person, "d": day}).mappings().first() # fmt: skip
|
||||
head = (
|
||||
con.execute(
|
||||
text(
|
||||
"\n select a.edf, a.valid, a.level, a.age_months from silver.eeg as e\n join bronze.eeg_analysis as a on a.edf = e.edf\n where e.person_id = :p and cast(e.study_date as varchar(10)) = :d\n "
|
||||
),
|
||||
{"p": person, "d": day},
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
if head is None:
|
||||
return None
|
||||
scored = inspect(con).has_table("eeg_scores", schema="bronze")
|
||||
score = "s.z, s.outside, s.model" if scored else "null as z, null as outside, null as model"
|
||||
join = ("left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code "
|
||||
"and s.part = 'value'") if scored else "" # fmt: skip
|
||||
metrics = con.execute(text(f"""
|
||||
select m.code, m.value, {score} from bronze.eeg_metrics as m {join}
|
||||
where m.edf = :e and m.value is not null order by m.code
|
||||
"""), {"e": head["edf"]}).mappings() # fmt: skip
|
||||
score = (
|
||||
"s.z, s.outside, s.p5, s.median, s.p95, s.model"
|
||||
if scored
|
||||
else "null as z, null as outside, null as p5, null as median, null as p95, null as model"
|
||||
)
|
||||
join = (
|
||||
"left join bronze.eeg_scores as s on s.edf = m.edf and s.metric = m.code and s.part = 'value'"
|
||||
if scored
|
||||
else ""
|
||||
)
|
||||
metrics = con.execute(
|
||||
text(
|
||||
f"\n select m.code, m.value, m.electrodes, m.zones, {score}\n from bronze.eeg_metrics as m {join}\n where m.edf = :e and m.value is not null order by m.code\n "
|
||||
),
|
||||
{"e": head["edf"]},
|
||||
).mappings()
|
||||
found = [dict(m) for m in metrics]
|
||||
return {"id": eeg_id, "valid": head["valid"], "level": head["level"],
|
||||
"age_months": head["age_months"], "metrics": found} # fmt: skip
|
||||
sites: dict[tuple[str, str, str], float | None] = {}
|
||||
if scored:
|
||||
for r in con.execute(
|
||||
text(
|
||||
"\n select metric, part, site, z from bronze.eeg_scores\n where edf = :e and part in ('zones', 'electrodes')\n "
|
||||
),
|
||||
{"e": head["edf"]},
|
||||
).mappings():
|
||||
sites[r["metric"], r["part"], r["site"]] = r["z"]
|
||||
for m in found:
|
||||
for part in ("zones", "electrodes"):
|
||||
values = json.loads(m[part] or "{}")
|
||||
m[part] = [
|
||||
{"site": k, "value": v, "z": sites.get((m["code"], part, k))}
|
||||
for k, v in values.items()
|
||||
if v is not None and v == v
|
||||
]
|
||||
return {
|
||||
"id": eeg_id,
|
||||
"valid": head["valid"],
|
||||
"level": head["level"],
|
||||
"age_months": head["age_months"],
|
||||
"metrics": found,
|
||||
"relation": relation(head["edf"]),
|
||||
}
|
||||
|
||||
@@ -1,95 +1,50 @@
|
||||
"""The rows the FHIR resources are built from (core.fhir): persons, their identifiers and
|
||||
names, and every study instance of the catalog (`silver.<study>`), up to a cut-off day."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import bindparam, inspect, text
|
||||
|
||||
from core import catalog
|
||||
from persistance.destination import engine
|
||||
|
||||
PERSONS = """
|
||||
select p.person_id, p.birth_date, p.sex, d.death_date{extra}
|
||||
from silver.person as p
|
||||
left join (select person_id, min(death_date) as death_date from silver.death
|
||||
group by person_id) as d on d.person_id = p.person_id{join}
|
||||
"""
|
||||
PERSONS = "\n select p.person_id, p.birth_date, p.sex, d.death_date{extra}\n from silver.person as p\n left join (select person_id, min(death_date) as death_date from silver.death\n group by person_id) as d on d.person_id = p.person_id{join}\n"
|
||||
CACU_PERSONS = PERSONS.format(
|
||||
extra=", f.first_case, f.first_treatment, f.first_colposcopy",
|
||||
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
|
||||
)
|
||||
CAMA_PERSONS = PERSONS.format(extra="", join="")
|
||||
|
||||
COMMON = {
|
||||
"names": "select person_id, text from silver.person_name where person_id in :persons",
|
||||
"identifiers": """
|
||||
select person_id, system, value from silver.person_identifier
|
||||
where person_id in :persons order by system, value
|
||||
""",
|
||||
"identifiers": "\n select person_id, system, value from silver.person_identifier\n where person_id in :persons order by system, value\n ",
|
||||
"replaced": "select person_id, replaced_by from silver.person_link where person_id = :id",
|
||||
"replaces": """
|
||||
select person_id, replaced_by from silver.person_link where replaced_by in :persons
|
||||
""",
|
||||
"condition": """
|
||||
select person_id, note_date, specialty, icd10, reason, diagnosis_text
|
||||
from silver.clinical_note
|
||||
where person_id in :persons and note_date <= :cutoff
|
||||
and (icd10 is not null or diagnosis_text is not null)
|
||||
order by person_id, note_date
|
||||
""",
|
||||
# The timeline's inferred procedures of these kinds (the domain's `PROCEDURES`).
|
||||
"procedure": """
|
||||
select distinct person_id, date, type from gold.{domain}_events
|
||||
where person_id in :persons and date <= :cutoff and type in :types
|
||||
order by person_id, date, type
|
||||
""",
|
||||
"risk": """
|
||||
select model, version, person_id, index_date, horizon_years, probability, ci_low,
|
||||
ci_high, scored_at
|
||||
from gold.{domain}_risk
|
||||
where person_id in :persons
|
||||
order by person_id, model, index_date, horizon_years
|
||||
""",
|
||||
"replaces": "\n select person_id, replaced_by from silver.person_link where replaced_by in :persons\n ",
|
||||
"condition": "\n select person_id, note_date, specialty, icd10, reason, diagnosis_text\n from silver.clinical_note\n where person_id in :persons and note_date <= :cutoff\n and (icd10 is not null or diagnosis_text is not null)\n order by person_id, note_date\n ",
|
||||
"procedure": "\n select distinct person_id, date, type from gold.{domain}_events\n where person_id in :persons and date <= :cutoff and type in :types\n order by person_id, date, type\n ",
|
||||
"risk": "\n select model, version, person_id, index_date, horizon_years, probability, ci_low,\n ci_high, scenarios, scored_at\n from gold.{domain}_risk\n where person_id in :persons\n order by person_id, model, index_date, horizon_years\n ",
|
||||
}
|
||||
|
||||
TEA_PERSONS = PERSONS.format(extra="", join="")
|
||||
READS = {
|
||||
"cacu": {
|
||||
"person": CACU_PERSONS + " where p.person_id = :id",
|
||||
"persons": CACU_PERSONS + " order by p.person_id",
|
||||
# The list: whoever had a cytology sampled within [start, cutoff], with the latest one.
|
||||
"follow_up": f"""
|
||||
select x.*, w.recent from ({CACU_PERSONS}) as x
|
||||
join (select person_id, max(sample_date) as recent from silver.cervical_cytology
|
||||
where sample_date >= :start and sample_date <= :cutoff
|
||||
group by person_id) as w on w.person_id = x.person_id
|
||||
order by w.recent desc, x.person_id
|
||||
""",
|
||||
# Days from a sample to its diagnosis, when known by the cut-off (gold).
|
||||
"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
|
||||
""",
|
||||
"stage_samples": "select person_id, sample_date, colposcopy_date, diagnosis_date from gold.cacu_samples where person_id in :persons and sample_date <= :cutoff",
|
||||
"stage_biopsies": "select person_id, cytology_sample_date, request_date, report_date, rows_merged from silver.cervical_biopsy where person_id in :persons and request_date <= :cutoff",
|
||||
"stage_events": "select person_id, date, type, source_table, source_id from gold.cacu_events where person_id in :persons and date <= :cutoff and type in ('colposcopy', 'diagnosis')",
|
||||
"follow_up": f"\n select x.*, w.recent from ({CACU_PERSONS}) as x\n join (select person_id, max(sample_date) as recent from silver.cervical_cytology\n where sample_date >= :start and sample_date <= :cutoff\n group by person_id) as w on w.person_id = x.person_id\n order by w.recent desc, x.person_id\n ",
|
||||
"diagnosis_days": "\n select person_id, sample_date, days_sample_diagnosis as days\n from gold.cacu_samples\n where person_id in :persons and history = 0 and diagnosis_date <= :cutoff\n ",
|
||||
},
|
||||
"tea": {
|
||||
"person": TEA_PERSONS + " where p.person_id = :id",
|
||||
"persons": TEA_PERSONS + " order by p.person_id",
|
||||
"follow_up": "\n select s.*, mc.score, {ados2}, e.eeg_id, e.study_date as eeg_study_date, e.valid,\n m.code as metric, m.outside\n from gold.tea_screening as s\n left join (select person_id, max(screening_date) as last_mchat from silver.mchat\n where screening_date <= :cutoff group by person_id) as lm\n on lm.person_id = s.person_id\n left join silver.mchat as mc\n on mc.person_id = lm.person_id and mc.screening_date = lm.last_mchat\n left join (select person_id, max(evaluation_date) as last_ados from silver.ados2\n where evaluation_date <= :cutoff group by person_id) as la\n on la.person_id = s.person_id\n left join silver.ados2 as a\n on a.person_id = la.person_id and a.evaluation_date = la.last_ados\n left join gold.tea_eegs as e on e.person_id = s.person_id\n left join gold.tea_eeg_metrics as m\n on m.eeg_id = e.eeg_id and m.outside is not null and m.outside <> 0\n where s.mchat_date <= :cutoff\n ".replace(
|
||||
"{ados2}", ", ".join((f"a.{f}" for f in catalog.studies()["ados2"].fields))
|
||||
),
|
||||
},
|
||||
"cama": {
|
||||
"person": CAMA_PERSONS + " where p.person_id = :id",
|
||||
"persons": CAMA_PERSONS + " order by p.person_id",
|
||||
# The list's candidates: each reported mammogram by the cut-off and its biopsies
|
||||
# (core.cama.follow_up picks the latest per patient and places her in the window).
|
||||
"follow_up": """
|
||||
select * from gold.cama_mammogram_biopsies
|
||||
where birads is not null and report_date <= :cutoff
|
||||
""",
|
||||
"procedure": "\n select distinct person_id, date, value_code as type from gold.cama_events\n where person_id in :persons and date <= :cutoff and type in :types\n and value_code is not null\n order by person_id, date, type\n ",
|
||||
"condition": "\n select person_id, note_date, specialty, icd10, reason, diagnosis_text,\n null as study, null as code\n from silver.clinical_note\n where person_id in :persons and note_date <= :cutoff\n and (icd10 is not null or diagnosis_text is not null)\n union all\n select person_id, diagnosis_date, null, null, null, null, 'breast_recurrence', site\n from silver.breast_recurrence\n where person_id in :persons and diagnosis_date <= :cutoff\n order by person_id, note_date\n ",
|
||||
"diagnosis_days": "\n select person_id, exam_date as sample_date, days_sample_diagnosis as days\n from gold.cama_mammograms\n where person_id in :persons and history = 0 and diagnosis_date <= :cutoff\n ",
|
||||
"follow_up": "\n select * from gold.cama_mammogram_biopsies\n where birads is not null and report_date <= :cutoff\n ",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def rows(domain: str, kind: str, **params) -> list[dict]:
|
||||
"""The rows of one kind for the domain. `persons` (and `types`) limit them to those;
|
||||
none when the table doesn't exist yet (no risk batch)."""
|
||||
sql = text((READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain))
|
||||
for many in ("persons", "types"):
|
||||
if many in params:
|
||||
@@ -97,19 +52,16 @@ def rows(domain: str, kind: str, **params) -> list[dict]:
|
||||
if not params[many]:
|
||||
return []
|
||||
with engine().connect() as con:
|
||||
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
|
||||
if kind == "risk" and (not inspect(con).has_table(f"{domain}_risk", schema="gold")):
|
||||
return []
|
||||
return [dict(r) for r in con.execute(sql, params).mappings()]
|
||||
|
||||
|
||||
def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
|
||||
"""A study's instances of these persons that began by the cut-off (its first event's
|
||||
date), as `silver.<study>` holds them; what was known by then is core.fhir.known's."""
|
||||
spec = catalog.studies()[study]
|
||||
first = next(e.date for e in spec.events.values() if e.parent is None)
|
||||
first = next((e.date for e in spec.events.values() if e.parent is None))
|
||||
sql = text(
|
||||
f"select * from silver.{study} where person_id in :persons and {first} <= :cutoff "
|
||||
f"order by person_id, {first}"
|
||||
f"select * from silver.{study} where person_id in :persons and {first} <= :cutoff order by person_id, {first}"
|
||||
).bindparams(bindparam("persons", expanding=True))
|
||||
if not persons:
|
||||
return []
|
||||
@@ -120,8 +72,6 @@ def instances(study: str, persons: list[str], cutoff: str) -> list[dict]:
|
||||
|
||||
|
||||
def last_data_day(domain: str) -> date | None:
|
||||
"""The last day anything happened in the domain's timeline (up to today): the default
|
||||
cut-off."""
|
||||
sql = text(f"select max(date) from gold.{domain}_events where date <= :today")
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table(f"{domain}_events", schema="gold"):
|
||||
|
||||
@@ -1,53 +1,69 @@
|
||||
"""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 dlt
|
||||
from sqlalchemy import LargeBinary, Text, inspect, text
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from sqlalchemy import Column, LargeBinary, MetaData, Table, Text, inspect, text
|
||||
from sqlalchemy.types import TypeEngine
|
||||
|
||||
from persistance.destination import engine, platform
|
||||
from persistance.destination import engine
|
||||
|
||||
TABLE = "files"
|
||||
COLUMNS = {"key": {"data_type": "text"}, "content": {"data_type": "binary"}}
|
||||
INSERT_BYTES = 32000000
|
||||
FILES = Table(
|
||||
TABLE,
|
||||
MetaData(),
|
||||
Column("key", Text, primary_key=True),
|
||||
Column("content", LargeBinary, nullable=False),
|
||||
schema="bronze",
|
||||
)
|
||||
|
||||
|
||||
def key(content: bytes) -> str:
|
||||
return hashlib.sha256(content).hexdigest()
|
||||
|
||||
|
||||
class Collector:
|
||||
"""A dlt map that replaces each binary value of a row with its hash, keeping the
|
||||
content to store once the load is done (`keep`)."""
|
||||
FLUSH_BYTES = 256000000
|
||||
|
||||
|
||||
class Collector:
|
||||
def __init__(self):
|
||||
self.found: dict[str, bytes] = {}
|
||||
self.spool = Path(tempfile.mkdtemp(prefix="files-", dir=os.environ.get("ISSSTELEON_DATA")))
|
||||
self.keys: list[str] = []
|
||||
|
||||
def __call__(self, row: dict) -> dict:
|
||||
out = {}
|
||||
for name, value in row.items():
|
||||
if isinstance(value, bytes | bytearray | memoryview):
|
||||
value = bytes(value)
|
||||
self.found[found := key(value)] = value
|
||||
found = key(value)
|
||||
if not (self.spool / found).exists():
|
||||
(self.spool / found).write_bytes(value)
|
||||
self.keys.append(found)
|
||||
value = found
|
||||
out[name] = value
|
||||
return out
|
||||
|
||||
def keep(self) -> None:
|
||||
keep(self.found)
|
||||
try:
|
||||
batch: dict[str, bytes] = {}
|
||||
for k in self.keys:
|
||||
batch[k] = (self.spool / k).read_bytes()
|
||||
if sum(map(len, batch.values())) >= FLUSH_BYTES:
|
||||
keep(batch)
|
||||
batch = {}
|
||||
keep(batch)
|
||||
finally:
|
||||
self.discard()
|
||||
|
||||
def discard(self) -> None:
|
||||
shutil.rmtree(self.spool, ignore_errors=True)
|
||||
|
||||
|
||||
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()
|
||||
@@ -56,19 +72,45 @@ def known(keys: set[str]) -> set[str]:
|
||||
|
||||
|
||||
def keep(contents: dict[str, bytes]) -> None:
|
||||
"""Contents by hash, each written once."""
|
||||
new = [{"key": k, "content": c} for k, c in contents.items() if k not in known(set(contents))]
|
||||
if new:
|
||||
resource = dlt.resource(new, name=TABLE, primary_key="key", columns=COLUMNS,
|
||||
write_disposition="merge") # fmt: skip
|
||||
dlt.pipeline(TABLE, destination=platform(), dataset_name="bronze").run(resource)
|
||||
if not contents:
|
||||
return
|
||||
with engine().begin() as con:
|
||||
FILES.create(con, checkfirst=True)
|
||||
columns = {c["name"] for c in inspect(con).get_columns(TABLE, schema="bronze")}
|
||||
have = set(con.execute(text(f"select key from bronze.{TABLE}")).scalars())
|
||||
batch, size = ([], 0)
|
||||
for k, c in contents.items():
|
||||
if k in have:
|
||||
continue
|
||||
row = {"key": k, "content": c}
|
||||
if "_dlt_id" in columns:
|
||||
row |= {"_dlt_load_id": "files", "_dlt_id": k[:14]}
|
||||
batch.append(row)
|
||||
size += len(c)
|
||||
if size >= INSERT_BYTES:
|
||||
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
|
||||
batch, size = ([], 0)
|
||||
if batch:
|
||||
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
|
||||
|
||||
|
||||
def _with_dlt():
|
||||
return Table(
|
||||
TABLE,
|
||||
MetaData(),
|
||||
Column("key", Text, primary_key=True),
|
||||
Column("content", LargeBinary),
|
||||
Column("_dlt_load_id", Text),
|
||||
Column("_dlt_id", Text),
|
||||
schema="bronze",
|
||||
).insert()
|
||||
|
||||
|
||||
def content(key: str) -> bytes | None:
|
||||
"""A file's content, or None when the platform has no file with that hash."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table(TABLE, schema="bronze"):
|
||||
return None
|
||||
found = con.execute(text(f"select content from bronze.{TABLE} where key = :k"),
|
||||
{"k": key}).scalar() # fmt: skip
|
||||
found = con.execute(
|
||||
text(f"select content from bronze.{TABLE} where key = :k"), {"k": key}
|
||||
).scalar()
|
||||
return bytes(found) if found is not None else None
|
||||
|
||||
@@ -1,41 +1,35 @@
|
||||
"""What the models read from gold, and the risk batches they write back."""
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import dlt
|
||||
import pandas as pd
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from persistance.destination import engine, platform
|
||||
|
||||
TIMELINE = ["person_id", "index_date", "date", "type", "value_code", "value_num",
|
||||
"source_table", "source_id", "record_number"] # fmt: skip
|
||||
TIMELINE = [
|
||||
"person_id",
|
||||
"index_date",
|
||||
"date",
|
||||
"type",
|
||||
"value_code",
|
||||
"value_num",
|
||||
"source_table",
|
||||
"source_id",
|
||||
"record_number",
|
||||
]
|
||||
|
||||
|
||||
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
|
||||
"""The events (`gold.<events>`) up to `as_of` (default: today) of every member of
|
||||
`gold.<cohort>`, each with her index date and her record number (the lowest of the
|
||||
hospital's numbers for her: a deterministic order among patients), in date order."""
|
||||
sql = text(f"""
|
||||
select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,
|
||||
e.source_table, e.source_id, n.record_number
|
||||
from gold.{events} as e
|
||||
join gold.{cohort} as c on c.person_id = e.person_id
|
||||
left join (select person_id, min(record_number) as record_number
|
||||
from bronze.staged__identity group by person_id) as n
|
||||
on n.person_id = e.person_id
|
||||
where c.excluded_by is null and e.date <= :as_of
|
||||
order by e.person_id, e.date, e.source_table, e.source_id
|
||||
""") # fmt: skip
|
||||
sql = text(
|
||||
f"\n select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,\n e.source_table, e.source_id, n.record_number\n from gold.{events} as e\n join gold.{cohort} as c on c.person_id = e.person_id\n left join (select person_id, min(record_number) as record_number\n from bronze.staged__identity group by person_id) as n\n on n.person_id = e.person_id\n where c.excluded_by is null and e.date <= :as_of\n order by e.person_id, e.date, e.source_table, e.source_id\n "
|
||||
)
|
||||
with engine().connect() as con:
|
||||
found = pd.read_sql(sql, con, params={"as_of": (as_of or date.today()).isoformat()})
|
||||
return found.astype({"value_num": float})[TIMELINE]
|
||||
|
||||
|
||||
def person_numbers() -> dict[str, str]:
|
||||
"""Each person's record numbers as the link node compared them (for checks and reviews)."""
|
||||
sql = text("select distinct person_id, record_number from bronze.staged__identity "
|
||||
"where person_id is not null and record_number is not null") # fmt: skip
|
||||
sql = text(
|
||||
"select distinct person_id, record_number from bronze.staged__identity where person_id is not null and record_number is not null"
|
||||
)
|
||||
with engine().connect() as con:
|
||||
return dict(con.execute(sql).fetchall())
|
||||
|
||||
@@ -44,14 +38,19 @@ SCORES = "model_scores"
|
||||
|
||||
|
||||
def save_scores(model: str, version: int, scores: pd.DataFrame) -> None:
|
||||
"""A model's risk batch into `bronze.model_scores`, replacing its previous batch; dbt
|
||||
places it in gold (`cacu_risk`)."""
|
||||
with engine().begin() as con:
|
||||
if inspect(con).has_table(SCORES, schema="bronze"):
|
||||
con.execute(text(f"delete from bronze.{SCORES} where model = :m"), {"m": model})
|
||||
rows = scores.assign(model=model, version=version, scored_at=datetime.now(UTC))
|
||||
resource = dlt.resource(rows.to_dict("records"), name=SCORES, write_disposition="append",
|
||||
columns={"ci_low": {"data_type": "double", "nullable": True},
|
||||
"ci_high": {"data_type": "double", "nullable": True},
|
||||
"index_date": {"data_type": "date"}}) # fmt: skip
|
||||
resource = dlt.resource(
|
||||
rows.to_dict("records"),
|
||||
name=SCORES,
|
||||
write_disposition="append",
|
||||
columns={
|
||||
"ci_low": {"data_type": "double", "nullable": True},
|
||||
"ci_high": {"data_type": "double", "nullable": True},
|
||||
"scenarios": {"data_type": "text", "nullable": True},
|
||||
"index_date": {"data_type": "date"},
|
||||
},
|
||||
)
|
||||
dlt.pipeline(SCORES, destination=platform(), dataset_name="bronze").run(resource)
|
||||
|
||||
@@ -1,46 +1,23 @@
|
||||
"""The gold rows each domain's measures are evaluated over (core.measures), by the name a
|
||||
measure gives (`Measure.rows`)."""
|
||||
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from persistance.destination import engine
|
||||
|
||||
READS = {
|
||||
"cacu": {
|
||||
"samples": "select * from gold.cacu_samples",
|
||||
"diagnosis_codes": "select * from gold.cacu_diagnosis_codes",
|
||||
"hpv_reports": "select * from gold.cacu_hpv_reports",
|
||||
"biopsy_reports": "select * from gold.cacu_biopsy_reports",
|
||||
"biopsy_requests": "select * from gold.cacu_biopsy_requests",
|
||||
"referral_facts": "select * from gold.cacu_referral_facts",
|
||||
"sample_biopsies": """
|
||||
select s.*, b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.severity
|
||||
from gold.cacu_samples as s
|
||||
left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id
|
||||
""",
|
||||
"risk": """
|
||||
select c.person_id, coalesce(r.index_date, c.index_date) as index_date,
|
||||
r.probability, r.scored_at as known_at
|
||||
from gold.cacu_cohort_surveillance as c
|
||||
join gold.cacu_risk as r on r.person_id = c.person_id
|
||||
where c.excluded_by is null and r.model = :model and r.horizon_years = 0
|
||||
""",
|
||||
"sample_biopsies": "\n select s.*, b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.severity\n from gold.cacu_samples as s\n left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id\n ",
|
||||
"risk": "\n select c.person_id, coalesce(r.index_date, c.index_date) as index_date,\n r.probability, r.scored_at as known_at\n from gold.cacu_cohort_surveillance as c\n join gold.cacu_risk as r on r.person_id = c.person_id\n where c.excluded_by is null and r.model = :model and r.horizon_years = 0\n ",
|
||||
},
|
||||
"cama": {
|
||||
"mammograms": "select * from gold.cama_mammograms",
|
||||
"biopsies": "select * from gold.cama_biopsies where report_date is not null",
|
||||
"mammogram_biopsies": "select * from gold.cama_mammogram_biopsies",
|
||||
},
|
||||
"tea": {
|
||||
"screening": "select * from gold.tea_screening",
|
||||
"eegs": "select * from gold.tea_eegs",
|
||||
},
|
||||
"tea": {"screening": "select * from gold.tea_screening", "eegs": "select * from gold.tea_eegs"},
|
||||
}
|
||||
|
||||
|
||||
def rows(domain: str, kind: str, **params) -> list[dict]:
|
||||
"""The rows of one kind; none while their tables don't exist (no risk batch yet)."""
|
||||
with engine().connect() as con:
|
||||
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
|
||||
if kind == "risk" and (not inspect(con).has_table(f"{domain}_risk", schema="gold")):
|
||||
return []
|
||||
return [dict(r) for r in con.execute(text(READS[domain][kind]), params).mappings()]
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
"""Node outputs: every node of a pipeline writes one bronze table, `n__<pipeline>__<node>`,
|
||||
through its own dlt pipeline. Targets write into one staging table per entity."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
@@ -8,11 +5,9 @@ from collections.abc import Iterable, Iterator
|
||||
from datetime import UTC, datetime
|
||||
from importlib import import_module
|
||||
from inspect import signature
|
||||
|
||||
import dlt
|
||||
from dlt.extract import DltResource, DltSource
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.pipeline import RECORD, Source
|
||||
from persistance import files
|
||||
from persistance.destination import engine, platform
|
||||
@@ -32,7 +27,6 @@ def _load(path: str):
|
||||
|
||||
|
||||
def _record(row: dict) -> dict:
|
||||
"""Stamp a source row with its record id: the hash of the row as it came in."""
|
||||
raw = json.dumps(
|
||||
row, sort_keys=True, default=lambda v: v.hex() if isinstance(v, bytes) else str(v)
|
||||
)
|
||||
@@ -40,14 +34,13 @@ def _record(row: dict) -> dict:
|
||||
|
||||
|
||||
def resources(source: str, args: dict) -> list[str]:
|
||||
"""What a source offers to pick from (a database's tables, a folder's readers...)."""
|
||||
made = _load(source)(**args)
|
||||
return sorted(made.resources) if isinstance(made, DltSource) else [made.name]
|
||||
|
||||
|
||||
def _resource(node: Source) -> DltResource:
|
||||
source, args = _load(node.source), dict(node.args)
|
||||
if "type_adapter_callback" in signature(source).parameters: # it reflects column types
|
||||
source, args = (_load(node.source), dict(node.args))
|
||||
if "type_adapter_callback" in signature(source).parameters:
|
||||
args.setdefault("type_adapter_callback", files.reference_type)
|
||||
made = source(**args)
|
||||
if isinstance(made, DltSource):
|
||||
@@ -55,11 +48,14 @@ def _resource(node: Source) -> DltResource:
|
||||
if node.resource is None and len(found) != 1:
|
||||
raise ValueError(f"{node.id}: pick one resource of {sorted(found)}")
|
||||
made = found[node.resource] if node.resource else next(iter(found.values()))
|
||||
return made | _load(node.then)() if node.then else made # a fresh transformer each time
|
||||
return made | _load(node.then)() if node.then else made
|
||||
|
||||
|
||||
def shown(row: dict) -> dict:
|
||||
return {k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v for k, v in row.items()}
|
||||
|
||||
|
||||
def preview(node: Source, limit: int) -> list[dict]:
|
||||
"""The first rows a source node would load, read with the same dlt resource."""
|
||||
out: list[dict] = []
|
||||
for item in _resource(node).add_limit(limit):
|
||||
out.extend(item if isinstance(item, list) else [item])
|
||||
@@ -67,31 +63,33 @@ def preview(node: Source, limit: int) -> list[dict]:
|
||||
|
||||
|
||||
def run_source(pipeline_id: str, node: Source):
|
||||
"""Merged on the source's own primary key (or the configured one); replaced whole when
|
||||
there is none, so a rerun never duplicates rows."""
|
||||
collected = files.Collector() # files are kept once; the row carries their hash
|
||||
collected = files.Collector()
|
||||
made = _resource(node).add_map(_record).add_map(collected)
|
||||
made.apply_hints(table_name=table(pipeline_id, node.id))
|
||||
if node.primary_key:
|
||||
made.apply_hints(primary_key=node.primary_key)
|
||||
keyed = any(c.get("primary_key") for c in made.compute_table_schema()["columns"].values())
|
||||
keyed = any((c.get("primary_key") for c in made.compute_table_schema()["columns"].values()))
|
||||
made.apply_hints(write_disposition="merge" if keyed else "replace")
|
||||
loaded = _pipeline(table(pipeline_id, node.id)).run(made)
|
||||
with engine().connect() as con:
|
||||
fresh = not inspect(con).has_table(table(pipeline_id, node.id), schema="bronze")
|
||||
try:
|
||||
loaded = _pipeline(table(pipeline_id, node.id)).run(
|
||||
made, refresh="drop_resources" if fresh else None
|
||||
)
|
||||
except BaseException:
|
||||
collected.discard()
|
||||
raise
|
||||
collected.keep()
|
||||
return loaded
|
||||
|
||||
|
||||
def write(pipeline_id: str, node_id: str, rows: Iterable[dict], columns: dict | None = None):
|
||||
"""A node's output, rewritten whole on every run."""
|
||||
name = table(pipeline_id, node_id)
|
||||
resource = dlt.resource(rows, name=name, columns=columns, write_disposition="replace")
|
||||
return _pipeline(name).run(resource)
|
||||
|
||||
|
||||
def rows(pipeline_id: str, node_id: str) -> Iterator[dict]:
|
||||
"""A node's output, without dlt's own bookkeeping columns; none if it never produced
|
||||
a row (dlt creates a table on its first row). Binary values come back as bytes on
|
||||
every engine (PostgreSQL's driver gives memoryview)."""
|
||||
name = table(pipeline_id, node_id)
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table(name, schema="bronze"):
|
||||
@@ -105,40 +103,47 @@ def rows(pipeline_id: str, node_id: str) -> Iterator[dict]:
|
||||
|
||||
|
||||
def stage(entity: str, pipeline_id: str, node_id: str, rows: list[dict], columns: dict):
|
||||
"""A target's rows into `bronze.staged__<entity>`, replacing what that target wrote
|
||||
before. Many pipelines and targets share the table; dbt places it into silver. Each row
|
||||
keeps `known_at`, when the platform first had it: a source row that changes is a new
|
||||
record, so it is known from the run that brought the change."""
|
||||
name = f"staged__{entity}"
|
||||
known: dict[tuple, datetime] = {}
|
||||
with engine().begin() as con:
|
||||
if inspect(con).has_table(name, schema="bronze"):
|
||||
where = {"p": pipeline_id, "t": node_id}
|
||||
found = con.execute(text(f"select {RECORD}, _index, known_at from bronze.{name} "
|
||||
"where _pipeline = :p and _target = :t"), where) # fmt: skip
|
||||
found = con.execute(
|
||||
text(
|
||||
f"select {RECORD}, _index, known_at from bronze.{name} where _pipeline = :p and _target = :t"
|
||||
),
|
||||
where,
|
||||
)
|
||||
known = {(r, i): k for r, i, k in found}
|
||||
con.execute(
|
||||
text(f"delete from bronze.{name} where _pipeline = :p and _target = :t"), where
|
||||
)
|
||||
now = datetime.now(UTC)
|
||||
tagged = [
|
||||
{**r, "_pipeline": pipeline_id, "_target": node_id,
|
||||
"known_at": known.get((r[RECORD], r.get("_index", 0)), now)}
|
||||
{
|
||||
**r,
|
||||
"_pipeline": pipeline_id,
|
||||
"_target": node_id,
|
||||
"known_at": known.get((r[RECORD], r.get("_index", 0)), now),
|
||||
}
|
||||
for r in rows
|
||||
] # fmt: skip
|
||||
]
|
||||
resource = dlt.resource(tagged, name=name, columns=columns, write_disposition="append")
|
||||
return _pipeline(name).run(resource)
|
||||
|
||||
|
||||
def reject(entity: str, record: str, reason: str, by: str):
|
||||
"""A reviewer's decision that one record's row must not reach silver (append-only)."""
|
||||
row = {"entity": entity, RECORD: record, "reason": reason, "by": by,
|
||||
"decided_at": datetime.now(UTC)} # fmt: skip
|
||||
row = {
|
||||
"entity": entity,
|
||||
RECORD: record,
|
||||
"reason": reason,
|
||||
"by": by,
|
||||
"decided_at": datetime.now(UTC),
|
||||
}
|
||||
return _pipeline("review_log").run([row], table_name="review_log", write_disposition="append")
|
||||
|
||||
|
||||
def cached(name: str, keys: set[str]) -> dict[str, dict]:
|
||||
"""Rows of a content-keyed cache (`bronze.<name>`, keyed by `key`) for these keys."""
|
||||
with engine().connect() as con:
|
||||
if not keys or not inspect(con).has_table(name, schema="bronze"):
|
||||
return {}
|
||||
@@ -148,13 +153,13 @@ def cached(name: str, keys: set[str]) -> dict[str, dict]:
|
||||
|
||||
def remember(name: str, rows: list[dict], columns: dict):
|
||||
if rows:
|
||||
resource = dlt.resource(rows, name=name, primary_key="key", columns=columns,
|
||||
write_disposition="merge") # fmt: skip
|
||||
resource = dlt.resource(
|
||||
rows, name=name, primary_key="key", columns=columns, write_disposition="merge"
|
||||
)
|
||||
_pipeline(name).run(resource)
|
||||
|
||||
|
||||
def rejected(entity: str) -> set[str]:
|
||||
"""Records reviewers rejected for this entity."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("review_log", schema="bronze"):
|
||||
return set()
|
||||
@@ -163,16 +168,19 @@ def rejected(entity: str) -> set[str]:
|
||||
|
||||
|
||||
def decide_persons(record_l: str, record_r: str, same: bool, by: str):
|
||||
"""A reviewer's answer to "are these the same person?" (append-only; latest wins)."""
|
||||
row = {"record_l": record_l, "record_r": record_r, "same": same, "by": by,
|
||||
"decided_at": datetime.now(UTC)} # fmt: skip
|
||||
row = {
|
||||
"record_l": record_l,
|
||||
"record_r": record_r,
|
||||
"same": same,
|
||||
"by": by,
|
||||
"decided_at": datetime.now(UTC),
|
||||
}
|
||||
return _pipeline("review_persons").run(
|
||||
[row], table_name="review_persons", write_disposition="append"
|
||||
)
|
||||
|
||||
|
||||
def person_decisions() -> dict[frozenset, bool]:
|
||||
"""Each pair of records reviewers judged, and their latest answer."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("review_persons", schema="bronze"):
|
||||
return {}
|
||||
@@ -181,17 +189,20 @@ def person_decisions() -> dict[frozenset, bool]:
|
||||
|
||||
|
||||
def correct(record: str, field: str, value: str, by: str, entity: str = "identity"):
|
||||
"""A reviewer's correction of one field of one record (append-only; latest wins). The
|
||||
source keeps its value; linking (identity fields) or the study's target uses it."""
|
||||
row = {RECORD: record, "entity": entity, "field": field, "value": value, "by": by,
|
||||
"decided_at": datetime.now(UTC)} # fmt: skip
|
||||
row = {
|
||||
RECORD: record,
|
||||
"entity": entity,
|
||||
"field": field,
|
||||
"value": value,
|
||||
"by": by,
|
||||
"decided_at": datetime.now(UTC),
|
||||
}
|
||||
return _pipeline("review_corrections").run(
|
||||
[row], table_name="review_corrections", write_disposition="append"
|
||||
)
|
||||
|
||||
|
||||
def corrections() -> dict[str, dict[str, str]]:
|
||||
"""The latest correction of each field of each record."""
|
||||
with engine().connect() as con:
|
||||
if not inspect(con).has_table("review_corrections", schema="bronze"):
|
||||
return {}
|
||||
@@ -205,33 +216,35 @@ def corrections() -> dict[str, dict[str, str]]:
|
||||
|
||||
|
||||
def stable_persons(clusters: dict[str, list[str]]) -> dict[str, str]:
|
||||
"""A person id for each cluster of records (the link node's persons) that survives
|
||||
reruns and reviews: a cluster keeps an id its records already had (the earliest minted
|
||||
when several meet, the others then `replaced_by` it); a cluster whose records had none
|
||||
gets a new UUID; an id whose records part goes with the larger part. Assignments and
|
||||
replacements are appended to `bronze.person_registry` and `bronze.person_link`."""
|
||||
known, minted = {}, {}
|
||||
known, minted = ({}, {})
|
||||
with engine().connect() as con:
|
||||
if inspect(con).has_table("person_registry", schema="bronze"):
|
||||
sql = text("select _record, person_id, assigned_at from bronze.person_registry "
|
||||
"order by assigned_at") # fmt: skip
|
||||
sql = text(
|
||||
"select _record, person_id, assigned_at from bronze.person_registry order by assigned_at"
|
||||
)
|
||||
for record, person, at in con.execute(sql):
|
||||
known[record] = person # the latest assignment wins
|
||||
known[record] = person
|
||||
minted.setdefault(person, at)
|
||||
now = datetime.now(UTC)
|
||||
found, taken, assigned, links = {}, set(), [], []
|
||||
found, taken, assigned, links = ({}, set(), [], [])
|
||||
for cluster, records in sorted(clusters.items(), key=lambda c: (-len(c[1]), c[0])):
|
||||
ids = {known[r] for r in records if r in known} - taken
|
||||
person = min(ids, key=lambda i: (str(minted[i]), i)) if ids else str(uuid.uuid4())
|
||||
links += [{"person_id": old, "replaced_by": person, "linked_at": now}
|
||||
for old in sorted(ids - {person})] # fmt: skip
|
||||
links += [
|
||||
{"person_id": old, "replaced_by": person, "linked_at": now}
|
||||
for old in sorted(ids - {person})
|
||||
]
|
||||
taken |= ids | {person}
|
||||
found[cluster] = person
|
||||
assigned += [{RECORD: r, "person_id": person, "assigned_at": now}
|
||||
for r in records if known.get(r) != person] # fmt: skip
|
||||
assigned += [
|
||||
{RECORD: r, "person_id": person, "assigned_at": now}
|
||||
for r in records
|
||||
if known.get(r) != person
|
||||
]
|
||||
if assigned:
|
||||
_pipeline("person_registry").run(assigned, table_name="person_registry",
|
||||
write_disposition="append") # fmt: skip
|
||||
_pipeline("person_registry").run(
|
||||
assigned, table_name="person_registry", write_disposition="append"
|
||||
)
|
||||
if links:
|
||||
_pipeline("person_link").run(links, table_name="person_link", write_disposition="append")
|
||||
return found
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user