Compare commits

...

13 Commits

Author SHA1 Message Date
edgar d6f79eff3e CaCu KPIs: HPV distribution and HPV groups in the referral PPVs
CACU_VPH counts each patient once, by her latest sample with an HPV result
in the period, with HPV 16 and 18 apart and initial and subsequent screening.
Both referral PPVs group by the referring cytology's HPV result (no_data
without one; the patient stays in the PPV). cacu_samples and
cacu_referral_facts carry hpv, hpv_16 and hpv_18.

Also reformats lines CI's ruff format check rejected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 20:41:48 -06:00
Angel Capetillo Zavala c5a92112c6 CaCu integration report and remote advances report 2026-11-27 18:43:48 -06:00
Angel Capetillo Zavala 3822959991 Point WebApp and WebApi at the CaCu follow-up, record and export commits 2026-11-27 18:43:47 -06:00
Angel Capetillo Zavala 758168de57 CaCu: biopsy and HPV report measures, biopsy request confirmation, ICD-10 diagnosis timing and individual stages
Gold models and measures for the HPV genotype and biopsy distributions, the biopsy
request confirmation and the sample-to-diagnosis time by ICD-10 code. Stage states and
dates are published on the diagnostic reports up to a cut-off, with their provenance
(structured link, temporal association, ambiguous or pending). Patient search takes age
bounds and a partial name or identifier. Each measure keeps the referral PPVs and the
screening-round strata already in the branch.
2026-11-27 18:43:47 -06:00
edgar f7faab7b56 CaCu KPIs: referral PPVs and screening-round breakdowns
Two PPVs, of the referral to colposcopy and to biopsy: of the patients with the
procedure in the period, those with histology LIEBG+. Each takes the latest
cytology sampled and reported strictly before its own procedure (up to 365 days
before), so no biopsy-cytology link is needed. A colposcopy is confirmed by a
biopsy requested that day. Once per patient, her first qualifying procedure;
cases are left out. Breakdowns: cytology (ASCUS+, LSIL+, HSIL+, overlapping),
histology (LIEBG+, LIEAG+, invasive, one denominator) and initial or
subsequent screening. Gold gives the facts and the measure chooses, so an
as-of evaluation picks among the cytologies known then.

The cytology distribution (CACU_EU7) gains the screening round and the results
within each round.

Still to confirm clinically: the 365 days, same-day biopsy matching and ASC-H in
LSIL+. The previous confirmation measure stays.

tests/ pass. On hospital_cacu a temporary copy of the end-to-end test, which
left the new measures and breakdowns out of the reference comparison, loaded,
built and compared, then stopped at HL7 validation (no validator configured).
WebApi/tests/test_cacu.py itself now fails: its reference lacks the new
measures and breakdowns. Web app labels are pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 17:43:06 -06:00
edgar 67b551867a CaCu cytology: the sample date is the form's reception date
sample_date is "Fecha de recepción", not the form's "Fecha" at the top. Both the
cytology and the HPV steps read it, since it is the cytology's key: reading
different dates would split one cytology in two. "Fecha de interpretación"
stays the report date, which also dates the HPV result.

In the synthetic form the top date now comes 1-4 days before reception, so the
two can't be confused. Records already loaded by the old date, if it differed,
would get a new key on reprocessing.

Checked on a fake digital form: both steps read the reception date. The test
suite is deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:45:54 -06:00
edgar 16b56b9457 CaCu cytology: take the result only from the squamous cell abnormalities answer
result was the first "negativo" or grade anywhere in the document. It is now
only the answer under "Anomalías en células escamosas", in the form's wording,
where "NO" is NILM; the section on epithelial abnormalities never sets it.
On a shared line a lone "NO" may be the neighbouring box's, so it stays empty.
ConceptMap, LLM hint and the synthetic form follow.

Checked on fake digital forms of the synthetic layout: no field took another's
text; the lone "NO" is the one answer missed. The test suite is deferred until
all the new fields are in; scans, OCR and the LLM path are untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:22:04 -06:00
edgar b7f1b54f72 CaCu cytology: additional findings as the cytologist confirmed them
No grades or scales: the inflammation severity field and its code system are
gone (the raw text keeps the grade). The two endometrial-cell findings are one,
for 40 or older. Catalog, ConceptMap, extraction and synthetic site.

Tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:03:20 -06:00
edgar f79421dd49 CaCu cytology: capture the cytologist's additional findings (data capture)
Free text on the form, known with the report: the text as written, the
inflammation grade, and 28 booleans that are true when a whole statement says
the finding, otherwise unknown. Catalog, ConceptMap, extraction patterns and
LLM hint, and a findings box in the synthetic form.

ConceptMap lookup now ignores line breaks and repeated spaces (all fields),
since a captured phrase can wrap.

The findings section's boundaries and punctuation are assumed; no real sample
yet. Pending: web app labels; evidence in gold if a use needs it.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:42:46 -06:00
edgar 2badff4ffc CaCu cytology: capture cervix_exam (data capture)
The form's "A la exploración se observa", recorded by the nurse at the sample:
catalog field and code system, ConceptMap, extraction pattern and LLM hint,
and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the pattern and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:38:33 -06:00
edgar 578c6b3bcc CaCu cytology: capture "actualmente presenta" (data capture)
Four booleans recorded at the sample: the recorded answer is true, the others
stay unknown, never false. Catalog, ConceptMap, extraction patterns and LLM
hint, and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:50:23 -06:00
edgar 009f9e2727 CaCu cytology: capture gynaecological/obstetric conditions (data capture)
The form's "Condiciones ginecoobstétricas a la detección" as eight booleans
recorded at the sample. The source records only one, so the others stay
unknown, never false. Catalog, ConceptMap, extraction patterns and LLM hint,
and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:36:07 -06:00
edgar 765c24bf37 CaCu cytology: capture screening_history (data capture)
The form's "Detección de cáncer de cérvix": catalog field and code system,
the site's ConceptMap, its extraction pattern and LLM hint, and the four
answers in the synthetic site.

Pending: KPI stratifier, cohorts, web app labels.
Tests are deferred until all the new fields are in; the pattern and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:33:32 -06:00
30 changed files with 1989 additions and 25 deletions
+12
View File
@@ -26,6 +26,18 @@ KPNC_3 = {
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# The referral PPVs (core.cacu.measures.ReferralPPV). Cytology groups overlap: each holds its
# grade and every more severe squamous one. Histology levels are numerators over one
# denominator; the first is the measure's score.
PPV_CYTOLOGY = {
"ASCUS+": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"LSIL+": ["LSIL", "ASC-H", "HSIL", "CIS"],
"HSIL+": ["HSIL", "CIS"],
}
PPV_HISTOLOGY = {"LIEBG+": ["LSIL", *CIN2_PLUS], "LIEAG+": CIN2_PLUS, "invasive": CANCER}
PREVIOUS_SCREENING = ["1_year_or_less", "2_years", "3_years_or_more"] # screening_history
REFERRAL_CYTOLOGY_DAYS = 365 # the referring cytology's report is at most this old
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
+265 -1
View File
@@ -1,6 +1,8 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from dataclasses import dataclass
from datetime import date
import statistics
from core import cacu
from core.measures import (
@@ -9,11 +11,15 @@ from core.measures import (
Composition,
Duration,
Measure,
Period,
Proportion,
Result,
RiskBand,
Result,
age_group,
as_day,
desc,
wilson,
)
@@ -63,11 +69,232 @@ def histology(row: dict) -> str:
return row.get("histology") or NO_DATA
@dataclass(frozen=True)
class BiopsyRequests:
"""Recorded request units, classified at the event cutoff, not all HIS referrals."""
kind: str = "composition"
def evaluate(self, rows, period, cutoff):
chosen = {}
severity = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY, 1)}
for row in rows:
request = as_day(row.get("request_date"))
if request not in period or request > cutoff:
continue
reported = as_day(row.get("report_date"))
if (row.get("rows_merged") or 0) > 1:
category, rank = "ambiguous", (4, 0, date.min)
elif reported is None or reported > cutoff:
category, rank = "pending", (0, 0, date.min)
elif reported < request:
category, rank = "inconsistent", (1, 0, reported)
elif row.get("histology") is None:
category, rank = "no_grade", (2, 0, reported)
elif row["histology"] not in severity:
category, rank = "unclassified", (2, 0, reported)
else:
grade = row["histology"]
category = "high_grade" if grade in cacu.CIN2_PLUS else "below_high_grade"
rank = (3, severity[grade], reported)
key = row["request_id"]
if key not in chosen or rank > chosen[key][0]:
chosen[key] = (rank, category)
categories = {}
for _, category in chosen.values():
cell = categories.setdefault(category, {"initial-population": 0})
cell["initial-population"] += 1
count = len(chosen)
return Result({"initial-population": count, "measure-observation": count},
strata={"category": categories})
@dataclass(frozen=True)
class DiagnosisDurations:
kind: str = "continuous-variable"
strata: tuple = (("diagnosis_code", None),)
def evaluate(self, rows, period, cutoff):
rule = Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0)
overall = rule.evaluate(rows, period, cutoff)
grouped = {}
for row in {r["sample_id"]: r for r in rows}.values():
if (row["sample_date"] not in period or row["history"] != 0
or row.get("days_sample_diagnosis") is None
or as_day(row.get("diagnosis_date")) is None
or as_day(row["diagnosis_date"]) > cutoff):
continue
code = row.get("diagnosis_code") or "sin_codigo"
grouped.setdefault(code, []).append(row)
cells, scores = {}, {}
for code, group in grouped.items():
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
median = statistics.median(values)
q1, q3 = (values[0], values[0]) if len(values) == 1 else (statistics.quantiles(values, n=4, method="inclusive")[0], statistics.quantiles(values, n=4, method="inclusive")[2])
descriptions = {r.get("diagnosis_description") for r in group if r.get("diagnosis_description")}
label = code + (" | " + next(iter(descriptions)) if len(descriptions) == 1 else "")
cells[label] = {"measure-observation": len(values)}
scores[label] = {"value": median, "unit": "d", "extension": [
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3}]}
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
{"diagnosis_code": cells}, {"diagnosis_code": scores})
def referring_cytology(cytologies: list[dict], day: date) -> dict | None:
"""Her latest valid cytology sampled and reported before `day` (a result of that same
day doesn't count: dates can't say which came first), its report at most
REFERRAL_CYTOLOGY_DAYS old."""
found = [
c for c in cytologies
if valid(c) and c.get("result") is not None
and as_day(c["date"]) < day and as_day(c["result_date"]) < day
and (day - as_day(c["result_date"])).days <= cacu.REFERRAL_CYTOLOGY_DAYS
] # fmt: skip
return max(found, key=lambda c: (as_day(c["date"]), as_day(c["result_date"]),
c["sample_id"]), default=None) # fmt: skip
def screening_round(cytology: dict | None) -> str:
"""`subsequent`: screened before (as her form says) or already past colposcopy or
treatment at the sample; `initial`: the first screening of her life, before colposcopy."""
if cytology is None:
return NO_DATA
# a referral fact is dated `date`; a gold sample `sample_date`
status = follow_up_status(cytology, as_day(cytology.get("date") or cytology["sample_date"]))
history = cytology.get("screening_history")
if history in cacu.PREVIOUS_SCREENING or status in ("post_colposcopy", "post_treatment"):
return "subsequent"
return "initial" if history == "first_time" else NO_DATA
def hpv_result(row: dict) -> str | None:
"""Her high-risk HPV result on a sample; none when it has none."""
return None if row.get("hpv") is None else "positive" if row["hpv"] else "negative"
def hpv_groups(cytology: dict | None) -> list[str]:
"""The referral PPVs' HPV groups of a referring cytology: its result and, apart, each
genotype it was positive for (they overlap with `positive`, and may with each other)."""
row = cytology or {}
found = [name for name in (hpv_result(row),) if name]
found += [name for name in ("hpv_16", "hpv_18") if row.get(name)]
return found or [NO_DATA]
@dataclass(frozen=True)
class ReferralPPV:
"""Of the patients with a procedure in the period, those whose histology confirms the
first level of PPV_HISTOLOGY. Rows are facts (`gold.cacu_referral_facts`: `fact` is
cytology, colposcopy or biopsy, each dated `date`), so the referring cytology is chosen
among those known at the evaluation's `as_of`.
A patient counts once, with her first procedure of the period that qualifies: she wasn't
a case already (at her referring sample, or at the procedure without one) and, for the
biopsy PPV, a biopsy requested that day has a histology. Its histology is that of the
biopsies requested that day and reported by the cut-off; with none, not confirmed."""
procedure: str # "colposcopy" or "biopsy"
kind: str = "proportion"
strata: tuple[tuple[str, None], ...] = (
("referral_cytology", None), ("referral_hpv", None), ("histology_level", None),
("screening_round", None),
) # fmt: skip
def _units(self, rows: list[dict], period: Period, cutoff: date):
"""Per patient counted: the histologies of her procedure and its referring cytology."""
mine: dict[str, dict[str, list[dict]]] = {}
for row in rows:
mine.setdefault(row["person_id"], {}).setdefault(row["fact"], []).append(row)
for facts in mine.values():
procedures: dict[date, list[dict]] = {}
for row in facts.get(self.procedure, []):
day = as_day(row["date"])
if day in period and day <= cutoff:
procedures.setdefault(day, []).append(row)
for day in sorted(procedures):
found = {
b["histology"] for b in facts.get("biopsy", [])
if as_day(b["date"]) == day and b.get("histology") is not None
and b.get("report_date") is not None
and day <= as_day(b["report_date"]) <= cutoff
} # fmt: skip
if self.procedure == "biopsy" and not found:
continue
cytology = referring_cytology(facts.get("cytology", []), day)
at = day if cytology is None else as_day(cytology["date"])
if follow_up_status(cytology or procedures[day][0], at) == "case":
continue
yield found, cytology
break
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = list(self._units(rows, period, cutoff))
def cell(members: list, level: list[str]) -> dict[str, int]:
n = len(members)
return {"initial-population": n, "denominator": n,
"numerator": sum(bool(found & set(level)) for found, _ in members)} # fmt: skip
score_level = next(iter(cacu.PPV_HISTOLOGY.values()))
total = cell(units, score_level)
strata: dict[str, dict] = {name: {} for name, _ in self.strata}
if not units:
return Result(total, strata=strata)
groups: dict[str, list] = {}
for unit in units:
cytology = unit[1]
names = (
[NO_DATA]
if cytology is None
else [g for g, codes in cacu.PPV_CYTOLOGY.items() if cytology["result"] in codes]
)
for name in names:
groups.setdefault(name, []).append(unit)
strata["referral_cytology"] = {g: cell(u, score_level) for g, u in groups.items()}
by_hpv: dict[str, list] = {}
for unit in units:
for name in hpv_groups(unit[1]):
by_hpv.setdefault(name, []).append(unit)
strata["referral_hpv"] = {g: cell(u, score_level) for g, u in by_hpv.items()}
strata["histology_level"] = {
name: cell(units, level) for name, level in cacu.PPV_HISTOLOGY.items()
}
rounds: dict[str, list] = {}
for unit in units:
rounds.setdefault(screening_round(unit[1]), []).append(unit)
strata["screening_round"] = {g: cell(u, score_level) for g, u in rounds.items()}
k, n = total["numerator"], total["denominator"]
low, high = wilson(k, n)
return Result(total, k / n, {"ic-bajo": low, "ic-alto": high}, strata=strata)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
SCREENING = ("screening_round", lambda row, p: screening_round(row))
def results_of(wanted: str):
"""The results of the patients in one screening round (the others are in no group)."""
return (f"result_{wanted}",
lambda row, p: result(row) if screening_round(row) == wanted else None) # fmt: skip
def genotype(name: str):
"""A genotype's result on the chosen sample (in no group when not reported)."""
return (name, lambda row, p: None if row.get(name) is None
else "positive" if row[name] else "negative") # fmt: skip
def hpv_of(wanted: str):
"""The HPV results of the patients in one screening round."""
return (f"hpv_{wanted}",
lambda row, p: hpv_result(row) if screening_round(row) == wanted else None) # fmt: skip
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
@@ -76,17 +303,54 @@ 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, SCREENING, results_of("initial"), results_of("subsequent")))),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "hpv_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="sample_id", date="sample_date"),
description="Reportes VPH con fecha de reporte y algún resultado VPH, por paciente y "
"fecha de toma; periodo por toma. Los nulos no son negativos; el contrato "
"booleano actual no representa resultados indeterminados."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "biopsy_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="biopsy_id", date="report_date"),
description="Reportes de biopsia por paciente y fecha de solicitud, incluidos los no "
"vinculados a una toma; periodo por fecha de reporte. El estrato no_data "
"identifica reportes sin grado; la distribución clasificable lo excluye."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", "Resultados por solicitudes de biopsia registradas",
"biopsy_requests", BiopsyRequests(), known="order_known_at", supports_as_of=False,
description="Solicitudes de biopsia registradas por persona y fecha de solicitud, "
"según fecha de solicitud; resultados hasta el corte. La clave puede "
"agrupar órdenes y no se conocen cancelaciones ni cobertura de referencias. "
"No admite corte histórico de conocimiento as-of."),
# Her latest sample with an HPV result in the period, whatever its cytology says.
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]), hpv_result,
where=lambda r: r.get("hpv") is not None,
strata=(AGE, STATUS, genotype("hpv_16"), genotype("hpv_18"), SCREENING,
hpv_of("initial"), hpv_of("subsequent"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
# Rows become known with `known_at`; a report's values only with `report_known_at`.
*(Measure(f"CACU_VPP_{name}", f"VPP de la referencia a {title}", "referral_facts",
ReferralPPV(procedure),
facts={"report_known_at": ("result", "result_date", "adequacy",
"histology", "report_date",
"hpv", "hpv_16", "hpv_18")})
for name, title, procedure in (("COLPOSCOPIA", "colposcopía", "colposcopy"),
("BIOPSIA", "biopsia", "biopsy"))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo a diagnóstico por CIE-10 (exploratorio)",
"diagnosis_codes", DiagnosisDurations(),
description="Agrupa la fecha diagnóstica ya seleccionada por asociación temporal; no confirma vínculo clínico."),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
+27
View File
@@ -0,0 +1,27 @@
"""Stage facts for a sample, using gold's dates and explicit biopsy links."""
def stage_facts(sample, biopsies, events, cutoff):
def day(value):
return str(value)[:10] if value is not None else None
start, end = day(sample['sample_date']), str(cutoff)[:10]
out = {}
for kind, column in [('colposcopy', 'colposcopy_date'), ('diagnosis', 'diagnosis_date')]:
selected = day(sample.get(column))
if selected and start < selected <= end:
matches = {(e['source_table'], e['source_id']) for e in events
if e['type'] == kind and day(e['date']) == selected}
out[kind] = ('inferred', selected) if len(matches) == 1 else ('ambiguous', None)
linked = [b for b in biopsies if day(b.get('cytology_sample_date')) == start
and day(b.get('request_date')) and start <= day(b['request_date']) <= end]
if len(linked) > 1 or any((b.get('rows_merged') or 0) > 1 for b in linked):
out['biopsy'] = ('ambiguous', None)
elif linked:
b = linked[0]
reported = day(b.get('report_date'))
if reported and reported < day(b['request_date']):
out['biopsy'] = ('ambiguous', None)
elif reported and reported <= end:
out['biopsy'] = ('structured', reported)
else:
out['biopsy'] = ('pending', None)
return out
+64
View File
@@ -7,6 +7,40 @@ cervical_cytology:
report: {date: report_date, parent: sample}
fields:
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
screening_history:
type: code
event: sample
title: Detección de cáncer de cérvix
system: cervical-screening-history
codes:
first_time: Primera vez en la vida
1_year_or_less: Un año o menos
2_years: 2 años
3_years_or_more: 3 o más años
# Condiciones ginecoobstétricas a la detección, as recorded at the sample: true when the
# form says it; otherwise unknown, never false (the source records only one of them).
gyn_puerperium: {type: boolean, event: sample, title: "Puerperio postparto o postaborto"}
gyn_pregnancy: {type: boolean, event: sample, title: "Embarazo actual"}
gyn_iud: {type: boolean, event: sample, title: "DIU in situ"}
gyn_hormonal_treatment: {type: boolean, event: sample, title: "Tratamiento hormonal"}
gyn_other_treatment: {type: boolean, event: sample, title: "Otro tratamiento ginecológico"}
gyn_postmenopause: {type: boolean, event: sample, title: "Posmenopausia"}
gyn_hysterectomy: {type: boolean, event: sample, title: "Histerectomía"}
gyn_not_applicable: {type: boolean, event: sample, title: "Condiciones ginecoobstétricas: no aplica"}
# Actualmente presenta, recorded like the conditions above: true or unknown, never false.
presents_discharge: {type: boolean, event: sample, title: "Actualmente presenta: flujo"}
presents_vulvar_pruritus: {type: boolean, event: sample, title: "Actualmente presenta: prurito o ardor vulvar"}
presents_abnormal_bleeding: {type: boolean, event: sample, title: "Actualmente presenta: sangrado anormal"}
presents_none: {type: boolean, event: sample, title: "Actualmente presenta: ninguno"}
cervix_exam:
type: code
event: sample
title: A la exploración se observa
system: cervix-exam
codes:
healthy: Cuello sano
abnormal_with_lesion: Cuello anormal con lesión
not_visible: No se observa cuello
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
@@ -29,6 +63,36 @@ cervical_cytology:
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# The cytologist's additional findings, free text on the form (known with the report).
# A finding is true when the text states it; otherwise unknown, never false.
cyto_findings_text: {type: text, event: report, title: Hallazgos adicionales}
cyto_inflammation: {type: boolean, event: report, title: "Inflamación"}
cyto_reactive_changes: {type: boolean, event: report, title: "Cambios reactivos"}
cyto_bacterial_vaginosis_flora: {type: boolean, event: report, title: "Flora sugestiva de vaginosis bacteriana"}
cyto_candida: {type: boolean, event: report, title: "Microorganismos compatibles con Candida sp"}
cyto_bacillary_flora_cytolysis: {type: boolean, event: report, title: "Aumento de la flora bacilar con citólisis"}
cyto_intermediate_cytolysis: {type: boolean, event: report, title: "Citólisis de las células intermedias"}
cyto_trichomonas: {type: boolean, event: report, title: "Trichomonas vaginalis"}
cyto_leptothrix: {type: boolean, event: report, title: "Microorganismos compatibles con Leptothrix"}
cyto_actinomyces_organisms: {type: boolean, event: report, title: "Microorganismos compatibles con Actinomyces sp"}
cyto_actinomyces_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con Actinomyces sp"}
cyto_herpes_simplex_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con virus herpes simple"}
cyto_squamous_tubular_metaplasia: {type: boolean, event: report, title: "Metaplasia escamosa tubular"}
cyto_keratotic_changes: {type: boolean, event: report, title: "Cambios queratósicos"}
cyto_pregnancy_changes: {type: boolean, event: report, title: "Cambios asociados al embarazo"}
cyto_atrophy: {type: boolean, event: report, title: "Atrofia"}
cyto_hypoestrogenism: {type: boolean, event: report, title: "Hipoestrogenismo"}
cyto_radiotherapy_effect: {type: boolean, event: report, title: "Efecto de radioterapia"}
cyto_iud_changes: {type: boolean, event: report, title: "Cambios compatibles con dispositivo intrauterino"}
cyto_post_hysterectomy_glandular_cells: {type: boolean, event: report, title: "Células glandulares post-histerectomía"}
cyto_bacteria: {type: boolean, event: report, title: "Bacterias"}
cyto_herpes_image: {type: boolean, event: report, title: "Imagen del virus del herpes"}
cyto_fungi: {type: boolean, event: report, title: "Hongos"}
cyto_radiation: {type: boolean, event: report, title: "Cambios reactivos: radiación"}
cyto_repair: {type: boolean, event: report, title: "Cambios reactivos: reparación"}
cyto_iud_effect: {type: boolean, event: report, title: "Efecto del DIU"}
cyto_endometrial_cells_40_plus: {type: boolean, event: report, title: "Células endometriales, 40 años o más"}
cyto_findings_none: {type: boolean, event: report, title: "Hallazgos adicionales: ninguno"}
cervical_biopsy:
title: Biopsia cervical
+6
View File
@@ -6,6 +6,12 @@ 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: Antecedente de detección de cáncer de cérvix
cervix-exam:
url: https://isssteleon.org/fhir/CodeSystem/cervix-exam
title: Exploración del cuello uterino
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
+20
View File
@@ -53,7 +53,15 @@ 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",
"diagnosis_code": "Diagnóstico CIE-10",
"birads": "BI-RADS de la mastografía",
"referral_cytology": "Citología previa", "histology_level": "Histología",
"screening_round": "Tamizaje inicial o subsecuente",
"result_initial": "Resultado en tamizaje inicial",
"result_subsequent": "Resultado en tamizaje subsecuente",
"referral_hpv": "VPH de la citología previa", "hpv_16": "VPH 16", "hpv_18": "VPH 18",
"hpv_initial": "VPH en tamizaje inicial",
"hpv_subsequent": "VPH en tamizaje subsecuente",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
@@ -89,6 +97,12 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
"stage-colposcopy-date": ("date", ["DiagnosticReport"]),
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
"stage-biopsy-date": ("date", ["DiagnosticReport"]),
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
"stage-diagnosis-date": ("date", ["DiagnosticReport"]),
} # fmt: skip
@@ -379,6 +393,8 @@ def measure(m, domain: str) -> Measure:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
if m.description:
found["description"] = m.description
return Measure.model_validate(found)
@@ -420,6 +436,10 @@ def extensions() -> list[StructureDefinition]:
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"stage-cutoff": ("DiagnosticReport", "date", "Cutoff for sample-linked stages"),
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cutoff"),
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cutoff"),
"follow-up-search": ("Patient", "string", "Partial name or identifier"),
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
+11 -2
View File
@@ -94,6 +94,7 @@ class Result:
score_extensions: dict[str, float] = field(default_factory=dict)
unit: str | None = None
strata: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)
stratum_scores: dict[str, dict[str, dict]] = field(default_factory=dict)
def wilson(k: int, n: int) -> tuple[float, float]:
@@ -170,7 +171,8 @@ 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)
if (value := stratum(row, period)) is None: # in no group of this stratum
continue
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
n = len(chosen)
@@ -363,6 +365,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)
description: str | None = None
# Some sources only retain an instance's first-known time, not each event's history.
supports_as_of: bool = True
def evaluate(
@@ -374,6 +379,8 @@ def evaluate(
) -> Result:
"""The measure over the rows known `as_of` (all by default) for one period; durations
count to `event_cutoff` (default: `as_of`'s day, or today)."""
if as_of is not None and not measure.supports_as_of:
raise ValueError("This measure cannot reconstruct knowledge at a historical as-of time")
as_of = _moment(as_of)
def known(column: str, row: dict) -> bool:
@@ -413,7 +420,9 @@ def report(
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": result.stratum_scores[name][value]}
if value in result.stratum_scores.get(name, {}) else {})}
for value, cells in sorted(values.items())]}
for name, values in result.strata.items()
] # fmt: skip
+5 -5
View File
@@ -267,14 +267,14 @@ Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
"""A raw value as the platform field expects it: the site's code translated (its
ConceptMap, case ignored), then its date format: a strptime format (spaces inside the
value ignored when the format has none), or `dateparser:<language>` for dates written
out ("9 de diciembre de 2025"). A value that doesn't parse is kept as written, so the
target holds it with the reason."""
ConceptMap; case, line breaks and repeated spaces ignored), then its date format: a
strptime format (spaces inside the value ignored when the format has none), or
`dateparser:<language>` for dates written out ("9 de diciembre de 2025"). A value that
doesn't parse is kept as written, so the target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = raw.strip()
raw = codes.get(field, {}).get(raw.casefold(), raw)
raw = codes.get(field, {}).get(" ".join(raw.split()).casefold(), raw)
fmt = node.formats.get(field)
if fmt and fmt.startswith("dateparser:"):
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
@@ -0,0 +1,11 @@
{# A biopsy report belongs to the person/request-date study, linked sample optional. #}
select
{{ dbt.concat(['person_id', "'|'", 'cast(request_date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
person_id, request_date, report_date, histology, known_at,
case
when histology is null then 'no_data'
when histology in ('normal', 'LSIL', 'HSIL', 'CIS', 'carcinoma') then histology
else 'unclassified'
end as category
from {{ ref('cervical_biopsy') }}
where report_date is not null
@@ -0,0 +1,7 @@
{# Recorded biopsy studies, including orders with no report. The silver study key is
person plus request date; it does not preserve an independent HIS order identifier. #}
select
{{ dbt.concat(['person_id', "'|'", 'cast(request_date as ' ~ dbt.type_string() ~ ')']) }} as request_id,
person_id, request_date, report_date, histology, order_known_at, report_known_at, rows_merged
from {{ ref('cervical_biopsy') }}
where request_date is not null
@@ -0,0 +1,17 @@
{% set p = var('cacu') %}
with candidates as (
select s.sample_id, replace(n.icd10, '.', '') as code, n.diagnosis_text
from {{ ref('cacu_samples') }} s
join {{ ref('clinical_note') }} n on n.person_id = s.person_id and n.note_date = s.diagnosis_date
where replace(n.icd10, '.', '') in {{ sql_list(p.diagnosis_icd10) }}
and n.specialty in {{ sql_list(p.diagnosis_specialties) }}
), grouped as (
select sample_id, count(distinct code) as codes, min(code) as code,
count(distinct nullif(trim(diagnosis_text), '')) as descriptions,
min(nullif(trim(diagnosis_text), '')) as description
from candidates group by sample_id
)
select s.*, case when coalesce(g.codes, 0) = 0 then 'sin_codigo'
when g.codes > 1 then 'ambiguo' else g.code end as diagnosis_code,
case when g.codes = 1 and g.descriptions = 1 then g.description end as diagnosis_description
from {{ ref('cacu_samples') }} s left join grouped g on g.sample_id = s.sample_id
@@ -0,0 +1,16 @@
{# One reported HPV result per person and sample date, the silver study key. #}
select
{{ dbt.concat(['person_id', "'|'", 'cast(sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
person_id, sample_date, report_date, known_at, hpv, hpv_16, hpv_18,
case
when hpv = false and (hpv_16 = true or hpv_18 = true) then 'inconsistent'
when hpv = false then 'negative'
when hpv = true and (hpv_16 is null or hpv_18 is null) then 'positive_incomplete'
when hpv = true and hpv_16 = true and hpv_18 = true then 'positive_16_18'
when hpv = true and hpv_16 = true and hpv_18 = false then 'positive_16'
when hpv = true and hpv_16 = false and hpv_18 = true then 'positive_18'
when hpv = true and hpv_16 = false and hpv_18 = false then 'positive_other'
else 'inconsistent'
end as category
from {{ ref('cervical_cytology') }}
where report_date is not null and (hpv is not null or hpv_16 is not null or hpv_18 is not null)
@@ -0,0 +1,40 @@
{#
What the referral PPVs (core.cacu.measures.ReferralPPV) count over: one row per fact of a
patient's route, in one shape, each dated `date`:
- cytology: a sample, with its results (cytology and HPV) and the screening history her
form says;
- colposcopy: a day she had one (cacu_events, which infers it). cacu_events also dates one
at the report of a biopsy taken at it; that day is not another colposcopy;
- biopsy: a biopsy, dated its request, with its histology once reported.
Every row carries the first day of her follow-up steps, for her status at any day.
`report_known_at`: when a report's values were first known (`known_at`: the row).
#}
with facts as (
select
'cytology' as fact, person_id, sample_date as date, sample_id, result, adequacy,
result_date, screening_history, hpv, hpv_16, hpv_18,
cast(null as {{ dbt.type_string() }}) as histology,
cast(null as date) as report_date,
known_at, report_known_at
from {{ ref('cacu_samples') }}
union all
select
'colposcopy', person_id, date, null, null, null, null, null, null, null, null, null, null,
min(known_at), null
from {{ ref('cacu_events') }}
where type = 'colposcopy'
and (source_table <> 'cervical_biopsy' or cast(date as {{ dbt.type_string() }}) = source_id)
group by person_id, date
union all
select
'biopsy', person_id, request_date, null, null, null, null, null, null, null, null,
histology, report_date,
known_at, report_known_at
from {{ ref('cervical_biopsy') }}
)
select t.*, f.first_case, f.first_treatment, f.first_colposcopy
from facts as t
left join {{ ref('cacu_follow_up') }} as f on f.person_id = t.person_id
@@ -12,6 +12,8 @@
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
@@ -0,0 +1,76 @@
version: 2
models:
- name: cacu_biopsy_requests
columns:
- name: request_id
data_tests: [not_null, unique]
- name: cacu_hpv_reports
columns:
- name: sample_id
data_tests: [not_null, unique]
- name: cacu_biopsy_reports
columns:
- name: biopsy_id
data_tests: [not_null, unique]
unit_tests:
- name: hpv_classification_preserves_unknowns
model: cacu_hpv_reports
given:
- input: ref('cervical_cytology')
format: sql
rows: |
select 'a' as person_id, '2026-01-01' as sample_date, '2026-01-02' as report_date, null as known_at, false as hpv, null as hpv_16, null as hpv_18
union all select 'b','2026-01-01','2026-01-02',null,true,true,false
union all select 'c','2026-01-01','2026-01-02',null,true,false,true
union all select 'd','2026-01-01','2026-01-02',null,true,true,true
union all select 'e','2026-01-01','2026-01-02',null,true,false,false
union all select 'f','2026-01-01','2026-01-02',null,true,true,null
union all select 'g','2026-01-01','2026-01-02',null,true,null,null
union all select 'h','2026-01-01','2026-01-02',null,false,true,false
union all select 'i','2026-01-01','2026-01-02',null,null,false,null
union all select 'j','2026-01-01','2026-01-02',null,null,null,null
union all select 'k','2026-01-01',null,null,true,true,true
expect:
format: sql
rows: |
select person_id || '|2026-01-01' as sample_id, person_id, '2026-01-01' as sample_date,
'2026-01-02' as report_date, null as known_at, hpv, hpv_16, hpv_18, category
from (
select 'a' as person_id, false as hpv, null as hpv_16, null as hpv_18, 'negative' as category
union all select 'b',true,true,false,'positive_16'
union all select 'c',true,false,true,'positive_18'
union all select 'd',true,true,true,'positive_16_18'
union all select 'e',true,false,false,'positive_other'
union all select 'f',true,true,null,'positive_incomplete'
union all select 'g',true,null,null,'positive_incomplete'
union all select 'h',false,true,false,'inconsistent'
union all select 'i',null,false,null,'inconsistent'
)
- name: biopsy_reports_include_unlinked_and_missing_grades
model: cacu_biopsy_reports
given:
- input: ref('cervical_biopsy')
format: sql
rows: |
select 'a' as person_id, '2026-01-01' as request_date, '2026-01-02' as report_date, 'normal' as histology, null as known_at
union all select 'b','2026-01-01','2026-01-02','LSIL',null
union all select 'c','2026-01-01','2026-01-02','HSIL',null
union all select 'd','2026-01-01','2026-01-02','CIS',null
union all select 'e','2026-01-01','2026-01-02','carcinoma',null
union all select 'f','2026-01-01','2026-01-02',null,null
union all select 'g','2026-01-01','2026-01-02','unknown',null
union all select 'h','2026-01-01',null,null,null
expect:
format: sql
rows: |
select person_id || '|2026-01-01' as biopsy_id, person_id, '2026-01-01' as request_date,
'2026-01-02' as report_date, histology, null as known_at, category
from (
select 'a' as person_id, 'normal' as histology, 'normal' as category
union all select 'b','LSIL','LSIL'
union all select 'c','HSIL','HSIL'
union all select 'd','CIS','CIS'
union all select 'e','carcinoma','carcinoma'
union all select 'f',null,'no_data'
union all select 'g','unknown','unclassified'
)
+3
View File
@@ -70,6 +70,9 @@ READS = {
from gold.cacu_samples
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
""",
"stage_samples": "select person_id, sample_date, colposcopy_date, diagnosis_date from gold.cacu_samples where person_id in :persons and sample_date <= :cutoff",
"stage_biopsies": "select person_id, cytology_sample_date, request_date, report_date, rows_merged from silver.cervical_biopsy where person_id in :persons and request_date <= :cutoff",
"stage_events": "select person_id, date, type, source_table, source_id from gold.cacu_events where person_id in :persons and date <= :cutoff and type in ('colposcopy', 'diagnosis')",
},
"cama": {
"person": CAMA_PERSONS + " where p.person_id = :id",
+5
View File
@@ -8,6 +8,11 @@ from persistance.destination import engine
READS = {
"cacu": {
"samples": "select * from gold.cacu_samples",
"diagnosis_codes": "select * from gold.cacu_diagnosis_codes",
"hpv_reports": "select * from gold.cacu_hpv_reports",
"biopsy_reports": "select * from gold.cacu_biopsy_reports",
"biopsy_requests": "select * from gold.cacu_biopsy_requests",
"referral_facts": "select * from gold.cacu_referral_facts",
"sample_biopsies": """
select s.*, b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.severity
from gold.cacu_samples as s
+1 -1
Submodule WebApi updated: 9c89c9e10d...4934f99c1d
+1 -1
Submodule WebApp updated: 07212a2083...c0e4920159
+115
View File
@@ -0,0 +1,115 @@
# Avances remotos en feature/risk-factors-cacu desde el diagnóstico
Fecha: 27 de noviembre de 2026. Investigación de solo lectura en `C:\dev\ISSSTELEON-CaCu-Revision-Remota` (clon independiente, HEAD separado en `f7faab7`). No se tocó el directorio de Codex ni el Rebuild (únicamente se leyeron sus archivos), y no se hicieron commits, merges, push ni despliegues.
## 1. SHA anterior y actual
| | SHA |
|---|---|
| Registrado en el diagnóstico | `67b551867a0b03fa6557be56e4ad3653b7a30419` |
| Actual (`git ls-remote`, 27-nov-2026) | `f7faab7b56425c007d0bb624c092c0a340f36c91` |
**Sí hay avance: exactamente un commit nuevo**, descendiente directo de `67b5518` (comprobado con `merge-base --is-ancestor`).
- `f7faab7` — «CaCu KPIs: referral PPVs and screening-round breakdowns», autor edgar, 27-nov-2026 17:43 (-0600).
- 8 archivos, +347 / −2: `Core/core/cacu/__init__.py`, `Core/core/cacu/measures.py`, `Core/core/fhir.py`, `Core/core/measures.py`, `Persistance/dbt/models/gold/cacu/cacu_referral_facts.sql` (nuevo), `Persistance/dbt/models/gold/cacu/cacu_samples.sql`, `Persistance/persistance/measures.py`, `tests/test_cacu_ppv.py` (nuevo).
- Los ocho commits anteriores (catálogo, mapeos, fuente sintética, fixtures) ya estaban en el diagnóstico y no se repiten aquí.
## 2. Referencias de submódulos
**Sin cambios.** Gitlinks idénticos en `67b5518` y `f7faab7`:
| Submódulo | SHA | Observación |
|---|---|---|
| WebApp | `07212a20834542ff856cb71dda7aae95a70b822b` | Sin commits nuevos asociados. |
| WebApi | `9c89c9e10ddd31cffc8b7235d87af88de4e4663a` | Sin commits nuevos. Ver el punto crítico de §6. |
| models | `a93292f3dda1afe09ae77f84bbf80937924afa94` | Es la punta de `feature/risk-factors-cacu` en models; no hay nada posterior. |
`ls-remote` sobre los espejos HTTPS de WebApp y WebApi no muestra ramas `feature/risk-factors-cacu` (solo existe en models). La punta de WebApp (`07212a2`) y la de models (`a93292f`) coinciden con los gitlinks. En WebApi la punta de ramas no coincide con `9c89c9e`; esa verificación solo cubre puntas de rama, así que **no demuestra** que el SHA sea alcanzable (ya señalado en el diagnóstico).
## 3. Clasificación del avance
| Categoría | Contenido de `f7faab7` |
|---|---|
| Cambios de fuentes y mapeos | Ninguno nuevo. Consume `screening_history` (ya mapeado en los 8 commits previos desde el formulario de citología). |
| Nuevos datos clínicos | Ninguno nuevo en el catálogo. Nuevo modelo gold `cacu_referral_facts`: una fila por hecho de la ruta (citología, colposcopia, biopsia) con `report_known_at`, `screening_history` y primeras fechas de caso, tratamiento y colposcopia. |
| Indicadores agregados | `CACU_VPP_COLPOSCOPIA` y `CACU_VPP_BIOPSIA` (proporción con IC de Wilson) con tres desgloses: citología previa (ASCUS+, LSIL+, HSIL+, solapados), nivel de histología (LIEBG+, LIEAG+, invasor, un solo denominador) y tamizaje inicial o subsecuente. Además `CACU_EU7` incorpora `screening_round`, `result_initial` y `result_subsequent`. |
| Modelos y factores de riesgo | **Ninguno.** No cambian `models/`, las especificaciones PIM/logística, ni RiskAssessment. El nombre de la rama sigue sin implicar un modelo nuevo. |
| Contratos de API | Cinco códigos nuevos en `measure-stratifier` (`referral_cytology`, `histology_level`, `screening_round`, `result_initial`, `result_subsequent`) y dos medidas nuevas en el catálogo `/Measure`. Sin cambios en WebApi ni en OpenAPI. |
| Cambios visuales | Ninguno. El propio commit indica «Web app labels are pending». |
| Correcciones técnicas | `Composition` ignora filas cuyo estrato devuelve `None` (fuera de todo grupo). `cacu_samples` expone `report_known_at` y `screening_history`. |
| Infraestructura y pruebas | `tests/test_cacu_ppv.py` (163 líneas). El autor declara que `WebApi/tests/test_cacu.py` **falla** porque su referencia no incluye las medidas nuevas, y que la prueba integral de `hospital_cacu` se detuvo en la validación HL7 (sin validador). |
## 4. Visualizaciones pendientes del Rebuild que podrían completarse
Referencia: tabla del diagnóstico del Rebuild (`DIAGNOSTICO-CACU-REBUILD.md`) y los informes posteriores.
| Pendiente del Rebuild | ¿Lo cubre `f7faab7`? | Estado de datos y contratos |
|---|---|---|
| Confirmación de referencia a colposcopia | **Sí, como aproximación** (`CACU_VPP_COLPOSCOPIA`) | Backend completo (fuente → gold → medida → FHIR); UI genérica sin etiquetas. Ver limitaciones. |
| Confirmación de referencia a biopsia | **Sí, como aproximación** (`CACU_VPP_BIOPSIA`) | Íd. Se solapa con nuestra `CACU_BIOPSIA_SOLICITUD_CONFIRMACION` (otro denominador). |
| Citología en barras, distribución Bethesda | Complemento: `CACU_EU7` gana desgloses por tamizaje inicial/subsecuente y resultado dentro de cada ronda | Datos presentes si el formulario trae `screening_history`; la presentación actual de EU7 no los dibuja con nombres legibles. |
| Antecedente de tamizaje como dimensión de análisis | Nuevo | Disponible vía los estratos anteriores. |
| VPH por genotipo, biopsia en barras, tiempos por CIE-10 | No (ya cubiertos por nuestras medidas locales) | Sin relación con el commit. |
| Individual: riesgos, escalas, etapas, ficha, exportaciones, búsqueda y filtros | **No** | El commit no toca RiskAssessment, modelos, ficha ni exportación. |
### Recorrido de datos comprobado
1. **Fuente.** `synthetic/site.py` imprime la detección en el formulario («PRIMERA VEZ EN LA VIDA», «UN AÑO O MENOS»…), el ConceptMap la mapea a `first_time`, `1_year_or_less`, `2_years`, `3_years_or_more`, y `pipeline.py` la extrae con una expresión regular sobre el texto del formulario. Esto es del bloque previo.
2. **Silver y gold.** `cervical_cytology.sql` es un pivote genérico; `cacu_samples.sql` ahora lee `report_known_at` y `screening_history`; `cacu_referral_facts.sql` une citologías, colposcopías (de `cacu_events`) y biopsias (`cervical_biopsy`).
3. **Medida.** `ReferralPPV` elige por paciente su primer procedimiento calificado, sin casos previos, y la citología previa más reciente tomada y reportada estrictamente antes (≤ 365 días). Devuelve `numerator`/`denominator` por total y por estrato.
4. **FHIR.** Los estratos salen como `MeasureReport.group.stratifier`; sus códigos se añadieron al sistema `measure-stratifier`.
5. **UI.** La WebApp del Rebuild lista medidas desde el catálogo y envía a «clínicas» las que no coloca explícitamente; `strataBars` ya usa `numerator/denominator` para proporciones. Por eso las dos VPP aparecerían solas, pero con la donut «Numerador y resto» y barras tituladas «Por referral_cytology», «Por histology_level», con valores `ASCUS+`, `LIEBG+`, `initial`, `subsequent` sin traducir (`STRATA` y `LABELS` de `measures.ts` no los conocen).
### Qué sí se verificó y qué no
- Verificado: las 8 pruebas de `tests/test_cacu_ppv.py` pasan sobre el código remoto, montado en solo lectura en un contenedor de la imagen local con pytest instalado en un directorio temporal. Cubren ventana de 365 días, mismo día, casos excluidos, primer procedimiento por paciente y el desglose de tamizaje.
- **No verificado:** dbt contra una base real, carga de la fuente sintética, la lectura FHIR de las medidas nuevas ni la interfaz. Esto último requiere el candidato integrado. Tampoco se ejecutó `WebApi/tests/test_cacu.py`, que el autor ya declara roto.
### Limitaciones de las VPP antes de implementar
- «Referencia» es un nombre generoso: no hay entidad de referencia. La unidad es un procedimiento registrado en el periodo; las colposcopias son **inferidas** de notas y biopsias en `cacu_events` (hallazgo ya documentado en nuestro informe de tiempos y confirmación), no órdenes emitidas.
- Pendientes clínicos que el propio commit marca por confirmar: 365 días, coincidencia de biopsia el mismo día y ASC-H dentro de LSIL+.
- La citología previa se elige por fechas; no hay vínculo biopsia-citología, de modo que es una asociación temporal, no confirmada.
- «LIEBG+» incluye LSIL y CIN2+; la numeración visual de la WebApp renombra LSIL a «LIEBG» pero no `LIEBG+`.
- Cada estrato `histology_level` comparte denominador: sirve para barras de tasa, no para una distribución que sume 100 %.
- La ronda de tamizaje es «Sin dato» cuando el formulario no trae la detección; hay que ver cuántos casos reales caen ahí antes de presentarla como desglose principal.
## 5. Posibles conflictos con el candidato integrado
Simulación de fusión a tres vías (base `359c241`; «nuestros» = archivos locales del Rebuild; «remoto» = `f7faab7`), sin escribir en ningún repositorio:
| Archivo | Resultado | Detalle |
|---|---|---|
| `Core/core/cacu/measures.py` | **2 conflictos** | Bloque de imports (ambos añaden `dataclass`, `Result`; el remoto añade `Period`, `wilson`; nosotros `statistics`) y la lista `MEASURES` (nuestras cuatro medidas locales frente a `CACU_VPP_*` y el nuevo `CACU_EU7`). Mantener ambos lados. |
| `Persistance/persistance/measures.py` | **1 conflicto** | `READS["cacu"]`: añadimos cuatro fuentes y el remoto `referral_facts`. Mantener todas. |
| `Core/core/fhir.py`, `Core/core/measures.py`, `Persistance/persistance/fhir.py` | Limpios en texto | Revisar semántica: ambos amplían `measure-stratifier` y las firmas de `Result`/`Measure`; hay que comprobar que el diccionario final contenga los cinco códigos nuevos y `diagnosis_code`. |
| `cacu_referral_facts.sql`, `cacu_samples.sql`, `test_cacu_ppv.py` | Sin conflicto | Nuevos o solo remotos. |
Riesgos semánticos adicionales:
- Dos medidas de confirmación de biopsia con denominadores distintos (`CACU_BIOPSIA_SOLICITUD_CONFIRMACION` local y `CACU_VPP_BIOPSIA`). Decidir si conviven y cómo se rotulan.
- `CACU_BIOPSIA_SOLICITUD_CONFIRMACION` declara `supports_as_of=False`; las VPP sí admiten `as_of` por `report_known_at`. Confirmar en el candidato que ambos comportamientos coexisten.
- `Result` ganó `stratum_scores` en nuestra rama; `ReferralPPV` lo ignora y construye `Result` por palabra clave, de modo que es compatible.
- Los tests de `WebApi/tests/test_cacu.py` requieren actualizar su referencia a las medidas nuevas, y nosotros también modificamos ese archivo.
- El `e2e/pages.spec.ts` local ya cubre el tamaño variable del catálogo; hay que reconfirmarlo con las dos medidas nuevas y los estratos extra de EU7.
## 6. Punto crítico, sin cambios desde el diagnóstico
Los tres submódulos mantienen sus gitlinks, pero el commit nuevo **añade lógica en el integrador (Core/Persistance) sin su contraparte en WebApi** (pruebas) ni en WebApp (etiquetas). Publicar el integrador con un gitlink de WebApi/WebApp que no conozca estas medidas deja `test_cacu.py` en rojo en CI. El diagnóstico ya exigía comprobar la accesibilidad de `9c89c9e`; sigue sin demostrarse.
## 7. Recomendaciones y prioridades
1. **Integrar primero el commit en Core/Persistance** resolviendo los tres conflictos anteriores; luego ejecutar sus 8 pruebas, dbt y una carga sintética nueva (revisar cuántos registros traen `screening_history`). Bloquea todo lo demás.
2. **Actualizar la referencia de `WebApi/tests/test_cacu.py`** con las medidas y desgloses nuevos, en la misma rama de trabajo de WebApi (conflicto previsible con nuestros cambios en ese archivo).
3. **WebApp (baja complejidad, tras 1 y 2):** añadir a `STRATA` y `LABELS` los nombres nuevos (citología previa, histología, tamizaje inicial/subsecuente; ASCUS+, LSIL+, HSIL+, LIEBG+, LIEAG+, invasor), ubicar las dos VPP junto a la confirmación y mostrar numerador/denominador/IC. Rotular como «VPP de colposcopía/biopsia registrada» con nota de que la colposcopia es inferida y la asociación con citología es temporal, hasta tener aprobación clínica.
4. **Decisión de producto:** reconciliar `CACU_VPP_BIOPSIA` con nuestra `CACU_BIOPSIA_SOLICITUD_CONFIRMACION` (mantener una como principal o presentar ambas con definiciones explícitas).
5. **Desgloses de EU7 por ronda:** valorar después de medir la cobertura de `screening_history`; no incluirlos si la mayoría queda en «Sin dato».
6. **No esperar nada de esta rama para riesgos individuales, escalas, etapas, ficha ni exportaciones:** esos pendientes siguen dependiendo únicamente de nuestro Rebuild.
7. Antes de publicar: confirmar la accesibilidad de los SHA de WebApi y WebApp, y volver a ejecutar `git ls-remote` para detectar nuevos commits en `feature/risk-factors-cacu` mientras Codex concluye.
## Alcance y límites de esta revisión
- Se consultó únicamente el remoto de Gitea y los espejos HTTPS de los tres submódulos; el URL real de los submódulos (SSH a `10.0.10.41`) no se consultó.
- La simulación de fusión usó copias normalizadas de fin de línea en el directorio temporal de la sesión; no sustituye a una fusión real en el candidato.
- No se ejecutó ninguna carga, entrenamiento, dbt ni prueba de interfaz; solo las 8 pruebas unitarias descritas.
@@ -0,0 +1,94 @@
# Candidato integrado CaCu — estado de cierre
Versión para **revisión del equipo**. No está certificada para producción: hay pruebas bloqueadas, una prueba integral no concluida y validaciones pendientes (ver «Pruebas» y «Pendientes»).
## Base
| Repositorio | Base | Contenido añadido por este trabajo |
|---|---|---|
| Integrador | `f7faab7` (punta de `feature/risk-factors-cacu` verificada el 27-nov-2026) | Core, Persistance, SQL gold, pruebas e informes. Las modificaciones se montan sobre `f7faab7`, de modo que la ascendencia de la rama se conserva. |
| WebApp | `07212a2` | Indicadores clínicos, etapas, riesgos, ficha, exportaciones y etiquetas de las VPP. |
| WebApi | `9c89c9e` | Búsqueda y filtros, etapas, exportador PDF/XLSX con Roboto y logotipo, pruebas. |
| models | `a93292f` (gitlink de la rama) | Sin cambios. |
El diagnóstico de integración (`INFORME-INTEGRACION-FEATURE-RISK-FACTORS-CACU.md`) y la investigación posterior (`INFORME-AVANCES-REMOTOS-CACU.md`, en `C:\dev\ISSSTELEON-CaCu-Revision-Remota`) describen la divergencia y el origen de cada decisión.
## Integración de `f7faab7` (VPP de referencia y desgloses de tamizaje)
- Se incorporó el commit completo: `cacu_referral_facts.sql`, `cacu_samples.sql`, `core/cacu/__init__.py`, `tests/test_cacu_ppv.py` y las medidas `CACU_VPP_COLPOSCOPIA` / `CACU_VPP_BIOPSIA`, más los estratos de `CACU_EU7` (`screening_round`, `result_initial`, `result_subsequent`).
- Conflictos de texto resueltos conservando ambos lados: `Core/core/cacu/measures.py` (clases `BiopsyRequests`, `DiagnosisDurations`, `ReferralPPV`; lista `MEASURES` con las medidas locales y las del equipo) y `Persistance/persistance/measures.py` (`READS["cacu"]` con las cuatro fuentes locales y `referral_facts`). `Core/core/fhir.py` y `Core/core/measures.py` se fusionaron sin conflicto; el diccionario `measure-stratifier` contiene `diagnosis_code` y los cinco estratos nuevos.
- `CACU_VPP_BIOPSIA` y `CACU_BIOPSIA_SOLICITUD_CONFIRMACION` conviven: sus denominadores son distintos (pacientes con biopsia reportada frente a solicitudes de biopsia registradas).
- La interfaz rotula las VPP como «VPP tras colposcopía/biopsia registrada» y avisa de que la colposcopía puede ser inferida de notas y de que la citología previa es una asociación por fechas, no una referencia emitida ni un vínculo clínico confirmado.
- Contrato de WebApi: `tests/test_cacu.py` acepta las dos medidas nuevas y los estratos nuevos de EU7, con invariantes (ver «Pruebas»).
## Fallo de memoria de la ingesta y solución
**Síntoma.** Las ejecuciones `dd4903cf…` y `51c8cbb2…` terminaron en FAILURE con `OSError: [Errno 12] Cannot allocate memory` (primero en la carga dlt de `biopsy_cytology`; después sobre `/data/dlt/pipelines/staged__held/load/normalized/.`).
**Diagnóstico.** El anfitrión tiene 10,9 GB de RAM (≈0,9 GB libres) y la VM de Docker/WSL2 5,4 GB con 2 GB de swap, que estaba lleno (2/2 GB), con `vm.overcommit_memory=1` (el fallo no era de límite de compromiso sino de agotamiento real). Había 14 contenedores activos de varias líneas de trabajo. El candidato escribía `/data` en un montaje de enlace de Windows (`./data`), que bajo presión de memoria falló en operaciones de directorio.
**Solución aplicada (proporcional, sin tocar servicios ajenos):**
1. Un solo worker por etapa de dlt en `compose.candidato.yml` (`EXTRACT__WORKERS=1`, `NORMALIZE__WORKERS=1`, `LOAD__WORKERS=2`).
2. `/data` del candidato pasó a un volumen Docker propio, `cacu-candidato-data`; la base nueva se creó vacía y las bases fallidas se conservaron en `data-fallida-dd4903cf` y `data-fallida-51c8cbb2`.
3. Con autorización, se detuvieron temporalmente los entornos de la fase 7C de sesiones anteriores (ver «Servicios detenidos»).
Un intento de añadir swap a la VM compartida fue rechazado por el control de permisos y no se aplicó.
**Resultado.** Ingesta `5f04e799-4bcd-4b6e-8644-9e2220d918d5`: **SUCCESS** en unos 2 minutos. Gold: 461 muestras, 604 hechos de referencia (461 citologías, 96 colposcopías, 47 biopsias), 221 reportes VPH, 40 reportes de biopsia, 47 solicitudes de biopsia, 312 personas. Las 19 medidas CaCu están publicadas.
## Validaciones funcionales (4312 contra la API 5070)
| Área | Resultado |
|---|---|
| Indicadores de oportunidad y clínicos | Cargan con datos del periodo Jul–Dic 2026; las distribuciones de citología, VPH y biopsia y la ruta del tamizaje se muestran con sus escalas. |
| VPP | `CACU_VPP_COLPOSCOPIA` 2026-S2: 4/20 (20,0 %); `CACU_VPP_BIOPSIA` 2026-S2: 13/14 (92,9 %). Invariantes confirmadas por la API: numerador total = nivel LIEBG+; LIEBG+ ≥ LIEAG+ ≥ invasor con el mismo denominador; denominadores de citología previa ASCUS+ ≥ LSIL+ ≥ HSIL+. |
| `screening_history` | **Cobertura 0 de 461 muestras** (todas `NULL`): el fixture `hospital_cacu` no trae el campo. El estrato «inicial» nunca aparece, «subsecuente» surge solo del estatus de ruta y casi todo cae en «Sin dato» (p. ej. EU7 2026-S2: 72 sin dato y 13 subsecuente de 85). Con esta fuente el desglose no es informativo; requiere la fuente del sitio con formularios. |
| Análisis de riesgos | Lista de 63 pacientes con nodos de etapas; las columnas de riesgo muestran «—» porque no se entrenaron ni puntuaron modelos. |
| Filtros y paginación | API: total 63 (páginas de 20: 20/20/20/3); edad 46–46: 3; edad 30–40 y pre colposcopía: 13; búsqueda por identificador `bb12c77f`: 1; sin coincidencias: 0; rango invertido: error de validación. |
| Exportación PDF completa | 63 identificadores, 11 páginas, «Página 11 de 11», encabezado, pie y leyenda de nodos en cada página. |
| Exportación PDF filtrada (30–40) | 16 pacientes, 4 páginas. |
| Exportación Excel filtrada | Hojas «Resultados» (16 filas, edades 30–39) y «Parámetros» (corte, ventana, edades 30 y 40, registros 16). |
| Ficha individual | Identificación, etapas con fechas e intervalos (colposcopía ambigua; diagnóstico «Registrada · Inferida temporalmente», «1 días (inferido)»), historial, pruebas y riesgos. |
| Escalas de riesgo | Respuesta sintética inyectada solo en memoria del navegador (nada persistido): 0, 2, 50, 98 y 100 % más un horizonte ausente. La ficha web y el PDF muestran el marcador en su posición, el intervalo de 95 % y «No disponible» sin marcador para el ausente; 0 % no se trata como ausente. |
| Fechas y desenlaces | Las fechas ISO se respetan (toma, reporte, intervalos); los desenlaces se rotulan CIN2+ y cáncer sin equiparar CIN2+ con LIEAG+; los ausentes se muestran como «No disponible». |
| Comparación con 4311 | Limitada: el diseño es el mismo código base. Durante la comparación 4311 se quedó en «Calculando…» mientras la prueba integral competía por memoria; no se completó una comparación de datos. |
## Pruebas
| Prueba | Estado |
|---|---|
| WebApp `ng test` | 21 aprobadas en 6 archivos; `follow-up.spec.ts` falla bajo el constructor Angular por `vi.mock` con importaciones relativas. |
| WebApp `vitest run follow-up.spec.ts` | 7/7 aprobadas (ese archivo se ejecutó aparte). |
| WebApp `ng build` | Aprobada. |
| Core/Persistance (pytest aislado, solo lectura): `test_cacu_ppv`, `test_cacu_report_measures`, `test_cacu_biopsy_requests`, `test_cacu_stages` | 14 aprobadas (incluye las 8 de las VPP). |
| Exportador (`unittest`) | Aprobadas en la intervención anterior (4) tras añadir los casos de PDF. |
| `WebApi/tests/test_cacu.py` (integral) | **No concluyó. Fallida por el entorno de prueba, no por el código**: el contenedor aislado montaba `Persistance` como solo lectura y `dbt` no pudo escribir `dbt/logs/dbt.log` (`Errno 30 Read-only file system`), de modo que la ingesta interna falló. No se repitió por tiempo. Sus aserciones nuevas (VPP y estratos de EU7) están escritas pero **no ejecutadas**. |
| `models/tests/test_silver.py` | **Bloqueada**: requiere Java y el jar de Synthea (`SYNTHEA_JAR`), que no están disponibles localmente; descargarlo exige autorización. Un intento anterior con 10 aprobadas y 2 errores de preparación por falta de `java` en la imagen. |
| `git diff --check` | Sin hallazgos en WebApp, WebApi e integrador. |
No deben darse por aprobadas las pruebas bloqueadas ni la prueba integral.
## Servicios locales detenidos y recuperación
Detenidos con `docker stop` (no se eliminó ningún contenedor, imagen, volumen ni base de datos). Detalle en `servicios-detenidos.md`:
- Instalador DEV, fase 7C: `isssteleon-dev-38380-webapp-1`, `-notebooks-1`, `-indicadores-1`, `-webapi-1`.
- `wnf7c-hospital-hospital-1` (MySQL del hospital sintético de la fase 7C).
Recuperación (volúmenes intactos):
docker start wnf7c-hospital-hospital-1 isssteleon-dev-38380-webapi-1 isssteleon-dev-38380-indicadores-1 isssteleon-dev-38380-notebooks-1 isssteleon-dev-38380-webapp-1
No se detuvieron los `cacu-webapi-*` (revisiones 4304/4305), el stack 4311 ni el servicio 5710. Los contenedores del candidato (`cacu-candidato-*`) y 4312 siguen activos. Reinicio del candidato: `docker compose --project-name cacu-candidato --env-file candidato.env -f compose.yml -f compose.candidato.yml up -d api dagster-daemon`; WebApp: `node node_modules/@angular/cli/bin/ng.js serve --host 127.0.0.1 --port 4312 --proxy-config ../proxy.candidato.json`.
## Pendientes para revisión del equipo
1. Repetir `WebApi/tests/test_cacu.py` en un entorno con escritura para dbt, con `java`/Synthea (entorno de pruebas del proyecto) y con memoria suficiente; incluye entrenamiento y promoción de modelos.
2. Ejecutar `models/tests/test_silver.py` con Synthea y el sitio SQL sintético.
3. Búsqueda por nombre: pendiente, el fixture `hospital_cacu` no trae nombres (`person_name` vacía); requiere la fuente del sitio.
4. Cobertura de `screening_history` con la fuente del sitio (formularios de citología); sin ella los desgloses por ronda no son informativos.
5. Revisión clínica de las VPP: ventana de 365 días, mismo día, ASC-H en LSIL+, y el uso de colposcopías inferidas.
6. Ajustes visuales: las tarjetas «Tasa de confirmación… a colposcopia/biopsia» aún dicen «No disponible» junto a las VPP; mostrar n/N y los intervalos en las barras de estratos; representar el estrato «Sin dato» de ronda de tamizaje de forma menos prominente; el campo «Expedientes» de la ficha repite identificadores duplicados; comparar con 4311 una vez liberada la memoria.
7. Riesgos individuales: no hay modelos entrenados en el candidato; las columnas de riesgo están vacías. La salida PIM publica horizonte, desenlace e IC; no se han demostrado equivalencias entre CIN2+, LIEAG+, CIN3+ y cáncer.
8. Licencias y procedencia de Roboto y del logotipo institucional antes de cualquier uso externo.
9. Gitlink de WebApi: el submódulo apunta al repositorio HTTPS de Gitea; `.gitmodules` conserva la URL SSH interna.
+1 -1
Submodule models updated: 999f0fb926...a93292f3dd
+4 -1
View File
@@ -61,7 +61,8 @@ 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 (free text), observations, reader,
reader_id."""
pdf = _pdf()
pdf.set_font("helvetica", "B", 15)
pdf.set_text_color(*GREEN)
@@ -110,6 +111,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, 40, "HALLAZGOS ADICIONALES:", c["findings"])
y += 40
_box(pdf, 50, y, 512, 70, value="Observaciones: " + c["observations"], size=7.5)
pdf.set_font("helvetica", "", 8.5)
+112 -10
View File
@@ -198,17 +198,96 @@ def _d(iso: str) -> date:
return date.fromisoformat(str(iso)[:10])
def _findings(rng: random.Random) -> tuple[str, dict]:
"""The cytologist's free text (none, one or two statements) and the values it states."""
picked = rng.sample(list(FINDINGS_CYTO), rng.choice((0, 1, 1, 2)))
if "cyto_findings_none" in picked:
picked = ["cyto_findings_none"]
said, values = [], {}
for field in picked:
statement, values[field] = FINDINGS_CYTO[field], True
if field == "cyto_inflammation": # a grade may follow; no field takes it
statement += rng.choice(("", " leve", " moderada", " severa"))
said.append(statement + ".")
text = " ".join(said)
if len(text) > 100: # one line: the expected text has no line break
return _findings(rng)
if text:
values["cyto_findings_text"] = text
return text, values
def _age(birth: date, on: date) -> int:
return on.year - birth.year - ((on.month, on.day) < (birth.month, birth.day))
# --- what each layout prints, from a study's platform values -------------------------
SQUAMOUS = {
"NILM": "NINGUNA",
DETECTION = { # the cytology form's box 2: screening_history -> as printed
"first_time": "PRIMERA VEZ EN LA VIDA",
"1_year_or_less": "UN AÑO O MENOS",
"2_years": "2 AÑOS",
"3_years_or_more": "3 O MÁS AÑOS",
}
GYN = { # box 3: the one condition the form records -> as printed
"gyn_puerperium": "PUERPERIO POSTPARTO O POSTABORTO",
"gyn_pregnancy": "EMBARAZO ACTUAL",
"gyn_iud": "DIU IN SITU",
"gyn_hormonal_treatment": "TRATAMIENTO HORMONAL",
"gyn_other_treatment": "OTRO TRATAMIENTO GINECOLÓGICO",
"gyn_postmenopause": "POST MENOPAUSIA",
"gyn_hysterectomy": "HISTERECTOMÍA",
"gyn_not_applicable": "NO APLICA",
}
PRESENTS = { # box 4: the one answer the form records -> as printed
"presents_discharge": "FLUJO",
"presents_vulvar_pruritus": "PRURITO O ARDOR VULVAR",
"presents_abnormal_bleeding": "SANGRADO ANORMAL",
"presents_none": "NINGUNO",
}
EXPLORES = { # box 5: cervix_exam -> as printed
"healthy": "CUELLO SANO",
"abnormal_with_lesion": "CUELLO ANORMAL CON LESIÓN",
"not_visible": "NO SE OBSERVA CUELLO",
}
FINDINGS_CYTO = { # the cytologist's additional findings: field -> as written
"cyto_inflammation": "Inflamación",
"cyto_reactive_changes": "Cambios reactivos",
"cyto_bacterial_vaginosis_flora": "Cambio en la flora sugestiva de vaginosis bacteriana",
"cyto_candida": "Microorganismos micóticos morfológicamente compatibles con Candida sp",
"cyto_bacillary_flora_cytolysis": (
"Aumento de la flora bacilar con citólisis de las células intermedias"
),
"cyto_intermediate_cytolysis": "Citólisis de las células intermedias",
"cyto_trichomonas": "Trichomonas vaginalis",
"cyto_leptothrix": "Microorganismos bacterianos morfológicamente compatibles con Leptothrix",
"cyto_actinomyces_organisms": "Microorganismos morfológicamente compatibles con Actinomyces sp",
"cyto_actinomyces_changes": "Cambios celulares compatibles con Actinomyces sp",
"cyto_herpes_simplex_changes": "Cambios celulares compatibles con virus herpes simple",
"cyto_squamous_tubular_metaplasia": "Metaplasia escamosa tubular",
"cyto_keratotic_changes": "Cambios queratósicos",
"cyto_pregnancy_changes": "Cambios asociados al embarazo",
"cyto_atrophy": "Atrofia",
"cyto_hypoestrogenism": "Hipoestrogenismo",
"cyto_radiotherapy_effect": "Efecto de radioterapia",
"cyto_iud_changes": "Cambios compatibles con presencia de dispositivo intrauterino",
"cyto_post_hysterectomy_glandular_cells": "Células glandulares post-histerectomía",
"cyto_bacteria": "Bacterias",
"cyto_herpes_image": "Imagen del virus del herpes",
"cyto_fungi": "Hongos",
"cyto_radiation": "Radiación",
"cyto_repair": "Reparación",
"cyto_iud_effect": "Efecto del DIU",
"cyto_endometrial_cells_40_plus": (
"Presencia de células endometriales en pacientes de 40 años o más"
),
"cyto_findings_none": "Ninguno",
}
SQUAMOUS = { # result -> as the form writes it
"NILM": "NO",
"ASC-US": "ASC-US",
"ASC-H": "ASC-H",
"LSIL": "LESIÓN DE BAJO GRADO (LIEBG)",
"HSIL": "LESIÓN DE ALTO GRADO (LIEAG)",
"LSIL": "LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)",
"HSIL": "LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)",
"CIS": "CARCINOMA IN SITU",
}
CERVIX = {
@@ -396,6 +475,11 @@ def build(bundles: list[dict], url: str, out: Path, *, seed: int = 7, years: int
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"))
detection_rng = random.Random(f"{seed}-detection")
gyn_rng = random.Random(f"{seed}-gyn")
presents_rng = random.Random(f"{seed}-presents")
explores_rng = random.Random(f"{seed}-explores")
findings_rng = random.Random(f"{seed}-findings")
# Namesakes: the second woman with a pathology report takes the first woman's name.
with_pathology = [
pid
@@ -461,14 +545,26 @@ def build(bundles: list[dict], url: str, out: Path, *, seed: int = 7, years: int
person, identity = _institute(p, taken, rng, i in sloppy)
result = r.get("result")
satisfactory = r.get("adequacy") == "satisfactory"
detection = detection_rng.choice(list(DETECTION))
gyn = gyn_rng.choice(list(GYN))
presents = presents_rng.choice(list(PRESENTS))
explores = explores_rng.choice(list(EXPLORES))
findings, stated = _findings(findings_rng)
# the request (FECHA) comes before the sample (FECHA DE RECEPCIÓN)
requested = taken - timedelta(days=rng.randint(1, 4))
# unused draws: they keep the main stream, so the rest of the site, as it was
rng.randrange(2)
rng.randrange(3)
rng.randrange(2)
rng.randrange(2)
form = {
"requested": taken,
"received": taken + timedelta(days=rng.randint(1, 4)),
"requested": requested,
"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": DETECTION[detection],
"conditions": GYN[gyn],
"presents": PRESENTS[presents],
"explores": EXPLORES[explores],
"nurse": rng.choice(NURSES),
"adequacy": "SATISFACTORIO" if satisfactory else "INSATISFACTORIO",
"lesion": "" if not result else "NEGATIVO" if result == "NILM" else "POSITIVO",
@@ -476,6 +572,7 @@ def build(bundles: list[dict], url: str, out: Path, *, seed: int = 7, years: int
"squamous": SQUAMOUS.get(result, ""),
"invasive": "NO" if result else "",
"glandular": "NINGUNA" if result else "",
"findings": findings,
"observations": "MUESTRA INSUFICIENTE, SE SOLICITA NUEVA TOMA."
if not satisfactory
else "",
@@ -484,6 +581,11 @@ def build(bundles: list[dict], url: str, out: Path, *, seed: int = 7, years: int
}
values = {
"sample_date": str(taken),
"screening_history": detection,
gyn: True,
presents: True,
"cervix_exam": explores,
**stated,
"report_date": str(reported),
"adequacy": r.get("adequacy"),
"result": result,
+696
View File
@@ -146,6 +146,162 @@
"equivalence": "equivalent"
}
]
},
{
"code": "NO",
"target": [
{
"code": "NILM",
"equivalence": "equivalent"
}
]
},
{
"code": "LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)",
"target": [
{
"code": "LSIL",
"equivalence": "equivalent"
}
]
},
{
"code": "LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)",
"target": [
{
"code": "HSIL",
"equivalence": "equivalent"
}
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/cervical-screening-history",
"element": [
{
"code": "PRIMERA VEZ EN LA VIDA",
"target": [
{
"code": "first_time",
"equivalence": "equivalent"
}
]
},
{
"code": "UN AÑO O MENOS",
"target": [
{
"code": "1_year_or_less",
"equivalence": "equivalent"
}
]
},
{
"code": "UN ANO O MENOS",
"target": [
{
"code": "1_year_or_less",
"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_years_or_more",
"equivalence": "equivalent"
}
]
},
{
"code": "3 O MAS AÑOS",
"target": [
{
"code": "3_years_or_more",
"equivalence": "equivalent"
}
]
},
{
"code": "3 O MÁS ANOS",
"target": [
{
"code": "3_years_or_more",
"equivalence": "equivalent"
}
]
},
{
"code": "3 O MAS ANOS",
"target": [
{
"code": "3_years_or_more",
"equivalence": "equivalent"
}
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/cervix-exam",
"element": [
{
"code": "CUELLO SANO",
"target": [
{
"code": "healthy",
"equivalence": "equivalent"
}
]
},
{
"code": "CUELLO ANORMAL CON LESIÓN",
"target": [
{
"code": "abnormal_with_lesion",
"equivalence": "equivalent"
}
]
},
{
"code": "CUELLO ANORMAL CON LESION",
"target": [
{
"code": "abnormal_with_lesion",
"equivalence": "equivalent"
}
]
},
{
"code": "NO SE OBSERVA CUELLO",
"target": [
{
"code": "not_visible",
"equivalence": "equivalent"
}
]
}
]
},
@@ -170,6 +326,546 @@
"equivalence": "equivalent"
}
]
},
{
"code": "PUERPERIO POSTPARTO O POSTABORTO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "EMBARAZO ACTUAL",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "DIU IN SITU",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "TRATAMIENTO HORMONAL",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "OTRO TRATAMIENTO GINECOLÓGICO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "OTRO TRATAMIENTO GINECOLOGICO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "POST MENOPAUSIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "POSTMENOPAUSIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "HISTERECTOMÍA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "HISTERECTOMIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "NO APLICA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "FLUJO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRURITO O ARDOR VULVAR",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PURITO O ARDOR VULVAR",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "SANGRADO ANORMAL",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "NINGUNO",
"target": [
{
"code": "true",
"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": "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": "PRESENCIA DE CÉLULAS ENDOMETRIALES EN ATIPIAS EN PACIENTES DE 45 AÑOS O MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN ATIPIAS EN PACIENTES DE 45 ANOS O MAS",
"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 MAYORES DE 40 AÑOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN MAYORES DE 40 ANOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "METAPLASIA ESCAMOSA TUBULAR",
"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 MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CÉLULAS ENDOMETRIALES EN ATIPIAS EN PACIENTES DE 40 AÑOS O MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN ATIPIAS EN PACIENTES DE 40 ANOS O MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN ATIPIAS EN PACIENTES DE 45 ANOS O MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
}
]
},
+47 -3
View File
@@ -52,17 +52,61 @@
{"id": "cytology", "kind": "extract", "inputs": ["cytology_forms"],
"column": "text", "entity": "cervical_cytology", "method": "auto",
"hints": "sample_date is the date of 'FECHA DE RECEPCIÓN' on the cytology form, never its 'FECHA' at the top; leave it out if that is empty. screening_history is the answer under 'DETECCIÓN DE CÁNCER DE CÉRVIX': 'PRIMERA VEZ EN LA VIDA' is first_time, 'UN AÑO O MENOS' is 1_year_or_less, '2 AÑOS' is 2_years, '3 O MÁS AÑOS' is 3_years_or_more. Leave it out if that box is empty or shows anything else. Under 'CONDICIONES GINECO-OBSTÉTRICAS A LA DETECCIÓN', set to true only the field the answer names: 'PUERPERIO POSTPARTO O POSTABORTO' is gyn_puerperium, 'EMBARAZO ACTUAL' is gyn_pregnancy, 'DIU IN SITU' is gyn_iud, 'TRATAMIENTO HORMONAL' is gyn_hormonal_treatment, 'OTRO TRATAMIENTO GINECOLÓGICO' is gyn_other_treatment, 'POST MENOPAUSIA' is gyn_postmenopause, 'HISTERECTOMÍA' is gyn_hysterectomy, 'NO APLICA' is gyn_not_applicable. Leave all the others out; never set any of these fields to false. Under 'ACTUALMENTE PRESENTA', the same: 'FLUJO' is presents_discharge, 'PRURITO O ARDOR VULVAR' is presents_vulvar_pruritus, 'SANGRADO ANORMAL' is presents_abnormal_bleeding, 'NINGUNO' is presents_none. Set to true only what the answer names; never set any of these fields to false. cervix_exam is the answer under 'A LA EXPLORACIÓN SE OBSERVA': 'CUELLO SANO' is healthy, 'CUELLO ANORMAL CON LESIÓN' is abnormal_with_lesion, 'NO SE OBSERVA CUELLO' is not_visible. Leave it out if that box is empty or shows anything else. 'HALLAZGOS ADICIONALES' is the cytologist's free text: cyto_findings_text is that text as written. Set a cyto_ finding to true only when the text states it as present; never from a negated, doubted or ruled-out mention, and never set one to false. The nurse's answers never set a cyto_ field, nor the reverse. 'Inflamación' is cyto_inflammation, 'Cambios reactivos' is cyto_reactive_changes, 'Cambio en la flora sugestiva de vaginosis bacteriana' is cyto_bacterial_vaginosis_flora, 'Microorganismos micóticos morfológicamente compatibles con Candida sp' is cyto_candida, 'Aumento de la flora bacilar con citólisis de las células intermedias' is cyto_bacillary_flora_cytolysis, 'Citólisis de las células intermedias' is cyto_intermediate_cytolysis, 'Trichomonas vaginalis' is cyto_trichomonas, 'Microorganismos bacterianos morfológicamente compatibles con Leptothrix' is cyto_leptothrix, 'Microorganismos morfológicamente compatibles con Actinomyces sp' is cyto_actinomyces_organisms, 'Cambios celulares compatibles con Actinomyces sp' is cyto_actinomyces_changes, 'Cambios celulares compatibles con virus herpes simple' is cyto_herpes_simplex_changes, 'Metaplasia escamosa tubular' is cyto_squamous_tubular_metaplasia, 'Cambios queratósicos' is cyto_keratotic_changes, 'Cambios asociados al embarazo' is cyto_pregnancy_changes, 'Atrofia' is cyto_atrophy, 'Hipoestrogenismo' is cyto_hypoestrogenism, 'Efecto de radioterapia' is cyto_radiotherapy_effect, 'Cambios compatibles con presencia de dispositivo intrauterino' is cyto_iud_changes, 'Células glandulares post-histerectomía' is cyto_post_hysterectomy_glandular_cells, 'Bacterias' is cyto_bacteria, 'Imagen del virus del herpes' is cyto_herpes_image, 'Hongos' is cyto_fungi, 'Radiación' is cyto_radiation, 'Reparación' is cyto_repair, 'Efecto del DIU' is cyto_iud_effect, endometrial cells reported for age 40 or older, however worded, is cyto_endometrial_cells_40_plus, 'Ninguno' is cyto_findings_none. Inflammation with any grade or scale is just cyto_inflammation. result is only the answer under 'ANOMALÍAS EN CÉLULAS ESCAMOSAS': 'NO' is NILM, 'ASC-US' is ASC-US, 'ASC-H' is ASC-H, 'LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)' is LSIL, 'LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)' is HSIL, 'CARCINOMA IN SITU' is CIS. Never take it from 'ANORMALIDADES EPITELIALES PRESENTES' or any other box; leave it out if that answer is empty or shows anything else.",
"patterns": {
"sample_date": "\\bfecha:\\s*(\\d{2}/\\d{2}/\\d{4})",
"sample_date": "fecha de recepci[oó]n:\\s*(\\d{2}/\\d{2}/\\d{4})",
"screening_history": "detecci[oó]n de c[aá]ncer de c[eé]rvix:[^\\n]*\\n[ \\t]*(primera vez en la vida|un a[nñ]o o menos|2 a[nñ]os|3 o m[aá]s a[nñ]os)\\b",
"gyn_puerperium": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(puerperio postparto o postaborto)\\b",
"gyn_pregnancy": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(embarazo actual)\\b",
"gyn_iud": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(diu in situ)\\b",
"gyn_hormonal_treatment": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(tratamiento hormonal)\\b",
"gyn_other_treatment": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(otro tratamiento ginecol[oó]gico)\\b",
"gyn_postmenopause": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(post ?menopausia)\\b",
"gyn_hysterectomy": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(histerectom[ií]a)\\b",
"gyn_not_applicable": "condiciones gineco-?o?bst[eé]tricas a la detecci[oó]n[^\\n]*\\n[^\\n]*?\\b(no aplica)\\b",
"presents_discharge": "actualmente presenta:[^\\n]*\\n[ \\t]*(flujo)\\b",
"presents_vulvar_pruritus": "actualmente presenta:[^\\n]*\\n[ \\t]*(pr?urito o ardor vulvar)\\b",
"presents_abnormal_bleeding": "actualmente presenta:[^\\n]*\\n[ \\t]*(sangrado anormal)\\b",
"presents_none": "actualmente presenta:[^\\n]*\\n[ \\t]*(ninguno)\\b",
"cervix_exam": "a la exploraci[oó]n se observa:[^\\n]*\\n[^\\n]*?\\b(cuello sano|cuello anormal con lesi[oó]n|no se observa cuello)\\b",
"cyto_findings_text": "hallazgos(?:\\s+adicionales)?\\s*:\\s*((?!observaciones:)\\S(?:(?!observaciones:)[\\s\\S])*?)\\s*(?=observaciones:)",
"cyto_inflammation": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(inflamaci[oó]n)(?=(?:\\s+(?:leve|moderada|severa|\\+{1,3}))?\\s*(?:[.;]|observaciones:|$))",
"cyto_reactive_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+reactivos)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_bacterial_vaginosis_flora": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambio\\s+en\\s+la\\s+flora\\s+sugestiva\\s+de\\s+vaginosis\\s+bacteriana)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_candida": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(microorganismos\\s+mic[oó]ticos\\s+morfol[oó]gicamente\\s+compatibles\\s+con\\s+candida\\s+sp)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_bacillary_flora_cytolysis": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\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*(?:[.;]|observaciones:|$))",
"cyto_intermediate_cytolysis": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cit[oó]lisis\\s+de\\s+las\\s+c[eé]lulas\\s+intermedias)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_trichomonas": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(trichomonas\\s+vaginalis)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_leptothrix": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(microorganismos\\s+bacterianos\\s+morfol[oó]gicamente\\s+compatibles\\s+con\\s+leptothrix)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_actinomyces_organisms": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(microorganismos\\s+morfol[oó]gicamente\\s+compatibles\\s+con\\s+actinomyces\\s+sp)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_actinomyces_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+actinomyces\\s+sp)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_herpes_simplex_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+virus\\s+herpes\\s+simple)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_squamous_tubular_metaplasia": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(metaplasia\\s+escamosa\\s+tubular)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_keratotic_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+querat[oó]sicos)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_pregnancy_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+asociados\\s+al\\s+embarazo)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_atrophy": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(atrofia)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_hypoestrogenism": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(hipoestrogenismo)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_radiotherapy_effect": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(efecto\\s+de\\s+radioterapia)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_iud_changes": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(cambios\\s+compatibles\\s+con\\s+presencia\\s+de\\s+dispositivo\\s+intrauterino)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_post_hysterectomy_glandular_cells": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(c[eé]lulas\\s+glandulares\\s+post-histerectom[ií]a)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_bacteria": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(bacterias)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_herpes_image": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(imagen\\s+del\\s+virus\\s+del\\s+herpes)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_fungi": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(hongos)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_radiation": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(radiaci[oó]n)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_repair": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(reparaci[oó]n)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_iud_effect": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(efecto\\s+del\\s+diu)(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_endometrial_cells_40_plus": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(presencia\\s+de\\s+c[eé]lulas\\s+endometriales\\s+en\\s+(?:mayores\\s+de\\s+40\\s+a[nñ]os|(?:atipias\\s+en\\s+)?pacientes\\s+de\\s+4[05]\\s+a[nñ]os\\s+o\\s+m[aá]s))(?=\\s*(?:[.;]|observaciones:|$))",
"cyto_findings_none": "hallazgos(?:\\s+adicionales)?\\s*:(?:(?:(?!observaciones:)[\\s\\S])*?[.;])??\\s*(ninguno)(?=\\s*(?:[.;]|observaciones:|$))",
"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 de bajo grado|lesi[oó]n de alto grado|carcinoma in situ)\\b"},
"result": "(?:anomal[ií]as\\s+en\\s+c[eé]lulas\\s+escamosas[ \\t]*:?[^\\n]*\\n[ \\t]*(?:(?:s[ií]|no)\\b)??[ \\t]*(?=(?:asc-us|asc-h|lesion\\s+intraepitelial\\s+escamosa\\s+de\\s+bajo\\s+grado\\s+\\(displasia\\s+leve\\s+y/o\\s+vph\\)|lesion\\s+intraepitelial\\s+escamosa\\s+de\\s+alto\\s+grado\\s+\\(displasia\\s+moderada\\s+y\\s+grave\\)|carcinoma\\s+in\\s+situ))|anomal[ií]as\\s+en\\s+c[eé]lulas\\s+escamosas[ \\t]*:?[^\\n]*\\n[ \\t]*(?:s[ií]|no)[ \\t]+(?=no(?=[ \\t]*(?:\\n|$)))|(?:^|\\n)[ \\t]*(?:\\d+[ \\t]*\\.-?[ \\t]*)?anomal[ií]as\\s+en\\s+c[eé]lulas\\s+escamosas[ \\t]*:?[ \\t]*\\n[ \\t]*(?=no(?=[ \\t]*(?:\\n|$))))(asc-us|asc-h|lesion\\s+intraepitelial\\s+escamosa\\s+de\\s+bajo\\s+grado\\s+\\(displasia\\s+leve\\s+y/o\\s+vph\\)|lesion\\s+intraepitelial\\s+escamosa\\s+de\\s+alto\\s+grado\\s+\\(displasia\\s+moderada\\s+y\\s+grave\\)|carcinoma\\s+in\\s+situ|no(?=[ \\t]*(?:\\n|$)))"},
"concept_map": "erick_site",
"formats": {"sample_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
{"id": "hpv", "kind": "extract", "inputs": ["hpv_orders"],
"column": ["text__cytology_forms", "text"], "entity": "cervical_cytology", "method": "auto",
"hints": "sample_date is the date of 'FECHA DE RECEPCIÓN' on the cytology form, never its 'FECHA' at the top; leave it out if that is empty.",
"patterns": {
"sample_date": "\\bfecha:\\s*(\\d{2}/\\d{2}/\\d{4})",
"sample_date": "fecha de recepci[oó]n:\\s*(\\d{2}/\\d{2}/\\d{4})",
"hpv": "\\nV{4}P{4}H{4} \\.[ .]+(\\w+)",
"hpv_16": "V{4}P{4}H{4} 1{4}6{4}[ .]+(\\w+)",
"hpv_18": "V{4}P{4}H{4} 1{4}8{4}[ .]+(\\w+)"},
+55
View File
@@ -0,0 +1,55 @@
"""Recorded biopsy-request measure: dates, missing data, deduplication and FHIR."""
import unittest
from datetime import date, datetime, timezone
from core.cacu.measures import MEASURES
from core.measures import Period, evaluate, report
def row(key, request, result=None, grade=None, report_known=None):
return {"request_id": key, "request_date": date.fromisoformat(request),
"report_date": date.fromisoformat(result) if result else None, "histology": grade,
"order_known_at": "2026-01-01T00:00:00+00:00", "report_known_at": report_known}
class BiopsyRequestTest(unittest.TestCase):
def test_categories_cutoff_and_deduplication(self):
m = MEASURES["CACU_BIOPSIA_SOLICITUD_CONFIRMACION"]
rows = [row("a", "2026-01-02", "2026-01-04", "LSIL"),
row("a", "2026-01-02", "2026-01-05", "HSIL"),
row("b", "2026-01-02"),
row("c", "2026-01-02", "2026-01-04"),
row("d", "2026-01-02", "2026-01-01", "HSIL"),
row("e", "2026-01-02", "2026-01-05", "unknown"),
row("f", "2026-01-02", "2026-03-01", "CIS"),
row("g", "2026-07-02", "2026-07-03", "normal"),
{**row("h", "2026-01-02", "2026-01-05", "CIS"), "rows_merged": 2}]
p = Period.parse("2026-S1")
r = evaluate(m, rows, p, event_cutoff=date(2026, 2, 1))
self.assertEqual(r.populations["initial-population"], 7)
self.assertEqual({k: v["initial-population"] for k, v in r.strata["category"].items()},
{"high_grade": 1, "pending": 2, "no_grade": 1,
"inconsistent": 1, "unclassified": 1, "ambiguous": 1})
self.assertEqual(report(m, p, r, None).get_resource_type(), "MeasureReport")
self.assertEqual(evaluate(m, rows, Period.parse("2026-02")).populations["initial-population"], 0)
self.assertEqual(evaluate(m, rows, Period.parse("2026-S2"),
event_cutoff=date(2026, 6, 30)).populations["initial-population"], 0)
def test_as_of_is_rejected_without_event_knowledge_times(self):
m = MEASURES["CACU_BIOPSIA_SOLICITUD_CONFIRMACION"]
rows = [row("a", "2026-01-02", "2026-01-04", "CIS", "2026-02-01T00:00:00+00:00")]
with self.assertRaises(ValueError):
evaluate(m, rows, Period.parse("2026-S1"),
as_of=datetime(2026, 1, 20, tzinfo=timezone.utc))
def test_zero_high_grade_with_nonzero_denominator(self):
m = MEASURES["CACU_BIOPSIA_SOLICITUD_CONFIRMACION"]
rows = [row("a", "2026-01-02", "2026-01-04", "normal")]
result = evaluate(m, rows, Period.parse("2026-S1"), event_cutoff=date(2026, 2, 1))
self.assertEqual(result.populations["initial-population"], 1)
self.assertNotIn("high_grade", result.strata["category"])
self.assertEqual(result.strata["category"]["below_high_grade"]["initial-population"], 1)
if __name__ == "__main__":
unittest.main()
+211
View File
@@ -0,0 +1,211 @@
"""CaCu's referral PPVs (core.cacu.measures.ReferralPPV) over made-up facts."""
from datetime import UTC, datetime
from decimal import Decimal
from core.cacu.measures import MEASURES
from core.measures import Period, evaluate, report
COLPOSCOPY, BIOPSY = MEASURES["CACU_VPP_COLPOSCOPIA"], MEASURES["CACU_VPP_BIOPSIA"]
S1 = Period.parse("2026-S1")
EARLY = "2025-01-01T00:00:00"
def fact(kind, person, day, **values):
empty = dict.fromkeys(
("sample_id", "result", "adequacy", "result_date", "screening_history", "histology",
"report_date", "first_case", "first_treatment", "first_colposcopy", "report_known_at",
"hpv", "hpv_16", "hpv_18")
) # fmt: skip
return {**empty, "fact": kind, "person_id": person, "date": day, "known_at": EARLY, **values}
def cytology(person, day, reported, result, history="first_time", **values):
return fact("cytology", person, day, sample_id=f"{person}|{day}", result=result,
result_date=reported, screening_history=history, **values) # fmt: skip
def colposcopy(person, day, **values):
return fact("colposcopy", person, day, **values)
def biopsy(person, day, histology, reported, **values):
return fact("biopsy", person, day, histology=histology, report_date=reported, **values)
def run(measure, rows, as_of=None, cutoff="2026-12-31"):
return evaluate(measure, rows, S1, as_of, datetime.fromisoformat(cutoff).date())
def counts(result, stratum=None, value=None):
cell = result.populations if stratum is None else result.strata[stratum][value]
return cell["numerator"], cell["denominator"]
def test_each_procedure_takes_the_cytology_before_it():
rows = [
cytology("a", "2026-01-10", "2026-01-20", "ASC-US"),
colposcopy("a", "2026-02-05"),
cytology("a", "2026-02-25", "2026-03-05", "HSIL"),
biopsy("a", "2026-03-15", "HSIL", "2026-03-25"),
cytology("a", "2026-05-20", "2026-05-30", "NILM"), # after both: never picked
]
colpo, bx = run(COLPOSCOPY, rows), run(BIOPSY, rows)
assert list(colpo.strata["referral_cytology"]) == ["ASCUS+"]
assert list(bx.strata["referral_cytology"]) == ["ASCUS+", "LSIL+", "HSIL+"]
assert counts(colpo) == (0, 1) # no biopsy requested on the colposcopy day
assert counts(bx) == (1, 1)
def test_a_result_of_the_same_day_or_too_old_is_not_the_referral():
rows = [
cytology("a", "2026-02-01", "2026-03-15", "HSIL"),
biopsy("a", "2026-03-15", "normal", "2026-03-25"),
cytology("b", "2024-01-01", "2024-02-01", "HSIL"),
biopsy("b", "2026-03-15", "LSIL", "2026-03-25"),
]
found = run(BIOPSY, rows)
assert counts(found) == (1, 2) # both stay in the PPV
assert counts(found, "referral_cytology", "no_data") == (1, 2)
assert counts(found, "screening_round", "no_data") == (1, 2)
def test_histology_levels_share_the_denominator_and_cytology_groups_overlap():
rows = []
for person, result, histology in (("a", "ASC-US", "normal"), ("b", "ASC-H", "LSIL"),
("c", "HSIL", "CIS"), ("d", "CIS", "carcinoma"),
("e", "NILM", "HSIL")): # fmt: skip
rows += [
cytology(person, "2026-01-10", "2026-01-20", result),
colposcopy(person, "2026-02-05"),
biopsy(person, "2026-02-05", histology, "2026-02-20"),
]
found = run(COLPOSCOPY, rows)
assert counts(found) == (4, 5) and found.score == 0.8
assert counts(found, "histology_level", "LIEBG+") == (4, 5)
assert counts(found, "histology_level", "LIEAG+") == (3, 5)
assert counts(found, "histology_level", "invasive") == (1, 5)
assert counts(found, "referral_cytology", "ASCUS+") == (3, 4) # NILM is in no group
assert counts(found, "referral_cytology", "LSIL+") == (3, 3)
assert counts(found, "referral_cytology", "HSIL+") == (2, 2)
assert report(COLPOSCOPY, S1, found, None).group[0].measureScore.value == Decimal("0.8")
def test_once_per_patient_with_her_first_qualifying_procedure():
rows = [
cytology("a", "2026-01-10", "2026-01-20", "LSIL"),
colposcopy("a", "2026-02-05"),
colposcopy("a", "2026-04-05"),
biopsy("a", "2026-02-05", None, None), # never reported: not a biopsy PPV unit
biopsy("a", "2026-04-05", "HSIL", "2026-04-20"),
biopsy("a", "2026-04-05", "normal", "2026-04-21"),
]
assert counts(run(COLPOSCOPY, rows)) == (0, 1) # the first colposcopy's biopsy only
assert counts(run(BIOPSY, rows)) == (1, 1) # the first with a histology, its worst
def test_initial_and_subsequent_screening():
people = {
"initial": ("first_time", {}),
"screened": ("2_years", {}),
"after_colposcopy": ("first_time", {"first_colposcopy": "2025-06-01"}),
"unknown": (None, {}),
# the colposcopy this sample leads to doesn't make it subsequent
"its_own_colposcopy": ("first_time", {"first_colposcopy": "2026-02-05"}),
}
rows = []
for person, (history, steps) in people.items():
rows += [cytology(person, "2026-01-10", "2026-01-20", "HSIL", history, **steps),
colposcopy(person, "2026-02-05", **steps)] # fmt: skip
rounds = run(COLPOSCOPY, rows).strata["screening_round"]
assert {k: v["denominator"] for k, v in rounds.items()} == {
"initial": 2, "subsequent": 2, "no_data": 1} # fmt: skip
def test_a_case_before_the_referring_sample_is_left_out():
case = {"first_case": "2025-01-01"}
rows = [
cytology("a", "2026-01-10", "2026-01-20", "HSIL", **case),
colposcopy("a", "2026-02-05", **case),
colposcopy("b", "2026-02-05", **case),
]
assert counts(run(COLPOSCOPY, rows)) == (0, 0)
assert run(COLPOSCOPY, rows).score is None
def test_only_what_was_known_and_reported_by_the_cut_offs_counts():
rows = [
cytology("a", "2025-10-01", "2025-10-10", "ASC-US", report_known_at=EARLY),
cytology("a", "2026-01-10", "2026-01-20", "HSIL", report_known_at="2026-09-01T00:00:00"),
colposcopy("a", "2026-02-05"),
biopsy("a", "2026-02-05", "HSIL", "2026-02-20", report_known_at="2026-09-01T00:00:00"),
]
then = run(COLPOSCOPY, rows, as_of=datetime(2026, 3, 1, tzinfo=UTC))
assert counts(then) == (0, 1)
assert list(then.strata["referral_cytology"]) == ["ASCUS+"] # the newer wasn't known
assert counts(run(COLPOSCOPY, rows)) == (1, 1)
assert counts(run(COLPOSCOPY, rows, cutoff="2026-02-10")) == (0, 1) # not yet reported
def test_the_cytology_distribution_splits_by_screening_round():
rows = []
for person, result, history in (("a", "NILM", "first_time"), ("b", "HSIL", "first_time"),
("c", "NILM", "2_years"), ("d", "LSIL", None)): # fmt: skip
rows.append({
"person_id": person, "sample_id": person, "sample_date": "2026-01-10",
"result": result, "result_date": "2026-01-20", "adequacy": None,
"screening_history": history, "first_case": None, "first_treatment": None,
"first_colposcopy": None, "birth_date": None, "known_at": EARLY,
}) # fmt: skip
strata = run(MEASURES["CACU_EU7"], rows).strata
count = lambda name: {k: v["initial-population"] for k, v in strata[name].items()} # noqa: E731
assert count("screening_round") == {"initial": 2, "subsequent": 1, "no_data": 1}
assert count("result_initial") == {"NILM": 1, "HSIL": 1}
assert count("result_subsequent") == {"NILM": 1}
def test_the_ppvs_group_by_the_hpv_of_the_referring_cytology():
people = {
"a": ({"hpv": True, "hpv_16": True, "hpv_18": True}, "HSIL"),
"b": ({"hpv": True, "hpv_16": False, "hpv_18": False}, "normal"),
"c": ({"hpv": False}, "LSIL"),
"d": ({}, "normal"),
}
rows = []
for person, (hpv, histology) in people.items():
rows += [cytology(person, "2026-01-10", "2026-01-20", "ASC-US", **hpv),
colposcopy(person, "2026-02-05"),
biopsy(person, "2026-02-05", histology, "2026-02-20")] # fmt: skip
found = run(COLPOSCOPY, rows)
assert {g: counts(found, "referral_hpv", g) for g in found.strata["referral_hpv"]} == {
"positive": (1, 2), "negative": (1, 1), "no_data": (0, 1),
"hpv_16": (1, 1), "hpv_18": (1, 1)} # fmt: skip
def test_the_hpv_distribution_takes_the_latest_sample_with_an_hpv_result():
def sample(person, day, hpv, history="first_time", **values):
return {
"person_id": person, "sample_id": f"{person}|{day}", "sample_date": day,
"result": None, "result_date": None, "adequacy": None,
"screening_history": history, "first_case": None, "first_treatment": None,
"first_colposcopy": None, "birth_date": None, "known_at": EARLY,
"report_known_at": EARLY, "hpv": hpv, "hpv_16": None, "hpv_18": None, **values,
} # fmt: skip
rows = [
sample("a", "2026-01-10", False),
sample("a", "2026-03-10", True, hpv_16=True, hpv_18=False),
sample("a", "2026-05-10", None), # no HPV result: not her HPV sample
sample("b", "2026-01-10", False, "2_years"),
sample("c", "2026-01-10", None), # never tested
sample("d", "2026-01-10", True, report_known_at="2026-09-01T00:00:00"),
]
found = run(MEASURES["CACU_VPH"], rows)
count = lambda name: {k: v["initial-population"] for k, v in found.strata[name].items()} # noqa: E731
assert count("category") == {"positive": 2, "negative": 1}
assert count("hpv_16") == {"positive": 1}
assert count("hpv_18") == {"negative": 1}
assert count("hpv_initial") == {"positive": 2}
assert count("hpv_subsequent") == {"negative": 1}
then = run(MEASURES["CACU_VPH"], rows, as_of=datetime(2026, 6, 1, tzinfo=UTC))
assert then.populations["initial-population"] == 2
+46
View File
@@ -0,0 +1,46 @@
"""Contract tests for the report units, period selection and FHIR serialization."""
import unittest
from datetime import date
from core.cacu.measures import MEASURES
from core.fhir import measure
from core.measures import Period, evaluate, report
class ClinicalReportMeasures(unittest.TestCase):
def test_hpv_counts_reports_not_patients_and_deduplicates(self):
rows = [
{"sample_id": "p|1", "sample_date": date(2026, 1, 1),
"report_date": date(2026, 1, 2), "category": "negative"},
{"sample_id": "p|1", "sample_date": date(2026, 1, 1),
"report_date": date(2026, 1, 2), "category": "negative"},
{"sample_id": "p|2", "sample_date": date(2026, 2, 1),
"report_date": date(2026, 2, 2), "category": "positive_16"},
{"sample_id": "p|3", "sample_date": date(2026, 7, 1),
"report_date": date(2026, 7, 2), "category": "positive_incomplete"},
]
m = MEASURES["CACU_VPH_GENOTIPO"]
result = evaluate(m, rows, Period.parse("2026-S1"))
self.assertEqual(result.populations["initial-population"], 2)
self.assertEqual(sum(c["initial-population"] for c in result.strata["category"].values()), 2)
self.assertEqual(evaluate(m, rows, Period.parse("2026-01")).populations["initial-population"], 1)
self.assertEqual(evaluate(m, rows, Period.parse("2025-S1")).populations["initial-population"], 0)
self.assertEqual(measure(m, "cacu").get_resource_type(), "Measure")
self.assertEqual(report(m, Period.parse("2026-S1"), result, None).get_resource_type(), "MeasureReport")
def test_biopsy_uses_report_date_and_keeps_missing_grade(self):
rows = [
{"biopsy_id": "p|1", "report_date": date(2026, 7, 2), "category": "no_data"},
{"biopsy_id": "p|2", "report_date": date(2026, 7, 3), "category": "HSIL"},
]
m = MEASURES["CACU_BIOPSIA_RESULTADOS"]
result = evaluate(m, rows, Period.parse("2026-S2"))
self.assertEqual(result.populations["initial-population"], 2)
self.assertEqual(result.strata["category"]["no_data"]["initial-population"], 1)
self.assertEqual(evaluate(m, rows, Period.parse("2026-S1")).populations["initial-population"], 0)
self.assertEqual(report(m, Period.parse("2026-S2"), result, None).get_resource_type(), "MeasureReport")
if __name__ == "__main__":
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
import unittest
from core.cacu.stages import stage_facts
class StageFactsTest(unittest.TestCase):
def test_cutoff_link_and_ambiguity(self):
s = {'sample_date':'2026-01-01','colposcopy_date':'2026-01-03','diagnosis_date':'2026-01-04'}
events = [{'type':'colposcopy','date':'2026-01-03','source_table':'note','source_id':'1'},
{'type':'diagnosis','date':'2026-01-04','source_table':'note','source_id':'2'}]
b = {'cytology_sample_date':'2026-01-01','request_date':'2026-01-02','report_date':'2026-01-05','rows_merged':1}
old = {**b,'cytology_sample_date':'2025-01-01'}
self.assertEqual(stage_facts(s,[b,old],events,'2026-01-04'),
{'colposcopy':('inferred','2026-01-03'),'diagnosis':('inferred','2026-01-04'),'biopsy':('pending',None)})
self.assertEqual(stage_facts(s,[b],events,'2026-01-05')['biopsy'],('structured','2026-01-05'))
self.assertEqual(stage_facts(s,[b,b],events,'2026-01-05')['biopsy'],('ambiguous',None))
self.assertEqual(stage_facts(s,[],events+[dict(events[0],source_id='3')],'2026-01-05')['colposcopy'],('ambiguous',None))
self.assertEqual(stage_facts(s,[b],events,'2026-01-01'),{})
if __name__ == '__main__':
unittest.main()