clinical-agent-memory-bench's picture
Upload 99 files
750b88d verified
Raw History Blame Contribute Delete
8.05 kB
#!/usr/bin/env python3
"""Stage B, deterministic parts of the evidence chain.
dept-index event chain by department -> _dept_event_index.json
prep evidence-chain batches for the evidence step -> _evidence_manifest.json
post TIMELINES timelines of the evidence step -> evidence_chain.jsonl
"""
from __future__ import annotations
import argparse
import json
import os
import re
from collections import OrderedDict, defaultdict
from pipeline.common import BASE, FIELDS
# A test or measurement whose value changes is a different fact at every visit; its readings are kept together as a
# series when the fact with its numbers removed recurs at two or more visits.
SERIES_FIELDS = ("tests_and_medication", "doctor_notes")
NUMBER = re.compile(r"\d+(?:\.\d+)?")
def dept_index() -> None:
"""Group the event chain by department in longitudinal order and build a per-department index of distinct
events and their occurrences."""
chain = [json.loads(l) for l in open(f"{BASE}/event_chain.jsonl")]
by_dept = defaultdict(list)
for r in chain:
by_dept[r["department"]].append(r)
dept_order = sorted(by_dept, key=lambda d: -len(by_dept[d]))
def norm(s):
s = re.sub(r"\s*\(\d[\d./~-]*\)", "", s)
return re.sub(r"\s+", " ", s.strip().lower())
index = OrderedDict()
for d in dept_order:
facts = defaultdict(lambda: {"variants": set(), "field": None, "occ": []})
for r in by_dept[d]:
for f in FIELDS:
for atom in r.get(f, []):
key = (f, norm(atom))
facts[key]["variants"].add(atom)
facts[key]["field"] = f
facts[key]["occ"].append({"v": r["visit_number"], "date": r["date"]})
series = defaultdict(set)
for (f, k), info in facts.items():
if f in SERIES_FIELDS and NUMBER.search(k):
series[(f, NUMBER.sub("#", k))].update(o["v"] for o in info["occ"])
rows = []
for (f, k), info in facts.items():
occ = sorted(info["occ"], key=lambda x: x["v"])
rows.append({"field": f, "fact": sorted(info["variants"], key=len)[0],
"n_visits": len(occ), "first": occ[0], "last": occ[-1],
"visits": [o["v"] for o in occ],
"series_visits": len(series.get((f, NUMBER.sub("#", k)), ())) if NUMBER.search(k) else 0})
rows.sort(key=lambda x: -x["n_visits"])
index[d] = rows
json.dump(index, open(f"{BASE}/_dept_event_index.json", "w"), ensure_ascii=False)
print("dept visits distinct_events (spanning >=3 visits)")
for d in dept_order:
rows = index[d]
multi = sum(1 for r in rows if r["n_visits"] >= 3)
print(f" {d.split(' (')[0]:32s} {len(by_dept[d]):5d} {len(rows):6d} {multi:4d}")
bt = defaultdict(int)
for d in dept_order:
for r in index[d]:
bt[r["field"]] += 1
print("\nper-bucket distinct events:", dict(bt))
print("wrote _dept_event_index.json")
def prep() -> None:
"""Write per-department batches for the evidence step and their manifest: the facts recorded at two or more
visits, and the readings of a test or measurement recorded at two or more visits."""
index = json.load(open(f"{BASE}/_dept_event_index.json"))
chain = [json.loads(l) for l in open(f"{BASE}/event_chain.jsonl")]
last_date = max(r["date"] for r in chain)
dept_last = {}
dept_visit_dates = {}
for r in chain:
dept_last[r["department"]] = max(dept_last.get(r["department"], ""), r["date"])
dept_visit_dates.setdefault(r["department"], {})[r["visit_number"]] = r["date"]
bdir = f"{BASE}/_evidence_batches"
os.makedirs(bdir, exist_ok=True)
for f in os.listdir(bdir):
os.remove(os.path.join(bdir, f))
manifest = []
bid = 0
MAXFACTS = 120
for dept, rows in index.items():
multi = [{"field": r["field"], "fact": r["fact"], "visits": r["visits"],
"first_date": r["first"]["date"], "last_date": r["last"]["date"]}
for r in rows if r["n_visits"] >= 2 or r.get("series_visits", 0) >= 2]
if not multi:
continue
for i in range(0, len(multi), MAXFACTS):
chunk = multi[i:i + MAXFACTS]
p = os.path.join(bdir, f"evidence_{bid:02d}.json")
json.dump({"department": dept, "dept_last_date": dept_last[dept],
"patient_last_date": last_date,
"visit_dates": dept_visit_dates[dept], "facts": chunk}, open(p, "w"), ensure_ascii=False)
manifest.append({"batch_id": bid, "path": p, "department": dept, "n_facts": len(chunk)})
bid += 1
json.dump(manifest, open(f"{BASE}/_evidence_manifest.json", "w"), ensure_ascii=False)
print(f"LLM batches (multi-visit events): {len(manifest)} across "
f"{len(set(m['department'] for m in manifest))} depts")
for m in manifest:
print(f" batch {m['batch_id']:2d} {m['department'].split(' (')[0]:28s} facts={m['n_facts']}")
TIMELINE_KEYS = ["entity", "aspect", "source_field", "current_status", "notes", "segments"]
SEGMENT_KEYS = ["value", "valid_from", "valid_until", "status", "supporting_visits", "superseded_by"]
def canonical(t):
"""The timeline with its keys in one order (TIMELINE_KEYS, then any other key, department and batch_id last)
and each segment's keys in SEGMENT_KEYS order."""
tail = [k for k in ("department", "batch_id") if k in t]
out = {k: t[k] for k in TIMELINE_KEYS if k in t}
out.update({k: v for k, v in t.items() if k not in out and k not in tail})
out.update({k: t[k] for k in tail})
out["segments"] = [{**{k: s[k] for k in SEGMENT_KEYS if k in s}, **{k: v for k, v in s.items() if k not in SEGMENT_KEYS}}
if isinstance(s, dict) else s for s in t.get("segments") or []]
return out
def post(timelines_path: str) -> None:
"""Write the timelines of the evidence step to evidence_chain.jsonl and check window sanity. A department's
facts go to the evidence step in batches, so an entity can have several timelines; each is kept as returned."""
raw = json.load(open(timelines_path))
timelines = raw["timelines"] if isinstance(raw, dict) else raw
timelines = [canonical(t) for t in timelines]
def d(x):
return x.get("date") if isinstance(x, dict) else (x if isinstance(x, str) else None)
bad = []
n_seg = 0
for t in timelines:
prev = None
for s in t.get("segments", []):
n_seg += 1
vf = d(s.get("valid_from"))
vu = s.get("valid_until")
vud = d(vu) if not (isinstance(vu, str) and vu == "current") else None
if vf and vud and vud < vf:
bad.append((t["entity"], "until<from", vf, vud))
if prev and vf and vf < prev:
bad.append((t["entity"], "non-monotonic", prev, vf))
prev = vud or vf or prev
with open(f"{BASE}/evidence_chain.jsonl", "w", encoding="utf-8") as fh:
for t in timelines:
fh.write(json.dumps(t, ensure_ascii=False) + "\n")
multiseg = [t for t in timelines if len(t.get("segments", [])) >= 2]
print(f"timelines: {len(timelines)} segments: {n_seg} multi-segment entities: {len(multiseg)}")
print(f"window sanity violations: {len(bad)}")
for b in bad[:20]:
print(" BAD", b)
print("wrote evidence_chain.jsonl")
def main():
ap = argparse.ArgumentParser(description="Stage B: evidence chain.")
sp = ap.add_subparsers(dest="cmd", required=True)
sp.add_parser("dept-index")
sp.add_parser("prep")
sp.add_parser("post").add_argument("timelines")
a = ap.parse_args()
if a.cmd == "dept-index":
dept_index()
elif a.cmd == "prep":
prep()
else:
post(a.timelines)
if __name__ == "__main__":
main()