File size: 10,561 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
#!/usr/bin/env python3
"""Full exact-combination atlas."""
import argparse
from collections import defaultdict
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, Normalize, TwoSlopeNorm
import numpy as np
import pandas as pd
from plot_difficulty import load_annotations, load_scores

FORBIDDEN={'box','permanent_mortise','nuisance_dent'}

def find_coco(entries, pattern):
    out = []
    for item in entries:
        p = Path(item)
        out.extend(p.rglob(pattern) if p.is_dir() else [p])
    return sorted(set(str(p) for p in out if p.is_file()))

def groups_from(memberships, min_count):
    g = defaultdict(list)
    for key, types in memberships.items():
        combo = tuple(sorted(set(types) - FORBIDDEN))
        if combo:
            g[combo].append(key)
    return {k: v for k, v in g.items() if len(v) >= min_count}

def summarize(groups, m3dm, stfpm):
    diff = {k: m3dm[k] - stfpm[k] for k in set(m3dm) & set(stfpm)}
    rows = []
    for combo, keys in groups.items():
        def stat(scores):
            x = np.array([scores[k] for k in keys if k in scores], float)
            return (float(x.mean()) if len(x) else np.nan,
                    float(x.std(ddof=1)) if len(x) > 1 else 0., len(x))
        mm, ms, mn = stat(m3dm)
        sm, ss, sn = stat(stfpm)
        dm, ds, dn = stat(diff)
        rows.append(dict(combo=combo, n_types=len(combo), dataset_n=len(keys),
            m3dm_mean=mm, m3dm_std=ms, m3dm_n=mn, stfpm_mean=sm, stfpm_std=ss,
            stfpm_n=sn, diff_mean=dm, diff_std=ds, paired_n=dn))
    rows.sort(key=lambda r: (r['n_types'], -r['dataset_n'], r['combo']))
    return rows

def short(s):
    return s.replace('nuisance_', '').replace('_', ' ')

def save_csv(path, rows, categories):
    out = []
    for rank, r in enumerate(rows, 1):
        d = {'rank': rank, 'combination': ' + '.join(r['combo']), 'n_types': r['n_types'],
             'dataset_n': r['dataset_n'], 'm3dm_mean': r['m3dm_mean'],
             'm3dm_std': r['m3dm_std'], 'm3dm_n': r['m3dm_n'],
             'stfpm_mean': r['stfpm_mean'], 'stfpm_std': r['stfpm_std'],
             'stfpm_n': r['stfpm_n'], 'm3dm_minus_stfpm': r['diff_mean'],
             'difference_std': r['diff_std'], 'paired_n': r['paired_n']}
        d.update({f'has_{c}': int(c in r['combo']) for c in categories})
        out.append(d)
    pd.DataFrame(out).to_csv(path, index=False)

def draw(rows, categories, metric, stem):
    nr, nc = len(rows), len(categories)
    y = np.arange(nr)
    mem = np.array([[c in r['combo'] for c in categories] for r in rows], int)
    counts = np.array([r['dataset_n'] for r in rows])
    m = np.array([r['m3dm_mean'] for r in rows])
    s = np.array([r['stfpm_mean'] for r in rows])
    d = np.array([r['diff_mean'] for r in rows])
    pn = np.array([r['paired_n'] for r in rows])
    absolute = np.r_[m[np.isfinite(m)], s[np.isfinite(s)]]
    anorm = Normalize(absolute.min(), absolute.max())
    finite = d[np.isfinite(d)]
    bound = max(np.abs(finite).max(), 1e-9)
    dnorm = TwoSlopeNorm(vmin=-bound, vcenter=0, vmax=bound)
    fig = plt.figure(figsize=(11.7, max(12, 0.25 * nr + 2.8)))
    gs = fig.add_gridspec(1, 6, width_ratios=[4.8, 2.4, 1.15, 1.15, 1.3, .75], wspace=.07)
    axm = fig.add_subplot(gs[0])
    axc = fig.add_subplot(gs[1], sharey=axm)
    ax1 = fig.add_subplot(gs[2], sharey=axm)
    ax2 = fig.add_subplot(gs[3], sharey=axm)
    axd = fig.add_subplot(gs[4], sharey=axm)
    axn = fig.add_subplot(gs[5], sharey=axm)
    axm.imshow(mem, aspect='auto', cmap=ListedColormap(['#f2f2f2', '#16324f']), vmin=0, vmax=1)
    axm.set_xticks(range(nc))
    axm.set_xticklabels([short(c) for c in categories], rotation=55, ha='right', fontsize=7)
    axm.set_yticks(y)
    axm.set_yticklabels(range(1, nr + 1), fontsize=5.5)
    axm.set_ylabel('exact combination rank')
    axm.set_title('Exact anomaly membership', fontsize=9)
    axm.set_xticks(np.arange(-.5, nc, 1), minor=True)
    axm.set_yticks(np.arange(-.5, nr, 1), minor=True)
    axm.grid(which='minor', color='white', lw=.45)
    axm.tick_params(which='minor', length=0)
    axc.barh(y, counts, height=.72, color='#6c879f')
    axc.invert_yaxis()
    axc.set_title('Images', fontsize=9)
    axc.set_xlabel('count')
    axc.tick_params(axis='y', left=False, labelleft=False)
    axc.spines[['top', 'right']].set_visible(False)
    axc.set_xlim(0, counts.max() * 1.2)
    for i, v in enumerate(counts):
        axc.text(v, i, f' {v}', va='center', fontsize=5.2)

    def col(ax, vals, title, norm):
        cmap = plt.cm.RdYlBu.copy()
        cmap.set_bad('#e8e8e8')
        im = ax.imshow(np.ma.masked_invalid(vals[:, None]), aspect='auto', cmap=cmap, norm=norm)
        ax.set_xticks([0])
        ax.set_xticklabels([title], rotation=55, ha='right', fontsize=7)
        ax.set_title(title, fontsize=9)
        ax.tick_params(axis='y', left=False, labelleft=False)
        for i, v in enumerate(vals):
            ax.text(0, i, f'{v:.2f}' if np.isfinite(v) else 'NA', ha='center', va='center', fontsize=5.1)
        return im

    im1 = col(ax1, m, 'M3DM', anorm)
    col(ax2, s, 'STFPM', anorm)
    imd = col(axd, d, 'M3DM - STFPM', dnorm)
    axn.imshow(pn[:, None], aspect='auto', cmap='Greys', vmin=0, vmax=max(pn.max(), 1))
    axn.set_xticks([0])
    axn.set_xticklabels(['paired n'], rotation=55, ha='right', fontsize=7)
    axn.set_title('Paired n', fontsize=9)
    axn.tick_params(axis='y', left=False, labelleft=False)
    for i, v in enumerate(pn):
        axn.text(0, i, str(v), ha='center', va='center', fontsize=5.1)
    starts, ends = {}, {}
    for i, r in enumerate(rows):
        starts.setdefault(r['n_types'], i)
        ends[r['n_types']] = i
    for k in sorted(starts):
        start = starts[k]
        if start:
            for ax in [axm, axc, ax1, ax2, axd, axn]:
                ax.axhline(start - .5, color='#b91c1c', lw=.8)
        axm.text(-1.05, (start + ends[k]) / 2, f'{k} type' if k == 1 else f'{k} types',
                 ha='right', va='center', fontsize=6.2, fontweight='bold', color='#7f1d1d', clip_on=False)
    cb = fig.colorbar(im1, ax=[ax1, ax2], fraction=.035, pad=.02)
    cb.set_label(f'mean {metric}', fontsize=7)
    cb = fig.colorbar(imd, ax=axd, fraction=.09, pad=.04)
    cb.set_label(f'delta {metric}', fontsize=7)
    fig.suptitle('Full exact anomaly-combination atlas: prevalence and localization difficulty', fontsize=12, y=.998)
    fig.text(.5, .003, 'Rows grouped by multiplicity and sorted by frequency; positive difference means M3DM performs better.',
             ha='center', fontsize=6.5, style='italic', color='.35')
    fig.subplots_adjust(left=.07, right=.985, bottom=.035, top=.975)
    for ext in ['pdf', 'png']:
        fig.savefig(f'{stem}.{ext}', 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/combination_atlas")
    if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
        return Path(__file__).resolve().parent.parent / "checkpoint_data/combination_atlas"
    return Path("./combination_atlas")

def main():
    p = argparse.ArgumentParser(description="Full exact-combination atlas")
    p.add_argument('--coco', nargs='+', default=None,
                   help="COCO annotation files or directory (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-count', type=int, default=1)
    p.add_argument('--out', default=None,
                   help="Output directory (default: checkpoint_data/combination_atlas or ./combination_atlas)")
    a = p.parse_args()

    coco_entries = a.coco if a.coco is not None else default_coco_search()
    coco = find_coco(coco_entries, a.coco_pattern)
    if not coco:
        raise SystemExit(f"No COCO 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"])

    memberships = load_annotations(coco)
    memberships = {k: set(v) - FORBIDDEN for k, v in memberships.items()}
    groups = groups_from(memberships, a.min_count)

    m3dm = load_scores(m3dm_paths, a.metric, 'M3DM') if m3dm_paths else {}
    stfpm = load_scores(stfpm_paths, a.metric, 'STFPM') if stfpm_paths else {}
    rows = summarize(groups, m3dm, stfpm)
    cats = sorted({c for r in rows for c in r['combo']})

    out = Path(a.out) if a.out is not None else default_out_dir()
    out.mkdir(parents=True, exist_ok=True)
    stem = out / 'combination_atlas_all'

    ann = {k for k, v in memberships.items() if v}
    print(f'COCO files: {len(coco)} | combinations: {len(rows)} | types: {len(cats)}')
    print(f'M3DM matched: {len(ann & set(m3dm))}/{len(m3dm)} | STFPM matched: {len(ann & set(stfpm))}/{len(stfpm)} | paired: {len(ann & set(m3dm) & set(stfpm))}')
    save_csv(f'{stem}_values.csv', rows, cats)
    draw(rows, cats, a.metric, stem)
    print(f'Wrote {stem}.pdf, .png, and _values.csv')

if __name__ == '__main__':
    main()