Files
Roberto Treviño Cervantes 0571b5e6af wording fixes
2026-11-17 02:17:31 -06:00

196 lines
10 KiB
Python

"""Read the breast screening cohort from the existing silver tables.
The current silver tables keep only the last version of each fact. Filtering by
load date prevents future facts from appearing at an earlier cutoff, but cannot
restore a previous value after an update.
"""
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy import func, select
from sqlalchemy.orm import aliased
from webapi.orchestration.tables.cama import TABLAS
COHORT = "cama_birads_v1"
SCENARIO = "diagnostico"
THRESHOLD = 5
# `core/catalogos/cama.toml`'s `mastografia.resultados.birads`: the cohort is restricted to the codes that call
# for a biopsy (B4 and its subcategories, B5, B6); B0 to B3 fall out by not being in this map.
BIRADS = {"B4": "BIRADS_4", "B4A": "BIRADS_4A", "B4B": "BIRADS_4B", "B4C": "BIRADS_4C", "B5": "BIRADS_5", "B6": "BIRADS_6"}
def mastografias(t):
"""One row per mammogram taken, with the report that hangs from it (nulls when it has none): the Python
equivalent of `Transformation/models/cama/silver/cama_mastografias.sql`, kept independent of dbt's manifest
since this reader runs without one."""
toma, reporte, obs_birads = aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Observacion)
return (
select(
toma.procedimiento_id.label("procedimiento_id"),
toma.fuente_tabla.label("fuente_tabla"),
toma.fuente_id.label("fuente_id"),
toma.pac_id.label("pac_id"),
toma.fecha.label("fecha_toma"),
reporte.procedimiento_id.label("reporte_id"),
reporte.fecha.label("fecha_reporte"),
func.coalesce(obs_birads.valor_id, obs_birads.valor_fuente).label("birads"),
)
.select_from(toma)
.outerjoin(reporte, (reporte.padre_id == toma.procedimiento_id) & (reporte.estudio_id == "mastografia")
& (reporte.clase == "reporte"))
.outerjoin(obs_birads, (obs_birads.procedimiento_id == reporte.procedimiento_id)
& (obs_birads.resultado_id == "mastografia.birads"))
.where(toma.estudio_id == "mastografia", toma.clase == "toma")
)
def biopsias(t):
"""One row per biopsy report with its grade, its order and the mammogram that led to it, if found: mammogram
(toma) -> biopsy order -> biopsy report, by `padre_id`. The Python equivalent of
`Transformation/models/cama/silver/cama_biopsias.sql`, plus the mammogram's own date and patient (`fecha_toma`,
`toma_pac_id`), which the cohort's cross-check needs and the dbt model doesn't expose."""
reporte, orden, toma, obs_grado = (aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Procedimiento),
aliased(t.Observacion))
return (
select(
reporte.procedimiento_id.label("procedimiento_id"),
reporte.fuente_tabla.label("fuente_tabla"),
reporte.fuente_id.label("fuente_id"),
reporte.pac_id.label("pac_id"),
reporte.fecha.label("fecha_reporte"),
func.coalesce(obs_grado.valor_id, obs_grado.valor_fuente).label("grado"),
orden.fecha.label("fecha_solicitud"),
toma.procedimiento_id.label("toma_id"),
toma.fecha.label("fecha_toma"),
toma.pac_id.label("toma_pac_id"),
)
.select_from(reporte)
.outerjoin(obs_grado, (obs_grado.procedimiento_id == reporte.procedimiento_id)
& (obs_grado.resultado_id == "biopsia.grado"))
.outerjoin(orden, (orden.procedimiento_id == reporte.padre_id) & (orden.estudio_id == "biopsia")
& (orden.clase == "orden"))
.outerjoin(toma, (toma.procedimiento_id == orden.padre_id) & (toma.estudio_id == "mastografia")
& (toma.clase == "toma"))
.where(reporte.estudio_id == "biopsia", reporte.clase == "reporte")
)
def _date(value):
return date.fromisoformat(value) if isinstance(value, str) else value
def _known(value, cutoff):
if value is None:
return False
if isinstance(value, str):
value = datetime.fromisoformat(value)
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc)
def _age_group(birth, cutoff):
if birth is None or birth > cutoff:
return "SIN_DATO"
age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day))
if age < 40:
return "MENOR_40"
if age >= 70:
return "70+"
return f"{age // 10 * 10}-{age // 10 * 10 + 9}"
class CamaCohort:
"""Materialize one row per eligible patient, using a caller-owned session."""
def __init__(self, session):
self.session = session
def rows(self, cutoff: date):
t = TABLAS
loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()}
procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()}
observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()}
people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()}
def procedure_known(identifier):
p = procedures.get(identifier)
return bool(p and _known(loads.get(p.carga_id), cutoff))
def observation_known(identifier, result, patient):
o = observations.get((identifier, result))
return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff))
def load_time(record):
value = loads.get(record.carga_id) if record else None
return value.isoformat() if value else None
candidates = {}
for row in self.session.execute(mastografias(t)).mappings():
taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte'])
if not (taken and reported and taken <= reported <= cutoff and row['birads']
and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id'])
and procedures[row['reporte_id']].pac_id == row['pac_id']
and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])):
continue
key = (taken, str(row['fuente_id']), reported, row['reporte_id'])
prior = candidates.get(row['pac_id'])
if prior is None or key > prior[0]:
candidates[row['pac_id']] = (key, row)
reports = {}
orders = {}
for p in procedures.values():
when = _date(p.fecha)
if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when
or when > cutoff or not procedure_known(p.procedimiento_id)):
continue
key = (p.pac_id, p.padre_id)
rank = (when, str(p.fuente_id), p.procedimiento_id)
if key not in orders or rank > orders[key][0]:
orders[key] = (rank, p)
for row in self.session.execute(biopsias(t)).mappings():
reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']),
_date(row['fecha_toma']))
procedure = procedures.get(row['procedimiento_id'])
order = procedures.get(procedure.padre_id) if procedure else None
if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id']
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)):
continue
key = (row['pac_id'], row['toma_id'])
rank = (reported, str(row['fuente_id']), row['procedimiento_id'])
if key not in reports or rank > reports[key][0]:
reports[key] = (rank, row)
rows = []
for patient, (_, m) in candidates.items():
code = BIRADS.get(m['birads'])
if not code or patient not in people:
continue
b = reports.get((patient, m['procedimiento_id']))
b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None
order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None
if not order:
found_order = orders.get((patient, m['procedimiento_id']))
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None,
'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]),
'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]),
'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))),
'biopsia_solicitud_carga_inicio': load_time(order),
'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None,
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))