Add synthetic breast cohort reconciliation

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 13:27:18 -06:00
parent ca54656124
commit 1d5f1e0cc4
7 changed files with 618 additions and 2 deletions
+2
View File
@@ -14,6 +14,7 @@ from webapi.blueprints.reportes import reportes_bp
from webapi.blueprints.tea import tea_bp
from webapi.seguimiento import blueprint_de_seguimiento
from webapi.seguimiento_cama import blueprint_seguimiento_cama
from webapi.cama_analysis import analysis as cama_analysis
class IsoJSONProvider(DefaultJSONProvider):
@@ -74,6 +75,7 @@ def create_app() -> Flask:
app.register_blueprint(cacu_bp, url_prefix="/cacu")
app.register_blueprint(cama_bp, url_prefix="/cama")
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
app.register_blueprint(cama_analysis, url_prefix="/cama")
app.register_blueprint(tea_bp, url_prefix="/tea")
app.register_blueprint(imports_bp, url_prefix="/imports")
app.register_blueprint(data_bp, url_prefix="/data")
+147
View File
@@ -0,0 +1,147 @@
"""Aggregate and select the breast cohort through the same configured reader."""
from datetime import date
import hashlib
import hmac
import json
from flask import Blueprint, current_app, jsonify, request
from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD
analysis = Blueprint('cama_analysis', __name__)
BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6')
AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO')
class SelectionError(Exception):
def __init__(self, message, status=400):
self.message, self.status = message, status
def read_cohort(cutoff):
reader = current_app.config.get('CAMA_COHORT_READER')
if current_app.config.get('CAMA_COHORT_SYNTHETIC') is not True or not callable(reader):
raise SelectionError('Cohorte no disponible', 503)
return reader(cutoff)
def cutoff_arg(args):
text = args.get('corte')
if not text:
raise SelectionError('Se requiere corte')
try:
value = date.fromisoformat(text)
if value.isoformat() != text or value.year == 9999:
raise ValueError()
return value
except ValueError:
raise SelectionError('Corte inválido') from None
def patient_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if not callable(check) or not check(request):
raise SelectionError('Acceso no autorizado', 403)
def revision_of(rows):
"""Identify the materialized cohort without exposing its patient identifiers."""
encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
return hashlib.sha256(encoded).hexdigest()
def cohort_request(args):
allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'}
if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args):
raise SelectionError('Parámetros desconocidos o repetidos')
if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO:
raise SelectionError('Cohorte o escenario desconocido')
revision = args.get('revision', '')
if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision):
raise SelectionError('Revisión de cohorte inválida')
cutoff = cutoff_arg(args)
try:
months = int(args.get('meses', '3'))
page = int(args.get('page', '1'))
size = int(args.get('page_size', '50'))
if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
raise ValueError()
except ValueError:
raise SelectionError('Ventana o paginación inválida') from None
filters = {key: args.get(key) for key in ('birads', 'grupo_edad')}
if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES):
raise SelectionError('Filtro inválido')
return cutoff, months, page, size, filters, revision
def selected(args):
patient_access()
cutoff, months, page, size, filters, revision = cohort_request(args)
rows = read_cohort(cutoff)
if not hmac.compare_digest(revision, revision_of(rows)):
raise SelectionError('La cohorte cambió; actualiza el análisis', 409)
selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())]
if months:
from webapi.seguimiento_cama import _desde
since = _desde(cutoff, months)
else:
since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff)
selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff]
# Every filtered selection is checked on the server after applying the window.
if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())):
raise SelectionError('Selección no disponible', 403)
return cutoff, months, page, size, filters, since, selected_rows, revision
def selection_response(args, mode, patient=None):
cutoff, months, page, size, filters, since, rows, revision = selected(args)
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
columns = [
{'clave': 'id_seudonimo', 'etiqueta': 'Identificador seudónimo'},
{'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'},
{'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]},
{'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]},
]
meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(),
'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()},
'campo_ventana': 'mastografia_fecha', 'filtros': filters,
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
for k, label, values in options], 'columnas': columns}
if mode == 'patient':
found = next((row for row in rows if row['id_seudonimo'] == patient), None)
if found is None:
raise SelectionError('Paciente no encontrado', 404)
return jsonify(**meta, item=found)
if mode == 'export':
if len(rows) > 5000:
raise SelectionError('La exportación supera el límite de 5000 registros', 413)
return jsonify(**meta, total_items=len(rows), items=rows)
return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows),
'total_pages': (len(rows) + size - 1) // size},
items=rows[(page - 1) * size:page * size])
@analysis.get('/analisis/indicadores')
def indicators():
try:
if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1:
raise SelectionError('Se requiere únicamente corte')
cutoff = cutoff_arg(request.args)
rows = read_cohort(cutoff)
groups = []
for code in BIRADS:
count = sum(r['birads'] == code for r in rows)
groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD})
return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(),
horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente',
denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
indicadores=[], grupos=groups)
except SelectionError as e:
return jsonify(error=e.message), e.status
@analysis.after_request
def no_cache(response):
response.headers['Cache-Control'] = 'no-store'
return response
+142
View File
@@ -0,0 +1,142 @@
"""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
import hashlib
import hmac
from sqlalchemy import select
from indicadores_kit.cama.consultas.plata import biopsias, mastografias
from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS
from indicadores_kit.cama.tablas import TABLAS
COHORT = "cama_birads_v1"
SCENARIO = "diagnostico"
THRESHOLD = 5
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, secret: bytes):
if not secret or len(secret) < 32:
raise ValueError("A stable secret of at least 32 bytes is required")
self.session = session
self.secret = secret
def _id(self, patient):
return hmac.new(self.secret, f"cama:{patient}".encode(), hashlib.sha256).hexdigest()
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):
o = observations.get((identifier, result))
return bool(o 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(select(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 observation_known(row['reporte_id'], 'mastografia.birads')):
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(select(biopsias(t))).mappings():
reported, ordered = _date(row['fecha_reporte']), _date(row['fecha_solicitud'])
procedure = procedures.get(row['procedimiento_id'])
order = procedures.get(procedure.padre_id) if procedure else None
if not (reported and ordered and ordered <= reported <= cutoff and row['toma_id']
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
and order 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') else None
rows.append({
'id_seudonimo': self._id(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') else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), row['id_seudonimo']))
+30 -2
View File
@@ -56,6 +56,9 @@ def _desde(corte, meses):
def _consulta(args):
allowed = {'corte', 'meses', 'page', 'page_size', *CATEGORIAS}
if set(args) - allowed or any(len(args.getlist(key)) != 1 for key in args):
raise ValueError('Parámetros desconocidos o repetidos')
pedido = _pedido(args)
corte = pedido.get("corte", date(2026, 10, 20))
meses, page, size = (pedido.get("meses", 3), pedido.get("page", 1), pedido.get("page_size", 50))
@@ -69,7 +72,14 @@ def _consulta(args):
def _filas(corte, desde, filtros):
filas = [fila for fila in leer_fixture(corte, desde)
fuente = []
for original in leer_fixture(corte, desde):
fila = dict(original)
if fila['biopsia_fecha'] and fila['biopsia_fecha'] > corte.isoformat():
fila.update(biopsia=None, biopsia_fecha=None, dias_mastografia_diagnostico=None,
estatus='INFO_INSUFICIENTE')
fuente.append(fila)
filas = [fila for fila in fuente
if desde.isoformat() <= fila["mastografia_fecha"] <= corte.isoformat()
and all(valor is None or fila[clave] == valor for clave, valor in filtros.items())]
filas.sort(key=lambda fila: fila["id_seudonimo"])
@@ -100,13 +110,19 @@ def blueprint_seguimiento_cama():
@blueprint.after_request
def sin_cache_en_contratos_nuevos(response):
if request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"):
if 'cohorte' in request.args or request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"):
response.headers["Cache-Control"] = "no-store"
return response
@blueprint.get("/seguimiento")
def seguimiento():
"""Lista sintética de seguimiento CaMa con filtros y columnas declarativos."""
if 'cohorte' in request.args:
from webapi.cama_analysis import SelectionError, selection_response
try:
return selection_response(request.args, 'list')
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
corte, meses, page, size, filtros, desde = _consulta(request.args)
except ValueError as error:
@@ -124,6 +140,12 @@ def blueprint_seguimiento_cama():
@blueprint.get("/seguimiento/exportacion")
def exportacion():
if 'cohorte' in request.args:
from webapi.cama_analysis import SelectionError, selection_response
try:
return selection_response(request.args, 'export')
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
corte, meses, _, _, filtros, desde = _consulta(request.args)
except ValueError as error:
@@ -140,6 +162,12 @@ def blueprint_seguimiento_cama():
@blueprint.get("/pacientes/<id_seudonimo>")
def paciente(id_seudonimo):
if 'cohorte' in request.args:
from webapi.cama_analysis import SelectionError, selection_response
try:
return selection_response(request.args, 'patient', id_seudonimo)
except SelectionError as error:
return jsonify(error=error.message), error.status
try:
corte, meses, _, _, _, desde = _consulta(request.args)
except ValueError as error: