155 lines
7.0 KiB
Python
155 lines
7.0 KiB
Python
"""Replay the frozen v5 public holdout without using the truth to answer questions."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from collections import Counter
|
|
from concurrent.futures import ProcessPoolExecutor
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
from typing import NamedTuple
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path[:0] = [str(ROOT), str(ROOT / "scripts")]
|
|
|
|
from scripts.chart_choice import adaptive, chart_questions, interview # noqa: E402
|
|
from scripts.chart_choice.boundaries import ChartRequest, find_lines # noqa: E402
|
|
|
|
DATASET = ROOT / "references/real_case_calibration/minute_rectification_holdout_v5.json"
|
|
OFFSETS = (-10, -5, -2, -1, 1, 2, 5, 10)
|
|
AS_OF = datetime(2026, 11, 14)
|
|
EVENT_DOMAIN = {
|
|
"education": "education", "residence": "relocation", "relationship": "relationship",
|
|
"career": "career", "public_work": "career", "finance": "finance",
|
|
"children": "family", "parents": "family", "health_pressure": "health_pressure",
|
|
}
|
|
|
|
|
|
class ReplayRow(NamedTuple):
|
|
health: bool
|
|
offset: int
|
|
hit: bool
|
|
random_hit_probability: float
|
|
centered_hit: bool
|
|
contains_reported: bool
|
|
questions: int
|
|
stop_reason: str
|
|
confidence: str
|
|
health_asked: bool
|
|
width_minutes: float
|
|
|
|
|
|
def equal_width_controls(truth: datetime, reported: datetime, window: tuple[datetime, datetime],
|
|
width: timedelta) -> tuple[float, bool]:
|
|
lo, hi = window
|
|
latest_start = hi - width
|
|
centered = reported - width / 2 <= truth <= reported + width / 2
|
|
if latest_start == lo:
|
|
return float(lo <= truth <= hi), centered
|
|
# An interval hits when its start lies between truth - width and truth.
|
|
# Start is uniform over the locations that fit inside the original window.
|
|
eligible = min(truth, latest_start) - max(lo, truth - width)
|
|
return max(0.0, eligible / (latest_start - lo)), centered
|
|
|
|
|
|
def answer(question: dict, events: list[dict], birth: datetime) -> dict:
|
|
if question["kind"] == "birthmarks":
|
|
return {"marks": ["none"]}
|
|
if question["kind"] != "event":
|
|
return {"choice": "unsure"}
|
|
domain = question["domain"]
|
|
# The frozen ledger supplies broad domains. Score only a matching dated
|
|
# event and keep its month when known. Unknown experiences stay neutral.
|
|
for event in sorted(events, key=lambda row: (-len(row["date"]), row["date"])):
|
|
if event["domain"] != EVENT_DOMAIN[domain]:
|
|
continue
|
|
date = event["date"][:7]
|
|
lo, hi = interview._date_span(datetime.fromisoformat(
|
|
date + ("-15" if len(date) == 7 else "-07-01")), "month" if len(date) == 7 else "year")
|
|
for option in question["options"]:
|
|
if not option.get("ages"):
|
|
continue
|
|
a, b = option["ages"]
|
|
if interview._age(lo, birth) <= b and interview._age(min(AS_OF, hi), birth) >= a:
|
|
return {"choice": option["value"], "date": date, "category": question["categories"][0]["id"]}
|
|
return {"choice": "unsure"}
|
|
|
|
|
|
def run_case(item: tuple[int, dict]) -> list[ReplayRow]:
|
|
index, case = item
|
|
interview._today = lambda req: AS_OF
|
|
birth = case["birth"]
|
|
truth = datetime.fromisoformat(f"{birth['date']}T{case['true_minute']}")
|
|
req = ChartRequest(birth["date"], birth["latitude"], birth["longitude"], birth["timezone_offset"])
|
|
# Assign the frozen offsets cyclically in the frozen case order, paired
|
|
# between both arms. Each person contributes one window per arm.
|
|
offset = OFFSETS[index % len(OFFSETS)]
|
|
reported = truth + timedelta(minutes=offset)
|
|
lo, hi = reported - timedelta(minutes=15), reported + timedelta(minutes=15)
|
|
lines = find_lines(req, lo, hi, adaptive.DIVISIONS)
|
|
rows = []
|
|
for include_health in (False, True):
|
|
answers = {}
|
|
while True:
|
|
replayed = adaptive.replay(req, reported, (lo, hi), lines, answers,
|
|
stop=False, include_health=include_health)
|
|
question = replayed["next"]
|
|
if question is None:
|
|
break
|
|
answers[question["id"]] = answer(question, case["events"], reported)
|
|
selected, _, _ = chart_questions.select_segment((lo, hi), reported, replayed["constraints"])
|
|
confidence = adaptive.confidence(req, reported, selected, replayed["atoms"],
|
|
replayed["events"] + replayed["health_events"])
|
|
start, end = selected
|
|
width = end - start
|
|
random_hit, centered_hit = equal_width_controls(truth, reported, (lo, hi), width)
|
|
rows.append(ReplayRow(include_health, offset, start <= truth <= end, random_hit, centered_hit,
|
|
start <= reported <= end, len(answers), replayed["stop_reason"], confidence,
|
|
any(question["chart"] == "D30" for question in replayed["asked"]),
|
|
width.total_seconds() / 60))
|
|
return rows
|
|
|
|
|
|
def hit_counts(rows: list[ReplayRow]) -> dict:
|
|
return {
|
|
"runs": len(rows), "contains_truth": sum(row.hit for row in rows),
|
|
"expected_same_width_random_hits": sum(row.random_hit_probability for row in rows),
|
|
"same_width_reported_center_hits": sum(row.centered_hit for row in rows),
|
|
}
|
|
|
|
|
|
def reported_overlap(rows: list[ReplayRow]) -> dict:
|
|
hits = sum(row.hit for row in rows)
|
|
return {"runs": len(rows), "hits": hits, "hit_rate": hits / len(rows) if rows else None}
|
|
|
|
|
|
def main() -> None:
|
|
cases = json.loads(DATASET.read_bytes())["cases"]
|
|
assert len(cases) == 77 and all(case["excluded_from_tuning"] for case in cases)
|
|
with ProcessPoolExecutor(max_workers=6) as workers:
|
|
rows = [row for batch in workers.map(run_case, enumerate(cases)) for row in batch]
|
|
result = {}
|
|
for mode in (False, True):
|
|
group = [row for row in rows if row.health == mode]
|
|
count = len(group)
|
|
containing = [row for row in group if row.contains_reported]
|
|
result["with_health" if mode else "without_health"] = {
|
|
**hit_counts(group),
|
|
"by_offset_minutes": {offset: hit_counts([row for row in group if row.offset == offset]) for offset in OFFSETS},
|
|
"contains_reported_share": len(containing) / count,
|
|
"contains_reported": reported_overlap(containing),
|
|
"excludes_reported": reported_overlap([row for row in group if not row.contains_reported]),
|
|
"mean_questions": sum(row.questions for row in group) / count,
|
|
"stop_reasons": Counter(row.stop_reason for row in group),
|
|
"confidence": {tier: {"total": sum(row.confidence == tier for row in group),
|
|
"hits": sum(row.hit and row.confidence == tier for row in group)}
|
|
for tier in ("high", "medium", "low", "tendency_only")},
|
|
"health_asked": sum(row.health_asked for row in group),
|
|
"mean_width_minutes": sum(row.width_minutes for row in group) / count,
|
|
}
|
|
print(json.dumps(result, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|