#!/usr/bin/env python3 """ validate_sample.py โ€” M1 exit check against the 60-person hand-labeled sample. analysis/career_stage/career_stage_sample.csv holds 60 UDE researchers with manually verified status (31 Professor / 29 Researcher incl. doctoral). The mentor sub-score is a proxy for supervision with no ground truth in OpenAlex, so the cheapest sanity check is: mentor scores must concentrate on the professors. If they don't, the proxy is wrong and M2 waits (plan ยง5, M1 exit). Usage: python validate_sample.py --institution-id I62318514 """ from __future__ import annotations import argparse import csv import gzip import json import statistics from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent REPO_ROOT = SCRIPT_DIR.parent.parent.parent SAMPLE_CSV = REPO_ROOT / "analysis" / "career_stage" / "career_stage_sample.csv" def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--institution-id", required=True) parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache")) args = parser.parse_args() short = args.institution_id.strip().rsplit("/", 1)[-1] scores_path = Path(args.cache_dir) / f"scores_{short}.jsonl.gz" if not scores_path.exists(): raise SystemExit(f"Run build.py first โ€” missing {scores_path}") scores: dict[str, dict] = {} with gzip.open(scores_path, "rt", encoding="utf-8") as f: for line in f: row = json.loads(line) scores[row["author_id"]] = row sample: list[dict] = [] with open(SAMPLE_CSV, newline="", encoding="utf-8-sig") as f: for rec in csv.DictReader(f): sample.append(rec) by_status: dict[str, list[dict]] = {} missing: list[str] = [] for rec in sample: aid = rec["openalex_author_id"].strip() row = scores.get(aid) if row is None: missing.append(f"{rec['name']} ({aid})") continue by_status.setdefault(rec["known_status"], []).append( {"name": rec["name"], "discipline": rec["discipline_group"], **row} ) print(f"Sample: {len(sample)} people, matched in scores: " f"{sum(len(v) for v in by_status.values())}, missing: {len(missing)}") for m in missing: print(f" MISSING: {m}") report: dict = {"missing": missing, "by_status": {}} for sub in ("mentor", "bridger", "amplifier"): print(f"\n=== {sub} sub-score by known status ===") for status, rows in sorted(by_status.items()): vals = [r["sub_scores"][sub] for r in rows] entry = { "n": len(vals), "median": round(statistics.median(vals), 3), "mean": round(statistics.fmean(vals), 3), "min": round(min(vals), 3), "max": round(max(vals), 3), } report["by_status"].setdefault(status, {})[sub] = entry print(f" {status:<12} n={entry['n']:>2} median={entry['median']:.3f} " f"mean={entry['mean']:.3f} range=[{entry['min']:.3f}, {entry['max']:.3f}]") # headline check: professors' median mentor score > researchers' prof = report["by_status"].get("Professor", {}).get("mentor", {}) res = report["by_status"].get("Researcher", {}).get("mentor", {}) if prof and res: ok = prof["median"] > res["median"] print(f"\nM1 exit check โ€” professors' median mentor score " f"({prof['median']}) > researchers' ({res['median']}): " f"{'PASS' if ok else 'FAIL'}") report["m1_exit_mentor_check"] = "PASS" if ok else "FAIL" # per-person detail for eyeballing print("\n=== per-person (sorted by mentor score) ===") everyone = [r for rows in by_status.values() for r in rows] for r in sorted(everyone, key=lambda x: x["sub_scores"]["mentor"], reverse=True): status = next(s for s, rows in by_status.items() if r in rows) print(f" {r['sub_scores']['mentor']:.3f} {status:<11} {r['career_bucket']:<12}" f" juniors={r['juniors_mentored']:>3} laj={r['last_author_with_junior_first']:>3}" f" {r['name']} ({r['discipline']})") out = Path(args.cache_dir) / f"validation_{short}.json" with open(out, "w", encoding="utf-8", newline="\n") as f: json.dump(report, f, ensure_ascii=False, indent=2) print(f"\nReport -> {out}") if __name__ == "__main__": main()