55 lines
2.2 KiB
Python
55 lines
2.2 KiB
Python
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
|
|
it is read in. The list holds every patient with a cytology sampled within the window
|
|
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
|
|
|
|
import calendar
|
|
from collections.abc import Iterable
|
|
from datetime import date
|
|
|
|
from core.measures import follow_up_status
|
|
|
|
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
|
|
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
|
|
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
|
|
DEFAULT_HORIZON = 5.0
|
|
|
|
|
|
def window_start(cutoff: date, months: int) -> date:
|
|
"""The first day of the window: `months` before the cut-off (the month's last day when
|
|
shorter), plus one day."""
|
|
total = cutoff.year * 12 + cutoff.month - 1 - months
|
|
year, month = divmod(total, 12)
|
|
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
|
|
return date.fromordinal(date(year, month + 1, day).toordinal() + 1)
|
|
|
|
|
|
def status(row: dict, cutoff: date) -> str:
|
|
"""Her follow-up status by the end of the cut-off day."""
|
|
return follow_up_status(row, cutoff, through=True)
|
|
|
|
|
|
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
|
|
"""Her current risk of an outcome at a horizon (years): from the latest index date any
|
|
of the outcome's models scored her at; the highest when several did."""
|
|
prefix = OUTCOMES[outcome]
|
|
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
|
|
if not mine:
|
|
return None
|
|
latest = max(str(r["index_date"]) for r in mine)
|
|
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
|
|
|
|
|
|
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
|
|
horizon: float) -> list[dict]: # fmt: skip
|
|
"""The list in reading order. `rows` come most recent first; by risk, highest first,
|
|
unscored patients last, ties kept most recent first."""
|
|
if sort == "-recent":
|
|
return rows
|
|
outcome = sort.removeprefix("-risk-")
|
|
|
|
def key(row: dict):
|
|
found = current_risk(risks.get(row["person_id"], []), outcome, horizon)
|
|
return (found is None, -(found or 0.0))
|
|
|
|
return sorted(rows, key=key)
|