"""Agreement of several blind raters with the code labels and with each other (trial audit, plan section 4.4). python scripts/09_rater_agreement.py [DIR] # DIR defaults to outputs/audit/trial_100 Reads DIR/key.csv and every DIR/RATINGS_.csv (the sheet of scripts/09_audit.py with the r_* columns filled). Writes DIR/raters.json: per rater Cohen's kappa against the code labels (NPT definitions a and b, cause group, operation class), kappa between every pair of raters, Fleiss' kappa over the raters, and the median over raters. The raters are LLMs, not people: the output is never an author or expert audit (plan section 12 item 20). """ from __future__ import annotations import itertools import json import sys from pathlib import Path import numpy as np import pandas as pd from volve_dia import audit, paths def fleiss(labels: pd.DataFrame) -> float | None: """Fleiss' kappa for a frame with one column per rater (rows with a missing label are dropped).""" x = labels.dropna() n, m = x.shape[1], len(x) cats = sorted(set(x.to_numpy().ravel())) if m == 0 or len(cats) < 2: return None c = np.array([[int((x.iloc[i] == k).sum()) for k in cats] for i in range(m)], dtype=float) pi = ((c ** 2).sum(axis=1) - n) / (n * (n - 1)) pj = c.sum(axis=0) / (n * m) pe = (pj ** 2).sum() return None if pe >= 1 else round(float((pi.mean() - pe) / (1 - pe)), 4) def main() -> int: d = Path(sys.argv[1]) if len(sys.argv) > 1 else paths.outputs_dir() / "audit" / "trial_100" key = pd.read_csv(d / "key.csv").set_index("item") files = sorted(d.glob("RATINGS_*.csv")) if len(files) < 2: print("[raters] need at least two RATINGS_*.csv files") return 1 r = {f.stem.removeprefix("RATINGS_"): pd.read_csv(f, dtype=str, encoding="utf-8-sig").set_index("item") .reindex(key.index) for f in files} out: dict = {"raters": list(r), "items": len(key), "vs_code": {}, "pairwise": {}, "fleiss": {}} for name, x in r.items(): npt = x["r_npt"].map({"y": True, "n": False}) cause = x["r_cause"].where(npt, "none").where(npt.notna()) ops = key["op_class"] != "interruption" res = {"unsure": int(npt.isna().sum())} for df in ("a", "b"): res[f"npt_{df}"] = audit.agreement(npt, key[f"npt_{df}"].astype(bool), key["weight"]) res[f"cause_{df}"] = audit.agreement(cause.fillna("unspecified").where(npt.notna()), key[f"cause_{df}"].fillna("none"), key["weight"]) res["op_class"] = audit.agreement(x.loc[ops, "r_op_class"], key.loc[ops, "op_class"], key.loc[ops, "weight"]) out["vs_code"][name] = res for a, b in itertools.combinations(r, 2): na, nb = (r[k]["r_npt"].map({"y": True, "n": False}) for k in (a, b)) out["pairwise"][f"{a}-{b}"] = { "npt": audit.agreement(na, nb), "npt_weighted": audit.agreement(na, nb, key["weight"]), "cause": audit.agreement(r[a]["r_cause"].fillna("none"), r[b]["r_cause"].fillna("none")), "op_class": audit.agreement(r[a]["r_op_class"], r[b]["r_op_class"])} out["fleiss"] = {"npt": fleiss(pd.DataFrame({k: v["r_npt"].map({"y": "y", "n": "n"}) for k, v in r.items()})), "cause": fleiss(pd.DataFrame({k: v["r_cause"].fillna("none") for k, v in r.items()})), "op_class": fleiss(pd.DataFrame({k: v["r_op_class"] for k, v in r.items()}))} med = {} for t in ("npt_a", "npt_b", "cause_a", "cause_b", "op_class"): ks = [out["vs_code"][n][t]["kappa"] for n in r if out["vs_code"][n][t]["kappa"] is not None] med[t] = round(float(np.median(ks)), 4) if ks else None out["median_kappa_vs_code_weighted"] = med (d / "raters.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8") print(json.dumps(out, indent=1)) return 0 if __name__ == "__main__": raise SystemExit(main())