"""Recompute the blog's three rank correlations from reported summary data.

Run with Python 3 (standard library only). No training or network access.
"""

import json
import math
import statistics
from pathlib import Path


def average_ranks(values):
    """One-based ranks, averaging tied positions."""
    ordered = sorted(values)
    return [
        statistics.mean(i + 1 for i, v in enumerate(ordered) if v == value)
        for value in values
    ]


def spearman(xs, ys):
    rx, ry = average_ranks(xs), average_ranks(ys)
    dx = [v - statistics.mean(rx) for v in rx]
    dy = [v - statistics.mean(ry) for v in ry]
    return sum(x * y for x, y in zip(dx, dy)) / math.sqrt(
        sum(x * x for x in dx) * sum(y * y for y in dy)
    )


def main():
    data = json.loads(Path(__file__).with_name("results.json").read_text())
    arms = list(data["scores"])
    scores = [data["scores"][arm] for arm in arms]
    for group in data["sets"]:
        runs = data["runs"][group["key"]]
        assert set(runs) == set(arms)
        means = [statistics.mean(runs[arm]) for arm in arms]
        rho = spearman(scores, means)
        assert round(rho, 2) == group["reported_rho"], (group["key"], rho)
        assert rho >= data["pass_threshold"], (group["key"], rho)
        print(f"{group['label']}: rho={rho:.6f} (reported {rho:.2f})")
    print("PASS: all three separately computed correlations match the report.")


if __name__ == "__main__":
    main()
