"""Agreement of the blind second reader (blind_codes.json) with the first coder (codes.py) on the stratified fifth (blind_key.json).
Cohen's kappa for F (seven categories), M3 (reversed or not) and each reader operation. Writes agreement.json."""
import json, collections
from codes import F, OPS, M3_REVERSED
key = json.load(open("blind_key.json")); B = json.load(open("blind_codes.json"))
def kappa(a, b):
    n = len(a); po = sum(x == y for x, y in zip(a, b)) / n
    ca, cb = collections.Counter(a), collections.Counter(b); pe = sum(ca[k] * cb[k] for k in set(ca) | set(cb)) / n / n
    return round((po - pe) / (1 - pe), 3) if pe < 1 else None, round(po, 3)
ids = sorted(key); first = {b: key[b] for b in ids}
out = {"n": len(ids)}
out["F"] = kappa([F[first[b]] for b in ids], [B[b]["F"] for b in ids])
out["M3_reversed"] = kappa([first[b] in M3_REVERSED for b in ids], [B[b]["M3"] == "reversed" for b in ids])
for op in OPS: out[op] = kappa([first[b] in OPS[op] for b in ids], [bool(B[b][op]) for b in ids])
conf = collections.Counter((F[first[b]], B[b]["F"]) for b in ids)
out["F_confusion"] = {f"{a}->{b}": n for (a, b), n in sorted(conf.items())}
json.dump(out, open("agreement.json", "w"), indent=1)
for k, v in out.items():
    if k != "F_confusion": print(k, v)
print(out["F_confusion"])
