Files
ISSSTELEON/Core/core/tea/follow_up.py
T
Roberto Treviño b9ed108855 ISSSTELEON 8a7974a
2026-11-29 18:09:05 -06:00

103 lines
3.4 KiB
Python

from datetime import date
from core import tea
from core.measures import as_day
from core.tea import ados2
WINDOWS = tea.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "tea-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"), ("eeg_date", "eeg"))
DATES = (
"mchat_date",
"psychology_date",
"neuro_date",
"confirmed_date",
"not_confirmed_date",
"eeg_date",
)
def _by(day, cutoff: date) -> date | None:
found = as_day(day)
return found if found is not None and found <= cutoff else None
def stage(row: dict, cutoff: date) -> str:
reached = "mchat_only"
for column, name in STEPS:
if _by(row.get(column), cutoff):
reached = name
return reached
def case(row: dict, cutoff: date) -> str:
if _by(row.get("confirmed_date"), cutoff):
return "confirmed"
if _by(row.get("not_confirmed_date"), cutoff):
return "not_confirmed"
return "in_process"
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
children: dict[str, dict] = {}
eegs: dict[str, dict[str, dict]] = {}
for row in rows:
person = row["person_id"]
if not _by(row.get("mchat_date"), cutoff):
continue
children.setdefault(person, row)
studied = _by(row.get("eeg_study_date"), cutoff)
if row.get("eeg_id") and studied:
eeg = eegs.setdefault(person, {}).setdefault(
row["eeg_id"], {"date": studied, "valid": row.get("valid"), "altered": set()}
)
if row.get("metric") and row.get("outside"):
side = "above" if row["outside"] > 0 else "below"
eeg["altered"].add(f"{row['metric']}:{side}")
out = []
for person, row in children.items():
steps = [d for c in DATES if (d := _by(row.get(c), cutoff))]
recent = max(steps)
if recent < start:
continue
mine = sorted(eegs.get(person, {}).values(), key=lambda e: e["date"])
valid = [e for e in mine if e["valid"]]
study = valid[0] if valid else mine[-1] if mine else None
if not valid:
eeg_status, altered = ("no_valid_eeg", [])
else:
altered = sorted(study["altered"])
eeg_status = "abnormal" if altered else "normal"
css = None
if row.get("module") and as_day(row.get("evaluation_date")):
evaluated = {**row, "evaluation_date": as_day(row["evaluation_date"])}
css, _ = ados2.score(evaluated, as_day(row.get("birth_date")))
out.append(
{
"person_id": person,
"birth_date": row.get("birth_date"),
"status": stage(row, cutoff),
"priority": None,
"recent": recent,
"age_group": row.get("age_group"),
"case": case(row, cutoff),
"eeg_status": eeg_status,
"alterations": altered,
"last_eeg": mine[-1]["date"] if mine else None,
"mchat_score": row.get("score"),
"ados2_css": css,
}
)
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows