Download PROJECT/tools/make_figures.py from Dhruv1000/TSRDA: direct link, hf CLI and curl.
- Browser
- Download file 23.8 kB
-
https://huggingface.co/Dhruv1000/TSRDA/resolve/main/PROJECT/tools/make_figures.py
- Command line
-
hf download hf://Dhruv1000/TSRDA/PROJECT/tools/make_figures.py
-
curl -L -o make_figures.py https://huggingface.co/Dhruv1000/TSRDA/resolve/main/PROJECT/tools/make_figures.py
23.8 kB
| """Figures and GIFs for the repository front page. Every plotted value is read from a result file | |
| (through the readers in make_reports.py); the architecture drawing and the attention animation | |
| carry no data. Output: hf_work/stage3/assets/. | |
| Palette: blue = T-SRDA / the reference run, orange = a variant that scores lower or an adverse | |
| result, gray = other methods. Validated with the dataviz skill's validator (all checks pass; the | |
| only warning is aqua's contrast, and aqua is not used). Every bar carries a direct value label, | |
| so identity is never colour-only; hatching marks results that are not clean comparisons. | |
| """ | |
| import re, sys, json | |
| from pathlib import Path | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, Rectangle | |
| from matplotlib import animation | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| import make_reports as MR | |
| OUT = MR.HF / "stage3" / "assets" | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| SURF, INK, INK2, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#8a8984", "#e4e3df" | |
| BLUE, ORANGE, GRAY, LGRAY = "#2a78d6", "#eb6834", "#9a9893", "#d6d5d0" | |
| plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10, "axes.edgecolor": GRID, | |
| "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2, | |
| "figure.facecolor": SURF, "axes.facecolor": SURF, "savefig.facecolor": SURF, | |
| "axes.spines.top": False, "axes.spines.right": False, "hatch.linewidth": 0.8}) | |
| def save(fig, name, dpi=170): | |
| fig.savefig(OUT / name, dpi=dpi) | |
| plt.close(fig) | |
| print("wrote", name) | |
| def style(ax, grid="x"): | |
| ax.grid(axis=grid, color=GRID, lw=0.8) | |
| ax.set_axisbelow(True) | |
| ax.tick_params(length=0) | |
| # ============================================================================ 1. architecture diagram | |
| def box(ax, x, y, w, h, text, fc=LGRAY, ec=GRAY, fs=9, tc=INK, lw=1.2, r=0.06): | |
| ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle=f"round,pad=0.01,rounding_size={r}", | |
| fc=fc, ec=ec, lw=lw)) | |
| ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=fs, color=tc, linespacing=1.35) | |
| def arrow(ax, p, q, color=INK2, lw=1.4, rad=0.0): | |
| ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=11, color=color, lw=lw, | |
| connectionstyle=f"arc3,rad={rad}", shrinkA=0, shrinkB=0)) | |
| def fig_architecture(): | |
| fig, ax = plt.subplots(figsize=(13.2, 7.4)) | |
| ax.set_xlim(0, 13.2); ax.set_ylim(0, 7.4); ax.axis("off") | |
| ax.text(0.1, 7.15, "T-SRDA β end-to-end", fontsize=14, fontweight="bold", color=INK) | |
| ax.text(0.1, 6.83, "one pixel-wise temporal sequence per location; the spatial and temporal parts are separate modules", | |
| fontsize=9.5, color=INK2) | |
| # main row | |
| y, h = 5.15, 1.1 | |
| box(ax, 0.1, y, 1.75, h, "Image time series\n(B, T, C, H, W)\n+ acquisition dates", fc="#ffffff") | |
| box(ax, 2.3, y, 2.4, h, "Atrous spatial encoder\ndilated stem β ASPP\n(rates 1, 2, 4) β SE\nper acquisition β d = 256", fc="#e8f0fb", ec=BLUE) | |
| box(ax, 5.15, y, 2.45, h, "Temporal SRDA encoder\n3 blocks, R = 4 each\n8 heads, + date encoding\n(global temporal field)", fc="#e8f0fb", ec=BLUE, lw=2) | |
| box(ax, 8.05, y, 1.95, h, "STA pool\nattention over T\nβ (B, d, H, W)", fc="#e8f0fb", ec=BLUE) | |
| box(ax, 10.45, y, 2.65, h, "Dual decoders\nsemantic + boundary\nβ gated refinement", fc="#e8f0fb", ec=BLUE) | |
| for a_, b_ in [(1.85, 2.3), (4.7, 5.15), (7.6, 8.05), (10.0, 10.45)]: | |
| arrow(ax, (a_, y + h / 2), (b_, y + h / 2)) | |
| box(ax, 4.85, 4.2, 3.05, 0.62, "Pre-training head: reconstruct masked\nframes (NDVI-gated, per frame)", fc="#fbeee8", ec=ORANGE, fs=8.3) | |
| arrow(ax, (6.375, y), (6.375, 4.82), color=ORANGE) | |
| ax.text(8.1, 4.5, "pre-train: no labels", fontsize=8.8, color=ORANGE, va="center") | |
| ax.text(8.05, 6.38, "fine-tune: labelled tiles / patches", fontsize=8.8, color=BLUE) | |
| box(ax, 10.45, 4.2, 2.65, 0.62, "class logits + field-edge logit", fc="#ffffff", fs=8.5) | |
| arrow(ax, (11.775, y), (11.775, 4.82)) | |
| # block detail | |
| ax.add_patch(Rectangle((0.1, 0.15), 13.0, 3.75, fc="#ffffff", ec=GRID, lw=1.2)) | |
| ax.text(0.3, 3.62, "Inside one temporal SRDA block (x: N pixel sequences Γ T acquisitions Γ d channels)", fontsize=11, fontweight="bold", color=INK) | |
| bx, by, bh = 0.35, 1.2, 1.15 | |
| box(ax, bx, by + 1.2, 1.5, 0.85, "x + date PE\n(N, T, d)", fc="#ffffff", fs=8.5) | |
| box(ax, 2.2, by + 1.45, 1.85, 0.8, "point-wise Linear\nd β d/R", fc="#e8f0fb", ec=BLUE, fs=8.5) | |
| box(ax, 4.4, by + 1.45, 1.95, 0.8, "group R steps\n(T, d/R) β (T/R, d)", fc="#e8f0fb", ec=BLUE, fs=8.5) | |
| box(ax, 6.7, by + 1.45, 1.75, 0.8, "self-attention\non T/R tokens", fc="#e8f0fb", ec=BLUE, fs=8.5) | |
| box(ax, 2.2, by - 0.05, 1.85, 0.8, "queries from all\nT tokens (full res.)", fc="#e8f0fb", ec=BLUE, fs=8.5) | |
| box(ax, 6.7, by - 0.05, 2.45, 0.8, "cross-attention Q(T) Γ K,V(T/R)\nattention matrix T Γ T/R", fc="#e8f0fb", ec=BLUE, fs=8.5, lw=2) | |
| box(ax, 9.55, by - 0.05, 1.45, 0.8, "residual\n+ LayerNorm", fc="#ffffff", fs=8.5) | |
| box(ax, 11.3, by - 0.05, 1.6, 1.4, "scMLP\nFC β GELU\n+ depth-wise\nConv1d over T\nβ FC", fc="#e8f0fb", ec=BLUE, fs=8.5) | |
| arrow(ax, (1.85, by + 1.62), (2.2, by + 1.85)); arrow(ax, (4.05, by + 1.85), (4.4, by + 1.85)); arrow(ax, (6.35, by + 1.85), (6.7, by + 1.85)) | |
| arrow(ax, (1.1, by + 1.2), (2.2, by + 0.35), rad=0.0); arrow(ax, (4.05, by + 0.35), (6.7, by + 0.35)) | |
| arrow(ax, (7.58, by + 1.45), (7.9, by + 0.75), color=BLUE) | |
| arrow(ax, (9.15, by + 0.35), (9.55, by + 0.35)); arrow(ax, (11.0, by + 0.35), (11.3, by + 0.35)) | |
| ax.text(0.35, 0.42, "Why it matters: after one block every acquisition can reach every other one (global temporal receptive field), " | |
| "at cost O(TΒ²Β·D / R) instead of O(TΒ²Β·D).", fontsize=9.3, color=INK2) | |
| ax.text(0.35, 0.22, "The date encoding is added BEFORE the grouping β grouped tokens from irregular acquisitions are meaningless without dates.", | |
| fontsize=9.3, color=INK2) | |
| save(fig, "architecture.png") | |
| # ============================================================================ 2. attention GIF | |
| def gif_reduction(): | |
| T, R = 12, 4 | |
| G = T // R | |
| rng = np.random.default_rng(3) | |
| base = rng.random((T, G)) ** 3 | |
| base = base / base.sum(1, keepdims=True) | |
| fig, ax = plt.subplots(figsize=(8.6, 4.6)) | |
| ax.set_xlim(0, 8.6); ax.set_ylim(0, 4.6); ax.axis("off") | |
| def draw(k): | |
| ax.clear(); ax.set_xlim(0, 8.6); ax.set_ylim(0, 4.6); ax.axis("off") | |
| cap = ["1 Acquisitions along time (T = 12), each already embedded to d channels", | |
| "2 Point-wise projection: every step shrinks d β d/R", | |
| "3 Group R = 4 consecutive steps β T/R = 3 reduced key/value tokens", | |
| "4 Self-attention among the 3 reduced tokens", | |
| "5 Every one of the 12 queries attends to the 3 tokens: matrix 12 Γ 3", | |
| "6 Full attention would need 12 Γ 12 β the reduction cuts the cost by R"][k] | |
| ax.text(0.2, 4.35, cap, fontsize=11.5, fontweight="bold", color=INK) | |
| cols = [BLUE, "#4f95e8", "#7db1ee"] | |
| for t in range(T): | |
| x = 0.4 + t * 0.62 | |
| g = t // R | |
| shrink = k >= 1 | |
| h = 0.5 if not shrink else 0.5 / R * 1.6 | |
| ax.add_patch(Rectangle((x, 3.15), 0.5, h + (0 if not shrink else 0.0), fc=cols[g] if k >= 2 else BLUE, ec=SURF, lw=1.2)) | |
| ax.text(x + 0.25, 3.0, f"t{t+1}", ha="center", va="top", fontsize=7.5, color=MUTED) | |
| if k >= 2: | |
| for g in range(G): | |
| x0 = 0.4 + g * R * 0.62 | |
| ax.add_patch(Rectangle((x0 - 0.03, 3.1), R * 0.62 - 0.04, 0.78, fc="none", ec=cols[g], lw=1.6, ls="--")) | |
| ax.add_patch(Rectangle((1.2 + g * 2.45, 1.95), 1.9, 0.5, fc=cols[g], ec=SURF)) | |
| ax.text(1.2 + g * 2.45 + 0.95, 2.2, f"group {g+1} β 1 token", ha="center", va="center", fontsize=8.5, color="white") | |
| arrow(ax, (x0 + R * 0.62 / 2 - 0.1, 3.08), (1.2 + g * 2.45 + 0.95, 2.47), color=cols[g], lw=1.2) | |
| if k == 3: | |
| for g in range(G): | |
| for g2 in range(G): | |
| if g != g2: | |
| ax.add_patch(FancyArrowPatch((1.2 + g * 2.45 + 0.95, 1.93), (1.2 + g2 * 2.45 + 0.95, 1.93), | |
| arrowstyle="-|>", mutation_scale=9, lw=1, color=GRAY, connectionstyle="arc3,rad=-0.5")) | |
| c = 0.1 # one cell = 0.1 x 0.1 in both matrices, so areas compare directly | |
| top = 1.75 | |
| if k >= 4: | |
| for t in range(T): | |
| for g in range(G): | |
| a = base[t, g] | |
| ax.add_patch(Rectangle((0.7 + g * c, top - (t + 1) * c), c, c, fc=BLUE, alpha=0.15 + 0.85 * a / base.max(), ec=SURF, lw=0.3)) | |
| ax.text(0.7, top + 0.05, "queries 12 Γ keys 3", fontsize=8.5, color=INK2, va="bottom") | |
| if k >= 5: | |
| for t in range(T): | |
| for u in range(T): | |
| ax.add_patch(Rectangle((2.6 + u * c, top - (t + 1) * c), c, c, fc=ORANGE, alpha=0.45, ec=SURF, lw=0.2)) | |
| ax.text(2.6, top + 0.05, "full self-attention: 12 Γ 12", fontsize=8.5, color=ORANGE, va="bottom") | |
| ax.text(4.6, 1.15, "entries: 36 vs 144\n= R = 4Γ fewer", fontsize=12.5, fontweight="bold", color=INK) | |
| ax.text(0.2, 0.12, "T-SRDA temporal block β schematic with T = 12, R = 4 (the real model runs T β 30β61, R = 4 in three blocks)", | |
| fontsize=8, color=MUTED) | |
| anim = animation.FuncAnimation(fig, draw, frames=[0, 1, 2, 3, 4, 5], interval=1700) | |
| anim.save(OUT / "srda_reduction.gif", writer=animation.PillowWriter(fps=0.6), dpi=110) | |
| plt.close(fig) | |
| print("wrote srda_reduction.gif") | |
| # ============================================================================ 3. MTLCC | |
| def fig_mtlcc_benchmark(bl, seeds): | |
| rows = [(r["model"], r["mIoU"], None) for r in bl if r.get("mIoU") is not None and r["key"] != "tsrda"] | |
| sv = [seeds[s]["ema"]["mIoU"] for s in seeds if seeds[s].get("ema")] | |
| ts = next(r for r in bl if r["key"] == "tsrda") | |
| rows.append(("T-SRDA (3-seed mean Β± sd, EMA)", float(np.mean(sv)) if len(sv) > 1 else ts["mIoU"], float(np.std(sv, ddof=1)) if len(sv) > 1 else None)) | |
| rows.sort(key=lambda r: r[1]) | |
| fig, ax = plt.subplots(figsize=(9.2, 0.55 * len(rows) + 1.4)) | |
| for i, (n, v, e) in enumerate(rows): | |
| c = BLUE if n.startswith("T-SRDA") else GRAY | |
| ax.barh(i, v, color=c, height=0.62) | |
| if e: | |
| ax.errorbar(v, i, xerr=e, color=INK, capsize=3, lw=1.2) | |
| ax.text(v + (e or 0) + 0.006, i, f"{v:.4f}", va="center", fontsize=9.5, color=INK, fontweight="bold" if c == BLUE else "normal") | |
| ax.set_yticks(range(len(rows))); ax.set_yticklabels([r[0] for r in rows]) | |
| ax.set_xlim(0, 0.8); ax.set_xlabel("test mIoU (STCLN protocol, 1,495 tiles, 78 labelled tiles)") | |
| style(ax) | |
| ax.set_title("MTLCC β T-SRDA is level with STCLN_wp, not ahead of it", loc="left", fontsize=12, fontweight="bold", color=INK) | |
| fig.text(0.01, 0.01, "Each baseline: our run at its validation-selected lr. Error bar = sd over 3 fine-tuning seeds (the baselines have one seed).", | |
| fontsize=8, color=MUTED) | |
| fig.tight_layout(rect=(0, 0.03, 1, 1)) | |
| save(fig, "mtlcc_benchmark.png") | |
| def mtlcc_ablation_rows(main, seeds, abl, bl): | |
| ref = main["test_ema"]["stcln"]["mIoU"] | |
| d = {a["name"]: a["test"]["ema"]["mIoU"] for a in abl if a["test"].get("ema")} | |
| rows = [("full recipe (reference)", ref, BLUE)] | |
| lab = {"no_boundary": "no boundary loss", "plain_ce": "plain cross-entropy (STCLN's loss)", | |
| "scratch_R1": "no pre-training, R = 1", "scratch_R4": "no pre-training, R = 4"} | |
| for k in ("no_boundary", "plain_ce", "scratch_R1", "scratch_R4"): | |
| if k in d: | |
| rows.append((lab[k], d[k], ORANGE if k != "no_boundary" else GRAY)) | |
| return rows | |
| def fig_mtlcc_ablation(main, seeds, abl, bl): | |
| rows = mtlcc_ablation_rows(main, seeds, abl, bl)[::-1] | |
| sv = [seeds[s]["ema"]["mIoU"] for s in seeds if seeds[s].get("ema")] | |
| sd = float(np.std(sv, ddof=1)) if len(sv) > 1 else 0 | |
| stw = next((r["mIoU"] for r in bl if r["key"] == "stcln_wp"), None) | |
| ref = main["test_ema"]["stcln"]["mIoU"] | |
| fig, ax = plt.subplots(figsize=(9.2, 4.6)) | |
| ax.axvspan(ref - sd, ref + sd, color=BLUE, alpha=0.13, lw=0) | |
| for i, (n, v, c) in enumerate(rows): | |
| ax.plot([ref, v], [i, i], color=c, lw=2, alpha=0.55, zorder=2) | |
| ax.scatter([v], [i], s=95, color=c, zorder=3) | |
| ax.text(v + (0.004 if v >= ref else -0.004), i + 0.26, f"{v:.4f}", ha="left" if v >= ref else "right", fontsize=9.5, color=INK) | |
| if stw: | |
| ax.axvline(stw, color=INK2, lw=1.2, ls="--", zorder=1) | |
| ax.text(stw - 0.002, -0.62, f"STCLN_wp {stw:.4f}", fontsize=8.5, color=INK2, ha="right", va="center") | |
| ax.set_yticks(range(len(rows))); ax.set_yticklabels([r[0] for r in rows]) | |
| ax.set_xlim(0.54, 0.72); ax.set_ylim(-0.9, len(rows) - 0.4) | |
| ax.set_xlabel("test mIoU (EMA weights, seed 3407, one run per dot) β axis starts at 0.54") | |
| style(ax) | |
| ax.set_title("MTLCC ablations β what carries the score", loc="left", fontsize=12, fontweight="bold", color=INK) | |
| fig.text(0.01, 0.01, "Blue band = Β±1 sd over fine-tuning seeds of the reference run. Segments run from the reference to each variant.", | |
| fontsize=8, color=MUTED) | |
| fig.tight_layout(rect=(0, 0.04, 1, 1)) | |
| save(fig, "mtlcc_ablations.png") | |
| return rows[::-1] | |
| def gif_ablation(rows): | |
| rows = sorted(rows, key=lambda r: -r[1]) | |
| ref = max(rows, key=lambda r: r[1])[1] | |
| fig, ax = plt.subplots(figsize=(8.6, 3.9)) | |
| def draw(k): | |
| ax.clear() | |
| for i, (n, v, c) in enumerate(rows[::-1]): | |
| j = len(rows) - 1 - i | |
| if j <= k: | |
| ax.barh(i, v, color=c, height=0.62) | |
| ax.text(v + 0.004, i, f"{v:.4f} ({v - ref:+.4f})" if j else f"{v:.4f}", va="center", fontsize=9, color=INK) | |
| ax.set_yticks(range(len(rows))); ax.set_yticklabels([r[0] for r in rows[::-1]], fontsize=9) | |
| ax.set_xlim(0, 0.85); ax.set_ylim(-0.6, len(rows) - 0.4) | |
| ax.set_xlabel("test mIoU on MTLCC (EMA, seed 3407)") | |
| style(ax) | |
| fig.subplots_adjust(left=0.37, right=0.97, bottom=0.17, top=0.9) | |
| ax.set_title("Removing one thing at a time", loc="left", fontsize=11.5, fontweight="bold", color=INK) | |
| anim = animation.FuncAnimation(fig, draw, frames=list(range(len(rows))) + [len(rows) - 1] * 2, interval=1300) | |
| anim.save(OUT / "ablation_reveal.gif", writer=animation.PillowWriter(fps=0.8), dpi=110) | |
| plt.close(fig) | |
| print("wrote ablation_reveal.gif") | |
| # ============================================================================ 4. PLANTEUR | |
| def fig_planteur(rows): | |
| base = (MR.jload(MR.B / "results/planteur/summary.json", {}) or {}).get("baselines", []) | |
| fig, ax = plt.subplots(figsize=(9.4, 5.0)) | |
| xs = [r["frac"] * 100 for r in rows] | |
| means = [float(np.mean(r["test_vals"])) for r in rows] | |
| sds = [float(np.std(r["test_vals"], ddof=1)) if len(r["test_vals"]) > 1 else 0 for r in rows] | |
| ax.errorbar(xs, means, yerr=sds, color=BLUE, lw=2.2, marker="o", ms=7, capsize=3, zorder=3) | |
| for r in rows: | |
| ax.scatter([r["frac"] * 100] * len(r["test_vals"]), r["test_vals"], s=14, color=BLUE, alpha=0.35, zorder=2) | |
| for x, m in zip(xs, means): | |
| ax.text(x, m + 0.012, f"{m:.3f}", ha="center", fontsize=8.5, color=INK) | |
| prev = 9.0 | |
| for b in sorted(base, key=lambda b: -b["mIoU"]): | |
| ax.axhline(b["mIoU"], color=GRAY, lw=0.9, ls="--", zorder=1) | |
| ty = min(b["mIoU"], prev - 0.0125) # keep labels apart; the line itself stays exact | |
| prev = ty | |
| ax.annotate(f"{b['model']} {b['mIoU']:.3f}", xy=(100, b["mIoU"]), xytext=(112, ty), fontsize=8, color=INK2, | |
| va="center", annotation_clip=False, | |
| arrowprops=dict(arrowstyle="-", color=LGRAY, lw=0.7)) | |
| ax.set_xscale("log"); ax.set_xticks(xs); ax.set_xticklabels([f"{x:g}%" for x in xs]) | |
| ax.set_xlim(1.6, 100 * 1.02); ax.set_ylim(0.1, 0.42) | |
| ax.set_xlabel("share of labelled training patches used by T-SRDA (dashed lines: baselines at 100 %)") | |
| ax.set_ylabel("test mIoU-8") | |
| style(ax, "y") | |
| ax.set_title("PLANTEUR β T-SRDA's label-efficiency curve; baselines were run at 100 % only", loc="left", fontsize=12, fontweight="bold", color=INK) | |
| have = {round(r["frac"], 2) for r in rows} | |
| miss = [f"{int(f * 100)} %" for f in (0.5, 1.0) if round(f, 2) not in have] | |
| note = (f"{' and '.join(miss)} still running, so T-SRDA and the" if miss else "T-SRDA's 100 % point is in, so the") | |
| fig.text(0.01, 0.01, "Dots = individual seeds, line = mean Β± sd (one seed where no dots are spread). " + note + "\n" | |
| "baselines are compared at the same label budget only at 100 %.", fontsize=8, color=MUTED) | |
| fig.subplots_adjust(right=0.72, bottom=0.17, left=0.09, top=0.92) | |
| save(fig, "planteur_curve.png") | |
| # ============================================================================ 5. PASTIS | |
| def pastis_rows(): | |
| """(validation, test) mIoU as fractions, parsed from the PASTIS release table.""" | |
| t = Path("/home/ubuntu/pro/TSRDA/RESULTS.md").read_text() | |
| def g(label): | |
| m = re.search(r"\|\s*" + re.escape(label) + r"[^|]*\|\s*([\d.]+)%?\s*\|\s*([\d.]+)%?\s*\|", t) | |
| return (float(m.group(1)) / 100, float(m.group(2)) / 100) if m else (None, None) | |
| return {k: g(k) for k in ("Original SAM optimizer network", "Historical foundation ensemble", | |
| "5Γ5 feature mean + standard deviation, blended")} | |
| def pastis_values(): | |
| return {k: v[1] for k, v in pastis_rows().items()} | |
| def fig_pastis(): | |
| pv = pastis_values() | |
| rows = [("STCLN (published)", 0.4501, GRAY, ""), | |
| ("STCLN_wp (published)", 0.4843, GRAY, ""), | |
| ("T-SRDA, earlier single network", pv["Original SAM optimizer network"], BLUE, ""), | |
| ("T-SRDA, ensemble + external encoder\n(validation-selected)", pv["Historical foundation ensemble"], BLUE, "////"), | |
| ("T-SRDA, ensemble + external encoder\n(best test score seen)", pv["5Γ5 feature mean + standard deviation, blended"], BLUE, "////")] | |
| rows = [r for r in rows if r[1]] | |
| fig, ax = plt.subplots(figsize=(9.2, 4.3)) | |
| for i, (n, v, c, h) in enumerate(rows): | |
| ax.barh(i, v, color=c, height=0.62, hatch=h, edgecolor=SURF if not h else "white") | |
| ax.text(v + 0.005, i, f"{v:.4f}", va="center", fontsize=9.5, color=INK) | |
| ax.set_yticks(range(len(rows))); ax.set_yticklabels([r[0] for r in rows]); ax.invert_yaxis() | |
| ax.set_xlim(0, 0.72); ax.set_xlabel("test mIoU on PASTIS") | |
| style(ax) | |
| ax.set_title("PASTIS β no T-SRDA bar is a clean comparison", loc="left", fontsize=12, fontweight="bold", color=INK) | |
| fig.text(0.01, 0.01, "All T-SRDA bars come from a history of repeated inspection of the test fold. Hatched bars are also ensembles with a frozen,\n" | |
| "externally pre-trained component (geographic overlap with the test region uncertified). A clean single-network re-run is not done.", | |
| fontsize=8, color=MUTED) | |
| fig.tight_layout(rect=(0, 0.07, 1, 1)) | |
| save(fig, "pastis_scores.png") | |
| # ============================================================================ 6. enhancement attribution | |
| TEAL = "#1f8f84" | |
| def fig_enhancement(): | |
| """Where the gain comes from: T-SRDA alone (blue) vs. the external TESSERA encoder (teal, hatched).""" | |
| fd = MR.foundation() | |
| FS = fd.summary() if fd else {} | |
| m = FS.get("mtlcc"); lad = FS.get("planteur_ladder") | |
| if not m or not lad or lad.get("_partial"): | |
| print("enhancement figure skipped (results incomplete)"); return | |
| R = {r["system"]: r for r in lad["rows"]} | |
| sb = lad["strongest_baseline"] | |
| def pick(prefix): | |
| return next(r for k, r in R.items() if k.startswith(prefix)) | |
| pan = [ | |
| ("MTLCC β test mIoU (STCLN protocol)", m["base"], "STCLN_wp", | |
| [("core\nT-SRDA", m["core"], False), ("3-seed\nT-SRDA", m["ens3"], False), | |
| ("TESSERA\nalone", m["tess_alone"], True), ("core +\nTESSERA", m["net_g"], True), | |
| ("3-seed +\nTESSERA", m["ens3_g"], True)], None), | |
| ("PLANTEUR β test mIoU-8, 100 % labels", sb["test"], "STCLN", | |
| [("core T-SRDA", R["core T-SRDA"]["test"], False), | |
| ("best T-SRDA-only\nensemble", pick("best T-SRDA-only")["test"], False), | |
| ("TESSERA LDA\nalone", R["tess768_lda alone"]["test"], True), | |
| ("core + TESSERA\n(50/50)", pick("core 50/50 TESSERA 768-D")["test"], True), | |
| ("best overall\n(val-selected)", lad["validation_selected_overall"]["test"], True)], | |
| 0.4082), | |
| ] | |
| fig, axs = plt.subplots(1, 2, figsize=(12.4, 5.0)) | |
| bases = [] | |
| for ax, (title, base, bname, items, pub) in zip(axs, pan): | |
| vals = [v for _, v, _ in items] | |
| lo = min(vals + [base]) - 0.06 | |
| for i, (n, v, ext) in enumerate(items): | |
| ax.bar(i, v - lo, bottom=lo, width=0.66, color=TEAL if ext else BLUE, hatch="//" if ext else None, | |
| edgecolor=SURF if not ext else "#ffffff", lw=0) | |
| ax.text(i, v + 0.004, f"{v:.3f}", ha="center", fontsize=9, color=INK, fontweight="bold", zorder=6, | |
| bbox=dict(boxstyle="round,pad=0.12", fc=SURF, ec="none", alpha=0.9)) | |
| ax.axhline(base, color=ORANGE, lw=1.6, ls="--", zorder=4) | |
| bases.append((bname, base)) | |
| if pub: | |
| ax.axhline(pub, color=GRAY, lw=1.0, ls=":", zorder=1) | |
| ax.text(-0.45, pub + 0.003, f"published fine-tuned OlmoEarth {pub:.4f} (transcribed)", color=INK2, fontsize=8, va="bottom") | |
| ax.set_xticks(range(len(items))); ax.set_xticklabels([n for n, _, _ in items], fontsize=8.5) | |
| ax.set_ylim(lo, max(vals + [base, pub or 0]) + 0.03) | |
| ax.set_title(title, loc="left", fontsize=11.5, fontweight="bold", color=INK) | |
| style(ax, "y") | |
| from matplotlib.patches import Patch | |
| fig.legend(handles=[Patch(facecolor=BLUE, label="T-SRDA only (no external features)"), | |
| Patch(facecolor=TEAL, hatch="//", edgecolor="#ffffff", label="uses the externally pre-trained TESSERA v2 encoder"), | |
| plt.Line2D([], [], color=ORANGE, lw=1.6, ls="--", label="strongest reproduced baseline: " + " ".join(f"{n} {b:.3f} (left, MTLCC)" if i == 0 else f"{n} {b:.3f} (right, PLANTEUR)" for i, (n, b) in enumerate(bases)))], | |
| loc="lower center", ncol=1, frameon=False, fontsize=9.5) | |
| fig.suptitle("Where the gain comes from: the T-SRDA network vs. the external encoder", x=0.01, ha="left", fontsize=13.5, fontweight="bold", color=INK) | |
| fig.text(0.01, 0.135, "Bars start above zero to make differences legible. All selections were made on validation; test was scored once. " | |
| "PLANTEUR is one seed; the greedy rows over-fit validation and are upper estimates.", fontsize=8, color=MUTED) | |
| fig.subplots_adjust(top=0.86, bottom=0.27, left=0.06, right=0.99, wspace=0.12) | |
| save(fig, "enhancement_attribution.png") | |
| def main(): | |
| bl = MR.jload(MR.B / "results/mtlcc/summary.json", []) or [] | |
| main_ = MR.mtlcc_main(); seeds = MR.mtlcc_seeds(); abl = MR.mtlcc_ablations(); rows = MR.curve() | |
| fig_architecture() | |
| gif_reduction() | |
| fig_mtlcc_benchmark(bl, seeds) | |
| ab = fig_mtlcc_ablation(main_, seeds, abl, bl) | |
| gif_ablation(ab) | |
| fig_planteur(rows) | |
| fig_pastis() | |
| fig_enhancement() | |
| if __name__ == "__main__": | |
| main() | |