i-badas / scripts /plot_difficulty.py
moiaraya's picture
modify data and scripts
b6f22ac
Raw History Blame Contribute Delete
23.7 kB
#!/usr/bin/env python3
"""
Anomaly-type difficulty matrices for I-BADAS.
Joins per-image AUPRO (M3DM multimodal, STFPM RGB) to the anomaly-type sets
taken from the COCO annotation files, then writes ten standalone figures:
fig01_matrix_m3dm mean AUPRO per anomaly-type combination
fig02_matrix_stfpm same, RGB baseline
fig03_matrix_combined mean of the two methods, per image
fig04_matrix_m3dm_minus_stfpm paired difference
fig05_matrix_stfpm_minus_m3dm paired difference, sign flipped
fig06_multiplicity_m3dm AUPRO vs number of co-occurring types
fig07_multiplicity_stfpm
fig08_multiplicity_combined
fig09_multiplicity_m3dm_minus_stfpm paired difference vs multiplicity
fig10_multiplicity_stfpm_minus_m3dm
Each figure is written as PDF (vector, for the paper) and PNG, and every
underlying matrix is written as CSV so the numbers in the caption can be
checked without re-reading the figure.
Join key
--------
The three sources spell the same image differently:
COCO file_name 'anomaly/rgb/00001.png' + scene from the folder
M3DM image_id '000006/good/00015/rgb.png'
STFPM image_key '000004_zivid_darkblue/anomaly/rgb/00001.png'
so all three are reduced to a canonical (scene number, split, sample id)
triple. Unmatched keys are reported rather than silently dropped.
Category selection
------------------
'box' and 'permanent_mortise' are excluded by name. nuisance_dent is kept
even though its supercategory is 'box'. Everything else with supercategory
'nuisance' or 'object' is kept. Category names are shown verbatim, including
underscores.
Usage
-----
python plot_difficulty.py
python plot_difficulty.py \
--coco test \
--m3dm checkpoint_data/per_image_aupro_zivid.csv checkpoint_data/per_image_aupro_realsense.csv \
--stfpm checkpoint_data/per_image_aupro_stfpm.csv \
--out checkpoint_data/difficulty_figures
"""
from __future__ import annotations
import argparse
import re
import sys
from collections import Counter, defaultdict
from itertools import combinations
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
plt.rcParams.update({
"font.family": "serif",
"font.serif": ["Times New Roman", "DejaVu Serif"],
"font.size": 8,
"axes.linewidth": 0.6,
"pdf.fonttype": 42, # editable text in the PDF
})
# Transparent paper palette
COLORS = {
"yellow": "#48c16e80",
"teal": "#1e9c8980",
"purple": "#eae51a80",
"PASTEL_PURPLE": "#48237480",
}
# Sequential ramp for absolute metrics, dark to light.
PAPER_SEQUENTIAL = LinearSegmentedColormap.from_list(
"paper_sequential",
[COLORS["PASTEL_PURPLE"], COLORS["teal"], COLORS["yellow"], COLORS["purple"]],
N=256,
)
# Zero-centred ramp for paired differences.
PAPER_DIVERGING = LinearSegmentedColormap.from_list(
"paper_diverging",
[COLORS["PASTEL_PURPLE"], COLORS["purple"], COLORS["teal"]],
N=256,
)
for _cmap in (PAPER_SEQUENTIAL, PAPER_DIVERGING):
_cmap.set_bad("white")
# 'box' and 'permanent_mortise' are container structure and are excluded by name
DROP_SUPERCATEGORIES = {"box"}
DROP_NAMES = {"box", "permanent_mortise"}
FORCE_KEEP_NAMES = {"nuisance_dent"}
ANOMALOUS_SPLITS = {"anomaly", "anomalous", "test_bad", "bad", "defect"}
# ----------------------------------------------------------------------
# Canonical image key
# ----------------------------------------------------------------------
def canonical_key(path_like, scene_hint=None):
"""Reduce any of the path spellings to (scene, split, sample_id)."""
parts = [p for p in re.split(r"[\\/]+", str(path_like)) if p]
if scene_hint is not None:
parts = [str(scene_hint)] + parts
scene = None
scene_at = None
for i, part in enumerate(parts):
m = re.search(r"(\d{4,6})", part)
if m:
scene = m.group(1).zfill(6)
scene_at = i
break
if scene is None:
return None
split = None
for part in parts[scene_at + 1:]:
low = part.lower()
if low in ANOMALOUS_SPLITS:
split = "anomaly"
break
if low in {"good", "normal", "test_good", "ok"}:
split = "good"
break
if split is None:
split = "unknown"
stem = Path(parts[-1]).stem
if re.fullmatch(r"\d+", stem):
sample = stem.zfill(5)
else:
sample = None
after = [p for p in parts[scene_at + 1:] if p.lower() not in
ANOMALOUS_SPLITS | {"good", "normal", "test_good", "ok", "rgb", "xyz", "depth"}]
for part in after:
if re.fullmatch(r"\d+", part):
sample = part.zfill(5)
break
if sample is None:
return None
return (scene, split, sample)
# ----------------------------------------------------------------------
# Annotations
# ----------------------------------------------------------------------
def load_annotations(coco_paths, verbose=True):
"""Return {canonical_key: set(type names)} for anomalous images."""
import json
per_image = {}
supercats = defaultdict(set)
n_files = 0
for path in coco_paths:
with open(path, "r", encoding="utf-8") as f:
coco = json.load(f)
n_files += 1
scene_hint = Path(path).parent.name
id2name, keep_ids = {}, set()
for c in coco["categories"]:
name = str(c["name"]).strip()
sc = str(c.get("supercategory", "")).strip()
id2name[c["id"]] = name
supercats[name].add(sc)
if name in DROP_NAMES:
continue
if name in FORCE_KEEP_NAMES or sc not in DROP_SUPERCATEGORIES:
keep_ids.add(c["id"])
img_key = {}
for img in coco["images"]:
key = canonical_key(img["file_name"], scene_hint=scene_hint)
if key is None:
continue
img_key[img["id"]] = key
per_image.setdefault(key, set())
for ann in coco["annotations"]:
if ann["category_id"] not in keep_ids:
continue
key = img_key.get(ann["image_id"])
if key is not None:
per_image[key].add(id2name[ann["category_id"]])
inconsistent = {n: sorted(s) for n, s in supercats.items() if len(s) > 1}
if verbose:
dropped = sorted(n for n, s in supercats.items()
if n in DROP_NAMES
or (n not in FORCE_KEEP_NAMES and s & DROP_SUPERCATEGORIES))
print(f" annotation files read : {n_files}")
print(f" images with types : {sum(1 for v in per_image.values() if v)}")
print(f" excluded categories : {', '.join(dropped) or 'none'}")
if inconsistent:
print(f" ! supercategory differs across files: {inconsistent}",
file=sys.stderr)
return per_image
# ----------------------------------------------------------------------
# Per-image AUPRO
# ----------------------------------------------------------------------
def load_scores(csv_paths, metric, label, verbose=True):
"""Return {canonical_key: mean metric} averaged over runs/methods/sensors."""
frames = []
for path in csv_paths:
df = pd.read_csv(path)
frames.append(df)
if not frames:
return {}
df = pd.concat(frames, ignore_index=True)
id_col = None
for candidate in ("image_key", "image_id", "original_path"):
if candidate in df.columns:
id_col = candidate
break
if id_col is None:
raise SystemExit(f"{label}: no image identity column found in {csv_paths}")
if metric not in df.columns:
raise SystemExit(f"{label}: metric {metric!r} not in {list(df.columns)}")
df["_key"] = df[id_col].map(canonical_key)
unresolved = int(df["_key"].isna().sum())
df = df[df["_key"].notna()]
grouped = df.groupby("_key")[metric].agg(["mean", "count"])
scores = grouped["mean"].to_dict()
if verbose:
print(f" {label}: {len(df)} rows -> {len(scores)} unique images "
f"(mean {grouped['count'].mean():.1f} rows/image)")
if unresolved:
print(f" ! {label}: {unresolved} rows had an unparsable image key",
file=sys.stderr)
anomalous = sum(1 for k in scores if k[1] == "anomaly")
if anomalous < len(scores):
print(f" ! {label}: {len(scores) - anomalous} images are not in an "
f"'anomaly' split but carry a score", file=sys.stderr)
return scores
# ----------------------------------------------------------------------
# Matrix construction
# ----------------------------------------------------------------------
def build_matrix(per_image, scores, categories):
n = len(categories)
idx = {c: i for i, c in enumerate(categories)}
total = np.zeros((n, n))
count = np.zeros((n, n), dtype=int)
exact_total = np.zeros((n, n))
exact_count = np.zeros((n, n), dtype=int)
for key, types in per_image.items():
if key not in scores:
continue
types = {t for t in types if t in idx}
if not types:
continue
value = scores[key]
for t in types:
i = idx[t]
total[i, i] += value
count[i, i] += 1
for a, b in combinations(sorted(types), 2):
i, j = idx[a], idx[b]
total[i, j] += value; total[j, i] += value
count[i, j] += 1; count[j, i] += 1
if len(types) == 2:
exact_total[i, j] += value; exact_total[j, i] += value
exact_count[i, j] += 1; exact_count[j, i] += 1
with np.errstate(invalid="ignore", divide="ignore"):
mean = np.where(count > 0, total / np.maximum(count, 1), np.nan)
exact_mean = np.where(exact_count > 0,
exact_total / np.maximum(exact_count, 1), np.nan)
return mean, count, exact_mean, exact_count
def multiplicity_stats(per_image, scores, categories):
keep = set(categories)
buckets = defaultdict(list)
for key, types in per_image.items():
if key not in scores:
continue
k = len({t for t in types if t in keep})
if k >= 1:
buckets[k].append(scores[key])
ks = sorted(buckets)
return (np.array(ks),
np.array([np.mean(buckets[k]) for k in ks]),
np.array([np.std(buckets[k], ddof=1) if len(buckets[k]) > 1 else 0.0
for k in ks]),
np.array([len(buckets[k]) for k in ks]))
# ----------------------------------------------------------------------
# Plotting
# ----------------------------------------------------------------------
def short(name):
return name.replace("nuisance_", "").replace("_", " ")
def plot_matrix(mean, count, categories, cbar_label, out_stem,
min_n, diverging_zero=False, vlim=None):
n = len(categories)
show = np.where(count >= min_n, mean, np.nan)
valid = show[np.isfinite(show)]
if valid.size == 0:
print(f" ! {out_stem}: every cell below min_n={min_n}, skipped",
file=sys.stderr)
return None
if vlim is not None:
vmin, vmax = vlim
elif diverging_zero:
m = np.nanmax(np.abs(valid))
vmin, vmax = -m, m
else:
centre = float(np.nanmean(valid))
spread = float(np.nanmax(np.abs(valid - centre)))
vmin, vmax = centre - spread, centre + spread
fig, ax = plt.subplots(figsize=(7.4, 6.2))
cmap = (PAPER_DIVERGING if diverging_zero else PAPER_SEQUENTIAL).copy()
cmap.set_bad("white")
im = ax.imshow(np.ma.masked_invalid(show), cmap=cmap, vmin=vmin, vmax=vmax)
for i in range(n):
for j in range(n):
if count[i, j] < min_n:
if count[i, j] > 0:
ax.text(j, i, f"{count[i, j]}", ha="center", va="center",
fontsize=4.8, color="black", zorder=5)
continue
ax.text(j, i, f"{mean[i, j]:.2f}\n{count[i, j]}",
ha="center", va="center", fontsize=5.4, linespacing=1.05,
color="black", zorder=5)
labels = list(categories)
ax.set_xticks(range(n)); ax.set_yticks(range(n))
ax.set_xticklabels(labels, rotation=50, ha="right", fontsize=6.5)
ax.set_yticklabels(labels, fontsize=6.5)
ax.set_xticks(np.arange(-.5, n, 1), minor=True)
ax.set_yticks(np.arange(-.5, n, 1), minor=True)
ax.grid(which="minor", color="0.82", linewidth=0.7)
ax.tick_params(which="minor", length=0)
ax.set_axisbelow(True)
cb = fig.colorbar(im, ax=ax, fraction=0.045, pad=0.03, shrink=0.72)
cb.set_label(cbar_label, fontsize=7.5)
cb.ax.tick_params(labelsize=6.5)
cb.outline.set_linewidth(0.6)
fig.tight_layout()
for ext in ("pdf", "png"):
fig.savefig(f"{out_stem}.{ext}", dpi=400, bbox_inches="tight")
plt.close(fig)
return (vmin, vmax)
def plot_multiplicity(series, ylabel, out_stem, zero_line=False):
fig, ax = plt.subplots(figsize=(5.0, 3.7))
for label, (ks, mu, sd, ns) in series.items():
if ks.size == 0:
continue
sem = np.divide(sd, np.sqrt(np.maximum(ns, 1)))
ax.errorbar(ks, mu, yerr=sem, marker="none", lw=1.4, capsize=2.5,
color="0.45", zorder=2, label=label)
grade = (ks - ks.min()) / max(ks.max() - ks.min(), 1)
ax.scatter(ks, mu, s=42, c=[PAPER_SEQUENTIAL(g) for g in grade],
edgecolor="black", linewidth=0.5, zorder=3)
for k, m, e, nn in zip(ks, mu, sem, ns):
ax.annotate(f"{nn}", (k, m + e), textcoords="offset points",
xytext=(0, 6), ha="center", fontsize=5.6, color="black")
if zero_line:
ax.axhline(0.0, color="black", lw=0.8, ls="--", zorder=0)
ax.set_xlabel("Distinct Anomaly Types Present", fontsize=8.5)
ax.set_ylabel(ylabel, fontsize=8.5)
all_ks = sorted({int(k) for ks, *_ in series.values() for k in ks})
if all_ks:
ax.set_xticks(all_ks)
ax.tick_params(labelsize=7.5)
ax.margins(y=0.13)
for s_ in ("top", "right"):
ax.spines[s_].set_visible(False)
if len(series) > 1:
ax.legend(fontsize=7.5, frameon=False)
fig.tight_layout()
for ext in ("pdf", "png"):
fig.savefig(f"{out_stem}.{ext}", dpi=400, bbox_inches="tight")
plt.close(fig)
def save_matrix_csv(path, mean, count, categories):
rows = []
for i, a in enumerate(categories):
for j, b in enumerate(categories):
if j < i:
continue
rows.append({"type_i": a, "type_j": b,
"kind": "single" if i == j else "pair",
"mean": mean[i, j], "n": int(count[i, j])})
pd.DataFrame(rows).to_csv(path, index=False)
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/difficulty_figures")
if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
return Path(__file__).resolve().parent.parent / "checkpoint_data/difficulty_figures"
return Path("./difficulty_figures")
# ----------------------------------------------------------------------
def main():
p = argparse.ArgumentParser(description="Anomaly-type difficulty matrices and multiplicity plots")
p.add_argument("--coco", nargs="+", default=None,
help="annotation files, or a directory to search (auto-detected if omitted)")
p.add_argument("--coco-pattern", default="annotations*.coco.json")
p.add_argument("--m3dm", nargs="*", default=None,
help="M3DM per-image CSVs (auto-detected from checkpoint_data/ if omitted)")
p.add_argument("--stfpm", nargs="*", default=None,
help="STFPM per-image CSVs (auto-detected from checkpoint_data/ if omitted)")
p.add_argument("--metric", default="aupro_30")
p.add_argument("--min-n", type=int, default=20)
p.add_argument("--out", default=None,
help="output directory (default: checkpoint_data/difficulty_figures or ./difficulty_figures)")
a = p.parse_args()
coco_entries = a.coco if a.coco is not None else default_coco_search()
coco_paths = []
for entry in coco_entries:
path = Path(entry)
coco_paths.extend(sorted(str(q) for q in path.rglob(a.coco_pattern))
if path.is_dir() else [str(path)])
if not coco_paths:
raise SystemExit(f"No annotation files found in {coco_entries}")
m3dm_paths = a.m3dm if a.m3dm is not None else find_files(["per_image_aupro_zivid.csv", "per_image_aupro_realsense.csv"])
stfpm_paths = a.stfpm if a.stfpm is not None else find_files(["per_image_aupro_stfpm.csv"])
out = Path(a.out) if a.out is not None else default_out_dir()
out.mkdir(parents=True, exist_ok=True)
print("Annotations")
per_image = load_annotations(coco_paths)
print("\nPer-image scores")
m3dm = load_scores(m3dm_paths, a.metric, "M3DM") if m3dm_paths else {}
stfpm = load_scores(stfpm_paths, a.metric, "STFPM") if stfpm_paths else {}
if not m3dm and not stfpm:
raise SystemExit("no per-image score files given or found")
ann_keys = {k for k, v in per_image.items() if v}
print("\nJoin")
for label, sc in (("M3DM", m3dm), ("STFPM", stfpm)):
if not sc:
continue
matched = ann_keys & set(sc)
print(f" {label}: {len(matched)} of {len(sc)} scored images matched "
f"an annotated image with >=1 anomaly type")
if not matched:
print(f" ! {label}: nothing matched.", file=sys.stderr)
paired = {k: 0.5 * (m3dm[k] + stfpm[k]) for k in set(m3dm) & set(stfpm)}
diff = {k: m3dm[k] - stfpm[k] for k in set(m3dm) & set(stfpm)}
print(f" images scored by both methods: {len(paired)}")
categories = sorted({t for k in ann_keys for t in per_image[k]})
print(f"\n{len(categories)} anomaly types: {', '.join(categories)}")
made = []
absolute = {}
for label, sc in (("M3DM", m3dm), ("STFPM", stfpm), ("Combined", paired)):
if sc:
absolute[label] = build_matrix(per_image, sc, categories)
pool = []
for label in ("M3DM", "STFPM"):
if label in absolute:
mean, count, *_ = absolute[label]
pool.append(mean[count >= a.min_n])
shared = None
if pool:
vals = np.concatenate(pool)
vals = vals[np.isfinite(vals)]
if vals.size:
centre = float(vals.mean())
spread = float(np.abs(vals - centre).max())
shared = (centre - spread, centre + spread)
metric_label = a.metric.replace("aupro_", "AUPRO@").replace("_", " ")
if metric_label.startswith("AUPRO@"):
metric_label += "%"
spec = [
("fig01_matrix_m3dm", "M3DM"),
("fig02_matrix_stfpm", "STFPM"),
("fig03_matrix_combined", "Combined"),
]
for stem, label in spec:
if label not in absolute:
continue
mean, count, exact_mean, exact_count = absolute[label]
plot_matrix(mean, count, categories,
f"Mean {metric_label}", str(out / stem), a.min_n,
vlim=shared if label != "Combined" else None)
save_matrix_csv(out / f"{stem}_values.csv", mean, count, categories)
save_matrix_csv(out / f"{stem}_exactpairs.csv", exact_mean,
exact_count, categories)
made.append(stem)
if diff:
dm, dc, dem, dec = build_matrix(per_image, diff, categories)
plot_matrix(dm, dc, categories,
f"Δ {metric_label} (Positive: M3DM Better)",
str(out / "fig04_matrix_m3dm_minus_stfpm"), a.min_n,
diverging_zero=True)
save_matrix_csv(out / "fig04_matrix_m3dm_minus_stfpm_values.csv",
dm, dc, categories)
plot_matrix(-dm, dc, categories,
f"Δ {metric_label} (Positive: STFPM Better)",
str(out / "fig05_matrix_stfpm_minus_m3dm"), a.min_n,
diverging_zero=True)
save_matrix_csv(out / "fig05_matrix_stfpm_minus_m3dm_values.csv",
-dm, dc, categories)
made += ["fig04_matrix_m3dm_minus_stfpm", "fig05_matrix_stfpm_minus_m3dm"]
mult = {}
for label, sc in (("M3DM", m3dm), ("STFPM", stfpm), ("Combined", paired)):
if sc:
mult[label] = multiplicity_stats(per_image, sc, categories)
for stem, label in (("fig06_multiplicity_m3dm", "M3DM"),
("fig07_multiplicity_stfpm", "STFPM"),
("fig08_multiplicity_combined", "Combined")):
if label not in mult:
continue
plot_multiplicity({label: mult[label]},
f"Mean {metric_label}", str(out / stem))
ks, mu, sd, ns = mult[label]
pd.DataFrame({"n_types": ks, "mean": mu, "std": sd, "n_images": ns}) \
.to_csv(out / f"{stem}_values.csv", index=False)
made.append(stem)
if diff:
dstats = multiplicity_stats(per_image, diff, categories)
plot_multiplicity({"difference": dstats},
f"Δ {metric_label} (Positive: M3DM Better)",
str(out / "fig09_multiplicity_m3dm_minus_stfpm"),
zero_line=True)
ks, mu, sd, ns = dstats
pd.DataFrame({"n_types": ks, "mean": mu, "std": sd, "n_images": ns}) \
.to_csv(out / "fig09_multiplicity_m3dm_minus_stfpm_values.csv",
index=False)
flipped = (dstats[0], -dstats[1], dstats[2], dstats[3])
plot_multiplicity({"difference": flipped},
f"Δ {metric_label} (Positive: STFPM Better)",
str(out / "fig10_multiplicity_stfpm_minus_m3dm"),
zero_line=True)
ks, mu, sd, ns = flipped
pd.DataFrame({"n_types": ks, "mean": mu, "std": sd, "n_images": ns}) \
.to_csv(out / "fig10_multiplicity_stfpm_minus_m3dm_values.csv",
index=False)
made += ["fig09_multiplicity_m3dm_minus_stfpm",
"fig10_multiplicity_stfpm_minus_m3dm"]
print(f"\nWrote {len(made)} figures (PDF + PNG) and underlying CSVs to {out}")
if __name__ == "__main__":
main()