File size: 16,611 Bytes
268c55e
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268c55e
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268c55e
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268c55e
 
7825400
268c55e
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""Compute annotation agreement, per-image evidence and summary tables offline."""
from __future__ import annotations

import argparse
import csv
import json
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

import numpy as np

from metrics.annotation_agreement import (METHOD_VERSION, SEED, FIELDS, RATING_WIDTH, prepare_image,
    image_statistics, agreement_summary, rating_summary, public_evidence, stable_seed)
from metrics.semantic import SemanticPolicy
from schemas.ground_truth import GoldDataset
from scripts.frontend.build_dataset_eda import GOLD_DIR, IAA_DIR, MANIFEST_PATH, DOMAIN_PATH, ROOT, _latest
from utils.io import sha256_file
from utils.release import release_paths, release_identity, release_config, validate_population

DEFAULT_OUTPUT = ROOT / "frontend/.generated/dataset_agreement.json"
DEFAULT_EVIDENCE = ROOT / "frontend/.generated/dataset_agreement_evidence.json"
DEFAULT_POLICY = ROOT / "data/semantic_similarity/bge-large-en-v1.5-description-v2.json"


def source(path, records=None):
    return {"filename": path.name, "sha256": sha256_file(path), "records": records}


def build_agreement(*, gold_path, iaa_path, manifest_path, domain_path, policy_path,
                    output, evidence_output, replicates=2000, report_dir=None, release=None):
    if replicates < 0:
        raise ValueError("Bootstrap replicate count must be non-negative")
    gold_raw = json.loads(gold_path.read_text())
    GoldDataset.from_file(gold_path)
    raw = json.loads(iaa_path.read_text())
    if not isinstance(raw, list) or len({r["image_id"] for r in raw}) != len(raw):
        raise ValueError("IAA requires unique image IDs")
    for r in raw:
        labels = r["first_pass"]
        if len(labels) < 2 or len({a["annotator"] for a in labels}) != len(labels) or r["n_first_pass"] != len(labels):
            raise ValueError("IAA requires at least two distinct first-pass annotators and matching counts")
    manifest = [json.loads(line) for line in manifest_path.read_text().splitlines() if line.strip()]
    by_id = {r["image_id"]: r for r in manifest}
    if release:
        validate_population(gold_raw, raw, manifest, release["expected"])
    if len(by_id) != len(manifest):
        raise ValueError("Manifest requires unique image IDs")
    if any(r["image_id"] not in by_id for r in raw + gold_raw):
        raise ValueError("Gold/IAA images must resolve to the selected manifest")
    domains = json.loads(domain_path.read_text())
    ids = [c for cs in domains.values() for c in cs]
    if len(ids) != len(set(ids)):
        raise ValueError("Each class must belong to exactly one domain")
    payload = json.loads(policy_path.read_text())
    policy = SemanticPolicy.from_dict(payload)
    if set(policy.class_ids) != set(ids):
        raise ValueError("Semantic policy and domain taxonomy must agree")
    matrix = np.asarray(policy.similarities)
    accepted = np.asarray(policy.accepted)
    if matrix.shape != (len(ids), len(ids)) or not np.isfinite(matrix).all() or not np.allclose(matrix, matrix.T):
        raise ValueError("Semantic matrix must be finite and symmetric")
    if not np.array_equal(accepted, (matrix > .8) | np.eye(len(ids), dtype=bool)):
        raise ValueError("Agreement analysis requires the frozen strict cosine >0.80 policy")
    gold = {}
    names = {}
    for r in gold_raw:
        g = r["gold"]
        if any(v["use_case_id"] not in ids for v in g["violations"]):
            raise ValueError("Unknown gold class")
        gold[r["image_id"]] = {k: g.get(k) for k in ("plausibility", "naturalness", "reported", "no_violation_detected")}
        gold[r["image_id"]]["violations"] = [{"use_case_id": v["use_case_id"], "name": v["use_case_name"], "bbox": v["bbox"]} for v in g["violations"]]
        names.update({v["use_case_id"]: v["use_case_name"] for v in g["violations"]})
    for r in raw:
        for a in r["first_pass"]:
            names.update({v["use_case_id"]: v.get("use_case_name", v["use_case_id"]) for v in a["violations"]})
    images = [prepare_image(r, gold.get(r["image_id"]), by_id[r["image_id"]].get("category", "unmapped"), domains, policy)
              for r in sorted(raw, key=lambda r: r["image_id"])]
    print(f"Prepared {len(images):,} images; computing aggregate bootstrap intervals", flush=True)
    sources = {"gold": source(gold_path, len(gold)), "iaa": source(iaa_path, len(raw)),
               "manifest": source(manifest_path, len(manifest)), "domains": source(domain_path, len(domains)),
               "policy": source(policy_path, len(ids))}
    selections = {}
    categories = sorted({im["category"] for im in images})
    for pop in ("all", "gold_linked"):
        for category in ["all", *categories]:
            selections[f"{pop}:{category}"] = np.array([i for i, im in enumerate(images)
                if (pop == "all" or im["gold"] is not None) and (category == "all" or im["category"] == category)], dtype=int)
    targets = [("overall", "All violations", "overall", set(ids))]
    targets += [(d, d, "domain", set(cs)) for d, cs in domains.items()]
    targets += [(c, names.get(c, c), "class", {c}) for c in ids]
    groups = {key: {"population": key.split(":", 1)[0], "source": key.split(":", 1)[1],
                    "images": len(indices), "rows": []} for key, indices in selections.items()}
    quality = {k: np.array([im["quality"][k] for im in images]).reshape(-1, RATING_WIDTH) for k in ("plausibility", "naturalness")}
    # Cache the common absent-class pattern without conflating missing labels.
    absent_cache = {}
    all_present = [set().union(*im["sets"].values()) if im["sets"] else set() for im in images]
    for target_index, (key, name, kind, classes) in enumerate(targets):
        per_class = kind == "class"
        stats = np.zeros((len(images), len(FIELDS)))
        for i, im in enumerate(images):
            if all_present[i] & classes:
                stats[i] = image_statistics(im, classes, per_class=per_class)
            else:
                cache_key = (len(im["sets"]), sum(a["box_eligible"] for a in im["labels"]), len(classes), per_class)
                if cache_key not in absent_cache:
                    absent_cache[cache_key] = image_statistics(im, classes, per_class=per_class)
                stats[i] = absent_cache[cache_key]
        for group_key, indices in selections.items():
            q_indices = indices if kind == "overall" else np.array([i for i in indices if images[i]["gold_ids"] & classes], dtype=int)
            rating = {k: rating_summary(v[q_indices], seed=stable_seed(f"{group_key}:{key}:{k}"), replicates=replicates) for k, v in quality.items()}
            for k in rating:
                rating[k]["excluded_images"] = len(q_indices)-rating[k]["eligible"]
            groups[group_key]["rows"].append({"id": key, "name": name, "kind": kind,
                "quality_images": len(q_indices), "quality": rating,
                "agreement": agreement_summary(stats[indices], per_class=per_class,
                    seed=stable_seed(f"{group_key}:{key}:agreement"), replicates=replicates)})
        if target_index % 10 == 0:
            print(f"Completed {target_index+1}/{len(targets)} slices: {key}", flush=True)
    audits = Counter()
    for im in images: audits.update(im["audit"])
    metadata = {"schema_version": 2, "method_version": METHOD_VERSION,
        "release": release,
        "generated_at": datetime.now(timezone.utc).isoformat(), "sources": sources,
        "bootstrap": {"replicates": replicates, "seed": SEED, "unit": "image", "interval": "95% percentile", "minimum_estimable_fraction": .95},
        "quality_alpha": {"primary": "ordinal", "sensitivity": "interval", "ordinal_distances": "sample cumulative category midranks", "bootstrap_distances": "recomputed per resample"},
        "semantic": {"cosine_strictly_greater_than": .8, "accepted_off_diagonal_pairs": int((accepted.sum()-len(ids))/2), "expert_validated": False},
        "coverage": {"gold": len(gold), "iaa": len(images), "overlap": sum(im["gold"] is not None for im in images),
                     "first_pass_submissions": sum(len(im["labels"]) for im in images),
                     "raters_per_image": dict(sorted(Counter(len(im["labels"]) for im in images).items())),
                     "report_disagreement_images": sum(len({a["reported"] for a in im["labels"]}) > 1 for im in images),
                     "annotation_exclusions": dict(audits)},
        "categories": categories, "domains": domains,
        "limitations": ["First-pass reliability does not prove gold correctness.",
            "The export does not establish independence from annotation prefill.",
            "Gold-defined quality slices are overlapping selected populations.",
            "Semantic relaxation is exploratory and not expert validated.",
            "Intervals resample images; unrecorded batch dependence is not modelled."]}
    artifact = {**metadata, "groups": groups}
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(artifact, separators=(",", ":"), allow_nan=False) + "\n")
    evidence_output.parent.mkdir(parents=True, exist_ok=True)
    evidence_output.write_text(json.dumps({"method_version": METHOD_VERSION, "sources": sources,
        "images": [public_evidence(im) for im in images]}, separators=(",", ":"), allow_nan=False) + "\n")
    if report_dir:
        write_report(artifact, report_dir)
    return artifact


def write_report(artifact, directory):
    directory.mkdir(parents=True, exist_ok=True)
    (directory / "agreement.json").write_text(json.dumps(artifact, separators=(",", ":"), allow_nan=False)+"\n")
    with (directory / "agreement.csv").open("w", newline="") as stream:
        writer = csv.writer(stream)
        writer.writerow(["population", "source", "slice_kind", "slice_id", "dimension", "metric", "value", "ci_low", "ci_high", "eligible_images", "positive_images", "bootstrap_valid"])
        for group in artifact["groups"].values():
            for row in group["rows"]:
                for dim, metrics in [*row["quality"].items(), ("labels_instances", row["agreement"])]:
                    for name, m in metrics.items():
                        if not isinstance(m, dict) or "value" not in m: continue
                        support = row["agreement"]["support"]
                        eligible = metrics.get("eligible", support["box_n"] if name in ("instance_f1", "semantic_instance_f1", "matched_iou") or name.startswith("iou_") else support["label_n"])
                        writer.writerow([group["population"], group["source"], row["kind"], row["id"], dim, name,
                            m["value"], *(m["ci"] or [None,None]), eligible, support["positive_images"], m["bootstrap_valid"]])
    def val(m):
        if m["value"] is None: return "Not estimable"
        ci = "" if m["ci"] is None else f" [{m['ci'][0]:.4f}, {m['ci'][1]:.4f}]"
        return f"{m['value']:.4f}{ci}"
    lines = ["# Annotation reliability results", "", f"Method `{METHOD_VERSION}`; generated {artifact['generated_at']}. Values in brackets are 95% image-bootstrap intervals.", "",
        "## Provenance", "", "| Input | File | SHA-256 |", "|---|---|---|"]
    lines += [f"| {k} | `{v['filename']}` | `{v['sha256']}` |" for k,v in artifact["sources"].items()]
    lines += ["", f"Bootstrap: {artifact['bootstrap']['replicates']} image resamples; seed {SEED}. All first-pass annotations remain together. Ordinal distances are recalculated from each selected sample’s category frequencies, including every bootstrap resample. Interval alpha is secondary. Standard alpha uses coincidence weights; descriptive pair counts are normalised within images.", "",
        "## Overall reliability", "", "| Population | Variable | Images | Exact | Within one | Ordinal alpha (primary) | Interval alpha (sensitivity) |", "|---|---|---:|---|---|---|---|"]
    for pop in ("all", "gold_linked"):
        row = artifact["groups"][f"{pop}:all"]["rows"][0]
        for k,q in row["quality"].items():
            lines.append(f"| {pop} | {k} | {q['eligible']} | {val(q['exact'])} | {val(q['within_one'])} | {val(q['alpha'])} | {val(q['interval_alpha'])} |")
    lines += ["", "| Population | Label images | Unanimous exact sets | Positive-label agreement | Instance F1 | Matched IoU |", "|---|---:|---|---|---|---|"]
    for pop in ("all", "gold_linked"):
        a=artifact["groups"][f"{pop}:all"]["rows"][0]["agreement"]
        lines.append(f"| {pop} | {int(a['support']['label_n'])} | {val(a['exact'])} | {val(a['positive_agreement'])} | {val(a['instance_f1'])} | {val(a['matched_iou'])} |")
    lines += ["", "## Semantic diagnostic", "", "Exact class agreement is primary. The frozen strict cosine >0.80 policy matches exact labels first; boxes also require IoU >=0.50. This policy has not been expert validated.", "",
        "| Population | Relaxed positive-label agreement | Relaxed instance F1 |", "|---|---|---|"]
    for pop in ("all", "gold_linked"):
        a=artifact["groups"][f"{pop}:all"]["rows"][0]["agreement"]
        lines.append(f"| {pop} | {val(a['semantic_positive_agreement'])} | {val(a['semantic_instance_f1'])} |")
    lines += ["", "## Reading the tables", "", "Quality domain/class slices use gold image membership. Class label/box rows consider that class across the full selected eligible population, including omissions. Domain label rows preserve constituent classes. Exact-set agreement includes shared clean labels; positive agreement excludes shared absence from its denominator and is undefined without any positive endpoint. Instance F1 includes one-sided boxes; both-empty comparisons have no spatial score. Matched IoU is conditional on exact-class one-to-one matches.", "",
        "`agreement.csv` and `agreement.json` contain all source/population/domain/class estimates, support and IoU sensitivity. No individual annotator rankings or source identities are exported. Per-image evidence is written to the configured evidence output.", "", "## Limitations", ""]
    lines += [f"- {s}" for s in artifact["limitations"]]
    lines += ["- Fewer than ten eligible or positive-support images is flagged; a narrow interval does not remove sparse-class or prevalence limitations.", "- Constant ratings/presence produce undefined alpha; negative alpha values are retained. These estimates measure agreement and do not independently verify gold correctness.", "", "## Calculation definitions", "", "The [metric-to-value table](../../../docs/reference/metrics.md#which-metric-calculates-each-displayed-value) identifies each displayed value's formula, denominator, weighting and artifact field. Quality percentages use image unanimity/range; quality alpha uses ordinal cumulative-frequency distances and all within-image coincidences; interval alpha is retained as sensitivity; label positive agreement uses pooled binary positive decisions; per-class alpha uses nominal coincidences; instance F1 uses weighted one-to-one match counts; mean IoU is conditional on matches. Annotation instance F1 is distinct from the model benchmark's F2.", ""]
    (directory / "REPORT.md").write_text("\n".join(lines))


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--gold", type=Path)
    parser.add_argument("--iaa", type=Path)
    parser.add_argument("--manifest", type=Path)
    parser.add_argument("--domains", type=Path, default=DOMAIN_PATH)
    parser.add_argument("--policy", type=Path, default=DEFAULT_POLICY)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--evidence-output", type=Path, default=DEFAULT_EVIDENCE)
    parser.add_argument("--bootstrap", type=int, default=2000)
    parser.add_argument("--report-dir", type=Path)
    args=parser.parse_args()
    pinned = args.gold is None and args.iaa is None and args.manifest is None
    paths = release_paths(verify=pinned)
    gold_path, iaa_path = args.gold or paths["gold"], args.iaa or paths["iaa"]
    report_dir = args.report_dir or ROOT / "results/dataset_evaluation" / "synthetic11534" / "agreement"
    build_agreement(gold_path=gold_path, iaa_path=iaa_path,
        manifest_path=args.manifest or paths["manifest"], domain_path=args.domains, policy_path=args.policy,
        output=args.output, evidence_output=args.evidence_output, replicates=args.bootstrap, report_dir=report_dir,
        release=release_identity() if pinned else None)
    print(f"Wrote {args.output} and {report_dir}", flush=True)


if __name__ == "__main__":
    main()