#!/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()