File size: 31,309 Bytes
4a3ac26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#!/usr/bin/env python3
"""Additional Brigalow technical figures, showing both capabilities and shortfalls.

Outputs (in figures/):
  fig0_architecture.png            End-to-end architecture & data pipeline schematic
  fig2_bioregion_matrix.png        Recall & precision across all 17 Queensland IBRA bioregions (incl. held-out & arid shortfalls)
  fig4b_tolerance_honesty.png      Precision sensitivity: masked vs 2-yr tol vs strict 1-yr vs no-tolerance
  fig5_ablations_and_stability.png Controlled ablation ladder + date/crop-shift stability
  fig6_size_and_type_recall.png    Recall by clearing patch size (1 ha to >=100 ha) and SLATS clearing type
  fig12_visual_examples.png        Real 2023-24 Sentinel-2 before/after/SWIR/overlay gallery (detections + shortfalls)
  fig11_three_year_trends.png      (when --three-year-csv is provided) 2023-24 vs 2024-25 vs 2025-26 bioregion trends
"""
import argparse, json, os, re
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT_DIR = os.path.join(REPO, "figures")

# Okabe-Ito colourblind-safe palette
C = dict(
    blue="#0072B2",
    sky="#56B4E9",
    orange="#E69F00",
    verm="#D55E00",
    green="#009E73",
    purple="#CC79A7",
    yellow="#F0E442",
    grey="#777777",
    lgrey="#E6E6E2",
    dark="#1D1D1B",
)

HELD_OUT = {"Mulga Lands", "Desert Uplands"}


def setup():
    plt.rcParams.update({
        "font.family": "DejaVu Sans",
        "font.size": 8.5,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.grid": True,
        "grid.alpha": 0.28,
        "grid.linewidth": 0.6,
        "savefig.dpi": 200,
        "savefig.facecolor": "white",
    })


def _parse_ci(s):
    if s is None:
        return None
    if isinstance(s, (list, tuple)):
        return [100.0 * float(x) for x in s]
    m = re.match(r"([\d.]+)\s*\[([\d.]+)-([\d.]+)\]", str(s).strip())
    if m:
        return [float(m.group(1)), float(m.group(2)), float(m.group(3))]
    try:
        v = float(s)
        return [v, v, v]
    except Exception:
        return None


def _box(ax, x, y, w, h, title, body, fc="#F4F8FB", ec=C["blue"], title_color=C["dark"], fs_t=8.5, fs_b=7.3):
    p = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.015,rounding_size=0.025",
                       facecolor=fc, edgecolor=ec, linewidth=1.4, zorder=3)
    ax.add_patch(p)
    ax.text(x + w / 2, y + h - 0.032, title, ha="center", va="top", fontsize=fs_t,
            fontweight="bold", color=title_color, zorder=4)
    if body:
        ax.text(x + w / 2, y + h - 0.088, body, ha="center", va="top", fontsize=fs_b,
                color="#333333", linespacing=1.32, zorder=4)


def _arrow(ax, x0, y0, x1, y1, color="#444444", lw=1.4):
    ax.add_patch(FancyArrowPatch((x0, y0), (x1, y1), arrowstyle="-|>,head_length=6,head_width=3.5",
                                 color=color, linewidth=lw, zorder=5))


def fig0_architecture():
    setup()
    fig, ax = plt.subplots(figsize=(11.4, 5.2))
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")

    ax.text(0.01, 0.965, "Brigalow v1: End-to-End Architecture & Calibration Pipeline",
            fontsize=12.5, fontweight="bold", color=C["dark"], va="top")
    ax.text(0.01, 0.918, "9-band x 3-season Sentinel-2 + optional Queensland masks -> Spatial-Context Anomaly -> 5-fold Cross-Architecture Ensemble -> Calibrated Alerts",
            fontsize=8.3, color="#555555", va="top")

    # Stage 1: Inputs (left column)
    _box(ax, 0.015, 0.50, 0.215, 0.36, "1A. Sentinel-2 L2A (20 m)",
         "3 seasonal composites:\nβ€’ Before dry (Jun–Aug Y-1)\nβ€’ Mid wet (mid-Nov–mid-May)\nβ€’ After dry (Jul–Sep Y)\n9 spectral bands/period\n(B02,B03,B04,B05-B07,\nB08,B11,B12) -> 99 ch:\nmedians, deltas, 9 indices,\nmin/max/std temporal stats",
         fc="#EEF6FB", ec=C["blue"])

    _box(ax, 0.015, 0.14, 0.215, 0.30, "1B. QLD Mask Inputs (11 ch)",
         "Optional (dropped randomly\nin training for s2only mode):\nβ€’ SLATS woody / non-woody\nβ€’ QLD cropping (lag <=3y)\nβ€’ QLD fire scars (pre-window\n  & in-window for standard)\nβ€’ 4 known flags + 2 map ages\n99 + 11 = 110 input ch",
         fc="#FFF7EC", ec=C["orange"])

    # Stage 2: Spatial-Context Anomaly Module
    _box(ax, 0.275, 0.34, 0.185, 0.44, "2. Spatial-Context\n    Anomaly Module",
         "\nIn-network, parameter-free:\nβ€’ 15 core change channels\n  (d_bands + d_idx), each as\n  - minus 5 km crop mean\n  - crop z-score (clamp Β±6)\n  - minus 33x33 px (660 m)\n    local mean\nβ€’ Cancels regional drought\n  & phenology; isolates\n  paddock-scale clearing\nβ€’ Output: 110 + 45 = 155 ch",
         fc="#F1F9F6", ec=C["green"])

    # Stage 3: 5-Fold Cross-Architecture Ensemble
    _box(ax, 0.505, 0.16, 0.245, 0.70, "3. 5-Fold Cross-Architecture\n    Ensemble (TTA = 2)",
         "\n5 spatial-CV folds (149 cells,\n<=2023; Mulga & Desert held out):\n\nβ€’ F0 & F3: CAFormer-S36\n  (Hybrid Conv + Attention, 40M)\nβ€’ F1 & F4: ConvNeXt-Small\n  (Pure Modern ConvNet, 53M)\nβ€’ F2: SatlasPretrain Swin-B\n  (Sentinel-2 Pretrained, 99M)\n\nEach member: Siamese before/\nafter stem + backbone + ASPP\n+ U-Net decoder (scSE, 20 m\nskips); aux heads in training;\ntrained with Aligned Tversky +\nLovasz + soft-BCE loss.\nInference: 256-px crops, stride\n128, Hann + horizontal-flip TTA.",
         fc="#F6F2FA", ec=C["purple"])

    # Stage 4: Calibration & Outputs
    _box(ax, 0.795, 0.50, 0.19, 0.36, "4. Drought-Aware\n    Calibration",
         "\nPer-setting temperature\n(T, b) locked strictly on\n<=2023 data (12.8M px,\n860 uniform windows\nacross 2019–2023 incl.\nsevere 2019–20 droughts):\nβ€’ standard: T=1.149, b=-1.2\nβ€’ s2only:   T=1.072, b=-1.3",
         fc="#FDF3EE", ec=C["verm"])

    _box(ax, 0.795, 0.14, 0.19, 0.31, "5. Two-Layer Outputs",
         "8-connected >= 13 px (0.52 ha):\nβ€’ Main (alerts, p >= 0.40):\n  76.2% R / 88.8% P (2-yr)\n  80.5% strict 1-yr\nβ€’ Screening (candidates,\n  p >= 0.048):\n  94.0% R / 55.7% P (2-yr)\nβ€’ Native UTM COGs + QGIS",
         fc="#F4F4F0", ec=C["dark"])

    # Arrows
    _arrow(ax, 0.232, 0.68, 0.273, 0.60, C["blue"])
    _arrow(ax, 0.232, 0.29, 0.273, 0.44, C["orange"])
    _arrow(ax, 0.462, 0.56, 0.503, 0.56, C["green"])
    _arrow(ax, 0.752, 0.65, 0.793, 0.65, C["purple"])
    _arrow(ax, 0.890, 0.498, 0.890, 0.453, C["verm"])

    ax.text(0.015, 0.055,
            "All pretrained backbones are MIT or Apache-2.0. Exported to ONNX Runtime (max diff <= 2.5e-7 vs PyTorch) for CPU/laptop CLI inference.\n"
            "Zero 2023-24 data or held-out bioregions (Mulga Lands, Desert Uplands) entered training, checkpoint selection, calibration, or threshold locking.",
            fontsize=7.3, color="#555555", va="top")

    fig.tight_layout()
    out = os.path.join(OUT_DIR, "fig0_architecture.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig2_bioregion_matrix():
    setup()
    rs = json.load(open(os.path.join(REPO, "results/final/results_statewide.json")))
    std_rows = {r["bioregion"]: r for r in rs["net_standard"]["bioregion"]["12"]}
    hi_rows = {r["bioregion"]: r for r in rs["net_standard"]["bioregion"]["100"]}
    # Sort by number of SLATS polygons descending, keep all bioregions with n >= 10
    regs = sorted([b for b, r in std_rows.items() if r["n"] >= 10], key=lambda b: -std_rows[b]["n"])

    y = np.arange(len(regs))
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 6.2), sharey=True, gridspec_kw={"wspace": 0.08})

    for i, b in enumerate(regs):
        if b in HELD_OUT:
            ax1.axhspan(i - 0.44, i + 0.44, color="#ECECE8", zorder=0)
            ax2.axhspan(i - 0.44, i + 0.44, color="#ECECE8", zorder=0)
        elif std_rows[b]["slats_ha"] < 500:
            ax1.axhspan(i - 0.44, i + 0.44, color="#FFF3E8", zorder=0)
            ax2.axhspan(i - 0.44, i + 0.44, color="#FFF3E8", zorder=0)

    def plot_ci(ax, y_pos, ci, color, marker, label=None, fill=True):
        if ci is None:
            return
        m, lo, hi = ci
        ax.errorbar(m, y_pos, xerr=[[max(0, m - lo)], [max(0, hi - m)]], fmt=marker,
                    color=color, mfc=color if fill else "white", mec=color, mew=1.4,
                    ms=6, elinewidth=1.1, capsize=0, label=label, zorder=4)

    for i, b in enumerate(regs):
        sr, hr = std_rows[b], hi_rows[b]
        plot_ci(ax1, i - 0.14, _parse_ci(sr["recall30"]), C["blue"], "o",
                "Standard (p>=0.046)" if i == 0 else None, fill=True)
        plot_ci(ax1, i + 0.14, _parse_ci(hr["recall30"]), C["blue"], "s",
                "High confidence (p>=0.398)" if i == 0 else None, fill=False)

        plot_ci(ax2, i - 0.14, _parse_ci(sr["prec2"]), C["verm"], "o",
                "Standard (p>=0.046)" if i == 0 else None, fill=True)
        plot_ci(ax2, i + 0.14, _parse_ci(hr["prec2"]), C["green"], "s",
                "High confidence (p>=0.398)" if i == 0 else None, fill=False)

        # Annotate low-precision arid shortfalls clearly
        sp = _parse_ci(sr["prec2"])
        hp = _parse_ci(hr["prec2"])
        if b == "Channel Country" and sp and hp:
            ax2.text(36, i - 0.30, f"std {sp[0]:.1f}% / high {hp[0]:.1f}% (only 207 ha SLATS)",
                     va="bottom", fontsize=6.8, color=C["verm"], fontweight="bold",
                     bbox=dict(facecolor="#FFF3E8", edgecolor="none", pad=1.0, alpha=0.9))
        elif b in HELD_OUT and hp:
            ax2.text(hp[0] + 2.5, i + 0.14, f"{hp[0]:.1f}%", va="center", fontsize=7.0, color=C["green"], fontweight="bold")

    labels = []
    for b in regs:
        tag = " [HELD OUT]" if b in HELD_OUT else ""
        n = std_rows[b]["n"]
        ha = std_rows[b]["slats_ha"]
        labels.append(f"{b}{tag}  (n={n:,}, {ha:,} ha)")

    ax1.set_yticks(y); ax1.set_yticklabels(labels, fontsize=7.7); ax1.invert_yaxis()
    ax1.set_xlim(0, 105); ax2.set_xlim(0, 108)
    ax1.axvline(94.0, color=C["blue"], ls=":", lw=0.9, alpha=0.6)
    ax2.axvline(50.0, color="#666", ls="--", lw=0.9, alpha=0.7)
    ax2.axvline(80.0, color="#999", ls="--", lw=0.9, alpha=0.7)

    ax1.set_xlabel("Recall: SLATS polygons >= 1 ha with >= 30% alerted (%)")
    ax2.set_xlabel("Area precision, 2-year (%)")
    ax1.set_title("Recall by bioregion", loc="left", fontsize=9.8, fontweight="bold")
    ax2.set_title("Area precision by bioregion (shortfalls in arid floodplains)", loc="left", fontsize=9.8, fontweight="bold")
    ax1.legend(loc="lower left", fontsize=7.4, framealpha=0.92)
    ax2.legend(loc="lower left", fontsize=7.4, framealpha=0.92)

    fig.suptitle("Brigalow v1 across Queensland's IBRA bioregions (SLATS 2023-24, standard setting)",
                 x=0.02, ha="left", y=0.99, fontsize=11.2, fontweight="bold")
    fig.text(0.02, -0.02,
             "Grey rows = bioregions completely held out of training & calibration (Mulga Lands: 95.4% R / 61.4% P std, 83.6% R / 90.5% P high; Desert Uplands: 93.5% R / 64.2% P std, 72.7% R / 89.4% P high).\n"
             "Pale orange rows = very low-clearing arid/remote bioregions (< 500 ha SLATS clearing), where sparse natural soil/floodplain browning creates low area precision despite high recall.",
             fontsize=7.3, color="#444444")

    fig.tight_layout(rect=[0, 0.02, 1, 0.95])
    out = os.path.join(OUT_DIR, "fig2_bioregion_matrix.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig4b_tolerance_honesty():
    setup()
    rs = json.load(open(os.path.join(REPO, "results/final/results_statewide.json")))
    nt = rs["diagnostic_no_tolerance"]["results"]

    groups = [
        ("Standard\nstd (0.048)", "net_standard", "standard", "net_standard@12"),
        ("Standard\nhigh (0.40)", "net_standard", "high_confidence", "net_standard@100"),
        ("Immediate\nstd (0.048)", "net_immediate", "standard", "net_immediate@12"),
        ("Immediate\nhigh (0.452)", "net_immediate", "high_confidence", "net_immediate@113"),
        ("S2-only\nstd (0.12)", "net_s2only", "standard", "net_s2only@30"),
        ("S2-only\nhigh (0.60)", "net_s2only", "high_confidence", "net_s2only@150"),
    ]
    metrics = [
        ("Masked (excl. fire/crop/non-woody)", "masked", C["sky"]),
        ("Headline 2-yr (20 m tolerance)", "prec2_tolerant", C["blue"]),
        ("Strict 1-yr (20 m tolerance)", "prec1_tolerant", C["green"]),
        ("No-tolerance 2-yr (exact pixel)", "prec2_no_tolerance", C["orange"]),
        ("No-tolerance strict 1-yr", "prec1_no_tolerance", C["verm"]),
    ]

    fig, ax = plt.subplots(figsize=(10.8, 4.6))
    x = np.arange(len(groups))
    w = 0.155
    offsets = (np.arange(len(metrics)) - (len(metrics) - 1) / 2) * w

    for mi, (lab, key, col) in enumerate(metrics):
        vals, lo_e, hi_e = [], [], []
        for _, mkey, pt, ntkey in groups:
            if key == "masked":
                v = rs[mkey]["operating_points"][pt]["prec_masked"]
                m, lo, hi = [100 * z for z in v]
            else:
                v = nt[ntkey][key]
                m, lo, hi = [100 * z for z in v]
            vals.append(m); lo_e.append(max(0, m - lo)); hi_e.append(max(0, hi - m))
        bars = ax.bar(x + offsets[mi], vals, w * 0.92, color=col, label=lab, zorder=3)
        ax.errorbar(x + offsets[mi], vals, yerr=[lo_e, hi_e], fmt="none", ecolor="#222", elinewidth=0.8, zorder=4)
        for bx, val, he in zip(x + offsets[mi], vals, hi_e):
            ax.text(bx, val + he + 1.5, f"{val:.0f}", ha="center", va="bottom", fontsize=6.5, color="#222", rotation=90)

    ax.axhline(50, color="#555", ls="--", lw=0.9, zorder=1)
    ax.axhline(80, color="#888", ls="--", lw=0.9, zorder=1)
    ax.set_xticks(x); ax.set_xticklabels([g[0] for g in groups], fontsize=8.3)
    ax.set_ylim(0, 108); ax.set_ylabel("Area precision (%)")
    ax.set_title("Precision honesty check: how boundary tolerance & adjacent-year matching affect reported precision (SLATS 2023-24)",
                 loc="left", fontsize=9.8, fontweight="bold")
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.15), ncol=3, fontsize=7.6, frameon=False)
    fig.text(0.01, -0.10,
             "Every bar shows 95% cell-bootstrap CI. Removing the 20 m (1-pixel) boundary dilation drops precision by ~10–13 percentage points because SLATS polygon edges\n"
             "are manually edited on 10 m imagery while Brigalow predicts on a 20 m grid. High-confidence standard achieves 80.5% strict 1-yr precision and 78.0% no-tolerance 2-yr precision.",
             fontsize=7.3, color="#444444")

    fig.tight_layout()
    out = os.path.join(OUT_DIR, "fig4b_tolerance_honesty.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig5_ablations_and_stability():
    setup()
    ab_root = os.path.join(REPO, "results/dev/ablations")
    def read_ab(name):
        d = json.load(open(os.path.join(ab_root, name, "final_dev_fp32.json")))
        return 100 * d["standard"]["ap"][0], 100 * d["s2only"]["ap"][0]

    a2_std, a2_s2 = read_ab("A2_convnext_bcedice")
    a4_std, a4_s2 = read_ab("A4_satlas_swin_b")
    a1_std, a1_s2 = read_ab("A1_convnext_s")
    a3_std, a3_s2 = read_ab("A3_caformer_s36")

    # Locked 5-fold ensemble dev_uniform AP from dev2.json
    d5 = json.load(open(os.path.join(REPO, "results/dev/ensemble/dev2.json")))["results"]
    e5_std = 100 * d5["v2_5fold|standard"]["ap"][0]
    e5_s2 = 100 * d5["v2_5fold|s2only"]["ap"][0]
    stab_net = d5["v2_5fold|standard"]["stability"]

    # Stability rows from LightGBM baseline too
    gbt_d = json.load(open(os.path.join(REPO, "results/dev/baselines/dev2/dev2.json")))["results"]
    stab_gbt = next(iter(gbt_d.values()))["stability"]

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.4), gridspec_kw={"width_ratios": [1.35, 1.0], "wspace": 0.28})

    # Left: Controlled ablation ladder
    models = [
        "ConvNeXt-S\n(BCE+Dice)",
        "Satlas Swin-B\n(Aligned Tversky)",
        "ConvNeXt-S\n(Aligned Tversky)",
        "CAFormer-S36\n(Aligned Tversky)",
        "3-Arch Ensemble\n(A1+A3+A4, TTA=2)",
        "Locked 5-Fold\nEnsemble (TTA=2)",
    ]
    std_vals = [a2_std, a4_std, a1_std, a3_std, 84.23, e5_std]
    s2_vals = [a2_s2, a4_s2, a1_s2, a3_s2, 65.77, e5_s2]

    y = np.arange(len(models))
    ax1.barh(y - 0.17, std_vals, 0.32, color=C["blue"], label="Standard setting (with QLD masks)")
    ax1.barh(y + 0.17, s2_vals, 0.32, color=C["verm"], label="Sentinel-2 only (no external masks)")
    for yi, (sv, s2v) in enumerate(zip(std_vals, s2_vals)):
        ax1.text(sv + 0.7, yi - 0.17, f"{sv:.1f}%", va="center", fontsize=7.5, fontweight="bold" if yi == len(models) - 1 else "normal")
        ax1.text(s2v + 0.7, yi + 0.17, f"{s2v:.1f}%", va="center", fontsize=7.5, fontweight="bold" if yi == len(models) - 1 else "normal")
    ax1.set_yticks(y); ax1.set_yticklabels(models, fontsize=7.8); ax1.invert_yaxis()
    ax1.set_xlim(40, 96); ax1.set_xlabel("Development Average Precision on dev_uniform (%)")
    ax1.set_title("A. Controlled ablations & ensemble gain (<=2023 dev)", loc="left", fontsize=9.5, fontweight="bold")
    ax1.legend(loc="upper center", bbox_to_anchor=(0.48, -0.17), ncol=2, fontsize=7.4, frameon=False)

    # Right: Stability (date-subset & crop-offset IoU / r)
    cats = ["Another clear\ndate subset\n(Alert IoU)", "Crop grid\nshifted 48 px\n(Alert IoU)",
            "Another clear\ndate subset\n(Prob r)", "Crop grid\nshifted 48 px\n(Prob r)"]
    v_brig = [stab_net["date_iou"], stab_net["offset_iou"], stab_net["date_r"], stab_net["offset_r"]]
    v_gbt = [stab_gbt["date_iou"], stab_gbt["offset_iou"], stab_gbt["date_r"], stab_gbt["offset_r"]]
    x2 = np.arange(len(cats))
    ax2.bar(x2 - 0.18, v_brig, 0.34, color=C["blue"], label="Brigalow v1 (5-fold, TTA=2)")
    ax2.bar(x2 + 0.18, v_gbt, 0.34, color=C["green"], alpha=0.85, label="LightGBM (per-pixel, baseline features)")
    for xi, (vb, vg) in enumerate(zip(v_brig, v_gbt)):
        ax2.text(xi - 0.18, vb + 0.02, f"{vb:.2f}", ha="center", va="bottom", fontsize=7.5, fontweight="bold")
        ax2.text(xi + 0.18, vg + 0.02, f"{vg:.2f}", ha="center", va="bottom", fontsize=7.5)
    ax2.set_xticks(x2); ax2.set_xticklabels(cats, fontsize=7.4)
    ax2.set_ylim(0, 1.15); ax2.set_ylabel("Overlap (IoU) / Correlation (r)")
    ax2.set_title("B. Stability under date & grid perturbations", loc="left", fontsize=9.5, fontweight="bold")
    ax2.legend(loc="lower right", fontsize=7.3)

    fig.text(0.01, -0.16,
             "Left: All single-model ablations trained identically (180k crops on <=2023 data) and scored in fp32 on the 360-window dev_uniform set. Aligned Tversky+Lovasz beats BCE+Dice by +9.3 AP.\n"
             "Right: Measured on dev windows (n=60 for Brigalow v1, n=120 for LightGBM). LightGBM is per-pixel so crop shifts cannot affect it, but date-subset IoU is 0.38 vs Brigalow v1's 0.77.",
             fontsize=7.2, color="#444444")

    fig.tight_layout()
    out = os.path.join(OUT_DIR, "fig5_ablations_and_stability.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig6_size_and_type_recall():
    setup()
    ea = json.load(open(os.path.join(REPO, "results/final/error_analysis_2024.json")))
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12.6, 5.0), gridspec_kw={"width_ratios": [1.0, 1.2], "wspace": 0.62})

    # Left: Recall by polygon size bin
    bins = [b["bin"] for b in ea["standard|standard"]["by_size"]]
    x = np.arange(len(bins))
    for key, lab, col, mk, ls in [
        ("standard|standard", "Standard, std thr (95.9% area-wtd)", C["blue"], "o", "-"),
        ("s2only|standard", "Sentinel-2 only, std thr (93.7% area-wtd)", C["verm"], "^", "-."),
        ("standard|high_confidence", "Standard, high-conf thr (84.9% area-wtd)", C["green"], "s", "--"),
    ]:
        ys = [100 * b["r30"] for b in ea[key]["by_size"]]
        ax1.plot(x, ys, marker=mk, color=col, ls=ls, lw=2.0, ms=6.5, label=lab)
        for xi, yv in zip(x, ys):
            if key == "standard|standard":
                off = 1.8
            elif key == "s2only|standard":
                off = -3.8 if xi >= 3 else 1.8
            else:
                off = -4.2
            ax1.text(xi, yv + off, f"{yv:.1f}", ha="center", va="bottom" if off > 0 else "top", fontsize=7.0, color=col)
    counts = [b["n"] for b in ea["standard|standard"]["by_size"]]
    ax1.set_xticks(x)
    ax1.set_xticklabels([f"{b}\n(n={n:,})" for b, n in zip(bins, counts)], fontsize=7.2)
    ax1.set_ylim(58, 104); ax1.set_ylabel("Polygon recall (>=30% pixels alerted, %)")
    ax1.set_title("A. Recall rises steadily with clearing patch size", loc="left", fontsize=9.5, fontweight="bold")
    ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18), ncol=1, fontsize=7.4, frameon=False)

    # Right: Recall by SLATS clearing description (strengths & shortfalls!)
    std_d = {d["descr"]: d for d in ea["standard|standard"]["by_descr"]}
    hi_d = {d["descr"]: d for d in ea["standard|high_confidence"]["by_descr"]}
    s2_d = {d["descr"]: d for d in ea["s2only|standard"]["by_descr"]}
    order = sorted(std_d.keys(), key=lambda k: std_d[k]["r30"], reverse=True)
    short = lambda s: s.replace("Clearing - ", "").replace("Partial clearing ", "Partial: ")
    y2 = np.arange(len(order))
    ax2.barh(y2 - 0.22, [100 * std_d[k]["r30"] for k in order], 0.21, color=C["blue"], label="Standard (std thr)")
    ax2.barh(y2, [100 * s2_d[k]["r30"] for k in order], 0.21, color=C["verm"], label="S2-only (std thr)")
    ax2.barh(y2 + 0.22, [100 * hi_d[k]["r30"] for k in order], 0.21, color=C["green"], label="Standard (high-conf)")
    for yi, k in enumerate(order):
        ax2.text(100 * std_d[k]["r30"] + 1.0, yi - 0.22, f"{100 * std_d[k]['r30']:.1f}%", va="center", fontsize=6.8, color=C["blue"])
        ax2.text(100 * hi_d[k]["r30"] + 1.0, yi + 0.22, f"{100 * hi_d[k]['r30']:.1f}%", va="center", fontsize=6.8, color=C["green"])
    ax2.set_yticks(y2)
    ax2.set_yticklabels([f"{short(k)} (n={std_d[k]['n']:,})" for k in order], fontsize=7.5)
    ax2.invert_yaxis(); ax2.set_xlim(0, 114)
    ax2.set_xlabel("Polygon recall (>=30% pixels alerted, %)")
    ax2.set_title("B. Recall by SLATS clearing type (shortfall: minor thinning & partial forestry)", loc="left", fontsize=9.1, fontweight="bold")
    ax2.legend(loc="upper center", bbox_to_anchor=(0.45, -0.18), ncol=3, fontsize=7.4, frameon=False)

    fig.suptitle("Capabilities & shortfalls by patch size and clearing type (SLATS 2023-24, 27,543 polygons >= 1 ha)",
                 x=0.01, ha="left", y=1.01, fontsize=10.8, fontweight="bold")
    fig.text(0.01, -0.24,
             "Full clearing (settlement, plantation, infrastructure, mine, pasture) exceeds 94–99% recall at the standard threshold and 75–90% at high confidence.\n"
             "Partial clearing / light thinning leaves standing canopy, reducing high-confidence recall to 37–42% β€” motivating the two-layer (alerts + candidates) release.",
             fontsize=7.3, color="#444444")

    out = os.path.join(OUT_DIR, "fig6_size_and_type_recall.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig12_visual_examples(chips_dir):
    setup()
    from PIL import Image
    c = json.load(open(os.path.join(chips_dir, "chips.json")))
    by_id = {s["site"]: s for s in c["sites"]}
    picks = [
        ("S01", "FOUND: Pasture clearing (2.2 ha)\nEinasleigh Uplands β€” 100% alerted", C["green"]),
        ("S03", "FOUND: Mine clearing (3.2 ha)\nCape York Peninsula β€” 100% alerted", C["green"]),
        ("S05", "SHORTFALL (MISSED): Minor thinning (1.0 ha)\nSouth Eastern QLD β€” faint canopy change", C["purple"]),
        ("S09", "SHORTFALL (FALSE ALARM): Arid floodplain (1.9 ha)\nChannel Country β€” bare soil / water shift", C["verm"]),
        ("S13", "SHORTFALL (FIRE LOOK-ALIKE): Burn scar (27.9 ha)\nWet Tropics β€” 50% overlaps mapped fire", C["orange"]),
    ]
    picks = [p for p in picks if p[0] in by_id]
    cols = [("before_tc", "Before (True Colour)"), ("after_tc", "After (True Colour)"),
            ("after_fc", "After (SWIR / NIR / Red)"), ("overlay", "Brigalow v1 Alert + SLATS (blue)")]
    nrows = len(picks)
    fig, axs = plt.subplots(nrows, 4, figsize=(10.5, 2.35 * nrows), gridspec_kw={"wspace": 0.05, "hspace": 0.14})
    for r, (sid, label, col) in enumerate(picks):
        s = by_id[sid]
        for ci, (k, title) in enumerate(cols):
            ax = axs[r, ci]
            im = Image.open(os.path.join(chips_dir, s["files"][k]))
            ax.imshow(im); ax.set_xticks([]); ax.set_yticks([])
            for sp in ax.spines.values():
                sp.set_visible(True); sp.set_color(col if ci == 0 else "#CCCCCC"); sp.set_linewidth(2.0 if ci == 0 else 0.7)
            if r == 0:
                ax.set_title(title, fontsize=8.8, fontweight="bold", pad=6)
            if ci == 0:
                ax.set_ylabel(label, fontsize=7.6, fontweight="bold", color=col, rotation=0,
                              ha="right", va="center", labelpad=10)
            if ci == 3:
                d_b = s["dates"].get("before") or "?"
                d_a = s["dates"].get("after") or "?"
                ax.text(0.02, 0.03, f"{d_b} -> {d_a} ({s['box_km']:.1f} km box)", transform=ax.transAxes,
                        fontsize=6.4, color="white", bbox=dict(facecolor="black", alpha=0.65, pad=1.8, edgecolor="none"))
    fig.suptitle("Real Queensland Sentinel-2 examples (SLATS 2023-24): detections and real failure modes",
                 x=0.22, ha="left", y=0.995, fontsize=11.0, fontweight="bold")
    fig.text(0.22, 0.005,
             "Drawn deterministically from the statewide 2023-24 run (same sites appear in demo/index.html). Orange-red = Brigalow v1 alert (p>=0.046); blue outline = SLATS 2023-24 clearing; white ticks mark the target unit.",
             fontsize=7.2, color="#444444")
    fig.subplots_adjust(left=0.23, right=0.99, top=0.955, bottom=0.035)
    out = os.path.join(OUT_DIR, "fig12_visual_examples.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def fig11_three_year_trends(summary_csvs):
    """summary_csvs: list of (year_label, path_to_summary_csv)."""
    setup()
    import pandas as pd
    dfs = []
    for yr_lab, path in summary_csvs:
        df = pd.read_csv(path)
        df["year_label"] = yr_lab
        dfs.append(df)
    all_df = pd.concat(dfs, ignore_index=True)

    # High-confidence layer per bioregion
    hi = all_df[all_df.layer.str.contains("high confidence", case=False)]
    hi = hi[(hi.bioregion != "All") & (hi.bioregion.notna()) & (hi.bioregion != "")]
    piv = hi.pivot_table(index="bioregion", columns="year_label", values="hectares", aggfunc="sum", fill_value=0.0)
    top_regs = piv.sum(axis=1).sort_values(ascending=False).head(10).index.tolist()
    piv = piv.loc[top_regs]

    # Statewide totals (both layers)
    tot_hi = all_df[all_df.layer.str.contains("high confidence", case=False) & (all_df.bioregion == "All")].groupby("year_label")["hectares"].sum()
    tot_cand = all_df[all_df.layer.str.contains("standard", case=False) & (all_df.bioregion == "All")].groupby("year_label")["hectares"].sum()

    years = [y for y, _ in summary_csvs]
    cols = [C["blue"], C["orange"], C["green"]]

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.8), gridspec_kw={"width_ratios": [1.5, 1.0], "wspace": 0.25})
    y = np.arange(len(top_regs))
    h = 0.25
    for i, yr_lab in enumerate(years):
        vals = piv[yr_lab].values / 1e3
        ax1.barh(y + (i - 1) * h, vals, h * 0.92, color=cols[i], label=yr_lab)
    ax1.set_yticks(y); ax1.set_yticklabels([f"{b} *" if b in HELD_OUT else b for b in top_regs], fontsize=7.8)
    ax1.invert_yaxis(); ax1.set_xlabel("High-confidence alerted area (thousands of ha)")
    ax1.set_title("A. Top 10 bioregions by high-confidence alerted area", loc="left", fontsize=9.5, fontweight="bold")
    ax1.legend(loc="lower right", fontsize=8.0)

    # Right: Statewide totals bar chart
    x2 = np.arange(len(years))
    ax2.bar(x2 - 0.18, [tot_hi.get(y_, 0) / 1e3 for y_ in years], 0.34, color=C["blue"], label="Main alerts (high conf, p>=0.398)")
    ax2.bar(x2 + 0.18, [tot_cand.get(y_, 0) / 1e3 for y_ in years], 0.34, color=C["sky"], label="Candidates (standard, p>=0.046)")
    ax2.axhline(274.606, color=C["verm"], ls="--", lw=1.3, label="Official SLATS 2023-24 (274.6k ha)")
    for xi, y_ in enumerate(years):
        vh, vc = tot_hi.get(y_, 0) / 1e3, tot_cand.get(y_, 0) / 1e3
        if abs(vh - 274.6) < 35 and vh < 274.6:
            ax2.text(xi - 0.18, vh - 16, f"{vh:.0f}k", ha="center", va="top", fontsize=7.8, fontweight="bold", color="white")
        else:
            ax2.text(xi - 0.18, vh + 14, f"{vh:.0f}k", ha="center", va="bottom", fontsize=7.8, fontweight="bold", color=C["blue"],
                     bbox=dict(boxstyle="round,pad=0.1", fc="white", ec="none", alpha=0.85))
        ax2.text(xi + 0.18, vc + 14, f"{vc:.0f}k", ha="center", va="bottom", fontsize=7.8, color="#336688")
    ax2.set_xticks(x2); ax2.set_xticklabels(years, fontsize=8.5)
    ax2.set_ylim(0, max(tot_cand.max(), 825000) / 1e3 * 1.32)
    ax2.set_ylabel("Statewide alerted area (thousands of ha)")
    ax2.set_title("B. Statewide totals across three SLATS years", loc="left", fontsize=9.5, fontweight="bold")
    ax2.legend(loc="upper left", fontsize=7.2, framealpha=0.92)

    fig.suptitle("Brigalow v1 statewide clearing activity across 2023-24, 2024-25, and 2025-26 (* = held-out bioregion)",
                 x=0.01, ha="left", y=1.01, fontsize=10.6, fontweight="bold")
    fig.text(0.01, -0.04,
             "2023-24 is verified against official SLATS (274.6k ha; Brigalow high-confidence alerted 297.3k ha at 88.8% 2-yr / 80.5% strict 1-yr precision).\n"
             "2024-25 and 2025-26 have no official SLATS map yet; woody extent is clamped to 2023 (lag 2–3 yrs) and 2025-26 uses monthly fire scars through Sep 2026.",
             fontsize=7.2, color="#444444")
    fig.tight_layout()
    out = os.path.join(OUT_DIR, "fig11_three_year_trends.png")
    fig.savefig(out, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--chips-dir", default="/tmp/brigalow_gallery_chips")
    ap.add_argument("--three-year", nargs="*", default=[], help="Pairs LABEL=PATH for fig11_three_year_trends")
    ap.add_argument("--only", nargs="*", default=[])
    a = ap.parse_args()
    os.makedirs(OUT_DIR, exist_ok=True)
    jobs = {
        "fig0": fig0_architecture,
        "fig2": fig2_bioregion_matrix,
        "fig4b": fig4b_tolerance_honesty,
        "fig5": fig5_ablations_and_stability,
        "fig6": fig6_size_and_type_recall,
        "fig12": lambda: fig12_visual_examples(a.chips_dir) if os.path.exists(os.path.join(a.chips_dir, "chips.json")) else print("skip fig12: no chips"),
        "fig11": lambda: fig11_three_year_trends([tuple(x.split("=", 1)) for x in a.three_year]) if a.three_year else None,
    }
    for k, fn in jobs.items():
        if not a.only or k in a.only:
            fn()


if __name__ == "__main__":
    main()