File size: 4,945 Bytes
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
#!/usr/bin/env python3
"""Plot per-class multimodal isolated AUPRO comparison across models."""
import argparse
import json
import sys
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns


def find_data_file(explicit_path=None):
    if explicit_path:
        p = Path(explicit_path)
        if p.is_file():
            return p
        raise FileNotFoundError(f"Specified data file not found: {explicit_path}")

    candidates = [
        Path("checkpoint_data/multimodal_isolated_metrics.json"),
        Path("../checkpoint_data/multimodal_isolated_metrics.json"),
        Path(__file__).resolve().parent.parent / "checkpoint_data" / "multimodal_isolated_metrics.json",
        Path(__file__).resolve().parent / "multimodal_isolated_metrics.json",
        Path("multimodal_isolated_metrics.json"),
    ]
    for c in candidates:
        if c.is_file():
            return c
    raise FileNotFoundError(
        "Could not find 'multimodal_isolated_metrics.json'. Looked in: "
        + ", ".join(str(c) for c in candidates)
    )


def main():
    parser = argparse.ArgumentParser(description="Plot per-class multimodal isolated AUPRO")
    parser.add_argument(
        "--data",
        type=Path,
        default=None,
        help="Path to multimodal_isolated_metrics.json (auto-detected if omitted)",
    )
    parser.add_argument(
        "--out-dir",
        type=Path,
        default=None,
        help="Output folder for figures (default: checkpoint_data/ or current dir)",
    )
    parser.add_argument(
        "--stem",
        default="performance_aupro_multimodal",
        help="Output filename stem without extension",
    )
    parser.add_argument(
        "--show",
        action="store_true",
        help="Show interactive plot window",
    )
    args = parser.parse_args()

    data_file = find_data_file(args.data)
    print(f"Loading data from: {data_file}")

    with open(data_file, "r", encoding="utf-8") as f:
        data = json.load(f)

    # 2. Flatten the data
    rows = []
    for model, cameras in data.items():
        if model == "CMDR":
            model = "CMDR-IAD"
        for camera, scenes in cameras.items():
            for scene, classes in scenes.items():
                for cls, metrics in classes.items():
                    rows.append({
                        "Model": model,
                        "Class": cls,
                        "AUPRO": metrics.get("Pixel_AUPRO", metrics.get("aupro_30", 0.0)),
                    })

    if not rows:
        raise SystemExit("No metric records found in input file.")

    df = pd.DataFrame(rows)

    # 3. Aggregate: Mean performance per Model and Class
    df_agg = df.groupby(["Model", "Class"])["AUPRO"].mean().reset_index()

    # 4. Calculate Mean per Class (across all models)
    class_means = df_agg.groupby("Class")["AUPRO"].mean()

    # 5. Visualization
    sns.set_theme(style="whitegrid", font_scale=1.1)
    fig = plt.figure(figsize=(14, 5))

    # Create barplot
    chart = sns.barplot(
        data=df_agg,
        x="Class",
        y="AUPRO",
        hue="Model",
        hue_order=["M3DM", "CMDR-IAD", "CFM", "WinCLIP", "UniVAD"],
        palette="viridis",
    )

    # 6. Add dotted line segments and text labels
    classes = df_agg["Class"].unique()
    for i, cls in enumerate(classes):
        mean_val = class_means[cls]
        plt.hlines(
            y=mean_val,
            xmin=i - 0.4,
            xmax=i + 0.4,
            colors="red",
            linestyles=":",
            linewidth=3,
            label="Class Mean" if i == 0 else "",
        )
        plt.text(
            i + 0.3,
            mean_val + 0.018,
            f"{mean_val:.2f}",
            color="red",
            ha="left",
            va="center",
            fontsize=9,
            fontweight="bold",
        )

    plt.xticks(rotation=15, ha="right")
    plt.xlabel("")
    plt.ylabel("Mean Pixel AUPRO Score")

    plt.legend(
        loc="upper left",
        ncol=3,
        frameon=True,
        framealpha=0.2,
        facecolor="white",
        edgecolor="black",
    )

    plt.tight_layout()

    if args.out_dir is not None:
        out_dir = args.out_dir
    elif Path("checkpoint_data").is_dir():
        out_dir = Path("checkpoint_data")
    elif (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
        out_dir = Path(__file__).resolve().parent.parent / "checkpoint_data"
    else:
        out_dir = Path(".")

    out_dir.mkdir(parents=True, exist_ok=True)
    pdf_path = out_dir / f"{args.stem}.pdf"
    png_path = out_dir / f"{args.stem}.png"

    plt.savefig(pdf_path, bbox_inches="tight")
    plt.savefig(png_path, dpi=300, bbox_inches="tight")
    print(f"Saved: {pdf_path}")
    print(f"Saved: {png_path}")

    if args.show:
        plt.show()
    plt.close(fig)


if __name__ == "__main__":
    main()