#!/usr/bin/env python3 """Create class-specific multiplicity figures from per-class-per-image AUPRO CSVs. The script intersects M3DM/STFPM by (scene, split, image_id, class), so every method comparison uses identical class-specific samples. Dataset-wide uses sample counts only. """ import argparse from pathlib import Path import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns from matplotlib.patches import Patch CLASSES = ['residual_content', 'nuisance_sticker_inside', 'nuisance_gunk', 'nuisance_paper'] KS = list(range(1, 8)) def norm(df, fallback): required = {'scene', 'image_id', 'class', 'multiplicity', 'aupro_30'} missing = required - set(df.columns) if missing: raise SystemExit(f'missing columns: {sorted(missing)}') d = df.copy() if 'split' not in d: d['split'] = 'anomaly' if 'method' not in d: d['method'] = fallback d['scene'] = d['scene'].astype(str).str.zfill(6) d['image_id'] = d['image_id'].astype(str).str.replace(r'\.0$', '', regex=True).str.zfill(5) d['split'] = d['split'].astype(str).str.lower() d['class'] = d['class'].astype(str) d['multiplicity'] = pd.to_numeric(d['multiplicity']).astype(int) d['aupro_30'] = pd.to_numeric(d['aupro_30'], errors='coerce') return d def aggregate(d): return (d.groupby(['method', 'class', 'multiplicity'])['aupro_30'] .agg(Value='mean', n='count', std='std').reset_index()) def pooled_mean(agg): x = agg.assign(total=agg.Value * agg.n) return x.groupby('class').total.sum() / x.groupby('class').n.sum() def class_means(ax, means, ylim, fmt='{:.2f}'): for i, c in enumerate(CLASSES): if c not in means: continue v = float(means[c]) ax.hlines(v, i - .4, i + .4, color='red', linestyle=':', linewidth=3, label='Class Mean' if i == 0 else None) ax.text(i + .3, v + .018 * (ylim[1] - ylim[0]), fmt.format(v), color='red', ha='left', va='center', fontsize=9, fontweight='bold') def finish(ax, ylim, ylabel, handles=None, labels=None, ncol=4): ax.set_xlabel('') ax.set_ylabel(ylabel) ax.set_ylim(*ylim) ax.tick_params(axis='x', rotation=15) for t in ax.get_xticklabels(): t.set_ha('right') if handles is None: handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc='upper left', ncol=ncol, frameon=True, framealpha=.2, facecolor='white', edgecolor='black') def save(fig, stem): fig.tight_layout() fig.savefig(stem.with_suffix('.pdf'), bbox_inches='tight') fig.savefig(stem.with_suffix('.png'), dpi=300, bbox_inches='tight') plt.close(fig) def grouped(agg, means, stem, ylim, method=None): d = agg if method is None else agg[agg.method == method] sns.set_theme(style='whitegrid', font_scale=1.1) fig, ax = plt.subplots(figsize=(14, 5)) sns.barplot(data=d, x='class', y='Value', hue='multiplicity', order=CLASSES, hue_order=KS, palette='viridis', ax=ax) class_means(ax, means, ylim) h, l = ax.get_legend_handles_labels() l = [('1 type' if x == '1' else f'{x} types') if x.isdigit() else x for x in l] finish(ax, ylim, 'Mean Pixel AUPRO Score', h, l, 4) save(fig, stem) def counts(common, stem): unique = common[['scene', 'split', 'image_id', 'class', 'multiplicity']].drop_duplicates() a = (unique.groupby(['class', 'multiplicity']).size().reset_index(name='Value')) means = a.groupby('class').Value.mean() top = max(a.Value.max(), means.max()) * 1.42 sns.set_theme(style='whitegrid', font_scale=1.1) fig, ax = plt.subplots(figsize=(14, 5)) sns.barplot(data=a, x='class', y='Value', hue='multiplicity', order=CLASSES, hue_order=KS, palette='viridis', ax=ax) class_means(ax, means, (0, top), '{:.0f}') h, l = ax.get_legend_handles_labels() l = [('1 type' if x == '1' else f'{x} types') if x.isdigit() else x for x in l] finish(ax, (0, top), 'Number of Images', h, l, 4) save(fig, stem) a.to_csv(stem.with_name(stem.name + '_values.csv'), index=False) def compare_coloured(agg, means, stem, ylim, mode): methods = list(agg.method.drop_duplicates()) d = agg.copy() if mode == 'multiplicity': d['group'] = d.multiplicity.astype(str) + ' ' + d.method order = [f'{k} {m}' for k in KS for m in methods] else: d['group'] = d.method + ' k=' + d.multiplicity.astype(str) order = [f'{m} k={k}' for m in methods for k in KS] order = [x for x in order if x in set(d.group)] pal = {} for x in order: k = int(x.split()[0]) if mode == 'multiplicity' else int(x.rsplit('=', 1)[1]) m = x.split(' ', 1)[1] if mode == 'multiplicity' else x.rsplit(' k=', 1)[0] base = np.array(plt.cm.viridis((k - 1) / 6)[:3]) shade = 1 if m == methods[0] else .55 pal[x] = tuple(base * shade + (1 - shade) * np.ones(3)) sns.set_theme(style='whitegrid', font_scale=1.1) fig, ax = plt.subplots(figsize=(14, 5)) sns.barplot(data=d, x='class', y='Value', hue='group', order=CLASSES, hue_order=order, palette=pal, ax=ax) class_means(ax, means, ylim) finish(ax, ylim, 'Mean Pixel AUPRO Score', ncol=7) save(fig, stem) def geometry(groups, size, within, between, span=.8): block = size + (size - 1) * within total = groups * block + (groups - 1) * between scale = span / total start = -span / 2 out = [] for g in range(groups): for b in range(size): out.append(start + (g * (block + between) + b * (1 + within)) * scale + scale / 2) return np.array(out), scale def compare_spaced(agg, means, stem, ylim, mode): methods = list(agg.method.drop_duplicates()) lookup = {(r['class'], r.multiplicity, r.method): r.Value for _, r in agg.iterrows()} order = [(k, m) for k in KS for m in methods] if mode == 'pair' else [(k, m) for m in methods for k in KS] off, w = geometry(7, 2, .18, .75) if mode == 'pair' else geometry(2, 7, .06, 1.6) colors = {k: plt.cm.viridis((k - 1) / 6) for k in KS} sns.set_theme(style='whitegrid', font_scale=1.1) fig, ax = plt.subplots(figsize=(14, 5)) for ci, c in enumerate(CLASSES): for oi, (k, m) in enumerate(order): v = lookup.get((c, k, m)) if v is not None: ax.bar([ci + off[oi]], [v], width=w, color=colors[k], edgecolor='black', linewidth=.4) ax.set_xticks(range(4), CLASSES) class_means(ax, means, ylim) handles = [Patch(facecolor=colors[k], edgecolor='black', label='1 type' if k == 1 else f'{k} types') for k in KS] handles.append(plt.Line2D([], [], color='red', linestyle=':', linewidth=3, label='Class Mean')) finish(ax, ylim, 'Mean Pixel AUPRO Score', handles, [h.get_label() for h in handles], 4) note = 'left to right within each pair: ' if mode == 'pair' else 'left to right, block by block: ' ax.text(.5, -.30, note + ' → '.join(methods), transform=ax.transAxes, ha='center', va='top', fontsize=9, color='.3') save(fig, stem) def find_file(name): 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), ] for c in candidates: if c.is_file(): return c return None def default_out_dir(): if Path("checkpoint_data").is_dir(): return Path("checkpoint_data/figures_per_class_multiplicity") if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir(): return Path(__file__).resolve().parent.parent / "checkpoint_data/figures_per_class_multiplicity" return Path("./figures_per_class_multiplicity") def main(): p = argparse.ArgumentParser(description="Create class-specific multiplicity figures from per-class CSVs") p.add_argument('--m3dm', default=None, help="Path to per_class_image_aupro.csv (auto-detected if omitted)") p.add_argument('--stfpm', default=None, help="Path to per_class_image_aupro_stfpm.csv (auto-detected if omitted)") p.add_argument('--out', default=None, help="Output directory (default: checkpoint_data/figures_per_class_multiplicity)") a = p.parse_args() m3dm_path = Path(a.m3dm) if a.m3dm else find_file("per_class_image_aupro.csv") stfpm_path = Path(a.stfpm) if a.stfpm else find_file("per_class_image_aupro_stfpm.csv") if not m3dm_path or not m3dm_path.is_file(): raise SystemExit(f"M3DM per-class CSV not found: {m3dm_path}") if not stfpm_path or not stfpm_path.is_file(): raise SystemExit(f"STFPM per-class CSV not found: {stfpm_path}") m = norm(pd.read_csv(m3dm_path), 'M3DM') s = norm(pd.read_csv(stfpm_path), 'STFPM') key = ['scene', 'split', 'image_id', 'class'] m = m[m['class'].isin(CLASSES)] s = s[s['class'].isin(CLASSES)] common = m[key].drop_duplicates().merge(s[key].drop_duplicates(), on=key) m = m.merge(common, on=key) s = s.merge(common, on=key) chk = m[key + ['multiplicity']].merge(s[key + ['multiplicity']], on=key, suffixes=('_m', '_s')) if not (chk.multiplicity_m == chk.multiplicity_s).all(): raise SystemExit('multiplicity mismatch between CSVs') d = pd.concat([m, s], ignore_index=True) agg = aggregate(d) means = pooled_mean(agg) out = Path(a.out) if a.out is not None else default_out_dir() out.mkdir(parents=True, exist_ok=True) top = max(agg.Value.max(), means.max()) * 1.42 ylim = (0, top) counts(m, out / '01_multiplicity_dataset_wide') grouped(agg, agg[agg.method == 'M3DM'].groupby('class')[['Value', 'n']].apply(lambda x: np.average(x.Value, weights=x.n)), out / '02_multiplicity_m3dm', ylim, 'M3DM') grouped(agg, agg[agg.method == 'STFPM'].groupby('class')[['Value', 'n']].apply(lambda x: np.average(x.Value, weights=x.n)), out / '03_multiplicity_stfpm', ylim, 'STFPM') compare_coloured(agg, means, out / '04_multiplicity_compare_by_multiplicity', ylim, 'multiplicity') compare_coloured(agg, means, out / '05_multiplicity_compare_by_method', ylim, 'method') compare_spaced(agg, means, out / '06_multiplicity_paired_spaced', ylim, 'pair') compare_spaced(agg, means, out / '07_multiplicity_blocked_spaced', ylim, 'block') agg.to_csv(out / 'per_class_multiplicity_aggregates.csv', index=False) print(f'M3DM selected rows: {len(m)}') print(f'STFPM selected rows: {len(s)}') print(f'Common class-specific rows per method: {len(common)}') print(f'Wrote 7 figures to {out}') if __name__ == '__main__': main()