File size: 8,320 Bytes
e37baa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Scan runs/ and, for every model, plot Strategy 2 (supervised baseline) vs
Strategy 3 (refinement), AVERAGED ACROSS ALL PHASES found for that model.

Six measures per model (mean across phases, error bars = std across phases):

    * BIoU (band, d-pixel)       evaluation.json -> metrics.biou.mean
    * BIoU (contour, 1-pixel)    evaluation.json -> metrics.biou_contour.mean
    * Total training time (min)  summary.json    -> elapsed_seconds
    * Inference time (ms/image)  evaluation.json -> timing.mean_per_image_inference_ms
    * Time per epoch (s)         summary.json    -> seconds_per_epoch
    * Time to best ckpt (min)    best.pt.meta.json -> epoch  x  seconds_per_epoch
                                 (falls back to argmax of selection_metric_value in history.json)

Usage:
    python plot_s2_vs_s3.py                 # scans ./runs
    python plot_s2_vs_s3.py --runs-root X
"""
from __future__ import annotations

import argparse
import json
import pathlib
import re
from collections import defaultdict

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

STRATEGY_LABEL = {2: "S2 (baseline)", 3: "S3 (refinement)"}
BAR_COLORS = {2: "#4C78A8", 3: "#F58518"}

# key, title, ylabel, higher_is_better, value format
PANELS = [
    ("biou",             "Boundary IoU (band)",     "BIoU",         True,  "{:.4f}"),
    ("biou_contour",     "Boundary IoU (contour)",  "BIoU contour", True,  "{:.4f}"),
    ("infer_ms",         "Inference time",          "ms / image",   False, "{:.2f}"),
    ("train_min",        "Total training time",     "minutes",      False, "{:.1f}"),
    ("epoch_sec",        "Time per epoch",          "seconds",      False, "{:.1f}"),
    ("time_to_best_min", "Time to best checkpoint", "minutes",      False, "{:.1f}"),
]


def load_json(path: pathlib.Path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return None


def best_epoch_for(final_dir: pathlib.Path) -> int | None:
    """Epoch at which the best checkpoint was saved."""
    meta = load_json(final_dir / "checkpoints" / "best.pt.meta.json")
    if meta and meta.get("epoch") is not None:
        return int(meta["epoch"])

    # fallback: argmax of the selection metric recorded in history
    hist = load_json(final_dir / "history.json")
    if isinstance(hist, list) and hist:
        best_ep, best_val = None, None
        for row in hist:
            val = row.get("selection_metric_value")
            if val is None:
                continue
            if best_val is None or float(val) > float(best_val):
                best_val, best_ep = float(val), int(row.get("epoch", 0))
        return best_ep
    return None


def collect(runs_root: pathlib.Path) -> dict[str, dict[int, dict[str, list[float]]]]:
    """model -> strategy -> metric -> [one value per phase]"""
    data: dict[str, dict[int, dict[str, list[float]]]] = defaultdict(
        lambda: defaultdict(lambda: defaultdict(list))
    )
    for eval_path in runs_root.glob("*/**/strategy_*/final/evaluation.json"):
        final_dir = eval_path.parent
        m = re.search(r"strategy_(\d+)", final_dir.parent.name)
        if not m:
            continue
        strategy = int(m.group(1))
        if strategy not in (2, 3):
            continue
        try:
            model = eval_path.relative_to(runs_root).parts[0]
        except ValueError:
            continue

        ev = load_json(eval_path)
        if not ev:
            continue
        bucket = data[model][strategy]
        metrics = ev.get("metrics", {}) or {}

        for key in ("biou", "biou_contour"):
            val = (metrics.get(key) or {}).get("mean")
            if val is not None:
                bucket[key].append(float(val))

        infer = (ev.get("timing", {}) or {}).get("mean_per_image_inference_ms")
        if infer is not None:
            bucket["infer_ms"].append(float(infer))

        summary = load_json(final_dir / "summary.json")
        if summary:
            if summary.get("elapsed_seconds") is not None:
                bucket["train_min"].append(float(summary["elapsed_seconds"]) / 60.0)
            spe = summary.get("seconds_per_epoch")
            if spe is not None:
                bucket["epoch_sec"].append(float(spe))
                be = best_epoch_for(final_dir)
                if be:
                    bucket["time_to_best_min"].append(be * float(spe) / 60.0)

    return data


def plot_model(model: str, per_strategy: dict[int, dict[str, list[float]]],
               out_dir: pathlib.Path) -> pathlib.Path | None:
    strategies = [s for s in (2, 3) if per_strategy.get(s)]
    if not strategies:
        return None

    n_phases = max((len(v.get("biou", [])) for v in per_strategy.values()), default=0)
    fig, axes = plt.subplots(2, 3, figsize=(16, 8.5))
    fig.suptitle(f"{model}   —   Strategy 2 vs Strategy 3\n"
                 f"mean across {n_phases} phase(s), error bars = std across phases",
                 fontsize=14, fontweight="bold")

    for ax, (key, title, ylabel, higher_better, fmt) in zip(axes.ravel(), PANELS):
        xs, means, stds, labels, colors = [], [], [], [], []
        for i, s in enumerate(strategies):
            vals = per_strategy[s].get(key, [])
            if not vals:
                continue
            xs.append(i)
            means.append(float(np.mean(vals)))
            stds.append(float(np.std(vals)) if len(vals) > 1 else 0.0)
            labels.append(STRATEGY_LABEL[s])
            colors.append(BAR_COLORS[s])

        if not means:
            ax.set_title(f"{title}  (no data)")
            ax.axis("off")
            continue

        bars = ax.bar(xs, means, yerr=stds, capsize=5, color=colors, width=0.55)
        ax.set_xticks(xs)
        ax.set_xticklabels(labels, fontsize=9)
        ax.set_ylabel(ylabel)
        ax.set_title(f"{title}   ({'higher' if higher_better else 'lower'} is better)", fontsize=11)
        ax.grid(axis="y", alpha=0.3, linestyle="--")
        ax.margins(y=0.18)

        for b, mval in zip(bars, means):
            ax.annotate(fmt.format(mval), (b.get_x() + b.get_width() / 2, b.get_height()),
                        textcoords="offset points", xytext=(0, 4), ha="center", fontsize=9)

        if len(means) == 2:
            delta = means[1] - means[0]
            pct = (delta / means[0] * 100.0) if means[0] else 0.0
            good = (delta > 0) if higher_better else (delta < 0)
            ax.text(0.5, 0.02, f"Δ(S3−S2) = {delta:+.4g}  ({pct:+.1f}%)",
                    transform=ax.transAxes, ha="center", fontsize=9,
                    color=("green" if good else "red"))

    fig.tight_layout(rect=(0, 0, 1, 0.93))
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / f"{model}__s2_vs_s3.png"
    fig.savefig(out_path, dpi=150)
    plt.close(fig)
    return out_path


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--runs-root", default="runs")
    args = ap.parse_args()

    runs_root = pathlib.Path(args.runs_root).resolve()
    if not runs_root.is_dir():
        print(f"[plot] runs root not found: {runs_root}")
        return 1

    data = collect(runs_root)
    if not data:
        print(f"[plot] no evaluation.json found under {runs_root}")
        return 1

    out_dir = runs_root / "_plots"
    csv_rows = ["model,strategy,metric,mean,std,n_phases"]
    made = []

    for model in sorted(data):
        p = plot_model(model, data[model], out_dir)
        if p:
            made.append(p)
            n = max((len(v.get("biou", [])) for v in data[model].values()), default=0)
            print(f"[plot] {model:34s} n_phases={n:<3d} -> {p.name}")
        for s in sorted(data[model]):
            for key, *_ in PANELS:
                vals = data[model][s].get(key, [])
                if vals:
                    csv_rows.append(
                        f"{model},{s},{key},{np.mean(vals):.6f},"
                        f"{(np.std(vals) if len(vals) > 1 else 0.0):.6f},{len(vals)}"
                    )

    (out_dir / "summary_s2_vs_s3.csv").write_text("\n".join(csv_rows) + "\n", encoding="utf-8")
    print(f"\n[plot] {len(made)} figure(s) + summary_s2_vs_s3.csv written to {out_dir}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())