CaCu $eligibility and $risk-series, current risks only, rebuild runs; gates carry the declared CaCu and CaMa differences

This commit is contained in:
Roberto Treviño
2026-12-05 19:42:07 -06:00
parent 05d0e4c278
commit c8472c705e
7 changed files with 163 additions and 21 deletions
+30 -6
View File
@@ -16,7 +16,7 @@ from fhir.resources.R4B.capabilitystatement import CapabilityStatement
from fhir.resources.R4B.operationoutcome import OperationOutcome
from fhir.resources.R4B.resource import Resource
from core import catalog
from core import catalog, models
from core import fhir as f
from core import measures as m
from core.domains import Domain, measures, part
@@ -54,6 +54,25 @@ def _clinical(domain: Domain):
return found
def _risks(domain: Domain, persons: list[str], cutoff: date) -> tuple[list[dict], dict]:
"""The served models' risks of these persons that still apply at the cut-off, and why
each person's others are withheld (a domain's `currency`, when it has one)."""
found = [r for r in reads.rows(domain.value, "risk", persons=persons)
if models.served(r["model"])] # fmt: skip
if (currency := part(domain, "currency")) is None:
return found, {}
history = reads.rows(domain.value, "risk_history", persons=persons)
return currency.applying(found, history, cutoff)
def _noted(domain: Domain, rows: list[dict], cutoff: date) -> list[dict]:
"""The persons, each with why some of her risks are withheld at the cut-off."""
if part(domain, "currency") is None:
return rows
_, why = _risks(domain, [r["person_id"] for r in rows], cutoff)
return [{**r, "risk_withheld": why.get(r["person_id"])} for r in rows]
def _cutoff(domain: Domain, asked: date | None) -> date:
"""The day asked for, or by default the last day with data in the domain (up to today)."""
if asked is not None:
@@ -106,8 +125,8 @@ def read_patient(domain: Domain, id: str) -> Response:
if link is None:
raise HTTPException(404, f"no Patient/{id}")
return fhir(f.replaced_patient(id, link["replaced_by"]))
status = fu.status(row, _cutoff(domain, None))
(found,) = _with_identity(domain, [{**row, "status": status}])
day = _cutoff(domain, None)
(found,) = _with_identity(domain, _noted(domain, [{**row, "status": fu.status(row, day)}], day))
return fhir(f.patient(found, fu.STATUS_SYSTEM))
@@ -213,7 +232,7 @@ def search_patient(
persons = [r["person_id"] for r in rows]
risks: dict[str, list[dict]] = {}
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
for r in reads.rows(domain.value, "risk", persons=persons):
for r in _risks(domain, persons, at)[0]:
risks.setdefault(r["person_id"], []).append(r)
if window is not None:
rows = fu.ordered(rows, sort, risks, horizon)
@@ -222,7 +241,8 @@ def search_patient(
included = _included(domain, revinclude, include, sorted(mine), at,
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
patients = [f.patient(r, fu.STATUS_SYSTEM)
for r in _with_identity(domain, _noted(domain, page, at))] # fmt: skip
return bundle(request, patients, len(rows), count, offset, included,
applied) # fmt: skip
@@ -302,7 +322,11 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset):
params["cutoff"] = _cutoff(domain, None).isoformat()
if kind == "procedure":
params["types"] = list(fu.PROCEDURES)
found = build(reads.rows(domain.value, kind, **params))
if kind == "risk":
rows = _risks(domain, params["persons"], _cutoff(domain, None))[0]
else:
rows = reads.rows(domain.value, kind, **params)
found = build(rows)
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
+70
View File
@@ -0,0 +1,70 @@
"""CaCu's FHIR operations on a patient: `$eligibility` (gold.cacu_eligibility) and, off
unless CACU_NCI_REFERENCE=1, the experimental `$risk-series` (the models' and the NCI's)
and `$reference-risk` (disabled: its series are `$risk-series`')."""
import os
from datetime import date
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response
from core import fhir as f
from core import models
from core.cacu import parameters, reference, risk_series
from core.domains import Domain
from persistance import fhir as reads
from webapi.fhir import _OK, _cutoff, _risks, fhir
router = APIRouter(prefix="/cacu/fhir/Patient/{id}", tags=["fhir"])
NCI_REFERENCE = "CACU_NCI_REFERENCE"
CUTOFF = Query(None, description="Only what was reported by this day")
SAMPLE = Query(None, description="The cytology's sample day (default: her latest)")
def _person(id: str) -> dict:
(found,) = reads.rows("cacu", "person", id=id) or [None]
if found is None:
raise HTTPException(404, f"no Patient/{id}")
return found
def _reference_on():
if os.environ.get(NCI_REFERENCE) != "1":
raise HTTPException(404, "the NCI reference comparison is not enabled")
@router.get("/$eligibility", responses=_OK, response_class=Response)
def cacu_eligibility(
id: str,
scenario: str | None = Query(None, description="One CaCu scenario (default: every one)"),
cutoff: date | None = Query(None, description="Only index dates up to this day"),
) -> Response:
"""Her indexed candidates of each CaCu cohort: eligible, or every reason she is not."""
if scenario is not None and scenario not in f.CODE_SYSTEMS["cacu-eligibility-scenario"][1]:
raise HTTPException(422, f"no CaCu scenario {scenario}")
_person(id)
day = _cutoff(Domain.CACU, cutoff)
found = reads.rows("cacu", "eligibility", id=id, cutoff=day.isoformat(), scenario=scenario)
return fhir(parameters.eligibility(found, id, day))
@router.get("/$risk-series", responses=_OK, response_class=Response)
def cacu_risk_series(id: str, cutoff: date | None = CUTOFF, sample: date | None = SAMPLE):
"""EXPERIMENTAL. The risk series her record can draw: the models' and the NCI tables',
by outcome, with their published intervals."""
_reference_on()
person, day, one = _person(id), _cutoff(Domain.CACU, cutoff), {"persons": [id]}
facts = {"birth_date": person["birth_date"], "master": reads.rows("cacu", "reference_master"),
**{k: reads.rows("cacu", f"reference_{k}", **one)
for k in ("cytologies", "biopsies", "events", "requirements")}} # fmt: skip
resolution = reference.resolve(facts, day, sample)
risks, _ = _risks(Domain.CACU, [id], day)
found = risk_series.series(resolution, risks, day, models.title)
return fhir(parameters.risk_series(found, id, day))
@router.get("/$reference-risk", responses=_OK, response_class=Response)
def cacu_reference_risk(id: str, cutoff: date | None = CUTOFF, sample: date | None = SAMPLE):
"""Disabled: the NCI series, the master table's included, are in `$risk-series`."""
_reference_on()
raise HTTPException(503, "$reference-risk is disabled; the NCI series are in $risk-series")
+2 -1
View File
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
from starlette.exceptions import HTTPException
from core.domains import Domain
from webapi import eeg, fhir, ingest, models, review, runs, sources, users
from webapi import eeg, fhir, fhir_cacu, ingest, models, review, runs, sources, users
from webapi.auth import caller
app = FastAPI(
@@ -19,6 +19,7 @@ app.include_router(review.router)
app.include_router(runs.router)
app.include_router(models.router)
app.include_router(eeg.router)
app.include_router(fhir_cacu.router) # before the generic Patient/{id}
app.include_router(fhir.router)
app.include_router(users.router) # sign-in for the web app; no route requires it
+3 -2
View File
@@ -10,7 +10,7 @@ from fastapi.responses import Response
from pydantic import BaseModel
from core.domains import Domain
from core.models import title
from core.models import HIDDEN, title
from persistance import registry
from webapi.runs import dagster
@@ -35,7 +35,8 @@ class Model(BaseModel):
def models(domain: Domain) -> list[Model]:
"""The domain's registered models, with their names on screen."""
prefix = f"{domain.value}."
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)]
return [Model(name=n.removeprefix(prefix), title=title(n))
for n in registry.names(prefix) if n not in HIDDEN] # fmt: skip
@router.get("/{domain}/{name}/versions")
+10
View File
@@ -15,6 +15,16 @@ def dagster() -> DagsterGraphQLClient:
)
@router.post("/rebuild")
def rebuild_gold(client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
"""Starts rebuilding silver and gold with the deployed code (after an upgrade, before any
new data); follow it at /runs/{run_id}. The risk tables keep their last scores."""
try:
return {"run_id": client.submit_job_execution("rebuild")}
except DagsterGraphQLClientError as e:
raise HTTPException(502, detail=str(e)) from e
@router.get("/{run_id}")
def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
try: