File size: 22,268 Bytes
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
 
 
 
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6f22ac
4f3323a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76853d6
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
#!/usr/bin/env python3
"""Create the standalone dataset-wide UpSet diagram for I-BADAS.

This script is self-contained. It does not import plot_difficulty.py and does
not require M3DM or STFPM score files. It reads one or more COCO annotation
files, extracts the retained anomaly classes for every image, selects the most
frequent exact class combinations, and writes:

  01_upset_dataset_wide.pdf
  01_upset_dataset_wide.png
  01_upset_dataset_wide_values.csv

Category selection
------------------
- Exclude `box` and `permanent_mortise` by name.
- Retain `nuisance_dent`, even if its supercategory is `box`.
- Retain every other category whose supercategory is not `box`.

Combination selection
---------------------
The main selection contains the `--top-n` most frequent exact combinations
with at least `--min-count` images. Unless `--no-ensure-all-types` is supplied,
the most frequent combination containing each otherwise-missing anomaly class
is appended. The final combinations are sorted by descending image count.

Example
-------
python plot_upset_dataset_wide.py \
    --coco test \
    --top-n 20 \
    --min-count 5 \
    --out checkpoint_data/upset_figures
"""

from __future__ import annotations

import argparse
import json
import re
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
from matplotlib.patches import Patch
import numpy as np
import pandas as pd


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

COLORS = {
    "yellow": "#48c16e80",
    "teal": "#1e9c8980",
    "purple": "#eae51a80",
    "PASTEL_PURPLE": "#48237480",
}

PAPER_SEQUENTIAL = LinearSegmentedColormap.from_list(
    "paper_sequential",
    [COLORS["PASTEL_PURPLE"], COLORS["teal"],
     COLORS["yellow"], COLORS["purple"]],
    N=256,
)
PAPER_SEQUENTIAL.set_bad("white")

# Bars are taken straight from the palette rather than sampled from the ramp.
# Sampling gave #33af7b, a blend of two palette entries and not a palette
# colour itself.
#
# The palette keys do not describe the colours they hold: COLORS["yellow"] is
# green (#48c16e) and the actual yellow is stored under COLORS["purple"]
# (#eae51a). The keys are used here as they arrive, with the resulting colour
# named in the constant, so the figure shows teal and yellow as intended.
BAR_TEAL = COLORS["teal"]        # #1e9c89
BAR_YELLOW = COLORS["purple"]    # #eae51a, despite the key name

# The class whose presence the two highlight figures mark.
HIGHLIGHT_CLASS = "residual_content"


# ----------------------------------------------------------------------
# Annotation selection and canonical image keys
# ----------------------------------------------------------------------
DROP_SUPERCATEGORIES = {"box"}
DROP_NAMES = {"box", "permanent_mortise"}
FORCE_KEEP_NAMES = {"nuisance_dent"}
ANOMALOUS_SPLITS = {"anomaly", "anomalous", "test_bad", "bad", "defect"}
GOOD_SPLITS = {"good", "normal", "test_good", "ok"}


def canonical_key(path_like, scene_hint=None):
    """Reduce an image path to `(scene, split, sample_id)`.

    Examples
    --------
    COCO image path:
      anomaly/rgb/00001.png + scene hint 000004
      -> (000004, anomaly, 00001)

    Returns None when a scene or numeric sample ID cannot be resolved.
    """
    parts = [part for part in re.split(r"[\\/]+", str(path_like)) if part]
    if scene_hint is not None:
        parts = [str(scene_hint)] + parts

    scene = None
    scene_at = None
    for index, part in enumerate(parts):
        match = re.search(r"(\d{4,6})", part)
        if match:
            scene = match.group(1).zfill(6)
            scene_at = index
            break
    if scene is None:
        return None

    split = "unknown"
    for part in parts[scene_at + 1:]:
        low = part.lower()
        if low in ANOMALOUS_SPLITS:
            split = "anomaly"
            break
        if low in GOOD_SPLITS:
            split = "good"
            break

    stem = Path(parts[-1]).stem
    if re.fullmatch(r"\d+", stem):
        sample = stem.zfill(5)
    else:
        sample = None
        ignored = ANOMALOUS_SPLITS | GOOD_SPLITS | {"rgb", "xyz", "depth"}
        for part in parts[scene_at + 1:]:
            if part.lower() not in ignored and re.fullmatch(r"\d+", part):
                sample = part.zfill(5)
                break
        if sample is None:
            return None

    return scene, split, sample


def coco_files(entries, pattern):
    """Resolve COCO files from explicit files and recursively searched folders."""
    found = []
    for entry in entries:
        path = Path(entry)
        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 load_annotations(coco_paths, verbose=True):
    """Return `{canonical_key: set(anomaly class names)}`."""
    per_image = {}
    supercategories = defaultdict(set)
    unresolved_images = 0

    for path in coco_paths:
        with open(path, "r", encoding="utf-8") as handle:
            coco = json.load(handle)

        scene_hint = Path(path).parent.name
        id_to_name = {}
        keep_ids = set()

        for category in coco["categories"]:
            category_id = category["id"]
            name = str(category["name"]).strip()
            supercategory = str(category.get("supercategory", "")).strip()
            id_to_name[category_id] = name
            supercategories[name].add(supercategory)

            if name in DROP_NAMES:
                continue
            if name in FORCE_KEEP_NAMES or supercategory not in DROP_SUPERCATEGORIES:
                keep_ids.add(category_id)

        image_keys = {}
        for image in coco["images"]:
            key = canonical_key(image["file_name"], scene_hint=scene_hint)
            if key is None:
                unresolved_images += 1
                continue
            image_keys[image["id"]] = key
            per_image.setdefault(key, set())

        for annotation in coco["annotations"]:
            category_id = annotation["category_id"]
            if category_id not in keep_ids:
                continue
            key = image_keys.get(annotation["image_id"])
            if key is not None:
                per_image[key].add(id_to_name[category_id])

    inconsistent = {
        name: sorted(values)
        for name, values in supercategories.items()
        if len(values) > 1
    }

    if verbose:
        dropped = sorted(
            name for name, values in supercategories.items()
            if name in DROP_NAMES
            or (name not in FORCE_KEEP_NAMES
                and bool(values & DROP_SUPERCATEGORIES))
        )
        print(f"annotation files read : {len(coco_paths)}")
        print(f"images with types     : {sum(bool(v) for v in per_image.values())}")
        print(f"excluded categories   : {', '.join(dropped) or 'none'}")
        if unresolved_images:
            print(f"! unresolved image paths: {unresolved_images}", file=sys.stderr)
        if inconsistent:
            print(
                f"! supercategory differs across files: {inconsistent}",
                file=sys.stderr,
            )

    return per_image


# ----------------------------------------------------------------------
# Exact combinations
# ----------------------------------------------------------------------
def exact_groups(memberships):
    """Group image keys by their exact sorted anomaly-class combination."""
    groups = defaultdict(list)
    for key, anomaly_types in memberships.items():
        membership = tuple(sorted(anomaly_types))
        if membership:
            groups[membership].append(key)
    return groups


def choose(groups, top_n, min_count, all_types=None, ensure_all_types=False):
    """Select combinations by frequency and optionally retain every class.

    The initial selection contains the top-N combinations having at least
    `min_count` images. When `ensure_all_types` is true, any class absent from
    those combinations contributes its most frequent available combination.
    Those top-ups are allowed below `min_count`, and their true count remains
    visible in the final figure.
    """
    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 ensure_all_types and all_types:
        ranked = sorted(
            groups.items(),
            key=lambda item: (-len(item[1]), len(item[0]), item[0]),
        )
        covered = {name for membership in chosen for name in membership}

        for name in [value for value in all_types if value not in covered]:
            if name in {item for membership in chosen for item in membership}:
                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_missing = [
            value for value in all_types
            if value not in {item for membership in chosen for item in membership}
        ]
        if still_missing:
            print(
                f"! no combination found for: {', '.join(still_missing)}",
                file=sys.stderr,
            )

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


def combination_rows(combinations, groups):
    """Create plotting records for the selected exact combinations."""
    return [
        {
            "membership": membership,
            "dataset_n": len(groups[membership]),
        }
        for membership in combinations
    ]


def save_values(path, rows):
    records = []
    for rank, row in enumerate(rows, start=1):
        n_types = len(row["membership"])
        present = HIGHLIGHT_CLASS in row["membership"]
        records.append({
            "rank": rank,
            "combination": " + ".join(row["membership"]),
            "n_types": n_types,
            "dataset_n": row["dataset_n"],
            f"has_{HIGHLIGHT_CLASS}": int(present),
            # the exact fraction drawn in yellow in the share figure; not
            # rounded, so the CSV reproduces the plotted segment precisely
            "highlight_share": (1.0 / n_types) if present else 0.0,
        })
    pd.DataFrame(records).to_csv(path, index=False)


# ----------------------------------------------------------------------
# Plotting
# ----------------------------------------------------------------------
def draw(rows, categories, stem, highlight="whole"):
    """Draw the dataset-wide UpSet-style count figure.

    highlight
      "whole" : a bar is entirely yellow when its combination contains
                HIGHLIGHT_CLASS, teal otherwise.
      "share" : every bar is teal, with a yellow segment on top covering the
                share of the combination's anomaly types that HIGHLIGHT_CLASS
                accounts for. A five-type combination containing it therefore
                shows one fifth of the bar in yellow.

    The yellow segment in "share" is a share of the combination's TYPES, not of
    its images: all the images in that bar contain the class. It shows how much
    of the combination the class makes up, which is why a one-type combination
    is fully yellow.
    """
    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))

    # The third column is retained as empty space so the bar panel and dot
    # matrix keep the same x geometry as the manuscript version.
    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_empty = fig.add_subplot(grid[0, 2])
    ax_empty.axis("off")

    # Top bars: number of images in each exact combination.
    has_class = np.asarray(
        [HIGHLIGHT_CLASS in row["membership"] for row in rows]
    )

    if highlight == "share":
        # Yellow sits on top, sized to the class's share of the combination's
        # types. Drawn as two stacked segments so the total height is still the
        # image count.
        shares = np.asarray([
            (1.0 / len(row["membership"])) if HIGHLIGHT_CLASS in row["membership"]
            else 0.0
            for row in rows
        ])
        upper = counts * shares
        lower = counts - upper
        ax_bars.bar(
            x, lower, width=0.72, color=BAR_TEAL,
            edgecolor="black", linewidth=0.6,
        )
        ax_bars.bar(
            x, upper, width=0.72, bottom=lower, color=BAR_YELLOW,
            edgecolor="black", linewidth=0.6,
        )
    else:
        ax_bars.bar(
            x,
            counts,
            width=0.72,
            color=np.where(has_class, BAR_YELLOW, BAR_TEAL),
            edgecolor="black",
            linewidth=0.6,
        )

    for index, row in enumerate(rows):
        ax_bars.text(
            index,
            counts[index],
            str(row["dataset_n"]),
            ha="center",
            va="bottom",
            fontsize=7.5,
            color="black",
        )

    # The encoding is not self-evident, so it is named on the figure.
    if highlight == "share":
        yellow_label = "share of types that are non_empty"
        teal_label = "remaining anomaly types"
    else:
        yellow_label = "non_empty"
        teal_label = "empty_dirty"
    ax_bars.legend(
        handles=[
            Patch(facecolor=BAR_YELLOW, edgecolor="black", linewidth=0.6,
                  label=yellow_label),
            Patch(facecolor=BAR_TEAL, edgecolor="black", linewidth=0.6,
                  label=teal_label),
        ],
        loc="upper right",
        fontsize=9,
        frameon=True,
        framealpha=0.85,
        facecolor="white",
        edgecolor="0.7",
    )

    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))

    # Dot matrix: exact anomaly classes forming every combination.
    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(index + 1) for index 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)

    # Left bars: image count for each anomaly class within the displayed
    # combinations. These are not the full-dataset class totals when only a
    # subset of combinations is displayed.
    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)
    # Same two colours here, so the highlighted class is identifiable in both
    # panels of the figure.
    ax_sets.barh(
        y,
        sizes,
        height=0.55,
        color=[BAR_YELLOW if name == HIGHLIGHT_CLASS else BAR_TEAL
               for name in categories],
        edgecolor="black",
        linewidth=0.6,
    )
    ax_sets.invert_yaxis()
    ax_sets.invert_xaxis()
    ax_sets.set_yticks(y)
    ax_sets.set_yticklabels(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)

    # No title: the figure caption carries the description.
    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("datasets"),
        Path("../datasets"),
        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 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()
    parser.add_argument(
        "--coco",
        nargs="+",
        default=None,
        help="COCO annotation files or directories to search recursively (auto-detected if omitted)",
    )
    parser.add_argument(
        "--coco-pattern",
        default="annotations*.coco.json",
        help="filename/glob pattern used inside directories",
    )
    parser.add_argument(
        "--top-n",
        type=int,
        default=20,
        help="number of most frequent exact combinations before class top-ups",
    )
    parser.add_argument(
        "--min-count",
        type=int,
        default=5,
        help="minimum count for the initial top-N ranking",
    )
    parser.add_argument(
        "--no-ensure-all-types",
        action="store_true",
        help="do not append combinations needed to show otherwise-missing classes",
    )
    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} with pattern '{args.coco_pattern}'."
        )

    memberships = load_annotations(annotations)
    groups = exact_groups(memberships)
    if not groups:
        raise SystemExit("No retained anomaly combinations were found.")

    all_types = sorted({
        name
        for anomaly_types in memberships.values()
        for name in anomaly_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 the selection. "
            "Reduce --min-count or increase --top-n."
        )

    categories = sorted({
        name
        for membership in combinations
        for name in membership
    })
    rows = combination_rows(combinations, groups)

    output = Path(args.out) if args.out is not None else default_out_dir()
    output.mkdir(parents=True, exist_ok=True)

    figures = [
        ("01_upset_dataset_wide_residual_whole", "whole"),
        ("02_upset_dataset_wide_residual_share", "share"),
    ]
    for name, mode in figures:
        draw(rows, categories, output / name, highlight=mode)

    save_values(output / "upset_dataset_wide_values.csv", rows)

    with_class = sum(
        1 for row in rows if HIGHLIGHT_CLASS in row["membership"]
    )
    images_with_class = sum(
        row["dataset_n"] for row in rows
        if HIGHLIGHT_CLASS in row["membership"]
    )

    print(f"Observed exact combinations : {len(groups)}")
    print(f"Displayed combinations      : {len(combinations)}")
    print(f"Displayed anomaly classes   : {len(categories)}")
    print(f"Combinations with {HIGHLIGHT_CLASS}: {with_class} "
          f"({images_with_class} images)")
    print(f"Wrote 2 dataset-wide UpSet figures to {output}")
    for name, mode in figures:
        print(f"  {name}.pdf / .png   ({mode})")
    print("  upset_dataset_wide_values.csv")


if __name__ == "__main__":
    main()