Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b77c22168c | |||
| d3a02178d1 | |||
| 72cd19219a | |||
| de58f0db59 | |||
| 2fe5301fd1 | |||
| 4ddbabd90c | |||
| 0cf969c48e | |||
| 31ff84c89c | |||
| 70cde6d98b | |||
| 04f31d2adb | |||
| 606a2efc89 | |||
| d16d5ce7c5 | |||
| 8e4e080a11 | |||
| 2ff634c687 | |||
| 50289a5b36 | |||
| d5b466a77f | |||
| e1d3887e6c |
@@ -42,9 +42,13 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- run: git submodule update --init
|
||||
- run: |
|
||||
apt-get update
|
||||
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
|
||||
apt-get update --error-on=any
|
||||
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
|
||||
default-jre-headless
|
||||
default-jre-headless postgresql-common
|
||||
# pg_dump of the server's version (backups), as in the product's image.
|
||||
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
|
||||
apt-get install -y --no-install-recommends postgresql-client-17
|
||||
- name: HL7 validator, pinned
|
||||
run: |
|
||||
mkdir -p /opt/fhir
|
||||
@@ -96,7 +100,8 @@ jobs:
|
||||
run: npx ng test --watch=false
|
||||
- name: Every page loads from the API (Playwright over a loaded platform)
|
||||
run: |
|
||||
apt-get update
|
||||
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
|
||||
apt-get update --error-on=any
|
||||
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
|
||||
default-jre-headless
|
||||
mkdir -p /opt/synthea
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
[submodule "WebApi"]
|
||||
path = WebApi
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
||||
url = ../WebApi.git
|
||||
branch = rebuild
|
||||
[submodule "WebApp"]
|
||||
path = WebApp
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
||||
url = ../WebApp.git
|
||||
branch = rebuild
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
url = ../models.git
|
||||
branch = rebuild
|
||||
|
||||
@@ -40,6 +40,7 @@ POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after
|
||||
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
|
||||
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
|
||||
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
|
||||
CYTOLOGY_BEFORE_DAYS = 365 # a procedure's cytology was reported this long before at most
|
||||
HYSTERECTOMY_ICD10 = ["Z907"]
|
||||
|
||||
# Inferred procedures, from clinical notes (ICD-10 without the dot).
|
||||
@@ -70,6 +71,16 @@ ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
|
||||
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
|
||||
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
|
||||
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
|
||||
# The PPVs of a procedure: groups of its cytology (each holds the more severe squamous ones)
|
||||
# and of its histology; the first histology group is the score's.
|
||||
PROCEDURE_CYTOLOGY = {
|
||||
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
|
||||
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS"],
|
||||
"hsil_plus": ["HSIL", "CIS"],
|
||||
}
|
||||
PROCEDURE_HISTOLOGY = {
|
||||
"cin1_plus": ["LSIL", *CIN2_PLUS], "cin2_plus": CIN2_PLUS, "carcinoma": CANCER,
|
||||
} # fmt: skip
|
||||
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
|
||||
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
|
||||
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
|
||||
|
||||
@@ -15,7 +15,7 @@ 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": "route"} # what followed the sample
|
||||
|
||||
|
||||
def status(row: dict, cutoff: date) -> str:
|
||||
|
||||
+112
-1
@@ -63,6 +63,80 @@ def histology(row: dict) -> str:
|
||||
return row.get("histology") or NO_DATA
|
||||
|
||||
|
||||
def case_before(row: dict) -> bool:
|
||||
"""Whether she was a case already: at the procedure's cytology, or at it without one."""
|
||||
return follow_up_status(row, as_day(row["sample_date"] or row["date"])) == "case"
|
||||
|
||||
|
||||
def earliest(row: dict) -> tuple:
|
||||
return -as_day(row["date"]).toordinal(), row["procedure_id"]
|
||||
|
||||
|
||||
def groups_by_cytology(row: dict, p=None) -> list[str]:
|
||||
if row["result"] is None:
|
||||
return [NO_DATA]
|
||||
return [g for g, results in cacu.PROCEDURE_CYTOLOGY.items() if row["result"] in results]
|
||||
|
||||
|
||||
SIGN = {True: "positive", False: "negative"} # SQLite answers booleans as 1 and 0: the same keys
|
||||
|
||||
|
||||
def groups_by_hpv(row: dict, p=None) -> list[str]:
|
||||
"""Her HPV result and, apart, each genotype found (they overlap)."""
|
||||
said = [SIGN[row["hpv"]]] if row["hpv"] in SIGN else []
|
||||
return [*said, *(g for g in ("hpv_16", "hpv_18") if row[g])] or [NO_DATA]
|
||||
|
||||
|
||||
def round_of(row: dict, p=None) -> str:
|
||||
"""Subsequent: screened before, as her form says, or past colposcopy or treatment at the
|
||||
sample. Initial: the first screening of her life."""
|
||||
if row["sample_date"] is None:
|
||||
return NO_DATA
|
||||
if follow_up_status(row, as_day(row["sample_date"])) in ("post_colposcopy", "post_treatment"):
|
||||
return "subsequent"
|
||||
history = row["screening_history"]
|
||||
return NO_DATA if history is None else "initial" if history == "never" else "subsequent"
|
||||
|
||||
|
||||
def hpv_genotype(row: dict) -> str:
|
||||
"""What an HPV report says, a null never read as a negative."""
|
||||
hpv, found = row["hpv"], [g for g in ("16", "18") if row[f"hpv_{g}"]]
|
||||
if not hpv:
|
||||
return "inconsistent" if found else "no_result" if hpv is None else "negative"
|
||||
if row["hpv_16"] is None or row["hpv_18"] is None:
|
||||
return "positive_incomplete"
|
||||
return "positive_" + ("_".join(found) or "other")
|
||||
|
||||
|
||||
def biopsy_answer(row: dict) -> str:
|
||||
"""What became of a biopsy requested, by its report."""
|
||||
if row["report_date"] is None:
|
||||
return "pending"
|
||||
if as_day(row["report_date"]) < as_day(row["date"]):
|
||||
return "inconsistent"
|
||||
if row["histology"] is None:
|
||||
return "no_grade"
|
||||
return "high_grade" if row["histology"] in cacu.CIN2_PLUS else "below_high_grade"
|
||||
|
||||
|
||||
def ppv(id: str, title: str, procedure: str, counted) -> Measure:
|
||||
"""Of the patients with the procedure in the period (her first), those whose histology is
|
||||
LIEBG or more; those already cases are left out."""
|
||||
levels = tuple((name, lambda r, grades=grades: r["histology"] in grades)
|
||||
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()) # fmt: skip
|
||||
return Measure(
|
||||
id, title, "procedures",
|
||||
Proportion(levels[0][1], denominator=lambda r: counted(r) and not case_before(r),
|
||||
order=earliest, levels=levels, date="date",
|
||||
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv),
|
||||
("round", round_of))),
|
||||
params={"type": procedure},
|
||||
facts={"report_known_at": ("histology", "report_date"),
|
||||
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18")},
|
||||
dated={"report_date": ("histology",)},
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
H = cacu.HORIZONS
|
||||
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
|
||||
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
|
||||
@@ -76,7 +150,44 @@ MEASURES = {m.id: m for m in [
|
||||
and r.get("biopsy_report_date") is not None,
|
||||
strata=(AGE, STATUS)), group="principal"),
|
||||
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
|
||||
Composition(latest, result, strata=(AGE, STATUS))),
|
||||
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of)))),
|
||||
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
|
||||
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]),
|
||||
lambda r: SIGN[r["hpv"]],
|
||||
where=lambda r: r["hpv"] is not None,
|
||||
strata=(AGE, STATUS, ("round", round_of),
|
||||
*((g, lambda r, p, g=g: SIGN.get(r[g], []))
|
||||
for g in ("hpv_16", "hpv_18")))),
|
||||
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
|
||||
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "samples",
|
||||
Composition(lambda r: (), hpv_genotype, unit="sample_id",
|
||||
where=lambda r: r["report_date"] is not None and any(
|
||||
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))),
|
||||
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
|
||||
description="Reportes de VPH, por fecha de toma."),
|
||||
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "procedures",
|
||||
Composition(lambda r: (), lambda r: r["histology"] or NO_DATA,
|
||||
unit="procedure_id", date="report_date",
|
||||
where=lambda r: r["report_date"] is not None),
|
||||
params={"type": "biopsy"}, known="report_known_at",
|
||||
description="Reportes de biopsia, por fecha de reporte."),
|
||||
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
|
||||
"Confirmación por solicitudes de biopsia", "procedures",
|
||||
Composition(lambda r: (), biopsy_answer, unit="procedure_id", date="date"),
|
||||
params={"type": "biopsy"},
|
||||
facts={"report_known_at": ("histology", "report_date")},
|
||||
dated={"report_date": ("histology",)},
|
||||
description="Solicitudes de biopsia registradas, por fecha de solicitud."),
|
||||
ppv("CACU_VPP_COLPOSCOPIA", "Valor predictivo positivo de la colposcopía", "colposcopy",
|
||||
lambda r: True),
|
||||
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
|
||||
lambda r: r["histology"] is not None and r["report_date"] is not None),
|
||||
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo de tamizaje a diagnóstico por CIE-10",
|
||||
"samples",
|
||||
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
|
||||
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
|
||||
strata=(("diagnosis_code",
|
||||
lambda r, p: r["diagnosis_code"] or NO_DATA),)), "decrease"),
|
||||
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
|
||||
Composition(latest_most_severe_biopsy, histology,
|
||||
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
|
||||
|
||||
@@ -52,6 +52,11 @@ def biopsy_histology(row: dict) -> str:
|
||||
return row["histology"] or NO_DATA
|
||||
|
||||
|
||||
def should_be_biopsied(row: dict) -> bool:
|
||||
"""A reported mammogram whose BI-RADS asks for a biopsy (the confirmation's denominator)."""
|
||||
return reported(row) and row["birads"] in cama.SUSPICIOUS
|
||||
|
||||
|
||||
def four_to_six(row: dict) -> bool:
|
||||
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
|
||||
|
||||
@@ -111,4 +116,21 @@ MEASURES = {m.id: m for m in [
|
||||
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
|
||||
date="report_date"),
|
||||
"decrease", known="report_known_at"),
|
||||
# Pending the analysts' validation (LOTE-3-CAMA-REBUILD.md): the biopsy is the one whose
|
||||
# request names the mammogram, the first reported if several; the horizon is the
|
||||
# diagnosis's, as no other is set.
|
||||
Measure("CAMA_DIAS_RESULTADO_BIOPSIA",
|
||||
"Tiempo de resultado de mastografía a resultado de biopsia", "mammogram_first_biopsy",
|
||||
Duration("days_report_biopsy", "biopsy_report_date", "report_date", H["to_diagnosis"],
|
||||
units=should_be_biopsied, unit="mammogram_id", date="report_date"),
|
||||
"decrease", facts=REPORT | {"biopsy_known_at": ("biopsy_report_date",
|
||||
"days_report_biopsy")},
|
||||
description=(
|
||||
"PROVISIONAL, pendiente de validación metodológica de los analistas. Días del "
|
||||
"reporte de la mastografía (BI-RADS 4, 4A, 4B, 4C o 5) al reporte de la primera "
|
||||
"biopsia reportada cuya solicitud nombra esa mastografía; sin vínculo explícito "
|
||||
"no hay medición. Horizonte de 180 días reutilizado del tramo a diagnóstico "
|
||||
"(no hay uno propio). Por decidir: fuente real del vínculo, cohorte, selección "
|
||||
"con varias biopsias, horizonte, historia de cáncer y fechas inconsistentes."
|
||||
)),
|
||||
]} # fmt: skip
|
||||
|
||||
@@ -7,6 +7,49 @@ cervical_cytology:
|
||||
report: {date: report_date, parent: sample}
|
||||
fields:
|
||||
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
|
||||
screening_history:
|
||||
type: code
|
||||
event: sample
|
||||
title: Detección de cáncer de cérvix
|
||||
system: cervical-screening-history
|
||||
codes:
|
||||
never: Primera vez en la vida
|
||||
within_1_year: Un año o menos
|
||||
2_years: Dos años
|
||||
3_or_more_years: Tres o más años
|
||||
gynecologic_condition:
|
||||
type: code
|
||||
event: sample
|
||||
title: Condición ginecoobstétrica a la detección
|
||||
system: gynecologic-condition
|
||||
codes:
|
||||
postpartum: Puerperio posparto o posaborto
|
||||
pregnant: Embarazo actual
|
||||
iud: DIU in situ
|
||||
hormonal_treatment: Tratamiento hormonal
|
||||
other_treatment: Otro tratamiento ginecológico
|
||||
postmenopausal: Posmenopausia
|
||||
hysterectomy: Histerectomía
|
||||
not_applicable: No aplica
|
||||
presenting_symptom:
|
||||
type: code
|
||||
event: sample
|
||||
title: Actualmente presenta
|
||||
system: presenting-symptom
|
||||
codes:
|
||||
discharge: Flujo
|
||||
vulvar_itching: Prurito o ardor vulvar
|
||||
abnormal_bleeding: Sangrado anormal
|
||||
none: Ninguno
|
||||
cervix_appearance:
|
||||
type: code
|
||||
event: sample
|
||||
title: A la exploración se observa
|
||||
system: cervix-appearance
|
||||
codes:
|
||||
healthy: Cuello sano
|
||||
lesion: Cuello anormal con lesión
|
||||
not_seen: No se observa cuello
|
||||
report_date: {type: date, event: report, title: Fecha de reporte}
|
||||
adequacy:
|
||||
type: code
|
||||
@@ -29,6 +72,35 @@ cervical_cytology:
|
||||
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
|
||||
hpv_16: {type: boolean, event: report, title: VPH 16}
|
||||
hpv_18: {type: boolean, event: report, title: VPH 18}
|
||||
# What the cytologist adds in words. A finding is true when stated, otherwise unknown.
|
||||
findings: {type: text, event: report, title: Hallazgos adicionales}
|
||||
finding_inflammation: {type: boolean, event: report, title: "Hallazgo: inflamación"}
|
||||
finding_reactive: {type: boolean, event: report, title: "Hallazgo: cambios reactivos"}
|
||||
finding_vaginosis: {type: boolean, event: report, title: "Hallazgo: cambio en la flora sugestiva de vaginosis bacteriana"}
|
||||
finding_candida: {type: boolean, event: report, title: "Hallazgo: microorganismos micóticos morfológicamente compatibles con Candida sp"}
|
||||
finding_bacillary_cytolysis: {type: boolean, event: report, title: "Hallazgo: aumento de la flora bacilar con citólisis de las células intermedias"}
|
||||
finding_cytolysis: {type: boolean, event: report, title: "Hallazgo: citólisis de las células intermedias"}
|
||||
finding_trichomonas: {type: boolean, event: report, title: "Hallazgo: trichomonas vaginalis"}
|
||||
finding_leptothrix: {type: boolean, event: report, title: "Hallazgo: microorganismos bacterianos morfológicamente compatibles con Leptothrix"}
|
||||
finding_actinomyces: {type: boolean, event: report, title: "Hallazgo: microorganismos morfológicamente compatibles con Actinomyces sp"}
|
||||
finding_actinomyces_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con Actinomyces sp"}
|
||||
finding_herpes_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con virus herpes simple"}
|
||||
finding_tubular_metaplasia: {type: boolean, event: report, title: "Hallazgo: metaplasia escamosa tubular"}
|
||||
finding_keratotic: {type: boolean, event: report, title: "Hallazgo: cambios queratósicos"}
|
||||
finding_pregnancy: {type: boolean, event: report, title: "Hallazgo: cambios asociados al embarazo"}
|
||||
finding_atrophy: {type: boolean, event: report, title: "Hallazgo: atrofia"}
|
||||
finding_hypoestrogenism: {type: boolean, event: report, title: "Hallazgo: hipoestrogenismo"}
|
||||
finding_radiotherapy: {type: boolean, event: report, title: "Hallazgo: efecto de radioterapia"}
|
||||
finding_iud_changes: {type: boolean, event: report, title: "Hallazgo: cambios compatibles con presencia de dispositivo intrauterino"}
|
||||
finding_glandular_cells: {type: boolean, event: report, title: "Hallazgo: células glandulares post-histerectomía"}
|
||||
finding_bacteria: {type: boolean, event: report, title: "Hallazgo: bacterias"}
|
||||
finding_herpes_image: {type: boolean, event: report, title: "Hallazgo: imagen del virus del herpes"}
|
||||
finding_fungi: {type: boolean, event: report, title: "Hallazgo: hongos"}
|
||||
finding_radiation: {type: boolean, event: report, title: "Hallazgo: radiación"}
|
||||
finding_repair: {type: boolean, event: report, title: "Hallazgo: reparación"}
|
||||
finding_iud_effect: {type: boolean, event: report, title: "Hallazgo: efecto del DIU"}
|
||||
finding_endometrial_cells: {type: boolean, event: report, title: "Hallazgo: presencia de células endometriales en pacientes de 40 años o más"}
|
||||
finding_none: {type: boolean, event: report, title: "Hallazgo: ninguno"}
|
||||
|
||||
cervical_biopsy:
|
||||
title: Biopsia cervical
|
||||
|
||||
@@ -6,6 +6,18 @@ bethesda:
|
||||
who-cervical-histology:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
|
||||
title: Clasificación OMS de lesiones cervicales (histología)
|
||||
cervical-screening-history:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
|
||||
title: Detección de cáncer de cérvix
|
||||
gynecologic-condition:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/gynecologic-condition
|
||||
title: Condición ginecoobstétrica a la detección
|
||||
presenting-symptom:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/presenting-symptom
|
||||
title: Actualmente presenta
|
||||
cervix-appearance:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/cervix-appearance
|
||||
title: A la exploración se observa
|
||||
bi-rads:
|
||||
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
|
||||
title: BI-RADS
|
||||
|
||||
+33
-3
@@ -66,7 +66,10 @@ CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
|
||||
"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",
|
||||
"birads": "BI-RADS de la mastografía", "diagnosis_code": "Diagnóstico CIE-10",
|
||||
"cytology": "Citología previa", "hpv": "VPH de la citología previa",
|
||||
"level": "Histología confirmada", "round": "Tamizaje inicial o subsecuente",
|
||||
"hpv_16": "VPH 16", "hpv_18": "VPH 18",
|
||||
}),
|
||||
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
|
||||
} # fmt: skip
|
||||
@@ -91,18 +94,28 @@ CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
|
||||
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
|
||||
}) # fmt: skip
|
||||
|
||||
# Where a duration is scored: the whole, and each stratum with a score of its own.
|
||||
DURATIONS = ["MeasureReport.group.measureScore",
|
||||
"MeasureReport.group.stratifier.stratum.measureScore"] # fmt: skip
|
||||
# Our extensions: name -> (value type, the elements they extend).
|
||||
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
|
||||
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
|
||||
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
|
||||
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
|
||||
"q1": ("decimal", DURATIONS),
|
||||
"q3": ("decimal", DURATIONS),
|
||||
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
|
||||
"period-type": ("code", ["Measure"]),
|
||||
"follow-up-status": ("Coding", ["Patient"]),
|
||||
"follow-up-priority": ("Coding", ["Patient"]),
|
||||
"report-date": ("date", ["DiagnosticReport"]),
|
||||
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
|
||||
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
|
||||
# whether the biopsy's record names the cytology (recorded) or its dates do (inferred)
|
||||
"colposcopy-date": ("date", ["DiagnosticReport"]),
|
||||
"biopsy-request-date": ("date", ["DiagnosticReport"]),
|
||||
"biopsy-date": ("date", ["DiagnosticReport"]),
|
||||
"biopsy-link": ("code", ["DiagnosticReport"]),
|
||||
"diagnosis-date": ("date", ["DiagnosticReport"]),
|
||||
# a clinical scenario of the model's report the person falls in (its curves)
|
||||
"escenario-clinico": ("string", ["RiskAssessment"]),
|
||||
# a child on TEA's list: her age group, case, EEG and scores
|
||||
@@ -153,6 +166,21 @@ def ext(name: str, value_type: str, value) -> dict:
|
||||
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
|
||||
|
||||
|
||||
# A report's facts (a domain's `REPORT_FACTS` read): their column -> the extension.
|
||||
_REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
|
||||
"requested": "biopsy-request-date", "biopsy": "biopsy-date",
|
||||
"link": "biopsy-link", "diagnosis": "diagnosis-date"} # fmt: skip
|
||||
|
||||
|
||||
def report_facts(row: dict) -> list[dict]:
|
||||
found = []
|
||||
for column, name in _REPORT_FACTS.items():
|
||||
if (value := row.get(column)) is not None:
|
||||
kind = EXTENSIONS[name][0]
|
||||
found.append(ext(name, kind, {"integer": int, "date": _day}.get(kind, str)(value)))
|
||||
return found
|
||||
|
||||
|
||||
def subject(person_id: str) -> dict:
|
||||
return {"reference": f"Patient/{person_id}"}
|
||||
|
||||
@@ -439,6 +467,8 @@ def measure(m, domain: str) -> Measure:
|
||||
"extension": [ext("period-type", "code", p) for p in m.periods],
|
||||
"group": [group],
|
||||
} # fmt: skip
|
||||
if m.description:
|
||||
found["description"] = m.description
|
||||
if m.improvement:
|
||||
found["improvementNotation"] = {"coding": [{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
|
||||
+74
-27
@@ -99,8 +99,13 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
|
||||
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
|
||||
|
||||
|
||||
# A stratum: its name and the value a row takes in a period.
|
||||
Stratum = tuple[str, Callable[[dict, "Period"], str]]
|
||||
# A stratum: its name and the value a row takes in a period; a list when it takes several (its
|
||||
# groups overlap) or none.
|
||||
Stratum = tuple[str, Callable[[dict, "Period"], "str | list[str]"]]
|
||||
|
||||
|
||||
def groups(value: "str | list[str]") -> list[str]:
|
||||
return [value] if isinstance(value, str) else value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -115,6 +120,8 @@ class Result:
|
||||
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
|
||||
default_factory=dict
|
||||
)
|
||||
# A stratum value's own score: (stratum, value) -> score, its extensions and unit.
|
||||
scores: dict[tuple[str, str], tuple[float, dict[str, float], str]] = field(default_factory=dict)
|
||||
|
||||
|
||||
def wilson(k: int, n: int) -> tuple[float, float]:
|
||||
@@ -127,11 +134,15 @@ def wilson(k: int, n: int) -> tuple[float, float]:
|
||||
@dataclass(frozen=True)
|
||||
class Proportion:
|
||||
"""Units with a row dated in the period that meets `denominator` and, of them, those
|
||||
with such a row that also meets `numerator`; with a Wilson 95% interval."""
|
||||
with such a row that also meets `numerator`; with a Wilson 95% interval. With `order`, a
|
||||
unit counts with one row only, the one it ranks highest. `levels` are other numerators
|
||||
over the same denominator: the stratifier `level`."""
|
||||
|
||||
numerator: Callable[[dict], bool]
|
||||
strata: tuple[Stratum, ...] = ()
|
||||
denominator: Callable[[dict], bool] = lambda row: True
|
||||
order: Callable[[dict], tuple] | None = None
|
||||
levels: tuple[tuple[str, Callable[[dict], bool]], ...] = ()
|
||||
unit: str = "person_id"
|
||||
date: str = "sample_date"
|
||||
kind: str = "proportion"
|
||||
@@ -140,6 +151,8 @@ class Proportion:
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
mine = [r for r in rows if r[self.date] in period and self.denominator(r)]
|
||||
if self.order:
|
||||
mine = list({r[self.unit]: r for r in sorted(mine, key=self.order)}.values())
|
||||
den = {r[self.unit]: r for r in mine}
|
||||
num = {r[self.unit] for r in mine if self.numerator(r)}
|
||||
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
|
||||
@@ -147,14 +160,19 @@ class Proportion:
|
||||
for name, stratum in self.strata:
|
||||
values: dict[str, dict[str, int]] = {}
|
||||
for unit, row in den.items():
|
||||
cell = values.setdefault(
|
||||
stratum(row, period),
|
||||
{"initial-population": 0, "denominator": 0, "numerator": 0},
|
||||
)
|
||||
cell["initial-population"] += 1
|
||||
cell["denominator"] += 1
|
||||
cell["numerator"] += unit in num
|
||||
for value in groups(stratum(row, period)):
|
||||
cell = values.setdefault(
|
||||
value, {"initial-population": 0, "denominator": 0, "numerator": 0}
|
||||
)
|
||||
cell["initial-population"] += 1
|
||||
cell["denominator"] += 1
|
||||
cell["numerator"] += unit in num
|
||||
strata[name] = values
|
||||
if self.levels and den:
|
||||
strata["level"] = {
|
||||
level: {**found, "numerator": len({r[self.unit] for r in mine if meets(r)})}
|
||||
for level, meets in self.levels
|
||||
}
|
||||
if not den:
|
||||
return Result(found, strata=strata)
|
||||
low, high = wilson(len(num), len(den))
|
||||
@@ -195,21 +213,30 @@ class Composition:
|
||||
for name, stratum in (("category", lambda row, p: self.category(row)), *self.strata):
|
||||
values: dict[str, dict[str, int]] = {}
|
||||
for row in chosen.values():
|
||||
value = stratum(row, period)
|
||||
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
|
||||
for value in groups(stratum(row, period)):
|
||||
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
|
||||
strata[name] = values
|
||||
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
|
||||
for name, stratum in self.strata: # each also by category
|
||||
pairs: dict[tuple[str, str], dict[str, int]] = {}
|
||||
for row in chosen.values():
|
||||
key = (stratum(row, period), self.category(row))
|
||||
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
|
||||
for value in groups(stratum(row, period)):
|
||||
key = (value, self.category(row))
|
||||
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
|
||||
crossed[(name, "category")] = pairs
|
||||
n = len(chosen)
|
||||
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
|
||||
crossed=crossed) # fmt: skip
|
||||
|
||||
|
||||
def quartiles(values: list[float]) -> tuple[float, dict[str, float]]:
|
||||
"""The median, and the quartiles as score extensions."""
|
||||
if len(values) == 1:
|
||||
return values[0], {"q1": values[0], "q3": values[0]}
|
||||
q1, median, q3 = statistics.quantiles(values, n=4, method="inclusive")
|
||||
return median, {"q1": q1, "q3": q3}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Duration:
|
||||
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
|
||||
@@ -222,6 +249,7 @@ class Duration:
|
||||
horizon: int
|
||||
units: Callable[[dict], bool] = lambda row: True
|
||||
ended: str | None = None
|
||||
strata: tuple[Stratum, ...] = ()
|
||||
unit: str = "sample_id"
|
||||
date: str = "sample_date"
|
||||
kind: str = "continuous-variable"
|
||||
@@ -231,6 +259,7 @@ class Duration:
|
||||
|
||||
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
|
||||
measured, initial = [], 0
|
||||
grouped: dict[str, dict[str, list[float]]] = {name: {} for name, _ in self.strata}
|
||||
for row in {r[self.unit]: r for r in rows}.values():
|
||||
if row[self.date] not in period or not self.units(row):
|
||||
continue
|
||||
@@ -238,6 +267,9 @@ class Duration:
|
||||
has = row.get(self.value) is not None and end is not None and end <= cutoff
|
||||
if has:
|
||||
measured.append(float(row[self.value]))
|
||||
for name, stratum in self.strata:
|
||||
for value in groups(stratum(row, period)):
|
||||
grouped[name].setdefault(value, []).append(measured[-1])
|
||||
stop = as_day(row.get(self.ended)) if self.ended else None
|
||||
done = has or (stop is not None and stop <= cutoff)
|
||||
pending = not done and (cutoff - as_day(row[self.start])).days < self.horizon
|
||||
@@ -245,11 +277,14 @@ class Duration:
|
||||
found = {"initial-population": initial, "measure-observation": len(measured)}
|
||||
if not measured:
|
||||
return Result(found)
|
||||
if len(measured) == 1:
|
||||
q1 = median = q3 = measured[0]
|
||||
else:
|
||||
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
|
||||
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
|
||||
median, spread = quartiles(measured)
|
||||
return Result(
|
||||
found, median, spread, unit="d",
|
||||
strata={name: {v: {"measure-observation": len(days)} for v, days in values.items()}
|
||||
for name, values in grouped.items()},
|
||||
scores={(name, v): (*quartiles(days), "d")
|
||||
for name, values in grouped.items() for v, days in values.items()},
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -399,6 +434,9 @@ class Measure:
|
||||
# Facts a row carries that became known apart from the row itself: their `known_at`
|
||||
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
|
||||
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
# The same by the event cutoff: a date column -> the columns it dates.
|
||||
dated: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
description: str | None = None
|
||||
|
||||
|
||||
def evaluate(
|
||||
@@ -412,6 +450,10 @@ def evaluate(
|
||||
count to `event_cutoff` (default: `as_of`'s day, or today)."""
|
||||
as_of = _moment(as_of)
|
||||
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
|
||||
if measure.dated:
|
||||
rows = [{**row, **dict.fromkeys(c for day, cols in measure.dated.items()
|
||||
if (as_day(row.get(day)) or cutoff) > cutoff
|
||||
for c in (day, *cols))} for row in rows] # fmt: skip
|
||||
if as_of is None: # every row and fact is known
|
||||
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
|
||||
|
||||
@@ -458,6 +500,14 @@ def _population(code: str, count: int) -> dict:
|
||||
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
|
||||
|
||||
|
||||
def _score(value: float, extensions: dict[str, float], unit: str | None) -> dict:
|
||||
return {
|
||||
"value": value,
|
||||
**({"unit": unit} if unit else {}),
|
||||
"extension": [{"url": EXTENSION + k, "valueDecimal": v} for k, v in extensions.items()],
|
||||
}
|
||||
|
||||
|
||||
def report(
|
||||
measure: Measure, period: Period, result: Result, as_of: datetime | None
|
||||
) -> MeasureReport:
|
||||
@@ -467,19 +517,16 @@ def report(
|
||||
"population": [_population(c, n) for c, n in result.populations.items()],
|
||||
}
|
||||
if result.score is not None:
|
||||
group["measureScore"] = {
|
||||
"value": result.score,
|
||||
**({"unit": result.unit} if result.unit else {}),
|
||||
"extension": [{"url": EXTENSION + k, "valueDecimal": v}
|
||||
for k, v in result.score_extensions.items()],
|
||||
} # fmt: skip
|
||||
group["measureScore"] = _score(result.score, result.score_extensions, result.unit)
|
||||
elif measure.rule.kind == "composition": # a cohort scores its count
|
||||
group["measureScore"] = {"value": result.populations["initial-population"]}
|
||||
if result.strata:
|
||||
group["stratifier"] = [
|
||||
{"id": name, "code": [stratifier_code(name)],
|
||||
"stratum": [{"value": {"text": value},
|
||||
"population": [_population(c, n) for c, n in cells.items()]}
|
||||
"population": [_population(c, n) for c, n in cells.items()],
|
||||
**({"measureScore": _score(*result.scores[name, value])}
|
||||
if (name, value) in result.scores else {})}
|
||||
for value, cells in sorted(values.items())]}
|
||||
for name, values in result.strata.items()
|
||||
] + [
|
||||
@@ -502,7 +549,7 @@ def report(
|
||||
} # fmt: skip
|
||||
if as_of is not None:
|
||||
found["extension"] = [{"url": EXTENSION + "corte-conocimiento",
|
||||
"valueDateTime": as_of.isoformat()}] # fmt: skip
|
||||
"valueDateTime": _moment(as_of).isoformat()}] # fmt: skip
|
||||
if measure.improvement:
|
||||
found["improvementNotation"] = {"coding": [{"system": IMPROVEMENT,
|
||||
"code": measure.improvement}]} # fmt: skip
|
||||
|
||||
@@ -400,7 +400,7 @@ def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
|
||||
target holds it with the reason."""
|
||||
if not isinstance(raw, str):
|
||||
return raw
|
||||
raw = raw.strip()
|
||||
raw = _SPACE.sub(" ", raw.strip()) # a value read across a line break is one value
|
||||
raw = codes.get(field, {}).get(raw.casefold(), raw)
|
||||
fmt = node.formats.get(field)
|
||||
if fmt and fmt.startswith("dateparser:"):
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
{#
|
||||
One row per colposcopy day and per biopsy of a patient, with the cytology that led to it and
|
||||
the histology that answers it.
|
||||
- The cytology: the one the biopsy's record names (`link` recorded), else her latest valid
|
||||
one reported before the procedure, at most CYTOLOGY_BEFORE_DAYS before (inferred).
|
||||
- A colposcopy's histology: the most severe reported of the biopsies requested from that day
|
||||
and within the colposcopy_to_biopsy horizon.
|
||||
cacu_events also dates a colposcopy at the report of a biopsy taken at it: not a day of one.
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with biopsy as (
|
||||
select
|
||||
person_id, request_date as date, cytology_sample_date as recorded, report_date, histology,
|
||||
known_at, report_known_at,
|
||||
case
|
||||
{%- for grade in p.biopsy_severity %}
|
||||
when histology = '{{ grade }}' then {{ loop.index }}
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as severity
|
||||
from {{ ref('cervical_biopsy') }}
|
||||
),
|
||||
|
||||
colposcopy as (
|
||||
select person_id, date, min(known_at) as known_at
|
||||
from {{ ref('cacu_events') }}
|
||||
where type = 'colposcopy'
|
||||
and not (source_table = 'cervical_biopsy' and source_id <> cast(date as {{ dbt.type_string() }}))
|
||||
group by person_id, date
|
||||
),
|
||||
|
||||
answered as (
|
||||
select
|
||||
c.person_id, c.date, b.report_date, b.histology, b.report_known_at,
|
||||
row_number() over (partition by c.person_id, c.date
|
||||
order by b.severity desc, b.report_date, b.date) as n
|
||||
from colposcopy as c
|
||||
join biopsy as b on b.person_id = c.person_id and b.date >= c.date
|
||||
where b.histology is not null and b.report_date is not null
|
||||
and {{ days_between('c.date', 'b.date') }} <= {{ p.horizons.colposcopy_to_biopsy }}
|
||||
),
|
||||
|
||||
procedures as (
|
||||
select 'biopsy' as type, person_id, date, recorded, report_date, histology,
|
||||
known_at, report_known_at
|
||||
from biopsy
|
||||
union all
|
||||
select 'colposcopy', c.person_id, c.date, null, a.report_date, a.histology,
|
||||
c.known_at, a.report_known_at
|
||||
from colposcopy as c
|
||||
left join answered as a on a.person_id = c.person_id and a.date = c.date and a.n = 1
|
||||
),
|
||||
|
||||
referred as (
|
||||
select
|
||||
x.type, x.person_id, x.date, c.sample_date,
|
||||
row_number() over (partition by x.type, x.person_id, x.date
|
||||
order by c.sample_date desc, c.report_date desc) as n
|
||||
from procedures as x
|
||||
join {{ ref('cervical_cytology') }} as c on c.person_id = x.person_id
|
||||
where c.result is not null and coalesce(c.adequacy, '') <> 'unsatisfactory'
|
||||
and c.sample_date < x.date and c.report_date < x.date
|
||||
and {{ days_between('c.report_date', 'x.date') }} <= {{ p.cytology_before_days }}
|
||||
)
|
||||
|
||||
select
|
||||
{{ dbt.concat(['x.person_id', "'|'", 'cast(x.date as ' ~ dbt.type_string() ~ ')']) }} as procedure_id,
|
||||
x.type, x.person_id, x.date,
|
||||
coalesce(x.recorded, r.sample_date) as sample_date,
|
||||
case when x.recorded is not null then 'recorded'
|
||||
when r.sample_date is not null then 'inferred' end as link,
|
||||
x.report_date, x.histology, x.known_at, x.report_known_at
|
||||
from procedures as x
|
||||
left join referred as r
|
||||
on r.type = x.type and r.person_id = x.person_id and r.date = x.date and r.n = 1
|
||||
@@ -2,8 +2,8 @@
|
||||
BIOPSY_SEVERITY, from 1; -1 a report without a grade, 0 a grade outside it). #}
|
||||
{% set p = var('cacu') %}
|
||||
select
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.cytology_sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.request_date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
|
||||
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
|
||||
b.report_date, b.histology, b.known_at,
|
||||
case
|
||||
when b.histology is null then -1
|
||||
@@ -12,5 +12,5 @@ select
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as severity
|
||||
from {{ ref('cervical_biopsy') }} as b
|
||||
where b.cytology_sample_date is not null
|
||||
from {{ ref('cacu_procedures') }} as b
|
||||
where b.type = 'biopsy' and b.sample_date is not null
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
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
|
||||
@@ -29,13 +30,23 @@ events as (select * from {{ ref('cacu_events') }}),
|
||||
biopsy as (
|
||||
select s.sample_id, min(b.report_date) as date
|
||||
from sample as s
|
||||
join {{ ref('cervical_biopsy') }} as b
|
||||
on b.person_id = s.person_id and b.cytology_sample_date = s.sample_date
|
||||
join {{ ref('cacu_procedures') }} as b
|
||||
on b.type = 'biopsy' and b.person_id = s.person_id and b.sample_date = s.sample_date
|
||||
where b.report_date > s.sample_date
|
||||
and {{ days_between('s.sample_date', 'b.report_date') }} < {{ h.sample_to_biopsy }}
|
||||
group by s.sample_id
|
||||
),
|
||||
|
||||
diagnosis_code as ( -- the ICD-10 of the note that dates the diagnosis
|
||||
select d.sample_id, count(distinct n.value_code) as codes, min(n.value_code) as code
|
||||
from diagnosis as d
|
||||
join sample as s on s.sample_id = d.sample_id
|
||||
join events as e on e.person_id = s.person_id and e.type = 'diagnosis' and e.date = d.date
|
||||
join events as n on n.person_id = e.person_id and n.type = 'note' and n.date = e.date
|
||||
and n.source_id = e.source_id
|
||||
group by d.sample_id
|
||||
),
|
||||
|
||||
diagnosis_treatment as (
|
||||
select d.sample_id, min(e.date) as date
|
||||
from diagnosis as d
|
||||
@@ -62,6 +73,7 @@ select
|
||||
f.first_colposcopy,
|
||||
{{ days_between('s.sample_date', 's.result_date') }} as days_sample_result,
|
||||
dx.date as diagnosis_date,
|
||||
case when dc.codes > 1 then 'several' else dc.code end as diagnosis_code,
|
||||
{{ days_between('s.sample_date', 'dx.date') }} as days_sample_diagnosis,
|
||||
tx.date as treatment_date,
|
||||
{{ days_between('s.sample_date', 'tx.date') }} as days_sample_treatment,
|
||||
@@ -83,6 +95,7 @@ select
|
||||
from sample as s
|
||||
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
|
||||
left join diagnosis as dx on dx.sample_id = s.sample_id
|
||||
left join diagnosis_code as dc on dc.sample_id = s.sample_id
|
||||
left join treatment as tx on tx.sample_id = s.sample_id
|
||||
left join diagnosis_treatment as dt on dt.sample_id = s.sample_id
|
||||
left join colposcopy as col on col.sample_id = s.sample_id
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
{#
|
||||
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.
|
||||
to none): what the measures that follow a mammogram to its biopsy count over. The biopsy is
|
||||
the one whose request names the mammogram (`cama_biopsies`); none is matched by dates.
|
||||
`days_report_biopsy`: days from the mammogram's report to the biopsy's report; empty when
|
||||
either date is missing, and when the biopsy was reported before the mammogram (inconsistent).
|
||||
#}
|
||||
select
|
||||
m.*,
|
||||
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
|
||||
b.report_known_at as biopsy_known_at
|
||||
b.report_known_at as biopsy_known_at,
|
||||
case
|
||||
when b.report_date >= m.report_date then {{ days_between('m.report_date', 'b.report_date') }}
|
||||
end as days_report_biopsy
|
||||
from {{ ref('cama_mammograms') }} as m
|
||||
left join {{ ref('cama_biopsies') }} as b
|
||||
on b.mammogram_id = m.mammogram_id and b.report_date is not null
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
-- depends_on: {{ ref('tea_eegs') }}
|
||||
{%- do ref('tea_eegs') %}
|
||||
{#
|
||||
One row per EEG metric (the EEG job's `bronze.eeg_metrics`), with the age curve's score of
|
||||
its value (`bronze.eeg_scores`, when a curve in production scored it): what the EEG pages
|
||||
|
||||
@@ -66,11 +66,23 @@ READS = {
|
||||
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
|
||||
# What followed each sample by the cut-off (gold): her colposcopy, her biopsy (its first
|
||||
# request, and its report) and her diagnosis, with the days to it.
|
||||
"route": """
|
||||
select s.person_id, s.sample_date,
|
||||
case when s.history = 0 and s.diagnosis_date <= :cutoff
|
||||
then s.days_sample_diagnosis end as days,
|
||||
case when s.diagnosis_date <= :cutoff then s.diagnosis_date end as diagnosis,
|
||||
case when s.colposcopy_date <= :cutoff then s.colposcopy_date end as colposcopy,
|
||||
case when s.biopsy_date <= :cutoff then s.biopsy_date end as biopsy,
|
||||
b.requested, b.link
|
||||
from gold.cacu_samples as s
|
||||
left join (select person_id, sample_date, min(date) as requested, min(link) as link
|
||||
from gold.cacu_procedures
|
||||
where type = 'biopsy' and date <= :cutoff and person_id in :persons
|
||||
group by person_id, sample_date) as b
|
||||
on b.person_id = s.person_id and b.sample_date = s.sample_date
|
||||
where s.person_id in :persons
|
||||
""",
|
||||
},
|
||||
"tea": {
|
||||
|
||||
@@ -13,6 +13,16 @@ READS = {
|
||||
from gold.cacu_samples as s
|
||||
left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id
|
||||
""",
|
||||
"procedures": """
|
||||
select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history,
|
||||
s.report_known_at as cytology_known_at,
|
||||
f.first_case, f.first_treatment, f.first_colposcopy
|
||||
from gold.cacu_procedures as p
|
||||
left join gold.cacu_samples as s
|
||||
on s.person_id = p.person_id and s.sample_date = p.sample_date
|
||||
left join gold.cacu_follow_up as f on f.person_id = p.person_id
|
||||
where p.type = :type
|
||||
""",
|
||||
"risk": """
|
||||
select c.person_id, coalesce(r.index_date, c.index_date) as index_date,
|
||||
r.probability, r.scored_at as known_at
|
||||
@@ -25,6 +35,15 @@ READS = {
|
||||
"mammograms": "select * from gold.cama_mammograms",
|
||||
"biopsies": "select * from gold.cama_biopsies where report_date is not null",
|
||||
"mammogram_biopsies": "select * from gold.cama_mammogram_biopsies",
|
||||
# One row per mammogram: its first reported biopsy (ties: the lowest id), or the row
|
||||
# with none. The biopsy is the one whose request names the mammogram.
|
||||
"mammogram_first_biopsy": """
|
||||
select * from (
|
||||
select *, row_number() over (
|
||||
partition by mammogram_id order by biopsy_report_date, biopsy_id) as nth
|
||||
from gold.cama_mammogram_biopsies
|
||||
) as x where nth = 1
|
||||
""",
|
||||
},
|
||||
"tea": {
|
||||
"screening": "select * from gold.tea_screening",
|
||||
|
||||
+1
-1
Submodule WebApi updated: 88b22b9491...fee6a6622d
+1
-1
Submodule WebApp updated: ca887c29ab...749afe765d
+1
-1
@@ -67,7 +67,7 @@ services:
|
||||
|
||||
api:
|
||||
<<: *python
|
||||
command: fastapi run WebApi/webapi/main.py --host 0.0.0.0 --port 8000 --workers ${API_WORKERS:-4}
|
||||
command: uvicorn webapi.main:app --host 0.0.0.0 --port 8000 --workers ${API_WORKERS:-4} --timeout-worker-healthcheck 600
|
||||
ports: ["${BIND_ADDRESS:-127.0.0.1}:${API_PORT:-5711}:8000"]
|
||||
depends_on:
|
||||
dagster-webserver: { condition: service_healthy }
|
||||
|
||||
@@ -169,6 +169,7 @@ CONCEPT_MAPS = ROOT / "tests" / "fixtures" / "concept_maps"
|
||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
||||
WOMEN = 50 # the site's patients in tests (the dev deployment has a thousand)
|
||||
SYNTHEA_DAY = "20261124" # its simulation ends here: the same patients whatever day a test runs
|
||||
CHILDREN = 20 # and the children its TEA program saw
|
||||
|
||||
|
||||
@@ -180,6 +181,7 @@ def synthea(
|
||||
last eight years."""
|
||||
subprocess.run(
|
||||
["java", "-jar", SYNTHEA, "-p", str(people), "-s", str(seed), "-cs", str(seed),
|
||||
"-r", SYNTHEA_DAY, "-e", SYNTHEA_DAY,
|
||||
*(("-g", sex) if sex else ()), "-a", ages, "-d", str(MODULES), "-m", modules,
|
||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
||||
"--exporter.hospital.fhir.export", "false",
|
||||
|
||||
+9
-8
@@ -5,11 +5,11 @@
|
||||
COMPOSE_PROJECT_NAME=isssteleon
|
||||
|
||||
# Versión instalada (la escribe `isssteleon.sh instalar` y `actualizar`).
|
||||
ISSSTELEON_VERSION=
|
||||
ISSSTELEON_VERSION=1.0.0
|
||||
|
||||
# Dirección de la red interna donde escucha la plataforma (por ejemplo la de la VPN).
|
||||
# Obligatoria: la API responde sin sesión, así que solo debe verse desde la red interna.
|
||||
BIND_ADDRESS=
|
||||
BIND_ADDRESS=192.168.1.10
|
||||
|
||||
# Carpetas del servidor: los datos de la plataforma y sus respaldos (de preferencia en
|
||||
# otro disco).
|
||||
@@ -22,14 +22,15 @@ API_PORT=5711
|
||||
DAGSTER_PORT=5712
|
||||
MLFLOW_PORT=5713
|
||||
|
||||
# Primer administrador de las páginas (se crea al iniciar si no existe).
|
||||
AUTH_ADMIN_EMAIL=
|
||||
AUTH_ADMIN_PASSWORD=
|
||||
# Primer administrador de las páginas (se crea una vez, al iniciar). La contraseña es de
|
||||
# ejemplo: cámbiela antes de instalar.
|
||||
AUTH_ADMIN_EMAIL=admin@isssteleon.mx
|
||||
AUTH_ADMIN_PASSWORD=Isssteleon-Ejemplo-2026
|
||||
|
||||
# Respaldos: cuántos se conservan y cuándo se hacen (cron, hora UTC; vacío: ninguno
|
||||
# automático).
|
||||
# Respaldos: cuántos se conservan y cuándo se hacen (cron, hora UTC: 08:30 son las
|
||||
# 02:30 en Monterrey; vacío: ninguno automático).
|
||||
BACKUP_KEEP=14
|
||||
BACKUP_SCHEDULE="30 2 * * *"
|
||||
BACKUP_SCHEDULE="30 8 * * *"
|
||||
|
||||
# Informes que exige la promoción de un modelo (vacío: los tres, con la validación clínica).
|
||||
PROMOTION_REPORTS=
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ services:
|
||||
|
||||
api:
|
||||
<<: *python
|
||||
command: fastapi run WebApi/webapi/main.py --host 0.0.0.0 --port 8000 --workers ${API_WORKERS:-4}
|
||||
command: uvicorn webapi.main:app --host 0.0.0.0 --port 8000 --workers ${API_WORKERS:-4} --timeout-worker-healthcheck 600
|
||||
ports: ["${BIND_ADDRESS}:${API_PORT:-5711}:8000"]
|
||||
depends_on:
|
||||
dagster-webserver: { condition: service_healthy }
|
||||
|
||||
+29
-20
@@ -1,8 +1,8 @@
|
||||
#!/bin/sh
|
||||
# ISSSTELEON: instalar y operar una versión entregada (el paquete de `entregar.sh`).
|
||||
# ISSSTELEON: instalar y operar una versión, desde el paquete de `entregar.sh` o desde el código.
|
||||
#
|
||||
# ./isssteleon.sh instalar carga las imágenes de este paquete y arranca
|
||||
# ./isssteleon.sh actualizar respalda, carga las imágenes de este paquete y arranca
|
||||
# ./isssteleon.sh instalar carga las imágenes (del paquete o ya construidas) y arranca
|
||||
# ./isssteleon.sh actualizar respalda, carga las imágenes nuevas y arranca
|
||||
# ./isssteleon.sh detener detiene la plataforma (los datos quedan)
|
||||
# ./isssteleon.sh estado qué corre, si la API responde, el último respaldo
|
||||
# ./isssteleon.sh respaldar un respaldo ahora, en ISSSTELEON_RESPALDOS
|
||||
@@ -36,25 +36,34 @@ leer_env() {
|
||||
esac
|
||||
}
|
||||
|
||||
# La versión de este paquete, escrita en .env.
|
||||
fijar_version() {
|
||||
version="$(cat VERSION)"
|
||||
if grep -q '^ISSSTELEON_VERSION=' .env; then
|
||||
sed -i "s/^ISSSTELEON_VERSION=.*/ISSSTELEON_VERSION=$version/" .env
|
||||
# Un paquete trae sus imágenes (imagenes/) y su versión (VERSION); desde el código fuente, las
|
||||
# imágenes se construyen en este equipo y la versión es ISSSTELEON_VERSION de .env.
|
||||
cargar_imagenes() {
|
||||
if [ -d imagenes ]; then
|
||||
aviso "Verificando las imágenes"
|
||||
( cd imagenes && sha256sum -c --quiet SHA256SUMS ) || error "Una imagen está dañada: vuelva a copiar el paquete."
|
||||
for archivo in imagenes/*.tar.gz; do
|
||||
aviso "Cargando $(basename "$archivo")"
|
||||
gunzip -c "$archivo" | docker load >/dev/null
|
||||
done
|
||||
fijar_version "$(cat VERSION)"
|
||||
else
|
||||
echo "ISSSTELEON_VERSION=$version" >> .env
|
||||
[ -n "${ISSSTELEON_VERSION:-}" ] || error "ISSSTELEON_VERSION está vacío en .env: indique la versión construida."
|
||||
for imagen in app web; do
|
||||
docker image inspect "isssteleon/$imagen:$ISSSTELEON_VERSION" >/dev/null 2>&1 \
|
||||
|| error "No existe la imagen isssteleon/$imagen:$ISSSTELEON_VERSION: constrúyala (vea README.md)."
|
||||
done
|
||||
aviso "Imágenes construidas en este equipo, versión $ISSSTELEON_VERSION"
|
||||
fi
|
||||
ISSSTELEON_VERSION="$version"
|
||||
}
|
||||
|
||||
cargar_imagenes() {
|
||||
[ -d imagenes ] || error "Este paquete no trae imágenes (carpeta imagenes/)."
|
||||
aviso "Verificando las imágenes"
|
||||
( cd imagenes && sha256sum -c --quiet SHA256SUMS ) || error "Una imagen está dañada: vuelva a copiar el paquete."
|
||||
for archivo in imagenes/*.tar.gz; do
|
||||
aviso "Cargando $(basename "$archivo")"
|
||||
gunzip -c "$archivo" | docker load >/dev/null
|
||||
done
|
||||
fijar_version() {
|
||||
if grep -q '^ISSSTELEON_VERSION=' .env; then
|
||||
sed -i "s/^ISSSTELEON_VERSION=.*/ISSSTELEON_VERSION=$1/" .env
|
||||
else
|
||||
echo "ISSSTELEON_VERSION=$1" >> .env
|
||||
fi
|
||||
ISSSTELEON_VERSION="$1"
|
||||
}
|
||||
|
||||
esperar_api() {
|
||||
@@ -70,7 +79,7 @@ esperar_api() {
|
||||
cmd_instalar() {
|
||||
requisitos; leer_env
|
||||
mkdir -p "$ISSSTELEON_DATOS" "$ISSSTELEON_RESPALDOS"
|
||||
cargar_imagenes; fijar_version
|
||||
cargar_imagenes
|
||||
compose up -d
|
||||
esperar_api
|
||||
}
|
||||
@@ -82,7 +91,7 @@ cmd_actualizar() {
|
||||
else
|
||||
aviso "La plataforma no está corriendo: se actualiza sin respaldo previo."
|
||||
fi
|
||||
cargar_imagenes; fijar_version
|
||||
cargar_imagenes
|
||||
compose up -d
|
||||
esperar_api
|
||||
}
|
||||
|
||||
+1
-1
Submodule models updated: 3a749ba8d1...1a1ea5c7a9
@@ -0,0 +1,78 @@
|
||||
"""What the cytology form records beside its result, and a made-up answer to it."""
|
||||
|
||||
import random
|
||||
|
||||
# The cytology form's boxes 2 to 5 (field -> code -> as printed) and the cytologist's findings.
|
||||
BOXES = {
|
||||
"screening_history": {
|
||||
"never": "PRIMERA VEZ EN LA VIDA",
|
||||
"within_1_year": "UN AÑO O MENOS",
|
||||
"2_years": "2 AÑOS",
|
||||
"3_or_more_years": "3 O MÁS AÑOS",
|
||||
},
|
||||
"gynecologic_condition": {
|
||||
"postpartum": "PUERPERIO POSTPARTO O POSTABORTO",
|
||||
"pregnant": "EMBARAZO ACTUAL",
|
||||
"iud": "DIU IN SITU",
|
||||
"hormonal_treatment": "TRATAMIENTO HORMONAL",
|
||||
"other_treatment": "OTRO TRATAMIENTO GINECOLÓGICO",
|
||||
"postmenopausal": "POST MENOPAUSIA",
|
||||
"hysterectomy": "HISTERECTOMÍA",
|
||||
"not_applicable": "NO APLICA",
|
||||
},
|
||||
"presenting_symptom": {
|
||||
"discharge": "FLUJO",
|
||||
"vulvar_itching": "PRURITO O ARDOR VULVAR",
|
||||
"abnormal_bleeding": "SANGRADO ANORMAL",
|
||||
"none": "NINGUNO",
|
||||
},
|
||||
"cervix_appearance": {
|
||||
"healthy": "CUELLO SANO",
|
||||
"lesion": "CUELLO ANORMAL CON LESIÓN",
|
||||
"not_seen": "NO SE OBSERVA CUELLO",
|
||||
},
|
||||
}
|
||||
CYTOLOGY_FINDINGS = {
|
||||
"finding_inflammation": "Inflamación",
|
||||
"finding_reactive": "Cambios reactivos",
|
||||
"finding_vaginosis": "Cambio en la flora sugestiva de vaginosis bacteriana",
|
||||
"finding_candida": "Microorganismos micóticos morfológicamente compatibles con Candida sp",
|
||||
"finding_bacillary_cytolysis": (
|
||||
"Aumento de la flora bacilar con citólisis de las células intermedias"
|
||||
),
|
||||
"finding_cytolysis": "Citólisis de las células intermedias",
|
||||
"finding_trichomonas": "Trichomonas vaginalis",
|
||||
"finding_leptothrix": "Microorganismos bacterianos morfológicamente compatibles con Leptothrix",
|
||||
"finding_actinomyces": "Microorganismos morfológicamente compatibles con Actinomyces sp",
|
||||
"finding_actinomyces_changes": "Cambios celulares compatibles con Actinomyces sp",
|
||||
"finding_herpes_changes": "Cambios celulares compatibles con virus herpes simple",
|
||||
"finding_tubular_metaplasia": "Metaplasia escamosa tubular",
|
||||
"finding_keratotic": "Cambios queratósicos",
|
||||
"finding_pregnancy": "Cambios asociados al embarazo",
|
||||
"finding_atrophy": "Atrofia",
|
||||
"finding_hypoestrogenism": "Hipoestrogenismo",
|
||||
"finding_radiotherapy": "Efecto de radioterapia",
|
||||
"finding_iud_changes": "Cambios compatibles con presencia de dispositivo intrauterino",
|
||||
"finding_glandular_cells": "Células glandulares post-histerectomía",
|
||||
"finding_bacteria": "Bacterias",
|
||||
"finding_herpes_image": "Imagen del virus del herpes",
|
||||
"finding_fungi": "Hongos",
|
||||
"finding_radiation": "Radiación",
|
||||
"finding_repair": "Reparación",
|
||||
"finding_iud_effect": "Efecto del DIU",
|
||||
"finding_endometrial_cells": "Presencia de células endometriales en pacientes de 40 años o más",
|
||||
"finding_none": "Ninguno",
|
||||
}
|
||||
|
||||
|
||||
def answers(rng: random.Random) -> tuple[dict, dict]:
|
||||
"""The fields the form answers, and each box as printed; one or two findings, or none."""
|
||||
found = rng.sample(list(CYTOLOGY_FINDINGS)[:-1], rng.choice((0, 1, 1, 2)))
|
||||
found = found or ["finding_none"] * rng.choice((0, 1))
|
||||
if sum(len(CYTOLOGY_FINDINGS[f]) for f in found) > 95: # what fits one line of the form
|
||||
found = found[:1]
|
||||
boxes = {field: rng.choice(list(codes)) for field, codes in BOXES.items()}
|
||||
printed = {field: BOXES[field][code] for field, code in boxes.items()}
|
||||
printed["findings"] = " ".join(f"{CYTOLOGY_FINDINGS[f]}." for f in found)
|
||||
stated = {"findings": printed["findings"]} if found else {}
|
||||
return {**boxes, **stated, **dict.fromkeys(found, True)}, printed
|
||||
@@ -61,7 +61,7 @@ def cytology_form(p: dict, c: dict) -> bytes:
|
||||
p: full_name, employee, agency, age, birth_date (date), phone.
|
||||
c: requested (date), received (date), interpreted (date), detection, conditions,
|
||||
presents, explores, nurse, adequacy, lesion (POSITIVO/NEGATIVO), epithelial (SI/NO),
|
||||
squamous, invasive (SI/NO), glandular, observations, reader, reader_id."""
|
||||
squamous, invasive (SI/NO), glandular, findings, observations, reader, reader_id."""
|
||||
pdf = _pdf()
|
||||
pdf.set_font("helvetica", "B", 15)
|
||||
pdf.set_text_color(*GREEN)
|
||||
@@ -110,6 +110,8 @@ def cytology_form(p: dict, c: dict) -> bytes:
|
||||
_box(pdf, 50, y, 256, 36, left, lv)
|
||||
_box(pdf, 306, y, 256, 36, right, rv)
|
||||
y += 36
|
||||
_box(pdf, 50, y, 512, 36, "16.- HALLAZGOS ADICIONALES:", c["findings"])
|
||||
y += 36
|
||||
_box(pdf, 50, y, 512, 70, value="Observaciones: " + c["observations"], size=7.5)
|
||||
|
||||
pdf.set_font("helvetica", "", 8.5)
|
||||
@@ -199,6 +201,7 @@ def pathology_report(p: dict, b: dict) -> bytes:
|
||||
|
||||
p: surname_first (name as the report prints it), age, sex (F/M).
|
||||
b: requested (date), reported (date), time (HH:MM), physician, number (P-25-000000),
|
||||
mammogram (date of the mammogram it came from, when the request names it),
|
||||
clinical (clinical diagnosis), specimen, macroscopic, organ, diagnosis, pathologist,
|
||||
pathologist_id."""
|
||||
pdf = _pdf()
|
||||
@@ -228,9 +231,10 @@ def pathology_report(p: dict, b: dict) -> bytes:
|
||||
pdf.line(40, 208, 572, 208)
|
||||
pdf.set_font("helvetica", "", 8)
|
||||
pdf.set_xy(40, 218)
|
||||
summary = f"MASTOGRAFÍA DEL {_dmy(b['mammogram'])}" if b.get("mammogram") else "no referido"
|
||||
pdf.multi_cell(
|
||||
532, 10,
|
||||
"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: no referido. "
|
||||
f"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: {summary}. "
|
||||
f"Diagnóstico Clínico: {b['clinical']}.\n\nEspecimen\n1 - {b['specimen']}\n"
|
||||
f"Descripción Macroscópica:\n{b['macroscopic']}\n\nSe incluye total del especimen en "
|
||||
"un cassette.\n\nNo estudios previos",
|
||||
|
||||
@@ -32,7 +32,7 @@ import sqlalchemy as sa
|
||||
|
||||
from core import catalog, fhir_in
|
||||
from core.tea import RESTRICTED_REPETITIVE_ITEMS, SOCIAL_AFFECT_ITEMS
|
||||
from synthetic import erick, pdfs
|
||||
from synthetic import cytology_form, erick, pdfs
|
||||
|
||||
STUDIES = (
|
||||
"cervical_cytology",
|
||||
@@ -356,9 +356,36 @@ CAUSE = {"cervical": ("TUMOR MALIGNO DEL CUELLO DEL ÚTERO", "C53.9"),
|
||||
None: ("INFARTO AGUDO DEL MIOCARDIO", "I21.9")} # fmt: skip
|
||||
|
||||
|
||||
def mammogram_of_biopsies(bundle: dict) -> dict[str, str]:
|
||||
"""The exam date of the mammogram each breast biopsy came from, by the biopsy's request
|
||||
date. Synthea keeps one encounter open from a mammogram to the biopsy it leads to, so a
|
||||
biopsy report and its mammogram's report name the same encounter: that is the source's own
|
||||
link. An encounter with no mammogram, or with two, names none (nothing is inferred)."""
|
||||
by_encounter: dict[str, dict[str, list[str]]] = {}
|
||||
for entry in bundle["entry"]:
|
||||
r = entry["resource"]
|
||||
code = (r.get("code") or {}).get("coding", [{}])[0].get("code")
|
||||
encounter = (r.get("encounter") or {}).get("reference")
|
||||
if r["resourceType"] == "DiagnosticReport" and encounter and code in STUDY_LINK:
|
||||
by_encounter.setdefault(encounter, {}).setdefault(code, []).append(
|
||||
r["effectiveDateTime"][:10]
|
||||
)
|
||||
found: dict[str, set[str]] = {}
|
||||
for studies in by_encounter.values():
|
||||
exams = set(studies.get("mammography", []))
|
||||
if len(studies.get("mammography", [])) == 1:
|
||||
for requested in studies.get("breast_biopsy", []):
|
||||
found.setdefault(requested, set()).update(exams)
|
||||
return {requested: exams.pop() for requested, exams in found.items() if len(exams) == 1}
|
||||
|
||||
|
||||
STUDY_LINK = ("mammography", "breast_biopsy")
|
||||
|
||||
|
||||
def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
|
||||
"""Each Synthea patient's birth date, and her studies as platform rows (core.fhir_in):
|
||||
a biopsy Synthea sent as several same-day reports is one study."""
|
||||
a biopsy Synthea sent as several same-day reports is one study, which names the
|
||||
mammogram it came from (`mammogram_exam_date`) when the source does."""
|
||||
people = {}
|
||||
for bundle in bundles:
|
||||
patient = next(
|
||||
@@ -373,7 +400,11 @@ def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
|
||||
merged.setdefault(r["request_date"], {}).update(
|
||||
{k: v for k, v in r.items() if v is not None}
|
||||
)
|
||||
rows = list(merged.values())
|
||||
origin = mammogram_of_biopsies(bundle)
|
||||
rows = [
|
||||
{**r, "mammogram_exam_date": origin[requested]} if requested in origin else r
|
||||
for requested, r in merged.items()
|
||||
]
|
||||
studies[entity] = [{k: v for k, v in r.items() if not k.startswith("_")} for r in rows]
|
||||
if any(studies.values()):
|
||||
people[patient["id"]] = {"birth_date": _d(patient["birthDate"]), "studies": studies,
|
||||
@@ -519,6 +550,7 @@ def build(
|
||||
people = {k: p for k, p in people.items() if any(p["studies"].values())}
|
||||
ids = sorted(people)
|
||||
names = _names(ids, random.Random(f"{seed}-names"), {i: people[i]["sex"] for i in ids})
|
||||
form_rng = random.Random(f"{seed}-form")
|
||||
# Namesakes: the woman with the most pathology reports (a scan can misread the name on
|
||||
# any one of them) takes the name of a woman with none, so a report fits both.
|
||||
reports = {
|
||||
@@ -602,14 +634,15 @@ def build(
|
||||
person, identity = _institute(p, taken, rng, i in sloppy)
|
||||
result = r.get("result")
|
||||
satisfactory = r.get("adequacy") == "satisfactory"
|
||||
answered, printed = cytology_form.answers(form_rng)
|
||||
form = { # dated as the real forms are: FECHA is filled in days after reception
|
||||
"requested": max(taken, reported - timedelta(days=rng.randint(2, 6))),
|
||||
"received": taken,
|
||||
"interpreted": reported,
|
||||
"detection": rng.choice(("PRIMERA VEZ", "SUBSECUENTE")),
|
||||
"conditions": rng.choice(("NINGUNA", "USO DE DIU", "POSTMENOPAUSIA")),
|
||||
"presents": rng.choice(("ASINTOMÁTICA", "FLUJO TRANSVAGINAL")),
|
||||
"explores": rng.choice(("CÉRVIX DE ASPECTO NORMAL", "ECTROPIÓN")),
|
||||
"detection": printed["screening_history"],
|
||||
"conditions": printed["gynecologic_condition"],
|
||||
"presents": printed["presenting_symptom"],
|
||||
"explores": printed["cervix_appearance"],
|
||||
"nurse": rng.choice(NURSES),
|
||||
"adequacy": "SATISFACTORIO" if satisfactory else "INSATISFACTORIO",
|
||||
"lesion": "" if not result else "NEGATIVO" if result == "NILM" else "POSITIVO",
|
||||
@@ -617,6 +650,7 @@ def build(
|
||||
"squamous": SQUAMOUS.get(result, ""),
|
||||
"invasive": "NO" if result else "",
|
||||
"glandular": "NINGUNA" if result else "",
|
||||
"findings": printed["findings"],
|
||||
"observations": "MUESTRA INSUFICIENTE, SE SOLICITA NUEVA TOMA."
|
||||
if not satisfactory
|
||||
else "Negativo para lesión intraepitelial o malignidad."
|
||||
@@ -630,6 +664,7 @@ def build(
|
||||
"report_date": str(reported),
|
||||
"adequacy": r.get("adequacy"),
|
||||
"result": result,
|
||||
**answered,
|
||||
}
|
||||
scanned = rng.random() < 0.1
|
||||
blob = erick.cytology_form(person, form)
|
||||
@@ -733,6 +768,9 @@ def build(
|
||||
)
|
||||
}
|
||||
values = {k: v for k, v in values.items() if v is not None}
|
||||
if r.get("mammogram_exam_date"): # the request names its mammogram
|
||||
report["mammogram"] = _d(r["mammogram_exam_date"])
|
||||
values["mammogram_exam_date"] = r["mammogram_exam_date"]
|
||||
side = rng.choice(("IZQUIERDA", "DERECHA"))
|
||||
if r["histology"] == "benign":
|
||||
lines = [
|
||||
|
||||
+591
@@ -224,6 +224,348 @@
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "INFLAMACIÓN",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "INFLAMACION",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS REACTIVOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIO EN LA FLORA SUGESTIVA DE VAGINOSIS BACTERIANA",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS MICÓTICOS MORFOLÓGICAMENTE COMPATIBLES CON CANDIDA SP",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS MICOTICOS MORFOLOGICAMENTE COMPATIBLES CON CANDIDA SP",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "AUMENTO DE LA FLORA BACILAR CON CITÓLISIS DE LAS CÉLULAS INTERMEDIAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "AUMENTO DE LA FLORA BACILAR CON CITOLISIS DE LAS CELULAS INTERMEDIAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CITÓLISIS DE LAS CÉLULAS INTERMEDIAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CITOLISIS DE LAS CELULAS INTERMEDIAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "TRICHOMONAS VAGINALIS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS BACTERIANOS MORFOLÓGICAMENTE COMPATIBLES CON LEPTOTHRIX",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS BACTERIANOS MORFOLOGICAMENTE COMPATIBLES CON LEPTOTHRIX",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS MORFOLÓGICAMENTE COMPATIBLES CON ACTINOMYCES SP",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "MICROORGANISMOS MORFOLOGICAMENTE COMPATIBLES CON ACTINOMYCES SP",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS CELULARES COMPATIBLES CON ACTINOMYCES SP",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS CELULARES COMPATIBLES CON VIRUS HERPES SIMPLE",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "METAPLASIA ESCAMOSA TUBULAR",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS QUERATÓSICOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS QUERATOSICOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS ASOCIADOS AL EMBARAZO",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "ATROFIA",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "HIPOESTROGENISMO",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "EFECTO DE RADIOTERAPIA",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CAMBIOS COMPATIBLES CON PRESENCIA DE DISPOSITIVO INTRAUTERINO",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CÉLULAS GLANDULARES POST-HISTERECTOMÍA",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CELULAS GLANDULARES POST-HISTERECTOMIA",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "BACTERIAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "IMAGEN DEL VIRUS DEL HERPES",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "HONGOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "RADIACIÓN",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "RADIACION",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "REPARACIÓN",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "REPARACION",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "EFECTO DEL DIU",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "PRESENCIA DE CÉLULAS ENDOMETRIALES EN PACIENTES DE 40 AÑOS O MÁS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN PACIENTES DE 40 ANOS O MAS",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NINGUNO",
|
||||
"target": [
|
||||
{
|
||||
"code": "true",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1831,6 +2173,255 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "urn:isssteleon:site:erick_site",
|
||||
"target": "https://isssteleon.org/fhir/CodeSystem/cervical-screening-history",
|
||||
"element": [
|
||||
{
|
||||
"code": "PRIMERA VEZ EN LA VIDA",
|
||||
"target": [
|
||||
{
|
||||
"code": "never",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UN AÑO O MENOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "within_1_year",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UN ANO O MENOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "within_1_year",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "2 AÑOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "2_years",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "2 ANOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "2_years",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "3 O MÁS AÑOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "3_or_more_years",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "3 O MAS ANOS",
|
||||
"target": [
|
||||
{
|
||||
"code": "3_or_more_years",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "urn:isssteleon:site:erick_site",
|
||||
"target": "https://isssteleon.org/fhir/CodeSystem/gynecologic-condition",
|
||||
"element": [
|
||||
{
|
||||
"code": "PUERPERIO POSTPARTO O POSTABORTO",
|
||||
"target": [
|
||||
{
|
||||
"code": "postpartum",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "EMBARAZO ACTUAL",
|
||||
"target": [
|
||||
{
|
||||
"code": "pregnant",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "DIU IN SITU",
|
||||
"target": [
|
||||
{
|
||||
"code": "iud",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "TRATAMIENTO HORMONAL",
|
||||
"target": [
|
||||
{
|
||||
"code": "hormonal_treatment",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "OTRO TRATAMIENTO GINECOLÓGICO",
|
||||
"target": [
|
||||
{
|
||||
"code": "other_treatment",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "OTRO TRATAMIENTO GINECOLOGICO",
|
||||
"target": [
|
||||
{
|
||||
"code": "other_treatment",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "POST MENOPAUSIA",
|
||||
"target": [
|
||||
{
|
||||
"code": "postmenopausal",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "HISTERECTOMÍA",
|
||||
"target": [
|
||||
{
|
||||
"code": "hysterectomy",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "HISTERECTOMIA",
|
||||
"target": [
|
||||
{
|
||||
"code": "hysterectomy",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NO APLICA",
|
||||
"target": [
|
||||
{
|
||||
"code": "not_applicable",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "urn:isssteleon:site:erick_site",
|
||||
"target": "https://isssteleon.org/fhir/CodeSystem/presenting-symptom",
|
||||
"element": [
|
||||
{
|
||||
"code": "FLUJO",
|
||||
"target": [
|
||||
{
|
||||
"code": "discharge",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "PRURITO O ARDOR VULVAR",
|
||||
"target": [
|
||||
{
|
||||
"code": "vulvar_itching",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "SANGRADO ANORMAL",
|
||||
"target": [
|
||||
{
|
||||
"code": "abnormal_bleeding",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NINGUNO",
|
||||
"target": [
|
||||
{
|
||||
"code": "none",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "urn:isssteleon:site:erick_site",
|
||||
"target": "https://isssteleon.org/fhir/CodeSystem/cervix-appearance",
|
||||
"element": [
|
||||
{
|
||||
"code": "CUELLO SANO",
|
||||
"target": [
|
||||
{
|
||||
"code": "healthy",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CUELLO ANORMAL CON LESIÓN",
|
||||
"target": [
|
||||
{
|
||||
"code": "lesion",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CUELLO ANORMAL CON LESION",
|
||||
"target": [
|
||||
{
|
||||
"code": "lesion",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "NO SE OBSERVA CUELLO",
|
||||
"target": [
|
||||
{
|
||||
"code": "not_seen",
|
||||
"equivalence": "equivalent"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+35
-2
@@ -59,7 +59,39 @@
|
||||
"sample_date": "fecha de recepci[oó]n:[\\s—–-]*(\\d{2}/\\d{2}/\\d{4})",
|
||||
"report_date": "interpretaci[oó]n:[\\s\\S]{0,80}?(\\d{2}/\\d{2}/\\d{4})",
|
||||
"adequacy": "\\b(insatisfactorio|satisfactorio)\\b",
|
||||
"result": "\\b(negativo|asc-us|asc-h|lesi[oó]n (?:intraepitelial escamosa )?de bajo grado|lesi[oó]n (?:intraepitelial escamosa )?de alto grado|carcinoma in situ)\\b"},
|
||||
"result": "\\b(negativo|asc-us|asc-h|lesi[oó]n (?:intraepitelial escamosa )?de bajo grado|lesi[oó]n (?:intraepitelial escamosa )?de alto grado|carcinoma in situ)\\b",
|
||||
"screening_history": "detecci[oó]n de c[aá]ncer de c[eé]rvix[\\s\\S]{0,110}?\\b(primera\\s+vez\\s+en\\s+la\\s+vida|3\\s+o\\s+m[áa]s\\s+a[ñn]os|un\\s+a[ñn]o\\s+o\\s+menos|2\\s+a[ñn]os)\\b",
|
||||
"gynecologic_condition": "condiciones gineco-?obst[eé]tricas[\\s\\S]{0,110}?\\b(puerperio\\s+postparto\\s+o\\s+postaborto|otro\\s+tratamiento\\s+ginecol[óo]gico|tratamiento\\s+hormonal|embarazo\\s+actual|post\\s+menopausia|histerectom[íi]a|diu\\s+in\\s+situ|no\\s+aplica)\\b",
|
||||
"presenting_symptom": "actualmente presenta[\\s\\S]{0,110}?\\b(prurito\\s+o\\s+ardor\\s+vulvar|sangrado\\s+anormal|ninguno|flujo)\\b",
|
||||
"cervix_appearance": "a la exploraci[oó]n se observa[\\s\\S]{0,110}?\\b(cuello\\s+anormal\\s+con\\s+lesi[óo]n|no\\s+se\\s+observa\\s+cuello|cuello\\s+sano)\\b",
|
||||
"findings": "hallazgos adicionales:\\s*(?!observaciones)([^\\n]+)",
|
||||
"finding_inflammation": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(inflamaci[óo]n)(?:\\s+(?:leve|moderada|severa))?\\s*[.;]",
|
||||
"finding_reactive": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+reactivos)\\s*[.;]",
|
||||
"finding_vaginosis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambio\\s+en\\s+la\\s+flora\\s+sugestiva\\s+de\\s+vaginosis\\s+bacteriana)\\s*[.;]",
|
||||
"finding_candida": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+mic[óo]ticos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+candida\\s+sp)\\s*[.;]",
|
||||
"finding_bacillary_cytolysis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(aumento\\s+de\\s+la\\s+flora\\s+bacilar\\s+con\\s+cit[óo]lisis\\s+de\\s+las\\s+c[ée]lulas\\s+intermedias)\\s*[.;]",
|
||||
"finding_cytolysis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cit[óo]lisis\\s+de\\s+las\\s+c[ée]lulas\\s+intermedias)\\s*[.;]",
|
||||
"finding_trichomonas": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(trichomonas\\s+vaginalis)\\s*[.;]",
|
||||
"finding_leptothrix": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+bacterianos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+leptothrix)\\s*[.;]",
|
||||
"finding_actinomyces": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+actinomyces\\s+sp)\\s*[.;]",
|
||||
"finding_actinomyces_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+actinomyces\\s+sp)\\s*[.;]",
|
||||
"finding_herpes_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+virus\\s+herpes\\s+simple)\\s*[.;]",
|
||||
"finding_tubular_metaplasia": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(metaplasia\\s+escamosa\\s+tubular)\\s*[.;]",
|
||||
"finding_keratotic": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+querat[óo]sicos)\\s*[.;]",
|
||||
"finding_pregnancy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+asociados\\s+al\\s+embarazo)\\s*[.;]",
|
||||
"finding_atrophy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(atrofia)\\s*[.;]",
|
||||
"finding_hypoestrogenism": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(hipoestrogenismo)\\s*[.;]",
|
||||
"finding_radiotherapy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(efecto\\s+de\\s+radioterapia)\\s*[.;]",
|
||||
"finding_iud_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+compatibles\\s+con\\s+presencia\\s+de\\s+dispositivo\\s+intrauterino)\\s*[.;]",
|
||||
"finding_glandular_cells": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(c[ée]lulas\\s+glandulares\\s+post\\-histerectom[íi]a)\\s*[.;]",
|
||||
"finding_bacteria": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(bacterias)\\s*[.;]",
|
||||
"finding_herpes_image": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(imagen\\s+del\\s+virus\\s+del\\s+herpes)\\s*[.;]",
|
||||
"finding_fungi": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(hongos)\\s*[.;]",
|
||||
"finding_radiation": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(radiaci[óo]n)\\s*[.;]",
|
||||
"finding_repair": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(reparaci[óo]n)\\s*[.;]",
|
||||
"finding_iud_effect": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(efecto\\s+del\\s+diu)\\s*[.;]",
|
||||
"finding_endometrial_cells": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(presencia\\s+de\\s+c[ée]lulas\\s+endometriales\\s+en\\s+pacientes\\s+de\\s+40\\s+a[ñn]os\\s+o\\s+m[áa]s)\\s*[.;]",
|
||||
"finding_none": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(ninguno)\\s*[.;]"},
|
||||
"concept_map": "erick_site",
|
||||
"formats": {"sample_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
|
||||
{"id": "hpv", "kind": "extract", "label": "VPH", "inputs": ["hpv_orders"],
|
||||
@@ -116,6 +148,7 @@
|
||||
"patterns": {
|
||||
"request_date": "solicitud:\\s*(\\d{2}/\\d{2}/\\d{4})",
|
||||
"report_date": "reporte:\\s*(\\d{2}/\\d{2}/\\d{4})",
|
||||
"mammogram_exam_date": "res[uú]men cl[ií]nico:\\s*mastograf[ií]a del (\\d{2}/\\d{2}/\\d{4})",
|
||||
"histology": "biopsia:[\\s\\S]{0,300}?(negativo para malignidad|in situ|infiltrante)",
|
||||
"histologic_type": "\\((\\d{4}/\\d)\\)",
|
||||
"grade": "nottingham\\):\\s*(\\d)",
|
||||
@@ -126,7 +159,7 @@
|
||||
"size_mm": "tama[ñn]o tumoral:\\s*(\\d+)\\s*mm", "positive_nodes": "ganglios linf[aá]ticos positivos:\\s*(\\d+)",
|
||||
"stage": "estadio cl[ií]nico\\s+([0-9IVlO|]{1,4}[ABC]?)\\b"},
|
||||
"concept_map": "erick_site",
|
||||
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
|
||||
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y", "mammogram_exam_date": "%d/%m/%Y"}},
|
||||
|
||||
{"id": "mchat_forms", "kind": "route", "label": "Formatos M-CHAT", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)cuestionario m-chat"}]},
|
||||
{"id": "ados2_reports", "kind": "route", "label": "Reportes ADOS-2", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)informe de evaluaci[oó]n ados-2"}]},
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Phase 6's CaCu measures, their rules over made-up gold rows."""
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from core import fhir
|
||||
from core.cacu.measures import MEASURES, biopsy_answer, hpv_genotype
|
||||
from core.measures import Period, evaluate, report
|
||||
|
||||
S1 = Period.parse("2026-S1")
|
||||
CUTOFF = date(2026, 12, 31)
|
||||
|
||||
|
||||
def procedure(person, day, histology=None, reported=None, **more):
|
||||
return {
|
||||
"procedure_id": f"{person}|{day}", "person_id": person, "date": day,
|
||||
"sample_date": "2026-01-05", "result": "HSIL", "hpv": None, "hpv_16": None, "hpv_18": None,
|
||||
"screening_history": None, "histology": histology, "report_date": reported,
|
||||
|
||||
"known_at": "2026-01-01", "report_known_at": "2026-01-01",
|
||||
"cytology_known_at": "2026-01-01",
|
||||
"first_case": None, "first_treatment": None, "first_colposcopy": None, **more,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def ran(measure, rows, **kw):
|
||||
return evaluate(MEASURES[measure], rows, S1, event_cutoff=kw.pop("cutoff", CUTOFF), **kw)
|
||||
|
||||
|
||||
def cell(result, stratum, value):
|
||||
c = result.strata[stratum][value]
|
||||
return c["numerator"], c["denominator"]
|
||||
|
||||
|
||||
def test_a_patient_counts_once_with_her_first_procedure_that_counts():
|
||||
rows = [
|
||||
procedure("a", "2026-02-01"), # a biopsy without a report doesn't count
|
||||
procedure("a", "2026-03-01", "normal", "2026-03-10"),
|
||||
procedure("a", "2026-04-01", "HSIL", "2026-04-10"),
|
||||
procedure("b", "2026-02-01", "HSIL", "2026-02-10", first_case="2025-01-01"), # a case
|
||||
]
|
||||
found = ran("CACU_VPP_BIOPSIA", rows).populations
|
||||
assert (found["numerator"], found["denominator"]) == (0, 1)
|
||||
found = ran("CACU_VPP_COLPOSCOPIA", rows).populations
|
||||
assert (found["numerator"], found["denominator"]) == (0, 1)
|
||||
|
||||
|
||||
def test_levels_share_the_denominator_and_cytology_groups_overlap():
|
||||
rows = [
|
||||
procedure("a", "2026-02-01", "LSIL", "2026-02-10", result="ASC-US"),
|
||||
procedure("b", "2026-02-01", "HSIL", "2026-02-10", hpv=True, hpv_16=True, hpv_18=False),
|
||||
procedure("c", "2026-02-01", "carcinoma", "2026-02-10", result=None, sample_date=None),
|
||||
procedure("d", "2026-02-01", "normal", "2026-02-10", result="NILM"),
|
||||
]
|
||||
found = ran("CACU_VPP_BIOPSIA", rows)
|
||||
assert [cell(found, "level", k) for k in ("cin1_plus", "cin2_plus", "carcinoma")] == [
|
||||
(3, 4), (2, 4), (1, 4)] # fmt: skip
|
||||
assert cell(found, "cytology", "ascus_plus") == (2, 2)
|
||||
assert cell(found, "cytology", "hsil_plus") == (1, 1)
|
||||
assert cell(found, "cytology", "no_data") == (1, 1) # and NILM is in no group
|
||||
assert cell(found, "hpv", "positive") == cell(found, "hpv", "hpv_16") == (1, 1)
|
||||
assert found.score == 0.75
|
||||
assert report(MEASURES["CACU_VPP_BIOPSIA"], S1, found, None)
|
||||
|
||||
|
||||
def test_rounds():
|
||||
rows = [
|
||||
procedure("a", "2026-02-01", "normal", "2026-02-10", screening_history="never"),
|
||||
procedure("b", "2026-02-01", "normal", "2026-02-10", screening_history="2_years"),
|
||||
procedure(
|
||||
"c",
|
||||
"2026-02-01",
|
||||
"normal",
|
||||
"2026-02-10",
|
||||
screening_history="never",
|
||||
first_colposcopy="2025-06-01",
|
||||
), # fmt: skip
|
||||
procedure("d", "2026-02-01", "normal", "2026-02-10"),
|
||||
]
|
||||
found = ran("CACU_VPP_BIOPSIA", rows).strata["round"]
|
||||
assert {k: v["denominator"] for k, v in found.items()} == {
|
||||
"initial": 1, "subsequent": 2, "no_data": 1} # fmt: skip
|
||||
|
||||
|
||||
def test_a_report_counts_once_it_is_known_and_dated_by_the_cutoff():
|
||||
late = procedure("a", "2026-02-01", "HSIL", "2026-05-01", report_known_at="2026-06-01")
|
||||
for kw in ({"cutoff": date(2026, 4, 1)}, {"as_of": datetime(2026, 5, 15, tzinfo=UTC)}):
|
||||
assert ran("CACU_VPP_COLPOSCOPIA", [late], **kw).populations["numerator"] == 0
|
||||
answers = ran("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", [late], **kw).strata["category"]
|
||||
assert list(answers) == ["pending"]
|
||||
as_of = datetime(2026, 5, 15, tzinfo=UTC)
|
||||
assert not ran("CACU_BIOPSIA_RESULTADOS", [late], as_of=as_of).populations["initial-population"]
|
||||
assert ran("CACU_VPP_COLPOSCOPIA", [late]).populations["numerator"] == 1
|
||||
|
||||
|
||||
def test_biopsy_answers_and_hpv_genotypes():
|
||||
answers = [biopsy_answer(procedure("a", "2026-02-01", *x)) for x in (
|
||||
(None, None), ("HSIL", "2026-01-01"), (None, "2026-03-01"), ("HSIL", "2026-03-01"),
|
||||
("LSIL", "2026-03-01"))] # fmt: skip
|
||||
assert answers == ["pending", "inconsistent", "no_grade", "high_grade", "below_high_grade"]
|
||||
said = lambda *v: hpv_genotype(dict(zip(("hpv", "hpv_16", "hpv_18"), v, strict=True))) # noqa: E731
|
||||
assert said(False, False, False) == "negative"
|
||||
assert said(None, False, None) == "no_result" # a genotype's negative is not a negative HPV
|
||||
assert said(None, True, None) == said(False, True, False) == "inconsistent"
|
||||
assert said(True, None, False) == "positive_incomplete"
|
||||
assert said(True, True, True) == "positive_16_18"
|
||||
assert said(True, False, False) == "positive_other"
|
||||
|
||||
|
||||
def test_a_duration_by_code_scores_each_code():
|
||||
rows = [
|
||||
{"sample_id": str(i), "sample_date": "2026-02-01", "history": 0, "known_at": None,
|
||||
"diagnosis_date": "2026-03-01", "days_sample_diagnosis": days, "diagnosis_code": code}
|
||||
for i, (days, code) in enumerate([(10, "N870"), (20, "N870"), (28, None)])
|
||||
] # fmt: skip
|
||||
found = ran("CACU_TIEMPO_DIAGNOSTICO_CIE10", rows)
|
||||
assert found.scores["diagnosis_code", "N870"] == (15.0, {"q1": 12.5, "q3": 17.5}, "d")
|
||||
(by_code,) = (
|
||||
report(MEASURES["CACU_TIEMPO_DIAGNOSTICO_CIE10"], S1, found, None).group[0].stratifier
|
||||
)
|
||||
assert {s.value.text: s.measureScore.value for s in by_code.stratum} == {
|
||||
"N870": 15,
|
||||
"no_data": 28,
|
||||
}
|
||||
assert len(fhir.EXTENSIONS["q1"][1]) == 2
|
||||
@@ -0,0 +1,118 @@
|
||||
"""CaMa's time from a mammogram's report to its biopsy's report (CAMA_DIAS_RESULTADO_BIOPSIA),
|
||||
its rules over made-up gold rows (`persistance.measures`' `mammogram_first_biopsy`: one row per
|
||||
mammogram, with the biopsy whose request names it), and what the same link does to the two
|
||||
measures that already followed a mammogram to its biopsy, whose rules are not touched."""
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from core.cama.measures import MEASURES
|
||||
from core.measures import Period, evaluate
|
||||
|
||||
S1 = Period.parse("2026-S1")
|
||||
CUTOFF = date(2026, 12, 31)
|
||||
TIME = MEASURES["CAMA_DIAS_RESULTADO_BIOPSIA"]
|
||||
|
||||
|
||||
def mammogram(name, birads="4A", report="2026-02-10", biopsy=None, days=None, grade="benign"):
|
||||
"""One row: a reported mammogram and, when its request named it, its first biopsy report."""
|
||||
return {
|
||||
"mammogram_id": name, "person_id": name, "exam_date": "2026-02-05", "report_date": report,
|
||||
"birads": birads, "birads_rank": 5, "known_at": "2026-02-05",
|
||||
"report_known_at": "2026-02-10", "biopsy_known_at": "2026-03-01" if biopsy else None,
|
||||
"biopsy_id": f"{name}|b" if biopsy else None, "biopsy_report_date": biopsy,
|
||||
"days_report_biopsy": days, "histology": grade if biopsy else None,
|
||||
"histology_rank": 1 if biopsy else None,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def ran(measure, rows, **kw):
|
||||
return evaluate(measure, rows, S1, event_cutoff=kw.pop("cutoff", CUTOFF), **kw)
|
||||
|
||||
|
||||
def test_the_days_are_the_biopsy_reports_from_the_mammogram_report_with_their_quartiles():
|
||||
rows = [
|
||||
mammogram("a", biopsy="2026-02-20", days=10),
|
||||
mammogram("b", biopsy="2026-02-24", days=14),
|
||||
mammogram("c", biopsy="2026-03-02", days=20),
|
||||
mammogram("d", biopsy="2026-03-10", days=28),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations == {"initial-population": 4, "measure-observation": 4}
|
||||
assert found.score == 17.0 and found.score_extensions == {"q1": 13.0, "q3": 22.0}
|
||||
assert found.unit == "d"
|
||||
|
||||
|
||||
def test_a_biopsy_reported_the_day_of_the_mammogram_report_is_a_valid_zero():
|
||||
found = ran(TIME, [mammogram("a", biopsy="2026-02-10", days=0)])
|
||||
assert found.populations["measure-observation"] == 1
|
||||
assert found.score == 0.0 # a zero is a value, not an absence
|
||||
|
||||
|
||||
def test_a_mammogram_with_no_linked_biopsy_is_in_the_population_but_not_measured():
|
||||
# reported long enough ago for a biopsy to be missing, not pending
|
||||
rows = [mammogram("a", biopsy="2026-02-20", days=10), mammogram("b", report="2026-02-10")]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations == {"initial-population": 2, "measure-observation": 1}
|
||||
assert found.score == 10.0
|
||||
|
||||
|
||||
def test_a_biopsy_still_within_the_horizon_is_pending_not_missing():
|
||||
rows = [mammogram("a", report="2026-06-20")] # no biopsy reported yet
|
||||
soon = ran(TIME, rows, cutoff=date(2026, 9, 1)) # 73 days on: it may still come
|
||||
assert soon.populations["initial-population"] == 0
|
||||
late = ran(TIME, rows, cutoff=date(2026, 12, 31)) # 194 days on: it is missing
|
||||
assert late.populations == {"initial-population": 1, "measure-observation": 0}
|
||||
|
||||
|
||||
def test_inconsistent_or_missing_dates_leave_the_unit_unmeasured():
|
||||
rows = [
|
||||
mammogram("a", biopsy="2026-02-01", days=None), # biopsy reported before the mammogram
|
||||
mammogram("b", biopsy=None, days=None), # request named it, no report yet
|
||||
mammogram("c", report=None, biopsy="2026-02-20", days=None), # mammogram not reported
|
||||
mammogram("d", biopsy="2026-02-20", days=10),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations["measure-observation"] == 1 and found.score == 10.0
|
||||
|
||||
|
||||
def test_only_mammograms_that_should_be_biopsied_count():
|
||||
rows = [
|
||||
mammogram("a", birads="4A", biopsy="2026-02-20", days=10),
|
||||
mammogram("b", birads="5", biopsy="2026-02-22", days=12),
|
||||
mammogram("c", birads="6", biopsy="2026-02-24", days=14), # already confirmed by biopsy
|
||||
mammogram("d", birads="2", biopsy="2026-02-26", days=16),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations["measure-observation"] == 2 and found.score == 11.0
|
||||
|
||||
|
||||
def test_a_biopsy_reported_after_the_cutoff_or_not_yet_known_is_not_counted():
|
||||
rows = [mammogram("a", biopsy="2026-02-20", days=10)]
|
||||
early = ran(TIME, rows, cutoff=date(2026, 2, 15))
|
||||
assert early.populations["measure-observation"] == 0
|
||||
before = datetime(2026, 2, 25, tzinfo=UTC) # the report became known on 2026-03-01
|
||||
asked = ran(TIME, rows, as_of=before)
|
||||
assert asked.populations["measure-observation"] == 0
|
||||
|
||||
|
||||
def test_the_explicit_link_gives_the_confirmation_its_numerator_without_touching_its_rule():
|
||||
confirmation = MEASURES["CAMA_CONFIRMACION_BIRADS45"]
|
||||
linked = [mammogram("a", biopsy="2026-02-20", days=10), mammogram("b", biopsy="2026-03-02")]
|
||||
unlinked = [mammogram("a"), mammogram("b")]
|
||||
got = ran(confirmation, linked).populations
|
||||
assert (got["numerator"], got["denominator"]) == (2, 2)
|
||||
got = ran(confirmation, unlinked).populations
|
||||
assert (got["numerator"], got["denominator"]) == (0, 2)
|
||||
|
||||
|
||||
def test_the_explicit_link_gives_the_histopathology_its_results_instead_of_no_biopsy():
|
||||
histology = MEASURES["CAMA_HISTOPATOLOGIA_BIRADS"]
|
||||
rows = [mammogram("a", biopsy="2026-02-20", grade="invasive"), mammogram("b", birads="5")]
|
||||
found = ran(histology, rows)
|
||||
assert {k: v["initial-population"] for k, v in found.strata["category"].items()} == {
|
||||
"invasive": 1, "no_biopsy": 1} # fmt: skip
|
||||
cells = found.crossed["birads", "category"]
|
||||
assert cells["4A", "invasive"]["initial-population"] == 1
|
||||
assert cells["5", "no_biopsy"]["initial-population"] == 1
|
||||
nothing = ran(histology, [mammogram("a"), mammogram("b", birads="5")])
|
||||
assert list(nothing.strata["category"]) == ["no_biopsy"]
|
||||
@@ -10,8 +10,11 @@ import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cama import recurrence
|
||||
from models.cama.jobs import JOBS
|
||||
from models.cama.recurrence import calculator, reports, site
|
||||
from models.cama.recurrence.cohorts import UNKNOWN
|
||||
from models.cama.specs import MODELS
|
||||
from models.jobs import EmptyCohort
|
||||
|
||||
|
||||
def test_the_st_gallen_surrogate_names_the_subtype_as_scan_b():
|
||||
@@ -80,9 +83,9 @@ def test_the_scenarios_find_their_patients_though_a_redundant_covariate_is_dropp
|
||||
prepared = site.prepare(rows)
|
||||
assert prepared.eliminated # the subtype is the receptors and Ki-67 again
|
||||
assert not set(prepared.eliminated) & set(prepared.covariates)
|
||||
named = {v for cond in calculator.SCENARIOS["site"].values() for v in cond}
|
||||
named = {v for cond in site.SCENARIOS.values() for v in cond}
|
||||
assert named <= set(prepared.frame.columns)
|
||||
found = calculator.masks(prepared.frame, calculator.SCENARIOS["site"])
|
||||
found = calculator.masks(prepared.frame, site.SCENARIOS)
|
||||
assert found["Luminal B HER2−"].sum() == (rows["Subtipo_clinico"] == "Luminal B HER2-").sum()
|
||||
|
||||
|
||||
@@ -101,3 +104,17 @@ def test_the_report_says_the_cohort_is_the_sites_own():
|
||||
sampling = reports.routines({"site": prepared}, {"site": 40})["MUESTREO"]
|
||||
assert sampling["origen"] == "la sede (sus propias pacientes)"
|
||||
assert sampling["cohortes"]["site"]["pacientes"] == 200
|
||||
|
||||
|
||||
def test_a_cohort_with_too_few_recurrences_is_left_untrained():
|
||||
events = cohort(120)
|
||||
few = events[(events["type"] != "recurrence") | events["person_id"].isin(["p0001", "p0002"])]
|
||||
assert "recurred" in site.scarce(site.frame(few, date(2026, 1, 1)))
|
||||
with pytest.raises(EmptyCohort, match="cama.recurrence"):
|
||||
MODELS["recurrence"].train(few, date(2026, 1, 1))
|
||||
assert site.scarce(site.frame(cohort(600), date(2026, 1, 1))) is None
|
||||
assert site.scarce(site.frame(few[few["type"] != "recurrence"], date(2026, 1, 1)))
|
||||
|
||||
|
||||
def test_a_training_run_takes_every_model():
|
||||
assert "recurrence" in JOBS.routine() and set(JOBS.routine()) == set(MODELS)
|
||||
|
||||
@@ -12,6 +12,7 @@ from core.measures import (
|
||||
Proportion,
|
||||
evaluate,
|
||||
evaluate_periods,
|
||||
report,
|
||||
)
|
||||
|
||||
PERIODS = [Period.parse(f"{y}-{m:02d}") for y in (2023, 2024) for m in range(1, 13)] + [
|
||||
@@ -54,3 +55,11 @@ def test_each_period_gets_what_evaluate_gives_it():
|
||||
found = evaluate_periods(measure, rows, PERIODS, event_cutoff=cutoff)
|
||||
assert found == [evaluate(measure, rows, p, event_cutoff=cutoff) for p in PERIODS], rule
|
||||
assert any(r.populations["initial-population"] for r in found)
|
||||
|
||||
|
||||
def test_a_report_as_of_a_moment_without_an_offset_is_valid_fhir():
|
||||
measure = Measure(id="m", title="m", rows="x", rule=RULES[0])
|
||||
as_of = datetime(2024, 6, 30) # what `as-of=2024-06-30` parses to
|
||||
result = evaluate(measure, _rows(), PERIODS[0], as_of)
|
||||
found = report(measure, PERIODS[0], result, as_of)
|
||||
assert found.extension[0].valueDateTime.isoformat() == "2024-06-30T00:00:00+00:00"
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""The synthetic site names the mammogram a breast biopsy came from only when its source does:
|
||||
Synthea keeps one encounter open from a mammogram to the biopsy it leads to, so the two
|
||||
reports name the same encounter. Nothing is matched by dates."""
|
||||
|
||||
from synthetic import site
|
||||
|
||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||
|
||||
|
||||
def report(code, day, encounter, name):
|
||||
return {
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport", "id": name,
|
||||
"code": {"coding": [{"system": STUDY, "code": code}]},
|
||||
"effectiveDateTime": f"{day}T14:00:00+00:00",
|
||||
"encounter": {"reference": encounter},
|
||||
}
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def bundle(*reports):
|
||||
patient = {"resource": {"resourceType": "Patient", "id": "p", "birthDate": "1970-01-01"}}
|
||||
return {"entry": [patient, *reports]}
|
||||
|
||||
|
||||
def test_a_biopsy_names_the_mammogram_of_its_encounter():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("mammography", "2024-05-12", "urn:e0", "m0"), # an earlier one, another encounter
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {"2026-05-25": "2026-05-12"}
|
||||
|
||||
|
||||
def test_same_day_reports_of_one_biopsy_name_one_mammogram():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b2"), # a second report, same day
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {"2026-05-25": "2026-05-12"}
|
||||
|
||||
|
||||
def test_a_biopsy_with_no_mammogram_in_its_encounter_names_none():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e2", "b1"), # near in time, not the same one
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_an_encounter_with_two_mammograms_names_none():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("mammography", "2026-05-13", "urn:e1", "m2"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_a_biopsy_with_no_encounter_names_none():
|
||||
b = {"entry": [{"resource": {
|
||||
"resourceType": "DiagnosticReport", "id": "b",
|
||||
"code": {"coding": [{"system": STUDY, "code": "breast_biopsy"}]},
|
||||
"effectiveDateTime": "2026-05-25T14:00:00+00:00"}}]} # fmt: skip
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_the_study_rows_carry_the_link_and_the_other_biopsies_do_not():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("breast_biopsy", "2026-09-01", "urn:e9", "b9"), # no mammogram in its encounter
|
||||
)
|
||||
found = site.people_and_studies([b])["p"]["studies"]["breast_biopsy"]
|
||||
assert {r["request_date"]: r.get("mammogram_exam_date") for r in found} == {
|
||||
"2026-05-25": "2026-05-12", "2026-09-01": None} # fmt: skip
|
||||
@@ -19,10 +19,11 @@ La instalación no requiere internet ni un registro de imágenes.
|
||||
## Instalación
|
||||
|
||||
1. Copie `deploy/` al servidor.
|
||||
2. Copie `.env.ejemplo` como `.env` y llene:
|
||||
2. Copie `.env.ejemplo` como `.env` y ajuste:
|
||||
- `BIND_ADDRESS`: dirección interna del servidor; la plataforma solo escucha en ella.
|
||||
- `ISSSTELEON_DATOS` y `ISSSTELEON_RESPALDOS`: carpetas de datos y de respaldos.
|
||||
- `AUTH_ADMIN_EMAIL` y `AUTH_ADMIN_PASSWORD`: primer administrador.
|
||||
- `AUTH_ADMIN_EMAIL` y `AUTH_ADMIN_PASSWORD`: primer administrador; la contraseña incluida es de
|
||||
ejemplo y el administrador se crea una sola vez, en el primer arranque.
|
||||
3. Ejecute `./isssteleon.sh instalar`. La plataforma queda en el puerto 5710 de `BIND_ADDRESS`.
|
||||
|
||||
## Operación
|
||||
|
||||
+131
-15
@@ -14,24 +14,140 @@ mama y trastorno del espectro autista.
|
||||
|
||||
## Requisitos
|
||||
|
||||
- Servidor Linux en la red interna del hospital, con Docker y Docker Compose v2.
|
||||
- Una carpeta para los datos y otra, de preferencia en otro disco, para los respaldos.
|
||||
|
||||
## Construcción
|
||||
|
||||
```sh
|
||||
docker build --target app -t isssteleon/app:<versión> .
|
||||
docker build -t isssteleon/web:<versión> WebApp
|
||||
```
|
||||
- Servidor Linux (Ubuntu Server 24.04 o similar) en la red interna del hospital, con al menos
|
||||
4 núcleos, 16 GB de memoria y 200 GB libres.
|
||||
- Salida a internet durante la construcción de las imágenes.
|
||||
- Acceso de red del servidor a las fuentes de datos (por ejemplo, SQL Server en el puerto 1433) y
|
||||
un usuario de solo lectura en ellas.
|
||||
- Acceso a este repositorio con una cuenta de GitHub.
|
||||
|
||||
## Instalación
|
||||
|
||||
1. En `deploy/`, copie `.env.ejemplo` como `.env` y llene:
|
||||
- `ISSSTELEON_VERSION`: la versión construida.
|
||||
- `BIND_ADDRESS`: dirección interna del servidor; la plataforma solo escucha en ella.
|
||||
- `ISSSTELEON_DATOS` y `ISSSTELEON_RESPALDOS`: carpetas de datos y de respaldos.
|
||||
- `AUTH_ADMIN_EMAIL` y `AUTH_ADMIN_PASSWORD`: primer administrador.
|
||||
2. `docker compose up -d`. La plataforma queda en el puerto 5710 de `BIND_ADDRESS`.
|
||||
1. Instale Git, Docker y Docker Compose v2:
|
||||
|
||||
```sh
|
||||
sudo apt-get update && sudo apt-get install -y git curl
|
||||
curl -fsSL https://get.docker.com | sudo sh
|
||||
sudo usermod -aG docker $USER
|
||||
```
|
||||
|
||||
2. Cierre la sesión y vuelva a entrar. Compruebe la instalación:
|
||||
|
||||
```sh
|
||||
docker run --rm hello-world
|
||||
docker compose version
|
||||
```
|
||||
|
||||
3. Descargue el código (con su usuario de GitHub y un token de acceso como contraseña):
|
||||
|
||||
```sh
|
||||
git clone https://github.com/EscolarFCFM/sistemaIndicadores.git
|
||||
cd sistemaIndicadores
|
||||
```
|
||||
|
||||
4. Construya las dos imágenes:
|
||||
|
||||
```sh
|
||||
docker build --target app -t isssteleon/app:1.0.0 .
|
||||
docker build -t isssteleon/web:1.0.0 WebApp
|
||||
```
|
||||
|
||||
5. Cree las carpetas de datos y de respaldos (la de respaldos, de preferencia en otro disco):
|
||||
|
||||
```sh
|
||||
sudo mkdir -p /srv/isssteleon/datos /srv/isssteleon/respaldos
|
||||
sudo chown -R $USER /srv/isssteleon
|
||||
```
|
||||
|
||||
6. Obtenga la dirección interna del servidor:
|
||||
|
||||
```sh
|
||||
hostname -I
|
||||
```
|
||||
|
||||
7. Prepare la configuración:
|
||||
|
||||
```sh
|
||||
cd deploy
|
||||
cp .env.ejemplo .env
|
||||
chmod 600 .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
| Variable | Valor |
|
||||
| --- | --- |
|
||||
| `BIND_ADDRESS` | La dirección del paso 6 |
|
||||
| `AUTH_ADMIN_EMAIL` | Correo del primer administrador |
|
||||
| `AUTH_ADMIN_PASSWORD` | Una contraseña propia, con letras, números y guiones; la incluida es de ejemplo |
|
||||
|
||||
Las demás variables ya tienen un valor de uso. El administrador se crea una sola vez, en el
|
||||
primer arranque: cambiar después la contraseña en `.env` no la modifica.
|
||||
|
||||
8. Instale:
|
||||
|
||||
```sh
|
||||
./isssteleon.sh instalar
|
||||
```
|
||||
|
||||
Termina con `Lista: http://<BIND_ADDRESS>:5710`.
|
||||
|
||||
9. Compruebe el estado:
|
||||
|
||||
```sh
|
||||
./isssteleon.sh estado
|
||||
```
|
||||
|
||||
10. Desde otro equipo de la red, abra `http://<BIND_ADDRESS>:5710` e inicie sesión con el correo
|
||||
y la contraseña del paso 7.
|
||||
|
||||
11. Haga un primer respaldo y compruebe que aparece en `/srv/isssteleon/respaldos`:
|
||||
|
||||
```sh
|
||||
./isssteleon.sh respaldar
|
||||
```
|
||||
|
||||
Los puertos 5711 (API), 5712 (Dagster) y 5713 (MLflow) no piden sesión: limite su acceso a la red
|
||||
interna.
|
||||
|
||||
## Carga de datos y modelos
|
||||
|
||||
1. En **Conectar**, escriba un nombre en «Nueva canalización» (minúsculas, números y `_`) y
|
||||
presione Enter.
|
||||
2. Pulse «Fuente de datos», elija el tipo (por ejemplo, SQL Server) y llene servidor, base de
|
||||
datos, usuario y contraseña.
|
||||
3. Pulse «Probar conexión», elija la tabla, revise las primeras filas y pulse «Guardar».
|
||||
4. Agregue los pasos que sus datos necesitan y únalos con flechas:
|
||||
|
||||
| Paso | Uso |
|
||||
| --- | --- |
|
||||
| Leer documentos | Texto de PDF, Word y escaneos |
|
||||
| Separar por tipo | Un paso por tipo de documento (citología, VPH, biopsia, mastografía, nota…) |
|
||||
| Extraer datos | Fechas, resultados e identidad de cada tipo de documento |
|
||||
| Traducir códigos | Equivalencia entre los códigos del hospital y los de la plataforma |
|
||||
| Unir | Dos entradas del mismo registro (por ejemplo, resultado y orden) |
|
||||
| Identificar a la persona | A qué paciente pertenece cada registro |
|
||||
| Guardar en la plataforma | Un paso por estudio (citologías, biopsias, mastografías…) |
|
||||
|
||||
5. Use «Vista previa» en cada paso para comprobar lo que extrae.
|
||||
6. Pulse «Guardar» y después «Ejecutar». El estado `SUCCESS` indica que terminó.
|
||||
7. En **Revisión**, resuelva los registros retenidos, los valores en conflicto, los posibles
|
||||
duplicados y los documentos no reconocidos. Ejecute de nuevo la canalización para aplicarlo.
|
||||
8. En **Indicadores**, elija el dominio y compruebe los resultados del periodo.
|
||||
9. En **Gobernanza**, elija el dominio y pulse «Entrenar»; en TEA, antes, «Analizar EEG». Los
|
||||
modelos se entrenan con los datos de la propia plataforma; el que no tiene casos suficientes no
|
||||
genera versión.
|
||||
10. Revise los informes de cada versión, pulse «Subir validación clínica» y después «Promover».
|
||||
11. Pulse «Calcular riesgos». Los resultados aparecen en «Análisis de riesgos» y en el expediente
|
||||
de cada paciente.
|
||||
|
||||
## Actualización
|
||||
|
||||
1. `git pull` y construya las imágenes con la versión nueva (paso 4 de la instalación, por ejemplo
|
||||
`1.1.0`).
|
||||
2. Cambie `ISSSTELEON_VERSION` en `deploy/.env`.
|
||||
3. En `deploy/`, `./isssteleon.sh actualizar` (respalda y arranca la versión nueva). Para volver atrás: la
|
||||
versión anterior en `.env`, `./isssteleon.sh instalar` y `restaurar` con el respaldo de la
|
||||
actualización.
|
||||
|
||||
## Operación
|
||||
|
||||
|
||||
+32
-11
@@ -1,15 +1,22 @@
|
||||
#!/bin/sh
|
||||
# The product as a repository of its own, ready to publish: the same pruned source as a delivery
|
||||
# (tools/delivery/prune.py: no tests, tools, synthetic site, docstrings, comments or documents),
|
||||
# its README for building from source, one commit on `main` and no history.
|
||||
# its README for building from source. A new destination starts a repository on `main`; an
|
||||
# existing one (a clone of the published `main`) gets this version as one more commit on top, so
|
||||
# whoever pulls it gets a normal fast-forward. Development history never goes there.
|
||||
#
|
||||
# tools/delivery/repo.sh <destination>
|
||||
set -eu
|
||||
export LC_ALL=C.UTF-8
|
||||
HERE="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
cd "$HERE"
|
||||
fail() { echo "ERROR: $*" >&2; exit 1; }
|
||||
DEST="${1:?destination}"
|
||||
[ -e "$DEST" ] && fail "$DEST exists; remove it or pass another destination."
|
||||
if [ -e "$DEST" ]; then
|
||||
[ -d "$DEST/.git" ] || fail "$DEST exists and is not a repository."
|
||||
[ "$(git -C "$DEST" symbolic-ref --short HEAD)" = main ] || fail "$DEST is not on main."
|
||||
[ -z "$(git -C "$DEST" status --porcelain)" ] || fail "$DEST has uncommitted changes."
|
||||
fi
|
||||
[ -z "$(git status --porcelain)" ] || fail "Uncommitted changes: commit them first."
|
||||
git submodule status | grep -q '^[+-]' && fail "A submodule is not at its pinned commit." || true
|
||||
|
||||
@@ -25,23 +32,37 @@ git submodule status | while read -r line; do
|
||||
done
|
||||
python3 tools/delivery/prune.py "$WORK/codigo" "$HERE/WebApp/node_modules/typescript"
|
||||
|
||||
mkdir -p "$DEST"
|
||||
if [ -d "$DEST/.git" ]; then
|
||||
git -C "$DEST" rm -rqf --ignore-unmatch . # this version replaces the whole tree
|
||||
else
|
||||
mkdir -p "$DEST"
|
||||
git -C "$DEST" init -q -b main
|
||||
fi
|
||||
cp -a "$WORK/codigo/." "$DEST/"
|
||||
cp tools/delivery/README.repo.md "$DEST/README.md"
|
||||
cat > "$DEST/.gitignore" <<'EOF'
|
||||
.venv/
|
||||
__pycache__/
|
||||
deploy/.env
|
||||
data/
|
||||
WebApp/node_modules/
|
||||
WebApp/dist/
|
||||
WebApp/.angular/
|
||||
/deploy/.env
|
||||
/data/
|
||||
/WebApp/node_modules/
|
||||
/WebApp/dist/
|
||||
/WebApp/.angular/
|
||||
EOF
|
||||
if grep -rIil "erick" "$DEST"; then fail "Forbidden words in the repository (listed above)."; fi
|
||||
|
||||
VERSION="$(git describe --tags --always)"
|
||||
cd "$DEST"
|
||||
git init -q -b main
|
||||
git add -A
|
||||
# Every file of the export is in the commit: none lost to .gitignore.
|
||||
(cd "$WORK/codigo" && find . -type f | sed 's|^\./||' | sort) > "$WORK/exported"
|
||||
git -c core.quotePath=false ls-files | sort > "$WORK/tracked"
|
||||
MISSING="$(comm -23 "$WORK/exported" "$WORK/tracked")"
|
||||
[ -z "$MISSING" ] || fail "Files git would leave out: $MISSING"
|
||||
if git diff --cached --quiet; then
|
||||
echo "$DEST already holds this version: nothing to commit."
|
||||
exit 0
|
||||
fi
|
||||
git -c user.name="Roberto Treviño" -c user.email=rtrevinnoc@hotmail.com \
|
||||
commit -q -m "ISSSTELEON $(git -C "$HERE" describe --tags --always)"
|
||||
echo "Ready: $DEST (main, one commit)"
|
||||
commit -q -m "ISSSTELEON $VERSION"
|
||||
echo "Ready: $DEST ($(git log --oneline -1))"
|
||||
|
||||
+8
-4
@@ -26,8 +26,8 @@ FIXTURES = ROOT / "tests" / "fixtures"
|
||||
STEPS = ("maps", "erick", "tea", "synthea", "analyze", "train", "promote", "score",
|
||||
"association") # fmt: skip
|
||||
ASSOCIATION = ("tea", "eeg-ados2") # trained on the promoted curves, after them
|
||||
# What each domain trains first, by name (core.models.TITLES): every model, the slow ones too
|
||||
# (a train run without names leaves them out), and TEA's association after its curves.
|
||||
# What each domain trains first, by name (core.models.TITLES): every model, and
|
||||
# TEA's association after its curves.
|
||||
FIRST = {
|
||||
domain: [m.split(".", 1)[1] for m in TITLES
|
||||
if m.startswith(domain + ".") and m != ".".join(ASSOCIATION)]
|
||||
@@ -88,13 +88,15 @@ def synthea(site: Site, args) -> None:
|
||||
site.call("PUT", "/ingest/pipelines/synthea",
|
||||
json=_pipeline("fhir_door_cama.json", sender="synthea")) # fmt: skip
|
||||
files = sorted(Path(args.synthea).expanduser().glob("*.json"))
|
||||
for start in range(0, len(files), args.batch):
|
||||
for start in range(args.skip, len(files), args.batch):
|
||||
entries = []
|
||||
for f in files[start : start + args.batch]:
|
||||
entries += json.loads(f.read_text()).get("entry", [])
|
||||
bundle = {"resourceType": "Bundle", "type": "transaction", "entry": entries}
|
||||
t = time.monotonic()
|
||||
posted = site.http.post("/cama/fhir", params={"sender": "synthea"}, json=bundle)
|
||||
posted = site.http.post(
|
||||
"/cama/fhir", params={"sender": "synthea"}, json=bundle, timeout=3600
|
||||
) # a large Bundle on a busy host
|
||||
if posted.status_code != 202:
|
||||
sys.exit(f"FHIR door: {posted.status_code} {posted.text[:500]}")
|
||||
run_id = posted.headers["Location"].rstrip("/").split("/")[-1]
|
||||
@@ -152,6 +154,8 @@ def main() -> None:
|
||||
help="the synthetic hospitals' folder as the platform sees it") # fmt: skip
|
||||
parser.add_argument("--synthea", help="Synthea's FHIR Bundles (one file per patient)")
|
||||
parser.add_argument("--batch", type=int, default=2000)
|
||||
parser.add_argument("--skip", type=int, default=0,
|
||||
help="Synthea patients already posted (to resume that step)") # fmt: skip
|
||||
parser.add_argument("--steps", default=",".join(STEPS))
|
||||
args = parser.parse_args()
|
||||
site = Site(args.api)
|
||||
|
||||
Reference in New Issue
Block a user