"""Guerry (1833): run 'python analyse.py' next to guerry.csv. Python 3.8+."""
import csv
from itertools import groupby
from math import sqrt
from pathlib import Path
from statistics import mean


def ranks(values):
    """Assign mean ranks to ties, retaining the original observation order."""
    result = [0.0] * len(values)
    position = 1
    for _, group in groupby(sorted(enumerate(values), key=lambda p: p[1]), key=lambda p: p[1]):
        items = list(group)
        average = position + (len(items) - 1) / 2
        for index, _ in items:
            result[index] = average
        position += len(items)
    return result


def spearman(x, y):
    a, b = ranks(x), ranks(y)
    mean_a, mean_b = mean(a), mean(b)
    a = [v - mean_a for v in a]
    b = [v - mean_b for v in b]
    return sum(v * w for v, w in zip(a, b)) / sqrt(sum(v*v for v in a) * sum(w*w for w in b))


if __name__ == "__main__":
    with Path(__file__).with_name("guerry.csv").open(encoding="utf-8", newline="") as stream:
        rows = list(csv.DictReader(stream))
    assert len(rows) == len({r["dept"] for r in rows}) == 86
    for col in ("Literacy", "Crime_prop", "Crime_pers"):
        for row in rows:
            row[col] = int(row[col])
    for row in rows:
        assert 0 <= row["Literacy"] <= 100 and min(row["Crime_prop"], row["Crime_pers"]) > 0
        if row["Department"] in ("Seine", "Creuse"):
            print(f"{row['Department']}: {100000 / row['Crime_prop']:.2f} per 100,000 (property)")
    print("Subset, N, Spearman/property, Spearman/person")
    samples = {"All": rows, "Without Seine": [r for r in rows if r["Department"] != "Seine"]}
    samples["Mapped mainland"] = [r for r in rows if r["dept"] != "200"]
    for region in ("N", "E", "S", "W", "C"):
        samples[region] = [r for r in rows if r["Region"] == region]
    for label, group in samples.items():
        literacy = [r["Literacy"] for r in group]
        results = [spearman(literacy, [100000 / r[col] for r in group]) for col in ("Crime_prop", "Crime_pers")]
        print(f"{label}, {len(group)}, {results[0]:.4f}, {results[1]:.4f}")
