| import csv |
|
|
| from legex.analysis.iaa import ( |
| PRIMARY, |
| cohen_kappa, |
| pairwise_agreement, |
| summarise_by_field, |
| write_kappa_audit_csv, |
| ) |
|
|
|
|
| def test_cohen_kappa_perfect_agreement() -> None: |
| pairs = [("a", "a"), ("b", "b"), ("a", "a"), ("b", "b")] |
| assert cohen_kappa(pairs) == 1.0 |
|
|
|
|
| def test_cohen_kappa_chance_agreement_is_zero() -> None: |
| |
| pairs = [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")] |
| k = cohen_kappa(pairs) |
| assert k is not None |
| assert abs(k) < 1e-9 |
|
|
|
|
| def test_cohen_kappa_single_category_undefined() -> None: |
| assert cohen_kappa([("a", "a"), ("a", "a")]) is None |
|
|
|
|
| def test_cohen_kappa_too_few_items() -> None: |
| assert cohen_kappa([("a", "b")]) is None |
|
|
|
|
| def _labels_two_annotators(): |
| |
| return { |
| (PRIMARY, "ch", "c1"): {"f1": "x", "f2": "1"}, |
| (PRIMARY, "ch", "c2"): {"f1": "y", "f2": "2"}, |
| (PRIMARY, "ch", "c3"): {"f1": "z", "f2": ""}, |
| ("de", "ch", "c1"): {"f1": "x", "f2": "1"}, |
| ("de", "ch", "c2"): {"f1": "WRONG", "f2": "2"}, |
| ("de", "ch", "c3"): {"f1": "z", "f2": ""}, |
| } |
|
|
|
|
| def test_pairwise_agreement_counts() -> None: |
| rows = pairwise_agreement(_labels_two_annotators()) |
| by_field = {r.field: r for r in rows} |
| assert by_field["f1"].n == 3 |
| assert by_field["f1"].n_agree_exact == 2 |
| assert by_field["f2"].n_agree_exact == 3 |
| assert by_field["f2"].pct_exact == 1.0 |
|
|
|
|
| def test_pairwise_tolerant_handles_numeric() -> None: |
| labels = { |
| (PRIMARY, "ch", "c1"): {"amount": "1500"}, |
| ("de", "ch", "c1"): {"amount": "1500.0"}, |
| } |
| rows = pairwise_agreement(labels) |
| assert rows[0].n_agree_tolerant == 1 |
|
|
|
|
| def test_summarise_by_field_weights_by_n() -> None: |
| rows = pairwise_agreement(_labels_two_annotators()) |
| summary = summarise_by_field(rows) |
| assert summary["f2"]["pct_exact"] == 1.0 |
| assert 0.0 <= summary["f1"]["pct_exact"] <= 1.0 |
|
|
|
|
| def test_write_kappa_audit_csv(tmp_path) -> None: |
| labels = { |
| (PRIMARY, "ch", "c1"): {"f1": "x", "amount": "1500"}, |
| (PRIMARY, "ch", "c2"): {"f1": "y", "amount": "10"}, |
| ("de", "ch", "c1"): {"f1": "x", "amount": "1500.0"}, |
| ("de", "ch", "c2"): {"f1": "WRONG", "amount": "10"}, |
| } |
| path = tmp_path / "kappa_audit.csv" |
| n = write_kappa_audit_csv(labels, path) |
| rows = list(csv.DictReader(path.open(encoding="utf-8"))) |
| |
| assert n == 4 == len(rows) |
| cell = {(r["case_id"], r["field"]): r for r in rows} |
| |
| assert cell[("c1", "f1")]["decision_exact"] == "yes" |
| assert cell[("c1", "f1")]["decision_tolerant"] == "yes" |
| assert cell[("c1", "amount")]["decision_exact"] == "no" |
| assert cell[("c1", "amount")]["decision_tolerant"] == "yes" |
| |
| assert cell[("c2", "f1")]["decision_exact"] == "no" |
| assert cell[("c2", "f1")]["decision_tolerant"] == "no" |
|
|