"""Overall ranking 2026, method v3.7 (expanded edition) = METHOD-v2.md v2.0 + Amendments 1-18 (+errata); v3.7 = v3.6 + Amendment 18 Japan round
(student counts for Japan, raw-affiliation screen research_a18_rawaff.json).

Inputs : data/v2/universe.json, data/v2/*.json, data/v2/raw/enrollment/ef2023a/ef2023a.csv (US FTE),
         data/side/laureates.json, data/processed/scores.json (Research Index pillars + metrics),
         Amendment 15: data/v2/alumni_a15_corrections.json, data/v2/research_mergers_a15.json, data/side/retractions.json
         Amendment 16: data/v2/enrollment_a16_*.json, data/v2/incountry_r16_*.json
         Amendment 17: data/v2/incountry_r17_us.json (incountry_r17_au.json is display-only, not loaded)
         Amendment 18: data/v2/universe_ext_a18_candidates.json, enrollment_a18_*.json, research_a18.json, notable_alumni_a18.json,
                       incountry_a18_us.json, incountry_a18_uk.json, a11_meta_a18_us.json, data/side/laureates_a18.json,
                       data/v3/raw/a18_enr_us_*/ipeds_distance_rows.json (all optional; A18_DIR overrides the folder, for tests)
Output : data/processed/overall_v2.json
Usage  : python3 pipeline/score_v2.py                                   (v3.7)
         python3 pipeline/score_v2.py --no-a18 --out /tmp/v34.json       (Amendment 18 off: reproduces overall_v3.4.json)
         python3 pipeline/score_v2.py --no-a15 --out /tmp/v31.json       (Amendments 15-18 off: reproduces overall_v3.1.json)
Earlier versions: pipeline/score_v2_0_1.py (v2.0 / v2.1) ... score_v3_1.py ... score_v3_4.py, score_v3_5.py, score_v3_6.py (all frozen).
"""
import argparse, csv, json, math, os, re, sys
from pathlib import Path

import numpy as np
from scipy.stats import rankdata, spearmanr

ROOT = Path(__file__).resolve().parent.parent
V2 = ROOT / "data" / "v2"
_ap = argparse.ArgumentParser(description="Overall ranking scorer (v3.7)")
_ap.add_argument("--no-a15", action="store_true", help="switch Amendments 15-18 off (reproduces v3.1); needs --out")
_ap.add_argument("--no-a18", action="store_true", help="switch Amendment 18 off (reproduces v3.4); needs --out")
_ap.add_argument("--out", help="output path (default data/processed/overall_v2.json)")
ARGS = _ap.parse_args()
if (ARGS.no_a15 or ARGS.no_a18) and not ARGS.out:
    _ap.error("--no-a15 / --no-a18 need --out, so the live output is not overwritten")
A15 = not ARGS.no_a15      # Amendment 15 (v3.2, face-validity audit)
A18 = A15 and not ARGS.no_a18   # Amendment 18 (v3.5-v3.7, universities beyond the Leiden data)
A18_DIR = Path(os.environ["A18_DIR"]) if os.environ.get("A18_DIR") else None   # test fixtures only


def a18_path(name, default_dir=None):
    return (A18_DIR or default_dir or (ROOT / "data" / "v2")) / name
OUT = Path(ARGS.out) if ARGS.out else ROOT / "data" / "processed" / "overall_v2.json"
SEED, N_DRAWS = 20261010, 2000
GRAD_ONLY = {"Rockefeller University", "University of California, San Francisco",
             "University of Texas Southwestern Medical Center at Dallas", "King Abdullah University of Science and Technology",
             "Weizmann Institute of Science"}
G_W = {"res_quality": 15, "res_strength": 10, "founders": 10, "wealth": 10, "laureates": 10, "notable": 5, "heads": 5}
CUTOFF = {"founders": 241, "billionaires": 12, "uhnw_us": 2600, "uhnw_nonus": 800}
# Amendment 2.4: values excluded because they are not comparable by construction
W_EXCLUDE = {("greater_china_sea", "cn_gaokao_zhejiang_min_rank", "Zhejiang University"),
             ("jpkr_anz", "au_gos_ug_median_ft_salary", "University of Melbourne")}
if A15:   # Amendment 15.9: an undergraduate outcome is excluded where the main professional degrees are graduate-entry only
    W_EXCLUDE.add(("jpkr_anz", "au_gos_ug_median_ft_salary", "University of Western Australia"))


def load(name):
    return json.loads((V2 / f"{name}.json").read_text())


GRAD_ONLY_ROR = set()
for _gf in ("grad_only_all", "elite_grad_new"):
    _go = V2 / f"{_gf}.json"
    if _go.exists():
        GRAD_ONLY_ROR |= {r for r, rec in json.loads(_go.read_text()).get("by_ror", {}).items()
                          if isinstance(rec.get("graduate_only"), dict) and rec["graduate_only"].get("value") == 1}
universe = [u for u in load("universe_full") if u["name"] not in GRAD_ONLY and u["ror"] not in GRAD_ONLY_ROR]   # Amendment 8
# Amendment 5: universities without any enrollment figure are listed but not ranked overall
ENR_ORDER = ["enrollment_all_world", "enrollment_new_rest", "enrollment_new_asia", "enrollment_all_gapfill", "enrollment_cn_asia",
             "enrollment_uk_eu", "enrollment_anz_americas", "enrollment_us", "enrollment_all_official",
             "enrollment_new_official", "enrollment_a11"]      # Amendment 7.3: last wins (official files last); 11.9 refresh last
ENR_ORDER += sorted(p.stem for p in V2.glob("enrollment_a11b_*.json"))     # 11.9 second pass
ENR_ORDER += sorted(p.stem for p in V2.glob("enrollment_a16_*.json")) if A15 else []   # counts for universities that had none (Oct 2026 round); off with --no-a15 so v3.1 still reproduces
# Amendment 18: candidates beyond the Leiden data and their student counts (only candidate rors are read from these files)
A18_CANDS = json.loads(a18_path("universe_ext_a18_candidates.json").read_text())["candidates"] if A18 and a18_path("universe_ext_a18_candidates.json").exists() else []
A18_CAND_RORS = {c["ror"] for c in A18_CANDS}
A18_ENR_FILES = sorted((A18_DIR or V2).glob("enrollment_a18_*.json")) if A18 else []
A18_NOT_UNI, A18_UNIT_OF, A18_UNRESOLVED = {}, {}, {}
# Amendment 18.1(a) with Leiden's own affiliation file: candidates that Leiden counts as components or joint organisations are units
if A18 and a18_path("universe_ext_a18_leiden_units.json").exists():
    for _r, _x in json.loads(a18_path("universe_ext_a18_leiden_units.json").read_text())["by_ror"].items():
        if _r in A18_CAND_RORS:
            A18_UNIT_OF.setdefault(_r, {"name": _x["name"], "parent_ror": _x["parents"][0]["ror"], "parent_name": _x["parents"][0]["name"],
                                        "note": "Leiden counts its papers in " + ", ".join(f'{p["name"]} ({p["relation"]})' for p in _x["parents"])})
# Amendment 18.11: research that OpenAlex demonstrably attributes to another institution can't be measured (checked on raw affiliations)
A18_RESEARCH_EXCLUDE = {"022jz8688": "OpenAlex credits York University (Toronto) papers to York University (York, Nebraska); checked 28 Oct 2026"}
if A18 and a18_path("research_a18_attribution.json").exists():   # round 3 (31 Oct): 10%+ of works also credited to a same-named institution
    A18_RESEARCH_EXCLUDE.update({_r: _x["reason"] for _r, _x in json.loads(a18_path("research_a18_attribution.json").read_text())["exclude"].items()})
if A18 and a18_path("research_a18_rawaff.json").exists():   # Japan round (31 Oct): 10%+ of sampled authorships name a different, similarly named institution
    A18_RESEARCH_EXCLUDE.update({_r: _x["reason"] for _r, _x in json.loads(a18_path("research_a18_rawaff.json").read_text())["exclude"].items()
                                 if _r not in A18_RESEARCH_EXCLUDE})
for _p in A18_ENR_FILES:
    _d = json.loads(_p.read_text())
    A18_NOT_UNI.update({r: x for r, x in _d.get("not_a_university", {}).items() if r in A18_CAND_RORS})
    A18_UNIT_OF.update({r: x for r, x in _d.get("unit_of", {}).items() if r in A18_CAND_RORS})
    A18_UNRESOLVED.update({r: x for r, x in _d.get("unresolved", {}).items() if r in A18_CAND_RORS})
A16_PARTIAL = ("undergraduates only", "no postgraduate rows", "cannot be confirmed", "not stated whether", "does not say whether")   # partial or uncertain scope
PARTIAL_WORDS = ("not including", "undercount", "only its", "are excluded")   # scope-partial counts; rounded "余"/"more than" figures are fine


def _enr_valid(v, vetted=False):
    if not (isinstance(v, dict) and isinstance(v.get("value"), (int, float)) and v["value"] > 0):
        return False
    txt = (str(v.get("note", "")) + " " + str(v.get("tier", ""))).lower()
    years = [int(y) for y in re.findall(r"(?:19|20)\d\d", str(v.get("year", "")))]
    if years and max(years) < 2016:           # Amendment 11.9: older than 10 years before the edition
        return False
    if not vetted and re.search(r"distance-learning \(ead\) [\d,]+", txt):
        return True       # separable distance figure: subtracted in _in_person() (Amendment 11.9)
    if not vetted and any(w in txt for w in ("stale", "outdated", "distance-learning", "distance learning", "açıköğretim")):   # flagged stale / open-university scope
        return False      # (the Amendment 11.9 refresh files are vetted: their notes describe what was excluded)
    if vetted == "a16":           # checked round: notes describe proper exclusions, so only reject partial/uncertain scope
        return v.get("scope", "complete") == "complete" and not any(w in txt for w in A16_PARTIAL)
    return not any(w in txt for w in PARTIAL_WORDS)


def _in_person(v):
    """Amendment 11.9: subtract a separately reported distance-learning (EaD) figure from the count."""
    m = re.search(r"distance-learning \(EaD\) ([\d,]+)", str(v.get("note", "")), re.I)
    if m:
        v = dict(v, value=max(0, float(v["value"]) - float(m.group(1).replace(",", ""))))
    return v


ENR_RAW = {}
# Amendment 11.9: universities whose count is stale and for which no current official in-person count was found
_A11_UNRESOLVED = set()
for _p in [V2 / "enrollment_a11.json", *sorted(V2.glob("enrollment_a11b_*.json"))]:
    if _p.exists():
        _A11_UNRESOLVED |= set(json.loads(_p.read_text()).get("unresolved", {}))
_A11_RESOLVED = set()
for _p in [V2 / "enrollment_a11.json", *sorted(V2.glob("enrollment_a11b_*.json"))]:
    if _p.exists():
        _A11_RESOLVED |= set(json.loads(_p.read_text()).get("by_ror", {}))
for _name in ENR_ORDER:
    _f = V2 / f"{_name}.json"
    if not _f.exists():
        continue
    for _r, _rec in json.loads(_f.read_text()).get("by_ror", {}).items():
        for _k in ("ug_enrollment", "total_enrollment"):
            _vet = "a16" if _name.startswith("enrollment_a16") else _name.startswith("enrollment_a11")
            if _enr_valid(_rec.get(_k), vetted=_vet):
                ENR_RAW.setdefault(_r, {})[_k] = _rec[_k] if _vet else _in_person(_rec[_k])
for _p in A18_ENR_FILES:   # Amendment 18.2: checked round, same acceptance rule as the A16 round (scope must be complete)
    for _r, _rec in json.loads(_p.read_text()).get("by_ror", {}).items():
        if _r not in A18_CAND_RORS or _r in A18_NOT_UNI or _r in A18_UNIT_OF:
            continue
        _sc = _rec.get("scope", "complete")
        for _k in ("ug_enrollment", "total_enrollment"):
            _v = _rec.get(_k)
            if isinstance(_v, dict) and _enr_valid(dict(_v, scope=_v.get("scope", _sc)), vetted="a16"):
                ENR_RAW.setdefault(_r, {})[_k] = _v
_A16_RORS = set().union(*(set(json.loads((V2 / f"{_n}.json").read_text()).get("by_ror", {})) for _n in ENR_ORDER if _n.startswith("enrollment_a16"))) if A15 else set()
for _r in _A11_UNRESOLVED - _A11_RESOLVED - _A16_RORS:          # Amendment 11.9: no current in-person count -> listed, not ranked (A16 counts supersede)
    ENR_RAW.pop(_r, None)
_HAS_TOT = {r for r, e in ENR_RAW.items() if "total_enrollment" in e}          # Amendment 7.2
# Amendment 9.4: graduate-dominant institutions
GRAD_DOMINANT = {"01cdrde68", "05cncd958", "03gds6c39", "01k9xac83", "05msxaq47", "04f812k67", "00awd9g61"}
_OFFICIAL_FILES = {"enrollment_us", "enrollment_all_official", "enrollment_new_official", "enrollment_uk_eu"}
for _name in _OFFICIAL_FILES:
    _f = V2 / f"{_name}.json"
    if _f.exists():
        for _r, _rec in json.loads(_f.read_text()).get("by_ror", {}).items():
            _u, _t = _rec.get("ug_enrollment"), _rec.get("total_enrollment")
            if _enr_valid(_u) and _enr_valid(_t) and _u["value"] < 0.10 * _t["value"]:
                GRAD_DOMINANT.add(_r)
if A15:   # Amendment 15.10: the 9.4 test on every same-source ug/total pair, any tier, in precedence order (last wins), before
    _ug_share_low = {}      # the 7.3 drop; an undergraduate count of 0 counts as a value
    for _name in ENR_ORDER:
        _f = V2 / f"{_name}.json"
        if not _f.exists():
            continue
        for _r, _rec in json.loads(_f.read_text()).get("by_ror", {}).items():
            _u, _t = _rec.get("ug_enrollment"), _rec.get("total_enrollment")
            if not _enr_valid(_t):
                continue
            if isinstance(_u, dict) and isinstance(_u.get("value"), (int, float)) and 0 <= _u["value"] < 0.10 * _t["value"]:
                _ug_share_low[_r] = True
            elif _enr_valid(_u):
                _ug_share_low[_r] = False
    for _p in A18_ENR_FILES:   # Amendment 18.2: the 9.4 test on the A18 counts (checked round: notes describe exclusions)
        for _r, _rec in json.loads(_p.read_text()).get("by_ror", {}).items():
            _u, _t = _rec.get("ug_enrollment"), _rec.get("total_enrollment")
            if _r not in A18_CAND_RORS or not _enr_valid(_t, vetted="a16"):
                continue
            if isinstance(_u, dict) and isinstance(_u.get("value"), (int, float)) and 0 <= _u["value"] < 0.10 * _t["value"]:
                _ug_share_low[_r] = True
            elif _enr_valid(_u, vetted="a16"):
                _ug_share_low[_r] = False
    GRAD_DOMINANT |= {r for r, low in _ug_share_low.items() if low}
# Amendment 9.3: affiliating universities whose enrollment doesn't cover the whole system (+ CNAM)
SCOPE_MISMATCH = {"0175hh227", "05f5j6225"}   # + University Town of Shenzhen (A16.1: campus consortium of ranked parents)
_sf = V2 / "scope_affiliating.json"
if _sf.exists():
    for _r, _rec in json.loads(_sf.read_text()).get("by_ror", {}).items():
        if _rec.get("affiliating") is True and _rec.get("enrollment_scope") in ("own_departments", "unknown"):
            SCOPE_MISMATCH.add(_r)
GRAD_DOMINANT_EXCL = [u for u in universe if u["ror"] in GRAD_DOMINANT]
universe = [u for u in universe if u["ror"] not in GRAD_DOMINANT]
UNRANKED_NO_ENR = [u for u in universe if u["ror"] not in _HAS_TOT]
UNRANKED_SCOPE = [u for u in universe if u["ror"] in _HAS_TOT and u["ror"] in SCOPE_MISMATCH]
universe = [u for u in universe if u["ror"] in _HAS_TOT and u["ror"] not in SCOPE_MISMATCH]
for u in universe:
    if u["country"] == "China" and "Hong Kong" in u["name"]:
        u["country"] = "Hong Kong SAR, China"
    elif u["country"] == "China" and ("Macau" in u["name"] or "Macao" in u["name"]):
        u["country"] = "Macau SAR, China"            # Amendment 7.6
N_CORE = len(universe)   # Amendment 18.4: every scale is fitted on these (the Leiden universe), which keep their v3.4 order
# Amendment 18: extension universities are appended after the core, so each fit set is a leading slice of its array
RES18 = json.loads(a18_path("research_a18.json").read_text()) if A18 and a18_path("research_a18.json").exists() else {"by_ror": {}}
A18_STATUS = {}
if A18:
    _core = {u["ror"] for u in load("universe_full")}
    for _c in A18_CANDS:
        _r = _c["ror"]
        if _r in _core:
            raise SystemExit(f"A18 candidate {_r} is a Leiden-universe member")
        _st = ("not_a_university" if _r in A18_NOT_UNI else "unit_of" if _r in A18_UNIT_OF else "no_count" if _r not in _HAS_TOT
               else "graduate_dominant" if _r in GRAD_DOMINANT
               else "unmeasured" if (not (RES18["by_ror"].get(_r) or {}).get("P_oa") or _r in A18_RESEARCH_EXCLUDE) else "ranked")
        A18_STATUS[_r] = _st
        if _st == "ranked":
            universe.append({"name": _c["name"], "ror": _r, "ext": True,
                             "country": {"HK": "Hong Kong SAR, China", "MO": "Macau SAR, China"}.get(_c["country_code"], _c["country"])})
EXT = np.array([bool(u.get("ext")) for u in universe])
n = len(universe)
rors = [u["ror"] for u in universe]
names = [u["name"] for u in universe]
DS = {k: load(k) for k in ("us_scorecard", "us_roi", "uk", "greater_china_sea", "jpkr_anz", "europe_canada_other", "elite_outcomes", "notable_alumni")}
# Amendment 4: full-edition files extend (and for the 159 take precedence over) the original datasets
# Amendments 4 and 8: full- and expanded-edition files extend the original datasets (first match wins)
OVERRIDE = {"us_scorecard": ["us_all", "incountry_new_us_uk"], "us_roi": ["us_all", "incountry_new_us_uk"],
            "uk": ["uk_all", "incountry_new_us_uk"], "greater_china_sea": ["china_all", "incountry_new_cn_au_fr"],
            "jpkr_anz": ["au_fr_all", "incountry_new_cn_au_fr"], "europe_canada_other": ["au_fr_all", "incountry_new_cn_au_fr"],
            "notable_alumni": ["notable_alumni_all", "notable_alumni_new"], "elite_outcomes": ["elite_outcomes_all", "elite_grad_new"]}
OVERRIDE_METRIC = {("elite_outcomes", "rhodes_us_2021_2026"): ["us_all", "incountry_new_us_uk"]}
for _fs in OVERRIDE.values():
    for _f in _fs:
        if (V2 / f"{_f}.json").exists():
            DS[_f] = load(_f)
if A18:   # Amendment 18.2/18.5: alumni and in-country files for the extension universities (their rors appear nowhere else)
    for _ds, _f in (("notable_alumni", "notable_alumni_a18"), ("elite_outcomes", "elite_outcomes_a18"), ("us_scorecard", "incountry_a18_us"),
                    ("us_roi", "incountry_a18_us"), ("uk", "incountry_a18_uk")):
        if a18_path(f"{_f}.json").exists():
            DS[_f] = json.loads(a18_path(f"{_f}.json").read_text())
            DS[_f]["by_ror"] = {r: x for r, x in DS[_f].get("by_ror", {}).items() if r in A18_CAND_RORS}   # extension rors only
            OVERRIDE[_ds] = OVERRIDE[_ds] + [_f]
    if "incountry_a18_us" in DS:
        OVERRIDE_METRIC[("elite_outcomes", "rhodes_us_2021_2026")] = OVERRIDE_METRIC[("elite_outcomes", "rhodes_us_2021_2026")] + ["incountry_a18_us"]
# Amendment 10: official in-country measures for seven more countries, merged from the incountry_r10_*.json collection files
DS["r10"] = {"by_ror": {}}
R16_FILES = [V2 / f"incountry_r16_{g}.json" for g in ("indonesia", "brazil", "japan", "korea", "europe_small")] if A15 else []   # Amendment 16.2
R16_FILES += [V2 / "incountry_r17_us.json"] if A15 else []   # Amendment 17.1 (Australia's r17 file is display-only, not loaded here)
R18_FILES = [a18_path("incountry_a18_us.json"), a18_path("incountry_a18_uk.json")] if A18 else []   # Amendment 18.5
for _p in [*sorted(V2.glob("incountry_r10_*.json")), *sorted(V2.glob("incountry_r12_*.json")), *sorted(V2.glob("incountry_r13_*.json")), *sorted(V2.glob("incountry_r14_*.json")),
           *[q for q in R16_FILES if q.exists()], *[q for q in R18_FILES if q.exists()]]:   # + Amendments 12 (Japan), 13, 14, 16, 18
    for _r, _rec in json.loads(_p.read_text()).get("by_ror", {}).items():
        if _p in R18_FILES and _r not in A18_CAND_RORS:   # Amendment 18 files may only add extension universities
            continue
        DS["r10"]["by_ror"].setdefault(_r, {}).update({k: v for k, v in _rec.items() if isinstance(v, dict)})


def _get(ds, ror, metric):
    v = DS.get(ds, {}).get("by_ror", {}).get(ror, {}).get(metric)
    return v if isinstance(v, dict) and isinstance(v.get("value"), (int, float)) and v.get("scorable", True) is not False else None


def val(ds, ror, metric):
    for src in [*(OVERRIDE_METRIC.get((ds, metric)) or []), *(OVERRIDE.get(ds) or []), ds]:
        if src in DS:
            v = _get(src, ror, metric)
            if v is not None:
                return float(v["value"])
    return None


def home_province(ror):
    for f in ("china_all", "incountry_new_cn_au_fr"):
        v = DS.get(f, {}).get("by_ror", {}).get(ror, {}).get("cn_gaokao_zhejiang_min_rank")
        if isinstance(v, dict) and "home province" in (v.get("note") or "").lower():
            return True
    return False


def z(arr, knee=False, n_fit=None):
    """z-score clipped at +-2.5. knee=True (Amendment 15.1): unchanged inside +-2.5, 2.5 + ln(1 + excess) beyond it.
    n_fit (Amendment 18.4): mean and sd come from the first n_fit entries only (the core universities), applied to all."""
    a = np.array([np.nan if x is None else x for x in arr], float)
    f = a if n_fit is None else a[:n_fit]
    m = ~np.isnan(a)
    out = np.full(len(a), np.nan)
    if (~np.isnan(f)).sum() >= 3 and np.nanstd(f) > 0:
        zr = (a[m] - np.nanmean(f)) / np.nanstd(f)
        out[m] = np.where(np.abs(zr) > 2.5, np.sign(zr) * (2.5 + np.log1p(np.maximum(np.abs(zr) - 2.5, 0))), zr) if knee else np.clip(zr, -2.5, 2.5)
    return out


# ---------------- research pillars (Amendment 2.2: computed for universities below the Research Index threshold)
v1 = json.loads((ROOT / "data" / "processed" / "scores.json").read_text())
v1_idx = {u["ror"]: i for i, u in enumerate(v1["unis"])}
v1_row = {r[0]: r for r in v1["tables"]["all"]["balanced"]}
elig = [v1["metrics"][v1["unis"][i]["ror"]]["all"] for i in v1_row]
_sub = [m for r_, ms in v1["metrics"].items() for m in [ms.get("all")] if m and m.get("PP10") is not None and m.get("P", 0) > 0
        and v1_idx.get(r_) is not None and v1_idx[r_] not in v1_row]
MED10 = float(np.median([m["PP10"] for m in _sub])); MED1 = float(np.median([m["PP1"] or 0 for m in _sub]))   # Amendment 9.2
E10 = np.array([m["PP10"] for m in elig]); E1 = np.array([m["PP1"] for m in elig]); EP10 = np.array([m["PP10"] * m["P"] for m in elig])


def v1_pct(x, dist):
    """Research Index percentile definition (average ties, floor 1) for a value scored against the eligible set."""
    allv = np.append(dist, x)
    r = rankdata(allv, method="average")[-1]
    return max(1.0, (r - 1) / (len(allv) - 1) * 100)


A, B, research_note = [], [], {}
for r in rors:
    i = v1_idx.get(r)
    if i is not None and i in v1_row:
        A.append(v1_row[i][5]); B.append(v1_row[i][6])
    elif i is not None and v1["metrics"].get(r, {}).get("all") and v1["metrics"][r]["all"].get("PP10") is not None:
        m = v1["metrics"][r]["all"]
        k = 1500.0                                                   # Amendment 8: shrink toward the Research Index median
        pp10 = (m["P"] * m["PP10"] + k * MED10) / (m["P"] + k)
        pp1 = (m["P"] * (m["PP1"] or 0) + k * MED1) / (m["P"] + k)
        A.append((2 * v1_pct(pp10, E10) + v1_pct(pp1, E1)) / 3)
        B.append(v1_pct(pp10 * m["P"], EP10))
        research_note[r] = f"it has {m['P']:,.0f} core papers, below the Research Index threshold of 1,500, so its citation shares are shrunk toward the median of similarly small universities before scoring"
    elif A18 and r in A18_STATUS and RES18["by_ror"].get(r, {}).get("P_oa"):   # Amendment 18.3: OpenAlex, calibrated, then as 9.2
        m = RES18["by_ror"][r]
        k = 1500.0
        pp10 = (m["P_frac"] * m["PP10"] + k * MED10) / (m["P_frac"] + k)
        pp1 = (m["P_frac"] * m["PP1"] + k * MED1) / (m["P_frac"] + k)
        A.append((2 * v1_pct(pp10, E10) + v1_pct(pp1, E1)) / 3)
        B.append(v1_pct(pp10 * m["P_frac"], EP10))
        research_note[r] = ("it is outside the Leiden data: its research was measured from OpenAlex and calibrated to the Leiden scale "
                            "(Amendment 18.3), then shrunk toward the median of small universities before scoring")
    else:
        A.append(None); B.append(None)

MERGED_INTO = {}
if A15:   # Amendment 15.8: a merged university's research record pools its predecessors' (data/v3/scripts/a15_research_mergers.py)
    for _r, _m in json.loads((V2 / "research_mergers_a15.json").read_text())["by_ror"].items():
        if _r in rors:
            _i = rors.index(_r)
            A[_i] = (2 * v1_pct(_m["PP10"], E10) + v1_pct(_m["PP1"], E1)) / 3
            B[_i] = v1_pct(_m["PP10"] * _m["P"], EP10)
            research_note[_r] = f"research pools {' and '.join(_m['merged_from'].values())} (merged {_m['merged']} as {_m['name']}), matching the merged student count"
            MERGED_INTO.update({p: _r for p in _m["merged_from"] if p != _r})

# Amendment 15.7: integrity screen on pillar A. A Research Index member whose 2020-23 retraction rate per 1,000 full-count papers
# is at or above the 95th percentile of ranked members has A capped at the median A of the ranked universe. B is not changed.
INTEGRITY, INTEGRITY_THR = {}, None
if A15:
    _ret = json.loads((ROOT / "data" / "side" / "retractions.json").read_text())["by_ror"]
    _mrg = json.loads((V2 / "research_mergers_a15.json").read_text())["by_ror"]
    _rate = {}
    for _i, _r in enumerate(rors):
        if v1_idx.get(_r) in v1_row:
            _n_ret, _pf = (_mrg[_r]["retractions_full"], _mrg[_r]["P_full"]) if _r in _mrg else \
                ((_ret.get(_r, {}).get("retractions_full") or 0), (v1["metrics"].get(_r, {}).get("all") or {}).get("P_full"))
            if _pf:
                _rate[_i] = 1000 * _n_ret / _pf
    # Amendment 16.4: the threshold is computed over the universities ranked in v3.2, so it does not drift as the universe grows
    _v32 = {r["ror"] for r in json.loads((ROOT / "data" / "processed" / "overall_v3.2.json").read_text())["rows"]}
    INTEGRITY_THR = float(np.percentile([x for _i, x in _rate.items() if rors[_i] in _v32] or list(_rate.values()), 95))
    _medA = float(np.median([a for a in A[:N_CORE] if a is not None]))   # Amendment 18.4: core only
    for _i, _x in _rate.items():
        if _x >= INTEGRITY_THR and A[_i] is not None and A[_i] > _medA:
            INTEGRITY[rors[_i]] = {"retractions_per_1000": round(_x, 2), "A_before": round(A[_i], 1)}
            A[_i] = _medA
            research_note[rors[_i]] = (f"research quality capped at the median: {_x:.1f} retractions per 1,000 papers (2020-23), at or above the "
                                       f"95th percentile ({INTEGRITY_THR:.1f}); this is a screen, not a finding of misconduct")

# ---------------- alumni outcomes
laur = json.loads((ROOT / "data" / "side" / "laureates.json").read_text())["by_ror"]
if A18 and a18_path("laureates_a18.json", ROOT / "data" / "side").exists():   # Amendment 18.2: candidate rors only
    laur = {**laur, **{r: x for r, x in json.loads(a18_path("laureates_a18.json", ROOT / "data" / "side").read_text())["by_ror"].items() if r in A18_CAND_RORS}}
founders = [val("elite_outcomes", r, "vc_founders_undergrad") for r in rors]
bill = [val("elite_outcomes", r, "billionaire_alumni") for r in rors]
uhnw = [val("elite_outcomes", r, "uhnw_alumni_est") for r in rors]
laureates = [len({x["qid"] for x in laur.get(r, {}).get("alumni", [])}) for r in rors]   # erratum: people, not prizes
notable = [val("notable_alumni", r, "notable_alumni_15lang_post1946") or 0 for r in rors]
heads = [val("notable_alumni", r, "heads_of_state_gov_alumni") or 0 for r in rors]
# Amendment 11.10: re-credit alumni of dissolved sub-units to their successors; verified non-degree links removed
_A11A = json.loads((V2 / "alumni_a11_corrections.json").read_text()).get("by_ror", {}) if (V2 / "alumni_a11_corrections.json").exists() else {}
for _i, _r in enumerate(rors):
    _c = _A11A.get(_r, {})
    if _c:
        notable[_i] = max(0, notable[_i] + int((_c.get("notable_alumni_15lang_post1946") or {}).get("delta", 0)))
        heads[_i] = max(0, heads[_i] + int((_c.get("heads_of_state_gov_alumni") or {}).get("delta", 0)))
if A15:   # Amendments 15.5 (Swiss rotating presidency) and 15.6 (sole-successor merger alumni): data/v3/scripts/a15_alumni_build.py
    _A15A = json.loads((V2 / "alumni_a15_corrections.json").read_text())["by_ror"]
    for _i, _r in enumerate(rors):
        _c = _A15A.get(_r, {})
        if _c:
            for _m, _arr in (("notable_alumni_15lang_post1946", notable), ("heads_of_state_gov_alumni", heads)):
                _b = (_c.get(_m) or {}).get("before")
                if _b is not None and int(_arr[_i]) != int(_b):   # guards against a re-built Wikidata base that already contains the A15 change
                    raise SystemExit(f"alumni_a15_corrections.json is stale for {_r} {_m}: base {_arr[_i]} != recorded {_b}; re-run data/v3/scripts/a15_alumni_build.py")
            notable[_i] = max(0, notable[_i] + int((_c.get("notable_alumni_15lang_post1946") or {}).get("delta", 0)))
            heads[_i] = max(0, heads[_i] + int((_c.get("heads_of_state_gov_alumni") or {}).get("delta", 0)))
            laureates[_i] = len({x["qid"] for x in laur.get(_r, {}).get("alumni", [])} | {x["qid"] for x in _c.get("laureate_alumni_add", [])})
is_us = [u["country"] == "United States" for u in universe]

# ---------------- enrollment (Amendment 1; Amendment 2.6: US totals as FTE)
ENR = {}
for r, rec in ENR_RAW.items():
    for k, v in rec.items():
        ENR.setdefault(r, {})[k] = float(v["value"])
        if k == "total_enrollment":
            m = re.search(r"UNITID\s*(\d{6})", json.dumps(v))
            if m:
                ENR[r]["unitid"] = m.group(1)
ef = {}
efp = V2 / "raw" / "enrollment" / "ef2023a" / "ef2023a.csv"
if efp.exists():
    with open(efp, encoding="latin-1") as fh:
        for row in csv.DictReader(fh):
            if row["EFALEVEL"] in ("21", "41"):
                ef.setdefault(row["UNITID"], {})[row["EFALEVEL"]] = float(row["EFTOTLT"] or 0)
fte_used = {}
for r in rors:
    e = ENR.get(r, {})
    uid = e.get("unitid")
    if uid and uid in ef and "21" in ef[uid]:
        e["total_enrollment"] = ef[uid]["21"] + ef[uid].get("41", 0) / 3
        fte_used[r] = round(e["total_enrollment"])
# Amendment 11.9: US totals exclude students enrolled exclusively in distance education (IPEDS EF2023A_DIST share)
_DIST_ROWS = {x[0]: x for x in json.loads((V2 / "raw" / "enrollment" / "ipeds_exclusively_distance_share.json").read_text())} \
    if (V2 / "raw" / "enrollment" / "ipeds_exclusively_distance_share.json").exists() else {}   # ror, name, unitid, headcount, distance, share
if A18:   # Amendment 18.2: the same distance rows for the extension universities
    for _p in sorted((A18_DIR or (ROOT / "data" / "v3" / "raw")).glob("a18_enr_us_*/ipeds_distance_rows.json")) if not A18_DIR else sorted(A18_DIR.glob("ipeds_distance_rows*.json")):
        _DIST_ROWS.update({x[0]: x for x in json.loads(_p.read_text()) if x[0] in A18_CAND_RORS})
_DIST = {r: float(x[5]) for r, x in _DIST_ROWS.items()}
for r in rors:
    if r in _DIST and ENR.get(r, {}).get("total_enrollment"):
        uid = ENR[r].get("unitid")
        if A15 and r in fte_used and uid in ef:
            # Amendment 15.11 (erratum to 11.9): distance-only students are taken out of the part-time count first (an upper bound,
            # as IPEDS doesn't split them by full-/part-time); the rest, if any, out of the full-time count
            ft, pt, de = ef[uid]["21"], ef[uid].get("41", 0), float(_DIST_ROWS[r][4])
            ENR[r]["total_enrollment"] = ft + max(0.0, pt - de) / 3 if de <= pt else ft - (de - pt)
            fte_used[r] = round(ENR[r]["total_enrollment"])
        else:
            ENR[r]["total_enrollment"] *= (1 - _DIST[r])
for r, e in ENR.items():   # Amendment 7.3: implausible undergraduate share (tested on the in-person total, 11.9)
    if e.get("ug_enrollment") and e.get("total_enrollment") and e["ug_enrollment"] < 0.2 * e["total_enrollment"]:
        e.pop("ug_enrollment")


def enr(r, k):
    e = ENR.get(r, {})
    return e.get(k) or (e.get("total_enrollment") if k == "ug_enrollment" else None)


UG = [enr(r, "ug_enrollment") for r in rors]
TOT = [enr(r, "total_enrollment") for r in rors]
FLOOR_SIZE = float(np.median([t for t in TOT[:N_CORE] if t]))   # Amendment 9.1 (core only, Amendment 18.4)


def _listed_cap(counts, sizes, mask=None):
    vals = [math.log(c) - math.log(sz / 1000) for k, (c, sz) in enumerate(zip(counts, sizes)) if c and sz and (mask is None or mask[k])]
    return min(vals) if vals else None


CORE_MASK = [not e for e in EXT]   # Amendment 18.4
CAP = {"founders": _listed_cap(founders, UG, CORE_MASK), "billionaires": _listed_cap(bill, TOT, CORE_MASK),
       "uhnw_us": _listed_cap(uhnw, TOT, [x and c for x, c in zip(is_us, CORE_MASK)]),
       "uhnw_nonus": _listed_cap(uhnw, TOT, [(not x) and c for x, c in zip(is_us, CORE_MASK)])}


def g_metrics(rng=None):
    """dict metric -> z vector (nan where unavailable). rng=None gives point estimates."""
    def lograte(x, cutkey, size):
        if not size:
            return None
        ls = math.log(size / 1000)
        if x is not None:
            return math.log(x) - ls
        lo = -math.log(FLOOR_SIZE / 1000)                        # Amendment 9.1: one person per median-sized university
        hi = math.log(CUTOFF[cutkey]) - ls                       # cutoff per enrollment
        if CAP.get(cutkey) is not None:
            hi = min(hi, CAP[cutkey])                            # Amendment 4.3 cap
        lo = min(lo, hi)                                         # Amendment 7.1: cap below one person -> value = cap
        return (lo + hi) / 2 if rng is None else rng.uniform(lo, hi)

    def listed(x, cutkey):
        """Amendment 15.12: in each draw a listed count is redrawn as Poisson(count); a draw below the cutoff counts as unlisted."""
        if rng is None or x is None or not A15:
            return x
        y = int(rng.poisson(x))
        return y if y >= CUTOFF[cutkey] else None
    f = [lograte(listed(x, "founders"), "founders", UG[i]) for i, x in enumerate(founders)]
    b = [lograte(listed(x, "billionaires"), "billionaires", TOT[i]) for i, x in enumerate(bill)]
    w = [lograte(listed(x, k), k, TOT[i]) for i, (x, k) in enumerate(zip(uhnw, ["uhnw_us" if us else "uhnw_nonus" for us in is_us]))]
    zb, zw = z(b, n_fit=N_CORE), z(w, n_fit=N_CORE)
    wealth = np.where(np.isnan(zb), zw, np.where(np.isnan(zw), zb, (zb + zw) / 2))
    l1p = lambda cnt, size: None if not size else math.log1p(1000 * cnt / max(size, 5000))     # Amendments 2.5, 9.5
    return {
        "res_quality": z(A, n_fit=N_CORE), "res_strength": z(B, n_fit=N_CORE), "founders": z(f, n_fit=N_CORE), "wealth": wealth,
        "laureates": z([l1p(x, TOT[i]) for i, x in enumerate(laureates)], knee=A15, n_fit=N_CORE),        # Amendment 15.1: knee, not clip,
        "notable": z([l1p(x, TOT[i]) for i, x in enumerate(notable)], knee=A15, n_fit=N_CORE),            # for the three alumni counts observed
        "heads": z([l1p(x, TOT[i]) for i, x in enumerate(heads)], knee=A15, n_fit=N_CORE),                # for every university
    }


def g_score(Z, w):
    """Weighted mean over available metrics (Amendment 2.2), then standardised across the universe (2.3)."""
    M = np.vstack([Z[k] for k in G_W])
    wv = np.array([w[k] for k in G_W], float)[:, None]
    avail = ~np.isnan(M)
    g = (np.where(avail, M, 0) * wv).sum(0) / (avail * wv).sum(0)
    return (g - g[:N_CORE].mean()) / g[:N_CORE].std()   # Amendment 18.4: core scale


# ---------------- W (within-country)
W_SPEC = {
    "United States": {"sel": [["us_scorecard:admit_rate:-1"], ["us_scorecard:sat_avg:1"], ["us_scorecard:yield_rate:1"]],
                      "out": [(["r10:us_scorecard_earnings_field_ratio:1", "us_roi:roi_npv40:1"] if A15 else ["us_scorecard:median_earnings_10yr:1", "us_roi:roi_npv40:1"]), ["us_scorecard:completion_rate_150:1"],   # Amendment 17.1
                              ["elite_outcomes:rhodes_us_2021_2026:1:log1p"]]},
    "United Kingdom": {"sel": [["uk:offer_rate_uk18:-1"], ["uk:offer_acceptance_yield:1"], ["r10:uk_dfe_mean_tariff_2y:1"]], "out": [["uk:leo_median_5yr:1"]]},   # + Amendment 14 tariff
    "China": {"sel": [["greater_china_sea:cn_gaokao_zhejiang_min_rank:-1:log"]], "out": []},
    "Australia": {"sel": [], "out": [["jpkr_anz:au_gos_ug_median_ft_salary:1"]]},
    "France": {"sel": [["europe_canada_other:fr_parcoursup_access_rate:-1"], ["europe_canada_other:fr_admits_mention_tres_bien_pct:1"]], "out": []},
    # Amendment 10 (v2.7)
    "Taiwan": {"sel": [["r10:tw_uac_cutoff_benchmark_median:1"]], "out": [["r10:tw_mol_bachelor_wage_field_ratio:1"]]},
    "Hong Kong SAR, China": {"sel": [], "out": [["r10:hk_ugc_avg_annual_salary_3yr:1"]]},
    "Singapore": {"sel": [["r10:sg_igp_rank_points_weighted:1"]], "out": [["r10:sg_ges_median_salary_3yr:1"]]},
    "South Korea": {"sel": [["r10:kr_csat_70cut_percentile_median:1"]], "out": [["r10:kr_graduate_employment_rate:1"]]},
    "Turkey": {"sel": [["r10:tr_yok_selectivity:1"]], "out": []},
    "Ireland": {"sel": [["r10:ie_cao_r1_field_adjusted_median:1"]], "out": [["r10:ie_cso_earnings_5y_field_ratio:1"]]},
    # Amendment 12 (v2.9): Japan, Kawaijuku border hensachi (labelled non-official exception)
    "Japan": {"sel": [["r10:jp_kawaijuku_border_hensachi_mean:1" if A15 else "r10:jp_kawaijuku_border_hensachi_median:1"]], "out": []},   # mean: Amendment 15.13
    # Amendment 13 (v3.0): sixteen more countries
    "Brazil": {"sel": [["r10:br_sisu_ac_cut_weightnorm:1"]], "out": []},
    "Russia": {"sel": [["r10:ru_minobr_mean_ege_admits:1"]], "out": []},
    "Spain": {"sel": [["r10:es_qedu_median_nota_corte:1"]], "out": [["r10:es_siiu_bcm4_field_ratio:1"]]},
    "Poland": {"sel": [], "out": [["r10:pl_ela_earn_p1_field_ratio:1"]]},
    "Italy": {"sel": [], "out": [["r10:it_almalaurea_pay5y_field_ratio:1"]]},
    "Chile": {"sel": [["r10:cl_paes_enrolees_median:1"]], "out": [["r10:cl_mifuturo_income4_field_ratio:1"]]},
    "Sweden": {"sel": [["r10:se_uhr_bi_mean_cutoff:1"]], "out": [["r10:se_uka_establishment_field_ratio:1"]]},
    "Portugal": {"sel": [["r10:pt_infocursos_entry_percentile_median:1"]], "out": [["r10:pt_iefp_unemployment_std_ratio:-1"]]},
    "Colombia": {"sel": [], "out": [["r10:co_ole_ibc_field_ratio:1"]]},
    "Ukraine": {"sel": [["r10:ua_edbo_cutoff_median:1"]], "out": [["r10:ua_mon_employment_std_ratio:1"]]},
    "Greece": {"sel": [["r10:gr_minedu_basis_median:1"]], "out": []},
    "Hungary": {"sel": [["r10:hu_felvi_cutoff_median:1"]], "out": [["r10:hu_dpr_earn_field_ratio:1"]]},
    "Norway": {"sel": [["r10:no_so_cutoff_mean:1"]], "out": []},
    "Denmark": {"sel": [["r10:dk_kot_quotient_mean:1"]], "out": [["r10:dk_uddzoom_pay_field_ratio:1"]]},
    "Finland": {"sel": [["r10:fi_vipunen_field_percentile_median:1"]], "out": [["r10:fi_vipunen_employment_rate:1"]]},
    "Indonesia": {"sel": [["r10:id_snbt_ln_applicants_per_place:1"]], "out": []},
}
A10_COUNTRIES = {"Taiwan", "Hong Kong SAR, China", "Singapore", "South Korea", "Turkey", "Ireland", "Japan",
                 "Brazil", "Russia", "Spain", "Poland", "Italy", "Chile", "Sweden", "Portugal", "Colombia", "Ukraine",
                 "Greece", "Hungary", "Norway", "Denmark", "Finland", "Indonesia"}   # + Amendment 13
A10_COVERAGE = {}
# Amendment 11.4-11.6 inputs
A11_META = json.loads((V2 / "a11_meta.json").read_text()).get("by_ror", {}) if (V2 / "a11_meta.json").exists() else {}
if A18 and a18_path("a11_meta_a18_us.json").exists():   # Amendment 18.5: sample sizes for the extension universities' US measures
    A11_META.update({r: x for r, x in json.loads(a18_path("a11_meta_a18_us.json").read_text()).get("by_ror", {}).items() if r in A18_CAND_RORS})
FIELD_ADJUSTED = {"tw_mol_bachelor_wage_field_ratio", "ie_cso_earnings_5y_field_ratio", "ie_cao_r1_field_adjusted_median",
                  # Amendment 13
                  "es_siiu_bcm4_field_ratio", "pl_ela_earn_p1_field_ratio", "it_almalaurea_pay5y_field_ratio", "cl_mifuturo_income4_field_ratio",
                  "se_uka_establishment_field_ratio", "pt_iefp_unemployment_std_ratio", "co_ole_ibc_field_ratio", "ua_mon_employment_std_ratio",
                  "hu_dpr_earn_field_ratio", "dk_uddzoom_pay_field_ratio", "fi_vipunen_field_percentile_median",
                  "us_scorecard_earnings_field_ratio"}   # Amendment 17
RESIDUAL_RATES = {"kr_graduate_employment_rate", "se_uka_establishment_field_ratio", "ua_mon_employment_std_ratio"}   # denominators leave out graduates in further study
# Amendment 15.4: a raw (not field-adjusted) institution-total earnings measure can't be a university's only measure (as 11.6)
RAW_EARNINGS = {"au_gos_ug_median_ft_salary", "hk_ugc_avg_annual_salary_3yr", "median_earnings_10yr", "roi_npv40", "leo_median_5yr"} if A15 else set()
NOT_ALONE = RESIDUAL_RATES | RAW_EARNINGS
OUTCOME_METRICS = {p.split(":")[1] for spec in W_SPEC.values() for parts in spec.get("out", []) for p in parts}


SEL_METRICS = {p.split(":")[1] for spec in W_SPEC.values() for parts in spec.get("sel", []) for p in parts}


def a11_ok(ror, m):
    """Amendment 11.4 (enough sample) and 11.5 (single-field specialists) for the Amendment 10 measures."""
    v = A11_META.get(ror, {}).get(m, {})
    if m in SEL_METRICS and v.get("n_units") is not None and v["n_units"] < 10:   # 11.4: the 10-unit minimum is for selectivity only
        return False
    if v.get("n_grads") is not None and v["n_grads"] < 100:
        return False
    if m in FIELD_ADJUSTED and (v.get("top_field_share") or 0) >= 0.8:
        return False
    return True


def a10_val(ds, ror, m):
    x = val(ds, ror, m)
    return x if (x is None or ds != "r10" or a11_ok(ror, m)) else None


_COV_OK = {}


def _measure_passes_coverage(country, ds, m):
    """Would this measure survive the coverage guards (Amendment 10.2 for A10 countries, 11.3 everywhere)?"""
    key = (country, ds, m)
    if key not in _COV_OK:
        idx = [i for i, u in enumerate(universe) if u["country"] == country and not EXT[i]]   # Amendment 18.4: core only
        have = sum(a10_val(ds, rors[i], m) is not None and (ds, m, names[i]) not in W_EXCLUDE for i in idx)
        raw_ = [a10_val(ds, rors[i], m) if (ds, m, names[i]) not in W_EXCLUDE else None for i in idx]
        _COV_OK[key] = have >= 5 and (country not in A10_COUNTRIES or have >= len(idx) / 2 or (A15 and _student_share(idx, raw_) >= 0.5))
    return _COV_OK[key]


def _student_share(idx, raw):
    """Amendment 16.3: share of the country's ranked students at universities that have the measure."""
    tot = sum(TOT[i] or 0 for i in idx)
    return sum(TOT[i] or 0 for i, x in zip(idx, raw) if x is not None) / tot if tot else 0.0


def has_other_measure(country, i, but=None):
    """Amendment 11.6 (+ 15.3, 15.4): does university i have a usable measure in its country, other than `but`, that may stand alone?
    Only measures that pass the coverage guards count (otherwise the barred measure would end up standing alone)."""
    for parts in [p for subs in W_SPEC.get(country, {}).values() for p in subs]:
        for p in parts:
            ds, m, *_ = p.split(":")
            if m != but and m not in NOT_ALONE and a10_val(ds, rors[i], m) is not None and (ds, m, names[i]) not in W_EXCLUDE \
                    and _measure_passes_coverage(country, ds, m):
                return True
    return False


def small_sole(country, i, m):
    """Amendment 15.3: an outcome value resting on fewer than 500 graduates can't be the university's only measure."""
    if not A15 or m not in OUTCOME_METRICS:
        return False
    ng = A11_META.get(rors[i], {}).get(m, {}).get("n_grads")
    return ng is not None and ng < 500 and not has_other_measure(country, i, but=m)


A15_W_NOTE = {}   # i -> note, where an Amendment 15.3/15.4 rule removes a university's only measure


def barred_alone(country, i, ds, m):
    """Rules 11.6, 15.3 and 15.4: is measure m barred for university i because it would stand alone?"""
    if m in NOT_ALONE and not has_other_measure(country, i):
        if m in RAW_EARNINGS and a10_val(ds, rors[i], m) is not None:
            A15_W_NOTE[i] = ("its only within-country measure would be a raw graduate-earnings figure, not adjusted for subject mix, "
                             "which can't stand alone (Amendment 15.4), so its within-country part is estimated")
            if country == "Australia":   # Amendment 17.5: the subject-adjusted ratio exists but is not scored
                A15_W_NOTE[i] = ("its raw QILT graduate salary can't stand alone (Amendment 15.4); a study-area-adjusted ratio was built but is not scored, "
                                 "because regional and distance universities still lead for reasons of graduate age and study mode (Amendment 17.5), "
                                 "so its within-country part is estimated")
        return True
    if small_sole(country, i, m):
        A15_W_NOTE[i] = ("its only within-country measure rests on fewer than 500 graduates, which can't stand alone (Amendment 15.3), "
                         "so its within-country part is estimated")
        return True
    return False
# each inner list is one sub-metric (Amendment 2.4: US earnings + ROI averaged into one)
COUNTRY_SUB = {}   # country -> (idx list, [(group, z-vector, label)])
W_parts = [dict() for _ in range(n)]
for country, spec in W_SPEC.items():
    idx = [i for i, u in enumerate(universe) if u["country"] == country]
    nc = sum(1 for i in idx if not EXT[i])   # Amendment 18.4: the core members come first; tests and scales use them only
    assert not any(EXT[i] for i in idx[:nc])
    subs = []
    for g, submetrics in spec.items():
        for parts in submetrics:
            zs = []
            for p in parts:
                ds, m, sign, *tf = p.split(":")
                raw = []
                for i in idx:
                    x = None if ((ds, m, names[i]) in W_EXCLUDE or (m == "cn_gaokao_zhejiang_min_rank" and home_province(rors[i]))
                                 or (m == "rhodes_us_2021_2026" and val("us_scorecard", rors[i], "admit_rate") is None
                                     and val("us_scorecard", rors[i], "median_earnings_10yr") is None)
                                 or barred_alone(country, i, ds, m)) else a10_val(ds, rors[i], m)
                    if x is not None and tf == ["log"]:
                        x = math.log(x)
                    elif x is not None and tf == ["log1p"] and A15 and m == "rhodes_us_2021_2026":
                        # Amendment 15.2: Rhodes Scholars per 1,000 undergraduates (floor 5,000), as the G alumni measures
                        ug = val("us_scorecard", rors[i], "undergrad_size") or UG[i]
                        x = math.log1p(1000 * x / max(ug or 5000, 5000))
                    elif x is not None and tf == ["log1p"]:
                        x = math.log1p(x)
                    raw.append(x)
                have = sum(x is not None for x in raw[:nc])
                if country in A10_COUNTRIES:                    # Amendment 10.2: at least half the country's ranked universities
                    A10_COVERAGE[f"{country}:{m}"] = f"{have}/{nc}"
                    if have < 5 or (have < nc / 2 and not (A15 and _student_share(idx[:nc], raw[:nc]) >= 0.5)):   # 10.2 (+16.3)
                        continue
                if have >= 5:                                   # Amendment 11.3
                    zs.append(z(raw, n_fit=nc) * int(sign))
            if zs:
                zz = np.nanmean(np.vstack(zs), axis=0) if len(zs) > 1 else zs[0]
                label = "+".join(p.split(":")[1] for p in parts)
                subs.append((g, zz, label))
                for k, i in enumerate(idx):
                    if not np.isnan(zz[k]):
                        W_parts[i][label] = round(float(zz[k]), 2)
    if subs:
        COUNTRY_SUB[country] = (idx, subs)


def w_scores(rng=None, point=None):
    W = np.zeros(n)
    for country, (idx, subs) in COUNTRY_SUB.items():
        pick = subs if rng is None else [subs[j] for j in rng.integers(0, len(subs), len(subs))]   # Amendment 2.3 resampling
        barred = lambda lab: any(m in NOT_ALONE for m in lab.split("+"))
        if rng is not None and any(barred(lab) for _, _, lab in pick):                     # Amendments 11.6 and 15.4 inside draws
            other = np.zeros(len(idx), bool)
            for _, zz, lab in pick:
                if not barred(lab):
                    other |= ~np.isnan(zz)
            pick = [(g, (np.where(other, zz, np.nan) if barred(lab) else zz), lab) for g, zz, lab in pick]
        groups = {}
        for g, zz, _ in pick:
            groups.setdefault(g, []).append(zz)
        cols = [np.nanmean(np.vstack(v), axis=0) if len(v) > 1 else v[0] for v in groups.values()]
        M = np.vstack(cols)
        wc = np.where(np.isnan(M).all(0), np.nan, np.nanmean(M, axis=0))
        ok = ~np.isnan(wc)
        nc = CORE_N[country]                                                                    # Amendment 18.4: core scale
        if ok[:nc].sum() >= 3 and np.nanstd(wc[:nc]) > 0:
            kf = np.array([K_I[i] / (K_I[i] + 1) for i in idx])                                 # Amendment 11.1: own k
            wc = (wc - np.nanmean(wc[:nc])) / np.nanstd(wc[:nc]) * kf                           # Amendment 2.3
        for kk, i in enumerate(idx):
            if np.isnan(wc[kk]):
                W[i] = point[i] if (point is not None and HAS_W[i]) else 0.0                    # Amendment 11.2
            else:
                W[i] = float(wc[kk])
    return W


HAS_W = np.zeros(n, bool)
K_I = np.zeros(n, int)          # Amendment 11.1: number of measures each university actually has
for _c, (_idx, _subs) in COUNTRY_SUB.items():
    for _k, _i in enumerate(_idx):
        HAS_W[_i] = any(not np.isnan(zz[_k]) for _, zz, _ in _subs)
        K_I[_i] = len({lab for _, zz, lab in _subs if not np.isnan(zz[_k])})
COUNTRY_IDX = {}
for _i, _u in enumerate(universe):
    COUNTRY_IDX.setdefault(_u["country"], []).append(_i)
CORE_N = {c: sum(1 for i in idx if not EXT[i]) for c, idx in COUNTRY_IDX.items()}   # Amendment 18.4


def impute_w(G, W):
    """Amendment 6: W_est = beta * within-country z of G, beta fitted (no intercept) on universities with real W."""
    zg = np.zeros(n)
    for c, idx in COUNTRY_IDX.items():
        if CORE_N[c] >= 3:                                               # Amendment 18.4: core members' mean and sd
            g = G[idx]
            gc = g[:CORE_N[c]]
            sd = gc.std() or 1.0
            zg[idx] = (g - gc.mean()) / sd
            if A15:
                zg[idx] = np.clip(zg[idx], -2.5, 2.5)                    # Amendment 15.14 (1)
    big = np.array([CORE_N[universe[i]["country"]] >= 3 for i in range(n)])
    m = HAS_W & big & ~EXT                                               # Amendment 18.4: beta fitted on the core
    beta = float((zg[m] @ W[m]) / (zg[m] @ zg[m])) if m.any() else 0.0
    out = W.copy()
    est = (~HAS_W) & big
    out[est] = beta * zg[est]
    if A15:   # Amendment 15.14 (2): where >= 5 universities have measured W, an estimate stays inside their [min, max]
        for idx in COUNTRY_IDX.values():
            ia = np.array(idx)
            mw = ia[HAS_W[ia] & ~EXT[ia]]
            if len(mw) >= 5:
                e = ia[est[ia]]
                out[e] = np.clip(out[e], W[mw].min(), W[mw].max())
    return out, beta


Z0 = g_metrics()
G0 = g_score(Z0, G_W)
W_POINT = w_scores()
W0, BETA0 = impute_w(G0, W_POINT)
F0 = 0.65 * G0 + 0.35 * W0
disp = np.round(100 * (F0 - F0.min()) / (F0.max() - F0.min()), 1)
rank = np.array([1 + int((disp > s).sum()) for s in disp])

rng = np.random.default_rng(SEED)
alpha = np.array([G_W[k] for k in G_W], float) / 2.5
sim = np.empty((N_DRAWS, n), int)
for d in range(N_DRAWS):
    wv = dict(zip(G_W, rng.dirichlet(alpha)))
    gw = rng.beta(13, 7)
    Gd = g_score(g_metrics(rng), wv)
    Fd = gw * Gd + (1 - gw) * impute_w(Gd, w_scores(rng, W_POINT))[0]
    order = np.argsort(-Fd, kind="mergesort")
    r = np.empty(n, int)
    r[order] = np.arange(1, n + 1)
    sim[d] = r
lo = np.minimum(np.percentile(sim, 5, axis=0, method="lower").astype(int), rank)
hi = np.maximum(np.percentile(sim, 95, axis=0, method="higher").astype(int), rank)

rows = []
for i, u in enumerate(universe):
    notes = []
    if rors[i] in research_note:
        notes.append(research_note[rors[i]])
    if not TOT[i]:
        notes.append("no enrollment figure, so alumni outcomes are not scored")
    if home_province(rors[i]) and names[i] != "Zhejiang University":
        notes.append("its Zhejiang gaokao cutoff is excluded (home-province quota)")
    for (ds, m, nm) in W_EXCLUDE:
        if nm == names[i]:
            notes.append({"cn_gaokao_zhejiang_min_rank": "its Zhejiang gaokao cutoff is excluded (home-province quota)",
                          "au_gos_ug_median_ft_salary": "its undergraduate salary is excluded: most of its professional degrees are graduate-entry, so its undergraduate cohort isn't comparable"}[m])
    if i in A15_W_NOTE:
        notes.append(A15_W_NOTE[i])
    rows.append({
        "ror": rors[i], "name": names[i], "country": u["country"], "rank": int(rank[i]), "lo": int(lo[i]), "hi": int(hi[i]),
        "score": float(disp[i]), "G": round(float(G0[i]), 3), "W": round(float(W0[i]), 3), "w_estimated": bool(not HAS_W[i] and W0[i] != 0),
        "g": {k: (None if np.isnan(Z0[k][i]) else round(float(Z0[k][i]), 2)) for k in G_W}, "w": W_parts[i], "notes": notes,
        "raw": {"founders": founders[i], "billionaires": bill[i], "uhnw": uhnw[i], "laureate_alumni": laureates[i],
                "notable_alumni": notable[i], "heads": heads[i], "research_A": A[i], "research_B": B[i],
                "ug_enrollment": UG[i], "total_enrollment": TOT[i], "us_fte": fte_used.get(rors[i])},
        **({"ext": True} if EXT[i] else {}),   # Amendment 18: outside the Leiden data
    })
rows.sort(key=lambda r: (r["rank"], r["name"]))

diag = {}
for key in ("qs2027", "the2027", "arwu2026"):
    d = json.loads((ROOT / "data" / "side" / f"{key}.json").read_text())
    other = {e["ror"]: e["rank"] for e in d["entries"] if e.get("ror")}
    pairs = [(r["rank"], other[r["ror"]]) for r in rows if r["ror"] in other]
    diag[key] = {"n": len(pairs), "spearman": round(float(spearmanr([p[0] for p in pairs], [p[1] for p in pairs]).statistic), 3)}
yl = [(W0[i], val("us_scorecard", rors[i], "yield_rate")) for i in range(n) if is_us[i] and val("us_scorecard", rors[i], "yield_rate") is not None]
diag["us_W_vs_yield"] = round(float(spearmanr([a for a, _ in yl], [b for _, b in yl]).statistic), 3)

A15_META = {"integrity_threshold_per_1000": round(INTEGRITY_THR, 2), "integrity_screened": INTEGRITY, "merged_into": MERGED_INTO} if A15 else {}
_A18_META = {}
if A18:
    _cnt = {}
    for _st in A18_STATUS.values():
        _cnt[_st] = _cnt.get(_st, 0) + 1
    _core_c = {u["country"] for u in universe if not u.get("ext")}
    _A18_META = {"a18": {"candidates": len(A18_CANDS), "status_counts": _cnt, "ranked": int(EXT.sum()),
                         "fit": RES18.get("fit"), "new_countries": sorted({u["country"] for u in universe if u.get("ext")} - _core_c),
                         "status": A18_STATUS}}
OUT.write_text(json.dumps({"meta": {"method": ("v3.7 (expanded edition, Amendments 1-18)" if A18 else "v3.4 (expanded edition, Amendments 1-17)") if A15
                                    else "v3.1 (expanded edition, Amendments 1-14)",
                                    **A15_META, "floor_size": FLOOR_SIZE, "shrink_target": [MED10, MED1],
                                    "graduate_dominant_excluded": [{"ror": u["ror"], "name": u["name"], "country": u["country"]} for u in GRAD_DOMINANT_EXCL],
                                    "unranked_scope": [{"ror": u["ror"], "name": u["name"], "country": u["country"]} for u in UNRANKED_SCOPE],
                                    "enrollment_source": {r: {"tier": (ENR_RAW.get(r, {}).get("total_enrollment") or {}).get("tier"),
                                                              "confidence": (ENR_RAW.get(r, {}).get("total_enrollment") or {}).get("confidence"),
                                                              "source_url": (ENR_RAW.get(r, {}).get("total_enrollment") or {}).get("source_url"),
                                                              "ug_is_fallback": not bool(ENR.get(r, {}).get("ug_enrollment"))} for r in rors}, "beta_w_impute": round(BETA0, 3), "graduate_only_excluded": sorted(GRAD_ONLY_ROR), "caps": CAP,
                                    "unranked_no_enrollment": [{"ror": u["ror"], "name": u["name"], "country": u["country"]} for u in UNRANKED_NO_ENR], "n": n, "draws": N_DRAWS, "seed": SEED, "weights_G": G_W, "split": [0.65, 0.35],
                                    "w_countries": sorted(COUNTRY_SUB), "a10_coverage": A10_COVERAGE, "diagnostics": diag,
                                    **({"absorbed_into": {"03zzmyz63": "00ysqcn41"}} if A15 else {}),   # A16.1: merged into a continuing university (not credited, A15.6)
                                    "enrollment": {r: {"ug": UG[i], "total": TOT[i]} for i, r in enumerate(rors)}, **_A18_META},
                           "rows": rows}, ensure_ascii=False, indent=0))
print(json.dumps(diag), file=sys.stderr)
for r in rows[:45]:
    print(f"{r['rank']:>3} [{r['lo']:>3}-{r['hi']:<3}] {r['score']:5.1f}  G={r['G']:+.2f} W={r['W']:+.2f}  {r['name'][:44]} ({r['country']})")
