#!/usr/bin/env python3 """ founding_stats.py — statistical evaluation of the founder-potential fields in `multiplicators_v1`, next to the multiplicator archetypes. Reads the LIVE index (same precedent as make_report.py) and prints markdown: cohort overview, percentile distribution per career stage, the founder shortlist (plain and with the `publications >= 7` robustness co-filter that screens the measured population-boundary artifact), overlap with the three archetypes, research-area composition, and factor importance (the v2 model's permutation importances next to local Spearman correlations). There is deliberately no binary "is a founder": v2 emits a percentile, and the shortlist cutoff is operational (--threshold, default 90). Usage (repo root): conda run -n potential python -m service.scripts.profiling.multipliers.founding_stats \ --institution-id I62318514 ... --threshold 75 --min-pubs 7 # different shortlist definition ... --out service/scripts/profiling/multipliers/stats_generated.md """ from __future__ import annotations import argparse import csv import math from pathlib import Path from typing import Any, Iterable from service.scripts.profiling.multipliers.index import ( MULTIPLICATORS_INDEX, MultiplicatorsIndexClient, ) SCRIPT_DIR = Path(__file__).resolve().parent # Dimensions FOR 2-digit division names — only what founding.py can produce. FOR_NAMES = { "30": "Agricultural, Veterinary & Food Sciences", "31": "Biological Sciences", "32": "Biomedical & Clinical Sciences", "34": "Chemical Sciences", "35": "Commerce, Management, Tourism & Services", "36": "Creative Arts & Writing", "37": "Earth Sciences", "38": "Economics", "40": "Engineering", "41": "Environmental Sciences", "42": "Health Sciences", "44": "Human Society", "46": "Information & Computing Sciences", "49": "Mathematical Sciences", "51": "Physical Sciences", "52": "Psychology", "n.": "unknown / not classified", } BUCKET_ORDER = ["Early", "Emerging", "Established", "Senior"] DOC_FIELDS = [ "author_id", "display_name", "career_bucket", "active_years", "n_works", "suspicious_profile", "tags", "sub_scores", "founding", "founding_features", "news_mentions", ] # --------------------------------------------------------------------- # data access # --------------------------------------------------------------------- def fetch_rows(institution_id: str) -> list[dict[str, Any]]: """All docs for the institution via search_after (same pagination pattern as index.py's id collector).""" es = MultiplicatorsIndexClient() rows: list[dict[str, Any]] = [] search_after = None while True: body: dict[str, Any] = { "size": 1000, "_source": DOC_FIELDS, "query": {"term": {"institution_id": institution_id}}, "sort": [{"author_id": {"order": "asc"}}], } if search_after: body["search_after"] = search_after r = es._request("POST", f"{MULTIPLICATORS_INDEX}/_search", json=body) r.raise_for_status() hits = r.json()["hits"]["hits"] if not hits: break rows.extend(h["_source"] for h in hits) search_after = hits[-1]["sort"] return rows # --------------------------------------------------------------------- # small stats helpers (pure python — no pandas for a report tool) # --------------------------------------------------------------------- def quantile(sorted_values: list[float], q: float) -> float: if not sorted_values: return float("nan") pos = q * (len(sorted_values) - 1) lo, hi = int(math.floor(pos)), int(math.ceil(pos)) if lo == hi: return sorted_values[lo] frac = pos - lo return sorted_values[lo] * (1 - frac) + sorted_values[hi] * frac def _ranks(values: list[float]) -> list[float]: """Average ranks with tie handling (for Spearman).""" order = sorted(range(len(values)), key=lambda i: values[i]) ranks = [0.0] * len(values) i = 0 while i < len(order): j = i while j + 1 < len(order) and values[order[j + 1]] == values[order[i]]: j += 1 mean_rank = (i + j) / 2 + 1 for k in range(i, j + 1): ranks[order[k]] = mean_rank i = j + 1 return ranks def spearman(xs: list[float], ys: list[float]) -> float: """Spearman rank correlation, pure python. NaN-free inputs expected.""" if len(xs) < 3: return float("nan") rx, ry = _ranks(xs), _ranks(ys) mx = sum(rx) / len(rx) my = sum(ry) / len(ry) cov = sum((a - mx) * (b - my) for a, b in zip(rx, ry)) vx = math.sqrt(sum((a - mx) ** 2 for a in rx)) vy = math.sqrt(sum((b - my) ** 2 for b in ry)) return cov / (vx * vy) if vx and vy else float("nan") def md_table(headers: list[str], rows: Iterable[Iterable[Any]]) -> str: lines = ["| " + " | ".join(str(h) for h in headers) + " |", "|" + "|".join("---" for _ in headers) + "|"] for row in rows: lines.append("| " + " | ".join(str(c) for c in row) + " |") return "\n".join(lines) def pct(part: int, whole: int) -> str: return f"{100 * part / whole:.1f}%" if whole else "–" # --------------------------------------------------------------------- # report sections # --------------------------------------------------------------------- def section_overview(rows: list[dict[str, Any]]) -> str: n = len(rows) in_pop = [r for r in rows if r["founding"]["in_population"]] timing = sum(1 for r in rows if r["founding"]["timing_applicable"]) with_pat = sum(1 for r in rows if (r["founding_features"].get("patents") or 0) >= 1) sources = sorted({r["founding"]["patent_source"] for r in rows}) buckets = {b: 0 for b in BUCKET_ORDER} for r in rows: buckets[r["career_bucket"]] = buckets.get(r["career_bucket"], 0) + 1 out = [ "## 1. Cohort overview", "", md_table( ["", "n", "share"], [ ["documents", n, "100%"], ["`founding.in_population` (≥4 publications)", len(in_pop), pct(len(in_pop), n)], ["`founding.timing_applicable`", timing, pct(timing, n)], ["≥1 patent (`founding_features.patents`)", with_pat, pct(with_pat, n)], ["patent provenance", ", ".join(sources), ""], ], ), "", md_table( ["career stage", "n", "share"], [[b, buckets[b], pct(buckets[b], n)] for b in BUCKET_ORDER], ), ] return "\n".join(out) def _pctl(r: dict[str, Any]) -> float | None: return r["founding"].get("percentile") def section_percentile_by_stage(rows: list[dict[str, Any]], min_pubs: int) -> str: out = ["## 2. Founding percentile by career stage (in population)", ""] table = [] for b in BUCKET_ORDER + ["ALL"]: sub = [ r for r in rows if r["founding"]["in_population"] and (b == "ALL" or r["career_bucket"] == b) ] vals = sorted(v for v in (_pctl(r) for r in sub) if v is not None) if not vals: continue table.append([ b, len(vals), f"{quantile(vals, 0.50):.1f}", f"{quantile(vals, 0.90):.1f}", sum(1 for v in vals if v >= 75), sum(1 for v in vals if v >= 90), ]) out.append(md_table( ["career stage", "n (in pop.)", "pctl p50", "pctl p90", "n ≥75", "n ≥90"], table)) out.append("") out.append(f"Same, restricted to `publications >= {min_pubs}` " f"(screens the population-boundary artifact):") table = [] for b in BUCKET_ORDER + ["ALL"]: sub = [ r for r in rows if r["founding"]["in_population"] and (r["founding_features"].get("publications") or 0) >= min_pubs and (b == "ALL" or r["career_bucket"] == b) ] vals = sorted(v for v in (_pctl(r) for r in sub) if v is not None) if not vals: continue table.append([ b, len(vals), f"{quantile(vals, 0.50):.1f}", f"{quantile(vals, 0.90):.1f}", sum(1 for v in vals if v >= 75), sum(1 for v in vals if v >= 90), ]) out.append(md_table( ["career stage", "n", "pctl p50", "pctl p90", "n ≥75", "n ≥90"], table)) return "\n".join(out) def _shortlists(rows, threshold, min_pubs): plain = [r for r in rows if (_pctl(r) or 0) >= threshold] robust = [r for r in plain if (r["founding_features"].get("publications") or 0) >= min_pubs] return plain, robust def section_shortlist(rows, threshold, min_pubs) -> str: plain, robust = _shortlists(rows, threshold, min_pubs) out = [f"## 3. The shortlist: founding percentile ≥ {threshold}", ""] table = [] for b in BUCKET_ORDER: n_plain = sum(1 for r in plain if r["career_bucket"] == b) n_robust = sum(1 for r in robust if r["career_bucket"] == b) table.append([b, n_plain, n_robust]) table.append(["**ALL**", len(plain), len(robust)]) out.append(md_table( ["career stage", f"pctl ≥{threshold}", f"… AND pubs ≥{min_pubs} (robust)"], table)) out.append("") out.append( f"The gap between the columns is the measured boundary artifact: " f"{len(plain) - len(robust)} of {len(plain)} shortlisted profiles have " f"fewer than {min_pubs} publications (long-dormant / fragment profiles " f"scoring just above the ≥4 population cut)." ) return "\n".join(out) def section_archetype_overlap(rows, threshold, min_pubs) -> str: plain, robust = _shortlists(rows, threshold, min_pubs) out = ["## 4. Founder potential × multiplicator archetypes", ""] def tag_counts(subset): counts = {"mentor": 0, "bridger": 0, "amplifier": 0, "none": 0} for r in subset: tags = r.get("tags") or [] if not tags: counts["none"] += 1 for t in tags: if t in counts: counts[t] += 1 return counts tp, tr = tag_counts(plain), tag_counts(robust) out.append(md_table( ["", "mentor tag", "bridger tag", "amplifier tag", "no tag"], [[f"shortlist (≥{threshold})", tp["mentor"], tp["bridger"], tp["amplifier"], tp["none"]], [f"robust shortlist (pubs ≥{min_pubs})", tr["mentor"], tr["bridger"], tr["amplifier"], tr["none"]]], )) out.append("") out.append("Tags fire for ~3% of the cohort, so the softer view — sub-score " "≥ 0.7 within the person's career bucket — shows the overlap " "structure better:") table = [] for label, subset in [(f"shortlist (≥{threshold})", plain), (f"robust (pubs ≥{min_pubs})", robust)]: row = [label, len(subset)] for sub_name in ("mentor", "bridger", "amplifier"): row.append(sum(1 for r in subset if (r.get("sub_scores") or {}).get(sub_name, 0) >= 0.7)) table.append(row) out.append(md_table(["", "n", "mentor ≥0.7", "bridger ≥0.7", "amplifier ≥0.7"], table)) out.append("") out.append("And the reverse direction — the founding percentile of the tagged " "multiplicators (why round thresholds select nobody):") table = [] for tag in ("mentor", "bridger", "amplifier"): tagged = [r for r in rows if tag in (r.get("tags") or []) and r["founding"]["in_population"]] vals = sorted(v for v in (_pctl(r) for r in tagged) if v is not None) if not vals: table.append([tag, 0, "–", "–", 0]) continue table.append([tag, len(vals), f"{quantile(vals, 0.5):.0f}", f"{quantile(vals, 0.9):.0f}", sum(1 for v in vals if v >= 40)]) out.append(md_table( ["tagged as", "n (in pop.)", "founding pctl p50", "p90", "n ≥40"], table)) return "\n".join(out) def section_areas(rows, threshold, min_pubs) -> str: plain, robust = _shortlists(rows, threshold, min_pubs) cohort = [r for r in rows if r["founding"]["in_population"]] def area_counts(subset): counts: dict[str, int] = {} for r in subset: area = (r["founding_features"].get("publication_research_area")) or "n." counts[area] = counts.get(area, 0) + 1 return counts ca, pa, ra = area_counts(cohort), area_counts(plain), area_counts(robust) areas = sorted(ca, key=lambda a: -ca[a])[:10] out = ["## 5. Research areas (FOR division, from OpenAlex publication fields)", ""] table = [] for a in areas: table.append([ f"{a} {FOR_NAMES.get(a, '')}", f"{ca.get(a, 0)} ({pct(ca.get(a, 0), len(cohort))})", f"{pa.get(a, 0)} ({pct(pa.get(a, 0), len(plain))})", f"{ra.get(a, 0)} ({pct(ra.get(a, 0), len(robust))})", ]) out.append(md_table( ["area", "cohort (in pop.)", f"shortlist ≥{threshold}", f"robust (pubs ≥{min_pubs})"], table)) return "\n".join(out) def section_factors(rows, min_pubs: int) -> str: out = ["## 6. Which factors drive founder identification", "", "### 6a. The model's own permutation importances (training-side truth)", ""] imp_path = (SCRIPT_DIR.parent / "founding_potential" / "results" / "rq1_symmetric" / "permutation_importance.csv") if imp_path.exists(): with open(imp_path, newline="", encoding="utf-8") as f: imp = list(csv.DictReader(f))[:12] out.append(md_table( ["feature", "importance (mean ROC-AUC drop)"], [[r["feature"], f"{float(r['importance_mean']):.3f}"] for r in imp])) out.append("") out.append( "⚠️ Deployment caveat: the top feature `patent_research_area_n.` is " "CONSTANT in this index — our corpus has no IPC→FOR mapping, so every " "record (patent holders included) carries `patent_research_area = " "\"n.\"`. Locally that feature separates nothing, and the 152 patent " "holders sit slightly off the training manifold (patents present but " "no patent area). Mapping IPC→FOR (the backend's " "`ipc_openalex_mapping` is a starting point) would unlock the " "model's #1 and #8 features." ) else: out.append(f"(permutation_importance.csv not found at {imp_path})") out += ["", "### 6b. Local Spearman rank correlation with `founding.percentile`", ""] in_pop = [r for r in rows if r["founding"]["in_population"] and _pctl(r) is not None] ref_year = in_pop[0]["founding"]["as_of_year"] if in_pop else 2026 candidates = { "publications": lambda r: r["founding_features"].get("publications"), "pub_rate (pubs/career age)": lambda r: ( (r["founding_features"].get("publications") or 0) / max(1, ref_year - (r["founding_features"].get("first_publication_year") or ref_year)) ), "career_age": lambda r: r["founding"].get("current_career_age"), "active_years": lambda r: r.get("active_years"), "activity density (active_years/career_age)": lambda r: ( (r.get("active_years") or 0) / max(1, r["founding"].get("current_career_age") or 1) ), "patents": lambda r: r["founding_features"].get("patents"), "grants_capped": lambda r: r["founding_features"].get("grants_capped"), "industry_collab_papers": lambda r: r["founding_features"].get("industry_collab_papers"), "news_mentions": lambda r: r.get("news_mentions") if "news_mentions" in r else 0, "sub_score mentor": lambda r: (r.get("sub_scores") or {}).get("mentor"), "sub_score bridger": lambda r: (r.get("sub_scores") or {}).get("bridger"), "sub_score amplifier": lambda r: (r.get("sub_scores") or {}).get("amplifier"), } def corr_rows(subset): y = [float(_pctl(r) or 0) for r in subset] # subset pre-filtered to non-None return { name: spearman([float(g(r) or 0) for r in subset], y) for name, g in candidates.items() } robust = [r for r in in_pop if (r["founding_features"].get("publications") or 0) >= min_pubs] all_c = corr_rows(in_pop) rob_c = corr_rows(robust) ordered = sorted(candidates, key=lambda n: -abs(rob_c[n])) out.append(md_table( ["observable", f"ρ, all in population (n={len(in_pop)})", f"ρ, pubs ≥{min_pubs} (n={len(robust)})"], [[n, f"{all_c[n]:+.3f}", f"{rob_c[n]:+.3f}"] for n in ordered])) out.append("") out.append( "Correlation on the scored cohort, not causation in the model — 6a is " "what the model uses, 6b is how the score co-varies with everything " "observable here (including archetype sub-scores the model never saw). " "Read the two columns together: signs that flip or shrink between them " "are carried by the sub-7-publication boundary zone, not by the " "in-regime ranking." ) return "\n".join(out) # --------------------------------------------------------------------- def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--institution-id", required=True) parser.add_argument("--threshold", type=float, default=90.0, help="founding percentile defining the shortlist (default 90)") parser.add_argument("--min-pubs", type=int, default=7, help="publication floor for the robust shortlist (default 7)") parser.add_argument("--out", default=None, help="also write the report to this markdown file") args = parser.parse_args() short = args.institution_id.strip().rsplit("/", 1)[-1] rows = fetch_rows(short) if not rows: raise SystemExit(f"No documents for {short} in {MULTIPLICATORS_INDEX}.") sections = [ f"# Founder-potential statistics — {short}", "", f"Generated by `founding_stats.py` from the live `{MULTIPLICATORS_INDEX}` " f"index ({len(rows)} documents, config_hash of the newest run applies). " f"Shortlist = `founding.percentile >= {args.threshold:g}`; robust = " f"additionally `publications >= {args.min_pubs}`. Regenerate with:", "", "```bash", "conda run -n potential python -m " "service.scripts.profiling.multipliers.founding_stats \\", f" --institution-id {short} --threshold {args.threshold:g} " f"--min-pubs {args.min_pubs}", "```", "", section_overview(rows), "", section_percentile_by_stage(rows, args.min_pubs), "", section_shortlist(rows, args.threshold, args.min_pubs), "", section_archetype_overlap(rows, args.threshold, args.min_pubs), "", section_areas(rows, args.threshold, args.min_pubs), "", section_factors(rows, args.min_pubs), ] report = "\n".join(sections) + "\n" print(report) if args.out: Path(args.out).write_text(report, encoding="utf-8") print(f"\n[written to {args.out}]") if __name__ == "__main__": main()