Files
smartguide/service/scripts/profiling/multipliers/validate_sample.py
T
2026-08-27 13:53:10 +02:00

120 lines
4.7 KiB
Python

#!/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). The mentor sub-score
is a proxy for supervision with no ground truth in OpenAlex, so the check is:
mentor scores must concentrate on the professors.
Usage (from the repo root):
python -m service.scripts.profiling.multipliers.validate_sample --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
SAMPLE_RELATIVE = Path("analysis") / "career_stage" / "career_stage_sample.csv"
def _find_sample_csv() -> Path:
"""Locate the hand-labeled sample by walking up from this file — a walk
rather than fixed `.parent` hops, which broke when this module moved."""
for directory in SCRIPT_DIR.parents:
candidate = directory / SAMPLE_RELATIVE
if candidate.exists():
return candidate
raise SystemExit(f"Could not find {SAMPLE_RELATIVE} above {SCRIPT_DIR}")
SAMPLE_CSV = _find_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"
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()