Files
Jyotisha/scripts/research/rectification_blind_pick.py
T
Jesse_ChenandClaude Opus 5.5 7091c51df2
Independent Staging Quality Gate / validate-python (push) Successful in 8m32s
Independent Staging Quality Gate / validate-frontend (push) Failing after 5m25s
Independent Staging Quality Gate / publish (push) Skipped
research(rectification): blind-pick test — scorer cannot tell recorded birth time from random times
Recorded time + 4 random times (>=60 min away) on 77 public AA cases: the
production event scorer picks the recorded time 23.1% (chance 20%, z=0.06);
random times 'match' 87.2% of events vs 86.9% for the truth. Fake-event
control at chance; positive control (years nudged +-3 to the true chart)
82.2%, so the harness detects signal when present.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp17MSiRTd1f9VANYqb
2026-12-05 09:07:11 +08:00

207 lines
9.8 KiB
Python

"""Blind-pick test for the rectification event scorer (2026-12-05).
Question (product owner): if the agent matches a person's life events against candidate birth times and says
"this time fits", would a random birth time "fit" just as well? Many candidates times many interpretive angles
always yield some match (multiple comparisons). Test: give the scorer the recorded time and random times, do
not say which is real, and see whether it picks the real one more often than chance.
Pre-registered design (fixed before the first run):
- Data: v5 holdout, 77 public Rodden-AA cases, 964 dated life events.
- Scorer: the production event engine `compute_event_candidate_rows`, all layers, the dataset's ayanamsa / node mode.
- Candidates per case: 96 times on the birth date every 15 minutes, aligned so the recorded time is one of them.
- PRIMARY: 1-of-5 blind pick. Truth plus 4 decoys drawn from the grid times at least 60 minutes (circular) from
the truth; the scorer "picks" the top score, ties split evenly. 4000 draws per case; chance = 0.20.
- SECONDARY: truth's percentile among truth + decoy pool (0 = best, chance mean 0.5); cases with truth in top 20%.
Also decoys >= 120 min and 15-120 min.
- NEGATIVE CONTROL: same people, same event count / domains / precision, each event's date redrawn uniformly between
that person's earliest and latest event year (5 seeds). Must sit at chance.
- POSITIVE CONTROL (`--positive-control`): each event's year moved within +-3 years to the year that best suits the
recorded time's own chart. If the harness can detect a signal, truth must win clearly.
- BARNUM CHECK: share of events earning positive points ("matched") for truth vs for decoys.
Offline only; public cases only; does not touch production defaults.
"""
from __future__ import annotations
import argparse
import json
import math
import random
import statistics
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Sequence
ROOT = Path(__file__).resolve().parents[2]
for path in (ROOT, ROOT / "scripts"):
if str(path) not in sys.path:
sys.path.insert(0, str(path))
HOLDOUT_V5 = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v5.json"
STEP_MINUTES = 15
DRAWS = 4000
CONTROL_SEEDS = (11, 22, 33, 44, 55)
DESIGNS = {"far_60plus": (60, 720), "far_120plus": (120, 720), "near_15_to_120": (15, 120)}
POSITIVE_NUDGE_YEARS = 3
Scored = tuple[int, float, float] # (minute of day, score, share of events matched)
def circular_minutes(a: int, b: int) -> int:
d = abs(a - b) % 1440
return min(d, 1440 - d)
def grid_times(truth: datetime, step: int = STEP_MINUTES) -> list[datetime]:
"""Every `step` minutes on the truth's calendar date, the truth itself included."""
return [datetime.combine(truth.date(), (truth + timedelta(minutes=step * k)).time()) for k in range(1440 // step)]
def plain_events(case: dict[str, Any]) -> list[dict[str, Any]]:
return [{"id": e["id"], "domain": e["domain"], "date": e["date"], "precision": e["precision"]} for e in case["events"]]
def base_request(case: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
b = case["birth"]
return {"birth_date": b["date"], "start_time": "00:00", "end_time": "23:59", "lat": b["latitude"],
"lon": b["longitude"], "tz": b["timezone_offset"], "ayanamsa": data["ayanamsa"],
"node_mode": data["node_mode"], "minute_step": 1}
def truth_time(case: dict[str, Any]) -> datetime:
b = case["birth"]
return datetime.strptime(f"{b['date']} {b['time']}", "%Y-%m-%d %H:%M")
def score_grid(case: dict[str, Any], data: dict[str, Any], events: list[dict[str, Any]]) -> list[Scored]:
from scripts.active_rectification_event_engine import compute_event_candidate_rows
cands = grid_times(truth_time(case))
rows = compute_event_candidate_rows({**base_request(case, data), "events": events}, candidates=cands)
n_events = max(1, len(events))
out: list[Scored] = []
for cand, row in zip(cands, rows):
matched = {e["event_id"] for e in row["evidence"] if e.get("points", 0) > 0}
out.append((cand.hour * 60 + cand.minute, float(row["score"]), len(matched) / n_events))
return out
def evaluate(scored: Sequence[Scored], truth_minute: int, decoy_min: int, decoy_max: int,
rng: random.Random, draws: int = DRAWS) -> dict[str, Any]:
truth = next(s for s in scored if s[0] == truth_minute)
pool = [s for s in scored if decoy_min <= circular_minutes(s[0], truth_minute) <= decoy_max]
hit = 0.0
for _ in range(draws):
scores = [truth[1]] + [d[1] for d in rng.sample(pool, 4)]
best = max(scores)
if truth[1] == best:
hit += 1 / scores.count(best)
better = sum(1 for p in pool if p[1] > truth[1])
ties = sum(1 for p in pool if p[1] == truth[1])
pct = (better + ties / 2) / len(pool)
return {"hit": hit / draws, "pct": pct, "top20": pct < 0.2,
"match_truth": truth[2], "match_decoy": statistics.mean(p[2] for p in pool)}
def fake_events(case: dict[str, Any], rng: random.Random) -> list[dict[str, Any]]:
years = [int(e["date"][:4]) for e in case["events"]]
lo, hi = min(years), max(years)
out = []
for e in case["events"]:
y = rng.randint(lo, hi)
if e["precision"] == "year":
date = f"{y}"
elif e["precision"] == "month":
date = f"{y}-{rng.randint(1, 12):02d}"
else:
date = f"{y}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}"
out.append({"id": e["id"], "domain": e["domain"], "date": date, "precision": e["precision"]})
return out
def truth_favoured_events(case: dict[str, Any], data: dict[str, Any]) -> list[dict[str, Any]]:
"""Positive control: each event moved to the year (within +-3) that scores best for the recorded time."""
from scripts.active_rectification_event_engine import compute_event_candidate_rows
truth = truth_time(case)
base = base_request(case, data)
out = []
for e in case["events"]:
y = int(e["date"][:4])
best: tuple[float, dict[str, Any]] | None = None
for yy in range(y - POSITIVE_NUDGE_YEARS, y + POSITIVE_NUDGE_YEARS + 1):
ev = {"id": e["id"], "domain": e["domain"], "date": str(yy), "precision": "year"}
s = compute_event_candidate_rows({**base, "events": [ev]}, candidates=[truth])[0]["score"]
if best is None or s > best[0]:
best = (s, ev)
assert best is not None
out.append(best[1])
return out
def summarize(rows: Sequence[dict[str, Any]]) -> dict[str, Any]:
n = len(rows)
hits = [r["hit"] for r in rows]
pcts = [r["pct"] for r in rows]
mean_pct = statistics.mean(pcts)
return {"n": n, "pick1of5": round(statistics.mean(hits), 3),
"pick_se": round(statistics.pstdev(hits) / math.sqrt(n), 3),
"mean_percentile": round(mean_pct, 3),
"z_vs_chance": round((0.5 - mean_pct) / (math.sqrt(1 / 12) / math.sqrt(n)), 2),
"truth_top20_cases": sum(r["top20"] for r in rows),
"events_matched_truth": round(statistics.mean(r["match_truth"] for r in rows), 3),
"events_matched_decoy": round(statistics.mean(r["match_decoy"] for r in rows), 3)}
def run(data: dict[str, Any], *, positive_control: bool = False) -> dict[str, Any]:
real: dict[str, list[dict[str, Any]]] = {k: [] for k in DESIGNS}
control: dict[str, list[dict[str, Any]]] = {k: [] for k in DESIGNS}
per_case = []
for i, case in enumerate(data["cases"]):
t = truth_time(case)
tmin = t.hour * 60 + t.minute
tuning_free = not case.get("inherited_from_v4", False)
events = truth_favoured_events(case, data) if positive_control else plain_events(case)
scored = score_grid(case, data, events)
rec: dict[str, Any] = {"case": case["case_id"], "tuning_free": tuning_free, "events": len(events)}
for k, (lo, hi) in DESIGNS.items():
r = evaluate(scored, tmin, lo, hi, random.Random(f"{case['case_id']}-{k}"))
r["tuning_free"] = tuning_free
real[k].append(r)
rec[k] = {"hit": round(r["hit"], 3), "pct": round(r["pct"], 3)}
if not positive_control:
for seed in CONTROL_SEEDS:
fscored = score_grid(case, data, fake_events(case, random.Random(f"{case['case_id']}-{seed}")))
for k, (lo, hi) in DESIGNS.items():
r = evaluate(fscored, tmin, lo, hi, random.Random(f"{case['case_id']}-{k}-{seed}"))
r["tuning_free"] = tuning_free
control[k].append(r)
per_case.append(rec)
print(i + 1, case["case_id"], rec["far_60plus"], file=sys.stderr, flush=True)
summary: dict[str, Any] = {}
for k in DESIGNS:
summary[k] = {"real_all": summarize(real[k]),
"real_tuning_free": summarize([r for r in real[k] if r["tuning_free"]])}
if not positive_control:
summary[k]["fake_events_control"] = summarize(control[k])
return {"mode": "positive_control" if positive_control else "real_events",
"dataset": str(HOLDOUT_V5.relative_to(ROOT)), "step_minutes": STEP_MINUTES, "draws": DRAWS,
"summary": summary, "per_case": per_case}
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--positive-control", action="store_true")
args = parser.parse_args(argv)
data = json.loads(HOLDOUT_V5.read_text(encoding="utf-8"))
result = run(data, positive_control=args.positive_control)
args.out.write_text(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(result["summary"], ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())