File size: 12,580 Bytes
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
 
 
4f3323a
 
 
 
 
 
 
 
 
 
b6f22ac
 
 
 
4f3323a
 
 
 
 
 
 
 
 
 
 
b6f22ac
4f3323a
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
"""
Anomaly multiplicity per class: how many anomaly types share an image, broken
down by the class present in it. Same visual format as plot_multimodal_aupro.py:
seaborn whitegrid, viridis grouped bars, red dotted class means.

    x axis   the anchor classes
    hue      multiplicity 1..7, i.e. the total number of distinct anomaly
             types present in the image
"""

import argparse
import sys
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
import numpy as np
import pandas as pd
import seaborn as sns

from plot_difficulty import load_annotations, load_scores

DEFAULT_CLASSES = ["residual_content", "nuisance_sticker_inside",
                   "nuisance_gunk", "nuisance_paper"]


def coco_files(entries, pattern):
    found = []
    for item in entries:
        path = Path(item)
        if path.is_dir():
            found.extend(path.rglob(pattern))
        elif path.is_file():
            found.append(path)
    return sorted(set(str(path) for path in found))


def type_label(k):
    return f"{k} type" if k == 1 else f"{k} types"


def count_table(memberships, classes, max_k):
    rows = []
    for types in memberships.values():
        if not types:
            continue
        k = len(types)
        if k < 1 or k > max_k:
            continue
        for cls in classes:
            if cls in types:
                rows.append({"Class": cls, "Multiplicity": k})
    if not rows:
        return None, None
    df = pd.DataFrame(rows)
    agg = (df.groupby(["Class", "Multiplicity"]).size()
             .reset_index(name="Value"))
    agg["n"] = agg["Value"]
    means = agg.groupby("Class")["Value"].mean()
    return agg, means


def score_table(memberships, scores, classes, max_k):
    rows = []
    for key, types in memberships.items():
        if not types or key not in scores:
            continue
        k = len(types)
        if k < 1 or k > max_k:
            continue
        for cls in classes:
            if cls in types:
                rows.append({"Class": cls, "Multiplicity": k,
                             "Value": scores[key]})
    if not rows:
        return None, None
    df = pd.DataFrame(rows)
    agg = (df.groupby(["Class", "Multiplicity"])["Value"]
             .agg(["mean", "count"]).reset_index()
             .rename(columns={"mean": "Value", "count": "n"}))
    means = df.groupby("Class")["Value"].mean()
    return agg, means


def add_class_means(classes, class_means, ylim, fmt="{:.2f}"):
    for i, cls in enumerate(classes):
        if cls not in class_means:
            continue
        mean_val = float(class_means[cls])
        plt.hlines(y=mean_val, xmin=i - 0.4, xmax=i + 0.4,
                   colors="red", linestyles=":", linewidth=3,
                   label="Class Mean" if i == 0 else "")
        plt.text(i + 0.3, mean_val + 0.018 * (ylim[1] - ylim[0]),
                 fmt.format(mean_val), color="red", ha="left", va="center",
                 fontsize=9, fontweight="bold")


def draw(df_agg, class_means, classes, hue_col, hue_order, ylim, ylabel,
         stem, annotate_n=False, integer_y=False, mean_fmt="{:.2f}",
         legend_labels=None):
    sns.set_theme(style="whitegrid", font_scale=1.1)
    plt.figure(figsize=(14, 5))

    chart = sns.barplot(
        data=df_agg,
        x="Class",
        y="Value",
        order=classes,
        hue=hue_col,
        hue_order=hue_order,
        palette="viridis",
    )

    add_class_means(classes, class_means, ylim, fmt=mean_fmt)

    if annotate_n and "n" in df_agg.columns:
        for p in chart.patches:
            h = p.get_height()
            if not np.isfinite(h) or h <= 0:
                continue
            chart.annotate(f"{int(round(h))}",
                           (p.get_x() + p.get_width() / 2, h),
                           ha="center", va="bottom", fontsize=7, color="0.25",
                           xytext=(0, 2), textcoords="offset points")

    plt.xticks(rotation=15, ha="right")
    plt.xlabel("")
    plt.ylabel(ylabel)
    plt.ylim(ylim)
    if integer_y:
        plt.gca().yaxis.set_major_locator(
            matplotlib.ticker.MaxNLocator(integer=True)
        )

    handles, labels = plt.gca().get_legend_handles_labels()
    if legend_labels:
        labels = [legend_labels.get(l, l) for l in labels]
    plt.legend(
        handles, labels,
        loc="upper left",
        ncol=4,
        frameon=True,
        framealpha=0.2,
        facecolor="white",
        edgecolor="black",
    )

    plt.tight_layout()
    plt.savefig(f"{stem}.pdf", bbox_inches="tight")
    plt.savefig(f"{stem}.png", dpi=300, bbox_inches="tight")
    plt.close()


def report(label, agg, classes, ks, value_name):
    print(f"\n{label}")
    pivot = (agg.pivot(index="Class", columns="Multiplicity", values="Value")
                .reindex(index=classes, columns=ks))
    if value_name == "images":
        print("  images per group")
        print(pivot.fillna(0).astype(int).to_string().replace("\n", "\n  "))
        print(f"  total images (class occurrences): {int(agg['Value'].sum())}")
    else:
        pivot_n = (agg.pivot(index="Class", columns="Multiplicity", values="n")
                      .reindex(index=classes, columns=ks))
        print("  images per group")
        print(pivot_n.fillna(0).astype(int).to_string().replace("\n", "\n  "))
        print("  mean AUPRO per group")
        print(pivot.round(3).to_string().replace("\n", "\n  "))


def default_coco_search():
    candidates = [
        Path("test"),
        Path("../test"),
        Path(__file__).resolve().parent.parent / "test",
        Path("train"),
        Path("../train"),
        Path(__file__).resolve().parent.parent / "train",
        Path("."),
        Path(".."),
        Path(__file__).resolve().parent.parent,
    ]
    for c in candidates:
        if c.is_dir() and list(c.rglob("annotations*.coco.json")):
            return [str(c)]
    return ["."]


def find_files(names):
    resolved = []
    for name in names:
        candidates = [
            Path(f"checkpoint_data/{name}"),
            Path(f"../checkpoint_data/{name}"),
            Path(__file__).resolve().parent.parent / "checkpoint_data" / name,
            Path(__file__).resolve().parent / name,
            Path(name),
        ]
        found = next((str(c) for c in candidates if c.is_file()), None)
        if found:
            resolved.append(found)
    return resolved


def default_out_dir():
    if Path("checkpoint_data").is_dir():
        return Path("checkpoint_data/multiplicity_figures")
    if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
        return Path(__file__).resolve().parent.parent / "checkpoint_data/multiplicity_figures"
    return Path("./multiplicity_figures")


def main():
    parser = argparse.ArgumentParser(description="Anomaly multiplicity per class")
    parser.add_argument("--coco", nargs="+", default=None,
                        help="COCO annotation files or root directory (auto-detected if omitted)")
    parser.add_argument("--coco-pattern", default="annotations*.coco.json")
    parser.add_argument("--scores", action="append", default=[],
                        metavar="NAME=CSV[,CSV]",
                        help="repeatable: per-image AUPRO CSVs for one method. "
                             "Auto-detected from checkpoint_data/ if omitted.")
    parser.add_argument("--metric", default="aupro_30")
    parser.add_argument("--classes", nargs="+", default=DEFAULT_CLASSES,
                        help="anchor classes, in the order they appear on x")
    parser.add_argument("--max-k", type=int, default=7,
                        help="highest multiplicity shown (default 7)")
    parser.add_argument("--min-n", type=int, default=1,
                        help="groups with fewer images are left empty")
    parser.add_argument("--annotate-n", action="store_true",
                        help="print the image count above each bar")
    parser.add_argument("--no-shared-y", action="store_true",
                        help="let each method figure scale its own y axis")
    parser.add_argument("--out", default=None,
                        help="Output directory (default: checkpoint_data/multiplicity_figures or ./multiplicity_figures)")
    args = parser.parse_args()

    coco_entries = args.coco if args.coco is not None else default_coco_search()
    annotations = coco_files(coco_entries, args.coco_pattern)
    if not annotations:
        raise SystemExit(f"No COCO annotation files found in {coco_entries}")
    memberships = load_annotations(annotations)
    annotated = {key for key, types in memberships.items() if types}

    ks = list(range(1, args.max_k + 1))
    out = Path(args.out) if args.out is not None else default_out_dir()
    out.mkdir(parents=True, exist_ok=True)

    count_agg, count_means = count_table(memberships, args.classes, args.max_k)
    if count_agg is None:
        raise SystemExit("none of the requested classes occur in the data")

    classes = [c for c in args.classes if c in set(count_agg["Class"])]
    missing = [c for c in args.classes if c not in classes]
    if missing:
        print(f"! not present in the data: {', '.join(missing)}", file=sys.stderr)

    scores_specs = args.scores
    if not scores_specs:
        m3dm_csvs = find_files(["per_image_aupro_zivid.csv", "per_image_aupro_realsense.csv"])
        stfpm_csvs = find_files(["per_image_aupro_stfpm.csv"])
        if m3dm_csvs:
            scores_specs.append(f"M3DM={','.join(m3dm_csvs)}")
        if stfpm_csvs:
            scores_specs.append(f"STFPM={','.join(stfpm_csvs)}")

    per_method = {}
    for spec in scores_specs:
        if "=" not in spec:
            raise SystemExit(f"--scores needs NAME=CSV, got {spec!r}")
        name, paths = spec.split("=", 1)
        files = [p.strip() for p in paths.split(",") if p.strip()]
        per_method[name.strip()] = load_scores(files, args.metric, name.strip())

    if per_method:
        print()
        for name, scores in per_method.items():
            print(f"  {name:<20} {len(annotated & set(scores))} images matched to types")

    method_tables = {}
    for index, (name, scores) in enumerate(per_method.items(), start=2):
        agg, means = score_table(memberships, scores, classes, args.max_k)
        if agg is None:
            print(f"! {name}: no matching images, skipped", file=sys.stderr)
            continue
        thin = agg[agg["n"] < args.min_n]
        if len(thin):
            print(f"  {name}: {len(thin)} group(s) below --min-n {args.min_n}, left empty")
            agg = agg[agg["n"] >= args.min_n]
        slug = name.lower().replace(" ", "_").replace("/", "_")
        method_tables[f"{index:02d}_multiplicity_{slug}"] = (name, agg, means)

    method_ylim = None
    if method_tables and not args.no_shared_y:
        top = max(max(float(agg["Value"].max()), float(means.max()))
                  for _, agg, means in method_tables.values())
        method_ylim = (0, top * 1.42)

    thin_counts = count_agg[count_agg["n"] < args.min_n]
    if len(thin_counts):
        count_agg = count_agg[count_agg["n"] >= args.min_n]

    report("dataset-wide (composition)", count_agg, classes, ks, "images")
    count_top = max(float(count_agg["Value"].max()), float(count_means.max()))
    type_names = {k: type_label(k) for k in ks}
    draw(count_agg, count_means, classes, "Multiplicity", ks,
         (0, count_top * 1.42), "Number of Images",
         str(out / "01_multiplicity_dataset_wide"),
         annotate_n=False, integer_y=True, mean_fmt="{:.0f}",
         legend_labels={str(k): v for k, v in type_names.items()})
    count_agg.sort_values(["Class", "Multiplicity"]).to_csv(
        out / "01_multiplicity_dataset_wide_values.csv", index=False)

    for stem, (label, agg, means) in method_tables.items():
        report(label, agg, classes, ks, "aupro")
        ylim = method_ylim
        if ylim is None:
            top = max(float(agg["Value"].max()), float(means.max()))
            ylim = (0, top * 1.42)
        draw(agg, means, classes, "Multiplicity", ks, ylim,
             "Mean Pixel AUPRO Score", str(out / stem),
             annotate_n=args.annotate_n,
             legend_labels={str(k): v for k, v in type_names.items()})
        agg.sort_values(["Class", "Multiplicity"]).to_csv(
            out / f"{stem}_values.csv", index=False)

    print(f"\nWrote figures and CSVs to {out}")


if __name__ == "__main__":
    main()