File size: 14,238 Bytes
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
 
 
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/env python3
"""Create four standalone UpSet plots from plot_difficulty.py inputs."""
import argparse
import sys
from collections import Counter, defaultdict
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, Normalize, TwoSlopeNorm
import numpy as np
import pandas as pd

from plot_difficulty import (COLORS, PAPER_DIVERGING, PAPER_SEQUENTIAL,
                             load_annotations, load_scores)

plt.rcParams.update({
    "font.family": "serif",
    "font.serif": ["Times New Roman", "DejaVu Serif"],
    "font.size": 10,
    "axes.linewidth": 0.7,
    "pdf.fonttype": 42,
})

BAR_SINGLE = PAPER_SEQUENTIAL(0.5)


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 exact_groups(memberships):
    groups = defaultdict(list)
    for key, types in memberships.items():
        membership = tuple(sorted(types))
        if membership:
            groups[membership].append(key)
    return groups


def choose(groups, top_n, min_count, all_types=None, ensure_all_types=False):
    candidates = [(membership, len(keys)) for membership, keys in groups.items()
                  if len(keys) >= min_count]
    candidates.sort(key=lambda item: (-item[1], len(item[0]), item[0]))
    chosen = [membership for membership, _ in candidates[:top_n]]

    if not ensure_all_types or not all_types:
        chosen.sort(key=lambda m: (-len(groups[m]), len(m), m))
        return chosen

    covered = {name for membership in chosen for name in membership}
    missing = [t for t in all_types if t not in covered]
    if not missing:
        chosen.sort(key=lambda m: (-len(groups[m]), len(m), m))
        return chosen

    ranked = sorted(groups.items(),
                    key=lambda item: (-len(item[1]), len(item[0]), item[0]))
    for name in missing:
        if name in {n for c in chosen for n in c}:
            continue
        for membership, keys in ranked:
            if name in membership and membership not in chosen:
                chosen.append(membership)
                print(f"  added '{name}' via {' + '.join(membership)} "
                      f"({len(keys)} images)")
                break

    still = [t for t in all_types if t not in {n for c in chosen for n in c}]
    if still:
        print(f"  ! no combination found for: {', '.join(still)}", file=sys.stderr)

    chosen.sort(key=lambda m: (-len(groups[m]), len(m), m))
    return chosen


def stats(combinations, groups, scores=None):
    rows = []
    for membership in combinations:
        keys = groups[membership]
        row = {"membership": membership, "dataset_n": len(keys)}
        if scores is not None:
            values = np.asarray([scores[key] for key in keys if key in scores], float)
            row.update(
                n=int(values.size),
                mean=float(values.mean()) if values.size else np.nan,
                std=float(values.std(ddof=1)) if values.size > 1 else 0.0,
            )
        rows.append(row)
    return rows


def short(name):
    return name


def save_values(path, rows):
    output = []
    for rank, row in enumerate(rows, 1):
        record = {
            "rank": rank,
            "combination": " + ".join(row["membership"]),
            "n_types": len(row["membership"]),
            "dataset_n": row["dataset_n"],
        }
        for key in ("n", "mean", "std"):
            if key in row:
                record[key] = row[key]
        output.append(record)
    pd.DataFrame(output).to_csv(path, index=False)


def draw(rows, categories, stem, value_label=None, limits=None, difference=False):
    n_combinations = len(rows)
    n_categories = len(categories)
    x = np.arange(n_combinations)
    counts = np.asarray([row["dataset_n"] for row in rows])

    width = max(8.5, 0.46 * n_combinations + 3.4)
    fig = plt.figure(figsize=(width, 6.9))
    grid = fig.add_gridspec(2, 3, width_ratios=[1.3, 5.0, 0.22],
                            height_ratios=[2.3, 2.2], hspace=0.05, wspace=0.04)
    ax_sets = fig.add_subplot(grid[1, 0])
    ax_bars = fig.add_subplot(grid[0, 1])
    ax_dots = fig.add_subplot(grid[1, 1], sharex=ax_bars)
    ax_cbar = fig.add_subplot(grid[0, 2])

    if value_label is None:
        colors = [BAR_SINGLE] * n_combinations
        norm = None
        cmap = None
    else:
        values = np.asarray([row["mean"] for row in rows], float)
        finite = values[np.isfinite(values)]
        if not finite.size:
            raise ValueError(f"No finite performance values for {stem}")
        if difference:
            bound = max(float(np.abs(finite).max()), 1e-9)
            norm = TwoSlopeNorm(vmin=-bound, vcenter=0, vmax=bound)
            cmap = PAPER_DIVERGING
        else:
            low, high = limits if limits else (float(finite.min()), float(finite.max()))
            if np.isclose(low, high):
                low, high = low - 0.01, high + 0.01
            norm = Normalize(low, high)
            cmap = PAPER_SEQUENTIAL
        colors = [cmap(norm(value)) if np.isfinite(value) else "white"
                  for value in values]

    bars = ax_bars.bar(x, counts, width=0.72, color=colors,
                       edgecolor="black", linewidth=0.6)
    for index, (bar, row) in enumerate(zip(bars, rows)):
        ax_bars.text(index, bar.get_height(), str(row["dataset_n"]),
                     ha="center", va="bottom", fontsize=7.5, color="black")
        if value_label is not None:
            text = (f"{row['mean']:.2f}\nn={row['n']}"
                    if np.isfinite(row["mean"]) else "NA")
            ax_bars.text(index, max(bar.get_height() * 0.50, 0.25), text,
                         ha="center", va="center", fontsize=6.4, color="black")

    ax_bars.set_ylabel("Number of Images per Combination", fontsize=11)
    ax_bars.tick_params(axis="x", bottom=False, labelbottom=False)
    ax_bars.tick_params(labelsize=9)
    ax_bars.spines[["top", "right"]].set_visible(False)
    ax_bars.set_ylim(0, max(1, counts.max() * 1.18))

    if norm is not None:
        mapper = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
        mapper.set_array([])
        colorbar = fig.colorbar(mapper, cax=ax_cbar)
        colorbar.set_label(value_label, fontsize=10)
        colorbar.ax.tick_params(labelsize=8.5)
    else:
        ax_cbar.axis("off")

    category_index = {name: index for index, name in enumerate(categories)}
    for column, row in enumerate(rows):
        selected = sorted(category_index[name] for name in row["membership"])
        ax_dots.scatter(np.full(n_categories, column), np.arange(n_categories),
                        s=13, color="0.87", zorder=1)
        ax_dots.plot([column, column], [min(selected), max(selected)],
                     color="black", lw=1.1, zorder=2)
        ax_dots.scatter(np.full(len(selected), column), selected,
                        s=26, color="black", zorder=3)

    ax_dots.set_yticks(np.arange(n_categories))
    ax_dots.set_yticklabels([])
    ax_dots.invert_yaxis()
    ax_dots.set_xticks(x)
    ax_dots.set_xticklabels([str(i + 1) for i in range(n_combinations)], fontsize=8.5)
    ax_dots.set_xlabel("Anomaly Type Combination, Ordered by Frequency", fontsize=11)
    ax_dots.tick_params(axis="y", length=0)
    ax_dots.grid(axis="y", color="0.9", lw=0.6)
    ax_dots.spines[["top", "right", "left"]].set_visible(False)

    set_sizes = Counter()
    for row in rows:
        for name in row["membership"]:
            set_sizes[name] += row["dataset_n"]
    sizes = np.asarray([set_sizes[name] for name in categories])
    y = np.arange(n_categories)
    ax_sets.barh(y, sizes, height=0.55, color=BAR_SINGLE,
                 edgecolor="black", linewidth=0.6)
    ax_sets.invert_yaxis()
    ax_sets.invert_xaxis()
    ax_sets.set_yticks(y)
    ax_sets.set_yticklabels([short(name) for name in categories], fontsize=9.5)
    ax_sets.tick_params(axis="y", length=0, pad=3)
    ax_sets.set_xlabel("Number of Images per Anomaly Type", fontsize=10.5)
    ax_sets.tick_params(labelsize=8.5)
    ax_sets.spines[["top", "left", "right"]].set_visible(False)

    fig.subplots_adjust(left=0.20, right=0.97, bottom=0.13, top=0.94)
    for extension in ("pdf", "png"):
        fig.savefig(f"{stem}.{extension}", dpi=400, bbox_inches="tight")
    plt.close(fig)


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/upset_figures")
    if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
        return Path(__file__).resolve().parent.parent / "checkpoint_data/upset_figures"
    return Path("./upset_figures")


def main():
    parser = argparse.ArgumentParser(description="Create UpSet performance plots")
    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("--m3dm", nargs="+", default=None,
                        help="M3DM per-image CSVs (auto-detected from checkpoint_data/ if omitted)")
    parser.add_argument("--stfpm", nargs="+", default=None,
                        help="STFPM per-image CSVs (auto-detected from checkpoint_data/ if omitted)")
    parser.add_argument("--metric", default="aupro_30")
    parser.add_argument("--top-n", type=int, default=20)
    parser.add_argument("--min-count", type=int, default=5)
    parser.add_argument("--no-ensure-all-types", action="store_true")
    parser.add_argument("--out", default=None,
                        help="Output directory (default: checkpoint_data/upset_figures or ./upset_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)
    groups = exact_groups(memberships)
    all_types = sorted({name for types in memberships.values() for name in types})
    combinations = choose(groups, args.top_n, args.min_count,
                          all_types=all_types,
                          ensure_all_types=not args.no_ensure_all_types)
    if not combinations:
        raise SystemExit("No exact combinations satisfy --min-count")
    categories = sorted({name for membership in combinations for name in membership})

    m3dm_paths = args.m3dm if args.m3dm is not None else find_files(["per_image_aupro_zivid.csv", "per_image_aupro_realsense.csv"])
    stfpm_paths = args.stfpm if args.stfpm is not None else find_files(["per_image_aupro_stfpm.csv"])

    m3dm = load_scores(m3dm_paths, args.metric, "M3DM")
    stfpm = load_scores(stfpm_paths, args.metric, "STFPM")
    paired = set(m3dm) & set(stfpm)
    difference = {key: m3dm[key] - stfpm[key] for key in paired}

    annotation_keys = {key for key, value in memberships.items() if value}
    print(f"M3DM matched annotations : {len(annotation_keys & set(m3dm))}/{len(m3dm)}")
    print(f"STFPM matched annotations: {len(annotation_keys & set(stfpm))}/{len(stfpm)}")
    print(f"Paired images             : {len(paired)}")
    print(f"Observed combinations     : {len(groups)}")
    print(f"Displayed combinations    : {len(combinations)}")
    if not annotation_keys & set(m3dm) or not annotation_keys & set(stfpm):
        raise SystemExit("A method has no score-to-annotation matches")
    if not paired:
        raise SystemExit("No paired M3DM/STFPM images")

    dataset_rows = stats(combinations, groups)
    m3dm_rows = stats(combinations, groups, m3dm)
    stfpm_rows = stats(combinations, groups, stfpm)
    difference_rows = stats(combinations, groups, difference)

    absolute = np.asarray([row["mean"] for row in m3dm_rows + stfpm_rows
                           if np.isfinite(row["mean"])])
    limits = (float(absolute.min()), float(absolute.max()))

    output = Path(args.out) if args.out is not None else default_out_dir()
    output.mkdir(parents=True, exist_ok=True)
    metric_label = args.metric.replace("aupro_", "AUPRO@").replace("_", " ")
    if metric_label.startswith("AUPRO@"):
        metric_label += "%"

    plots = [
        (dataset_rows, output / "01_upset_dataset_wide", None, None, False),
        (m3dm_rows, output / "02_upset_m3dm_performance",
         f"Mean Pixel {metric_label}", limits, False),
        (stfpm_rows, output / "03_upset_stfpm_performance",
         f"Mean Pixel {metric_label}", limits, False),
        (difference_rows, output / "04_upset_m3dm_minus_stfpm",
         f"\u0394 {metric_label} (Positive: M3DM Better)", None, True),
    ]
    for rows, stem, label, scale, is_difference in plots:
        draw(rows, categories, stem, label, scale, is_difference)
        save_values(f"{stem}_values.csv", rows)

    print(f"Wrote 4 UpSet figures as PDF and PNG to {output}")


if __name__ == "__main__":
    main()