File size: 42,352 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
#!/usr/bin/env python3
"""Figures for Brigalow's model card and technical report.

Brigalow, a model that maps woody-vegetation clearing in Queensland. Every figure is drawn from small result files
(JSON / JSONL / NPZ); a figure is skipped or drawn in part when an input is missing, and the script prints which
inputs each figure used (also written to figures/inputs_used.json).

    python scripts/generate_figures.py                 # all figures from the default inputs (INPUTS below)
    python scripts/generate_figures.py --only fig8_dev_vs_test
    python scripts/generate_figures.py density --prob-dir prob/2024 --threshold 0.02 0.25 --label-year 2024 \
        --owner-root <statewide data>/masks --out figures/data/density_2024.npz   # where the probability tiles are
    python scripts/generate_figures.py outline --boundary geoBoundaries-AUS-ADM1.geojson

Figures (figures/*.png), test year = SLATS 2023-24 (label year 2024) unless the title says dev:
  fig1_pr_test            precision-recall, statewide: the network in three settings, the other free products as
                          points (DIST-ANN's anomaly score as a curve), the locked operating points, the 50% line
  fig3_area_bioregion     alerted hectares against SLATS hectares by bioregion (log-log, 1:1 line)
  fig4_attribution        what the alert area lies on (SLATS clearing, fire scars, cropping, non-woody, woody unexplained)
  fig7_density_2024       statewide share of land alerted per 0.05-degree cell at the standard threshold, 2023-24
  fig8_dev_vs_test        the locked operating points on dev and on the test year
  fig9_trees_vs_network   LightGBM baseline against the network on the 124 evenly placed blocks, three settings
  fig10_density_years     2023-24, 2024-25 and 2025-26 at the high-confidence threshold, one colour scale, no data shown
(fig0, fig2_bioregion_matrix, fig4b, fig5_ablations_and_stability, fig6_size_and_type_recall, fig11, fig12:
scripts/generate_extra_figures.py.) Plain, colour-blind-safe (Okabe-Ito colours plus marker and line-style differences), no decoration.
'density' and 'outline' need rasterio/pyproj/scipy/geopandas and run where the data are; plotting needs numpy and
matplotlib only.
"""
import argparse, glob, json, math, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
sys.path.insert(0, os.path.join(REPO, "src"))

# ------------------------------------------------------------------------------------------------ inputs (edit here)
INPUTS = dict(
    final="results/final/results_statewide.json",        # final scorer file (network, trees on blocks, products)
    products="results/baselines/products_2024_statewide.json",  # fallback for the products if the final file has none
    model_json="weights/brigalow/model.json",                   # locked thresholds and the release dev table
    dev_main="results/dev/ensemble/dev2.json",                 # locked ensemble on dev (fp32 release path)
    dev_trees="results/dev/baselines/dev2/dev2.json",     # LightGBM baselines on the dev blocks
    density="figures/data/density_{year}.npz",
    density_years=[2024, 2025, 2026],
    outline="figures/data/qld_outline.json",
    label_year=2024,
)
SETTINGS = ["standard", "immediate", "s2only"]
SETTING_LABEL = {"standard": "Brigalow, standard", "immediate": "Brigalow, immediate", "s2only": "Brigalow, Sentinel-2 only"}
POINT_LABEL = {"standard": "standard point", "high_confidence": "high-confidence point"}
PRODUCTS = [  # key in the products block, label, marker
    ("dist_ann_any", "NASA DIST-ANN (any confirmed)", "o"),
    ("dist_ann_win", "DIST-ANN, dated in the window", "v"),
    ("dist_ann_high", "DIST-ANN, high only", "^"),
    ("gfc113_loss", "Hansen GFC loss 2023/24", "s"),
    ("dea_lc_w2n", "DEA Land Cover woody -> non-woody", "D"),
]
HOLDOUT = ["Mulga Lands", "Desert Uplands"]
DEV_RULE = {"standard": 50, "high_confidence": 80}     # dev rule: most recall at >= this area precision (%)

# Okabe-Ito
C = dict(blue="#0072B2", sky="#56B4E9", verm="#D55E00", green="#009E73", orange="#E69F00", purple="#CC79A7",
         yellow="#F0E442", black="#000000", grey="#999999")
ROLE_STYLE = {"standard": dict(color=C["blue"], ls="-"), "immediate": dict(color=C["sky"], ls="--"),
              "s2only": dict(color=C["verm"], ls="-."), "trees": dict(color=C["green"], ls=":")}
PRODUCT_COLOR = {"dist_ann_any": C["orange"], "dist_ann_win": C["orange"], "dist_ann_high": C["orange"],
                 "dist_ann_anom": C["orange"], "gfc113_loss": C["purple"], "dea_lc_w2n": C["black"]}
CAT_STYLE = [("slats_cur", "SLATS clearing, label year", C["blue"]), ("slats_adj", "SLATS clearing, adjacent year", C["sky"]),
             ("slats_other", "other SLATS change", "#9ecae1"), ("fire", "fire scar", C["orange"]),
             ("crop", "cropping", C["yellow"]), ("nonwoody", "non-woody land", C["grey"]),
             ("woody_unexpl", "woody, unexplained", C["purple"])]
NODATA_COLOR = C["purple"]

USED = {}
FOOT = []


def p(path):
    return path if os.path.isabs(path) else os.path.join(REPO, path)


def load(path, fig):
    f = p(path) if path else ""
    if f and os.path.exists(f):
        USED.setdefault(fig, []).append(os.path.relpath(f, REPO))
        return json.load(open(f))
    USED.setdefault(fig, []).append(f"MISSING {path}")
    return None


def plt_setup():
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    plt.rcParams.update({"font.size": 9, "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True,
                         "grid.color": "#e5e5e5", "grid.linewidth": 0.6, "legend.frameon": False, "figure.dpi": 100,
                         "savefig.dpi": 200, "savefig.bbox": "tight", "font.family": "DejaVu Sans"})
    return plt


def note(text):
    """Footnote under the figure (drawn by save())."""
    FOOT.append(text)


def save(fig, name, out):
    if FOOT:
        fig.text(0.01, -0.01, "\n".join(FOOT), ha="left", va="top", fontsize=7, color="#555555")
        FOOT.clear()
    os.makedirs(out, exist_ok=True)
    fn = os.path.join(out, name + ".png")
    fig.savefig(fn)
    import matplotlib.pyplot as plt
    plt.close(fig)
    print(f"  wrote {os.path.relpath(fn, REPO) if fn.startswith(REPO) else fn}")
    return fn


def v100(e, k):
    """Metric k of a curve entry as a percentage triple (point, lo, hi), or None when not reached / missing."""
    x = (e or {}).get(k)
    if x is None or (isinstance(x, (list, tuple)) and x[0] is None):
        return None
    if isinstance(x, (list, tuple)):
        return tuple(None if t is None else 100 * t for t in x)
    return (100 * x, None, None)


def parse_ci(s):
    """'59.9 [53.5-66.7]' -> (59.9, 53.5, 66.7); None / 'n/a' / 'not reached' -> None."""
    if s is None:
        return None
    if isinstance(s, (list, tuple)):
        return tuple(None if v is None else 100 * v for v in s) if s and s[0] is not None else None
    m = re.match(r"\s*([\d.]+)\s*\[([\d.]+)-([\d.]+)\]", str(s))
    return tuple(float(x) for x in m.groups()) if m else None


def applied(t):
    """Threshold label with the rule the maps apply: stored round(p*250) >= ceil(t*250), i.e. p >= (cut - 0.5) / 250."""
    cut = math.ceil(float(t) * 250 - 1e-9); a = (cut - 0.5) / 250
    return f"t={float(t):g}" if abs(a - float(t)) < 1e-9 else f"t={float(t):g}, applied p>={a:.3f}"


def yr(Y):
    return f"{Y - 1}-{str(Y)[2:]}"


def err(v):
    """xerr / yerr pair from a (point, lo, hi) triple."""
    if v is None or v[1] is None:
        return None
    return [[v[0] - v[1]], [v[2] - v[0]]]


# ------------------------------------------------------------------------------------------------ final-file access
class Final:
    def __init__(self, a, fig):
        self.d = load(a.final, fig) or {}
        self.mj = load(a.model_json, fig) if a.model_json else None
        prods = self.d.get("products")
        self.products = prods if prods else (load(a.products, fig) or {})
        self.Y = (self.d.get("meta") or {}).get("label_year", a.label_year)

    def net(self, s):
        return self.d.get(f"net_{s}")

    def blocks(self, s):
        return self.d.get(f"net_{s}_blocks")

    def trees(self, s):
        return self.d.get(f"gbt_{s}")

    def op(self, s, point):
        """(cut, curve entry) of a locked operating point of setting s."""
        m = self.net(s) or {}
        o = (m.get("operating_points") or {}).get(point)
        if o:
            return o.get("cut"), o
        thr = ((self.mj or {}).get("thresholds") or {}).get(s, {}).get(point)
        if thr is None:
            return None, None
        cut = math.ceil(thr * 250 - 1e-9)
        return cut, next((e for e in m.get("curve", []) if e["cut"] == cut), None)

    def cut_of(self, s, point):
        return self.op(s, point)[0]


def curve_xy(method, key="r30"):
    cv = sorted(method["curve"], key=lambda e: e["cut"])
    pts = [(v100(e, key), v100(e, "prec2")) for e in cv]
    pts = [(x[0], y[0]) for x, y in pts if x and y]
    return [x for x, _ in pts], [y for _, y in pts]


def entry_at(method, cut):
    return next((e for e in (method or {}).get("curve", []) if e["cut"] == cut), None)


# ------------------------------------------------------------------------------------------------ fig 1
def _rule_lines(ax, which=("standard", "high_confidence")):
    for pt in which:
        col = "#444444" if pt == "standard" else "#9a9a9a"
        ax.axhline(DEV_RULE[pt], color=col, lw=0.9 if pt == "standard" else 0.7, ls=(0, (4, 3)), zorder=1,
                   label=f"{DEV_RULE[pt]}% precision: dev rule for the {POINT_LABEL[pt]}")


def _mark_point(ax, e, col, filled, label_txt=None, dx=1.5, dy=-4.5):
    x, y = v100(e, "r30"), v100(e, "prec2")
    if not (x and y):
        return
    ax.errorbar(x[0], y[0], xerr=err(x), yerr=err(y), fmt="o" if filled else "s", ms=7, mfc=col if filled else "white",
                mec=col, mew=1.5, color=col, elinewidth=0.9, capsize=0, zorder=6)
    if label_txt:
        ax.annotate(f"{label_txt}: R {x[0]:.1f}, P {y[0]:.1f}", (x[0], y[0]), xytext=(dx, dy), textcoords="offset points",
                    fontsize=7, color=col, ha="right" if dx < 0 else "left", va="top", zorder=7,
                    bbox=dict(facecolor="white", edgecolor="none", alpha=0.75, pad=0.5))


def fig1_test(a, out):
    plt = plt_setup()
    F = Final(a, "fig1_pr_test")
    if not F.d and not F.products:
        print("fig1_pr_test: no inputs, skipped"); return
    fig, ax = plt.subplots(figsize=(6.8, 5.0))
    _rule_lines(ax)
    drawn = False
    for s in SETTINGS:
        m = F.net(s)
        if not m:
            continue
        x, y = curve_xy(m)
        st = ROLE_STYLE[s]
        ax.plot(x, y, lw=1.6, label=SETTING_LABEL[s] + " (statewide)", **st)
        drawn = True
        if s in ("standard", "s2only"):
            for pt, filled in (("standard", True), ("high_confidence", False)):
                cut, e = F.op(s, pt)
                lab = applied(e.get('t', cut / 250)) if e else None
                _mark_point(ax, e, st["color"], filled, lab, dx=-8 if s == "standard" else 8, dy=-6 if filled else 10)
    if not drawn:
        note("Brigalow curves: pending (final statewide scores not found).")
    pr = F.products
    if pr:
        if "dist_ann_anom" in pr:
            x, y = curve_xy(pr["dist_ann_anom"])
            ax.plot(x, y, color=C["orange"], lw=1, ls=(0, (1, 1.5)), label="DIST-ANN anomaly score (curve)")
        for key, lab, mk in PRODUCTS:
            if key in pr:
                e = pr[key]["curve"][0]
                r, q = v100(e, "r30"), v100(e, "prec2")
                ax.errorbar(r[0], q[0], xerr=err(r), yerr=err(q), fmt=mk, color=PRODUCT_COLOR[key], mfc="white", ms=6,
                            mew=1.3, elinewidth=0.8, capsize=0, label=lab)
    ax.set_xlim(0, 100); ax.set_ylim(0, 100)
    ax.set_xlabel("Recall: SLATS clearing polygons >= 1 ha with >= 30% of pixels alerted (%)")
    ax.set_ylabel("Area precision, 2-year (%)")
    ax.set_title(f"Statewide test, SLATS {yr(F.Y)}, all of Queensland", loc="left", fontsize=10)
    ax.plot([], [], "o", color="#444", label="locked point: standard (filled), high confidence (open)")
    ax.legend(fontsize=7, loc="upper left", bbox_to_anchor=(1.02, 1.0))
    n = (F.d.get("meta") or {}).get("n_polys_ge1ha")
    note(f"{n - 1:,} SLATS clearing polygons >= 1 ha scored ({n:,} in the label year; one has under 60% of its pixels on "
         "owned tiles). Thresholds were chosen on dev data from the training years and applied once to the test year."
         if n else "Thresholds chosen on dev data, applied once to the test year.")
    std_op = F.op("standard", "standard")
    std_t = (std_op[0] / 250.0) if (std_op and std_op[0] is not None) else 0.048
    note("Area precision counts an alert pixel as on SLATS clearing if it lies within one pixel (20 m) of a 2023-24 "
         f"polygon or touches a 2022-23 one, for every method. Maps store round(p x 250), so {applied(std_t)}.")
    note("Locked points were chosen on dev: standard = most recall at >= 50% area precision, high confidence = most "
         "recall at >= 80%. Test-year precision against those targets:")
    res = []
    for st_ in SETTINGS:
        for pt in ("standard", "high_confidence"):
            e = F.op(st_, pt)[1]
            q = v100(e, "prec2") if e else None
            if q:
                res.append(f"{st_} {'std' if pt == 'standard' else 'high'} {q[0]:.1f}% ({'below' if q[0] < DEV_RULE[pt] else 'meets'} {DEV_RULE[pt]}%)")
    note("; ".join(res) + ". 95% intervals: bootstrap over 1-degree cells.")
    note("LightGBM was scored on 124 evenly placed blocks only, not statewide: see fig9.")
    save(fig, "fig1_pr_test", out)


def _bioregion_rows(method, cut=None):
    b = (method or {}).get("bioregion") or {}
    if not b:
        return None
    key = str(cut) if cut is not None and str(cut) in b else sorted(b, key=int)[0]
    return {r["bioregion"].replace(" (HELD OUT)", ""): r for r in b[key]}


def _place_labels(fig, ax, labels, fontsize=6):
    """Greedy label placement: try offsets around each point until the text box overlaps no placed label and no
    point; a thin leader line joins labels placed away from their point."""
    fig.canvas.draw()
    r = fig.canvas.get_renderer()
    pts = [ax.transData.transform((x, y)) for x, y, _ in labels]
    placed = []
    cand = [(4, 2), (4, -8), (-4, 2), (-4, -8), (4, 9), (-4, 9), (4, -15), (-4, -15), (8, 16), (8, -22), (-8, 16),
            (-8, -22), (12, 24), (12, -30), (-12, 24), (-12, -30)]
    for (x, y, txt), (px, py) in sorted(zip(labels, pts), key=lambda t: -t[1][1]):
        best = None
        for dx, dy in cand:
            t = ax.annotate(txt, (x, y), xytext=(dx, dy), textcoords="offset points", fontsize=fontsize, color="#333",
                            ha="left" if dx > 0 else "right", va="bottom")
            bb = t.get_window_extent(r).expanded(1.04, 1.1)
            hit = any(bb.overlaps(o) for o in placed) or any(bb.contains(qx, qy) for qx, qy in pts)
            if not hit:
                best = (t, bb, dx, dy); break
            t.remove()
        if best is None:
            t = ax.annotate(txt, (x, y), xytext=cand[0], textcoords="offset points", fontsize=fontsize, color="#333", va="bottom")
            best = (t, t.get_window_extent(r), *cand[0])
        t, bb, dx, dy = best
        if abs(dy) > 9 or abs(dx) > 4:
            t.arrow_patch = None
            t.remove()
            ax.annotate(txt, (x, y), xytext=(dx, dy), textcoords="offset points", fontsize=fontsize, color="#333",
                        ha="left" if dx > 0 else "right", va="bottom",
                        arrowprops=dict(arrowstyle="-", color="#999999", lw=0.5, shrinkA=0, shrinkB=3))
        placed.append(bb)


def fig3_area(a, out):
    plt = plt_setup()
    F = Final(a, "fig3_area_bioregion")
    series = []
    if F.net("standard"):
        for pt, filled in (("standard", True), ("high_confidence", False)):
            cut = F.cut_of("standard", pt)
            rows = _bioregion_rows(F.net("standard"), cut)
            if rows and str(cut) in F.net("standard").get("bioregion", {}):
                series.append((f"Brigalow, {POINT_LABEL[pt]} ({applied(F.op('standard', pt)[1].get('t', cut / 250))})", rows, C["blue"], "o", filled))
    old = load(a.products, "fig3_area_bioregion") or {}
    for key, lab, mk in (("dist_ann_any", "NASA DIST-ANN (any confirmed)", "s"), ("gfc113_loss", "Hansen GFC loss", "^"),
                         ("dea_lc_w2n", "DEA Land Cover woody -> non-woody", "D")):
        rows = _bioregion_rows(F.products.get(key)) or _bioregion_rows(old.get(key))
        if rows:
            series.append((lab, rows, PRODUCT_COLOR[key], mk, False))
    if not series:
        print("fig3_area_bioregion: no inputs, skipped"); return
    fig, ax = plt.subplots(figsize=(6.6, 5.2))
    lo, hi = 1e9, 0
    labels = []
    for k, (lab, rows, col, mk, filled) in enumerate(series):
        xs, ys, ns = [], [], []
        for n, r in rows.items():
            if r.get("slats_ha") and r["slats_ha"] >= 100:
                xs.append(r["slats_ha"]); ys.append(max(r["alert_ha"], 1)); ns.append(n)
        ax.scatter(xs, ys, marker=mk, s=28, facecolor=col if filled else "white", edgecolor=col, linewidth=1.2, label=lab, zorder=3)
        lo = min([lo] + xs + ys); hi = max([hi] + xs + ys)
        if k == 0:
            labels = [(x, y, n + (" *" if n in HOLDOUT else "")) for x, y, n in zip(xs, ys, ns)]
    ax.set_xscale("log"); ax.set_yscale("log")
    lo, hi = 10 ** math.floor(math.log10(max(lo, 1))), 10 ** math.ceil(math.log10(hi))
    ax.plot([lo, hi], [lo, hi], color="#666", lw=0.8, ls="--", label="alerted = SLATS (1:1)")
    ax.set_xlim(lo, hi); ax.set_ylim(lo, hi)
    _place_labels(fig, ax, labels)
    ax.set_xlabel(f"SLATS clearing mapped in {yr(F.Y)} (ha)"); ax.set_ylabel("Alerted area (ha)")
    ax.set_title(f"Alerted area against SLATS area by bioregion, SLATS {yr(F.Y)}", loc="left", fontsize=10)
    ax.legend(fontsize=7, loc="upper left")
    note("Bioregions with >= 100 ha of SLATS clearing; * held out; names on the first series. Alerted area includes "
         "alerts that SLATS does not confirm (fig4). Points at the lower axis limit are drawn there because their alerted "
         "area is near zero (for example Hansen in the Channel Country).")
    save(fig, "fig3_area_bioregion", out)


# ------------------------------------------------------------------------------------------------ fig 4
def fig4_attribution(a, out):
    plt = plt_setup()
    F = Final(a, "fig4_attribution")
    bars = []
    for s in SETTINGS:
        for pt in ("standard", "high_confidence"):
            if s == "immediate" and pt == "high_confidence":
                continue
            cut, e = F.op(s, pt)
            att = ((F.net(s) or {}).get("attribution") or {}).get(str(cut))
            src = att if att else e
            if src and "shares" not in src:
                src = dict(shares={k: v for k, v in src.items() if k != "alert_ha"}, alert_ha=src.get("alert_ha"))
            if src:
                bars.append((f"{SETTING_LABEL[s]}, {POINT_LABEL[pt]} ({applied((e or {}).get('t', cut / 250))})", src))
    for key, lab, _ in PRODUCTS:
        if key in F.products:
            bars.append((lab, F.products[key]["curve"][0]))
    if not bars:
        print("fig4_attribution: no inputs, skipped"); return
    fig, ax = plt.subplots(figsize=(7.4, 0.42 * len(bars) + 1.4))
    for i, (lab, e) in enumerate(bars):
        left = 0
        for cat, cl, col in CAT_STYLE:
            v = 100 * e["shares"][cat][0]
            ax.barh(i, v, left=left, color=col, edgecolor="white", linewidth=0.5, label=cl if i == 0 else None)
            if v >= 7:
                ax.text(left + v / 2, i, f"{v:.0f}", ha="center", va="center", fontsize=7,
                        color="white" if col in (C["blue"], C["purple"]) else "black")
            left += v
        ax.text(101, i, f"{e['alert_ha'] / 1e3:,.0f}k ha", va="center", fontsize=7, color="#444")
    ax.set_yticks(range(len(bars))); ax.set_yticklabels([b[0] for b in bars], fontsize=8); ax.invert_yaxis()
    ax.set_xlim(0, 112); ax.set_xticks(range(0, 101, 20)); ax.grid(axis="y", visible=False); ax.set_axisbelow(True)
    ax.set_xlabel("Share of alerted area (%); each pixel counted once, in the order of the legend")
    ax.set_title(f"What the alerts lie on, SLATS {yr(F.Y)}, statewide", loc="left", fontsize=10, pad=34)
    ax.legend(fontsize=7, ncol=4, loc="lower left", bbox_to_anchor=(0.0, 1.0))
    note("Layers: SLATS clearing and other change, Queensland fire scars, cropping and woody extent (TERN). 'Woody, "
         "unexplained' is woody land with none of these records: unmapped clearing, thinning, drought or model error.")
    save(fig, "fig4_attribution", out)


# ------------------------------------------------------------------------------------------------ fig 5
def fig8_dev_vs_test(a, out):
    plt = plt_setup()
    F = Final(a, "fig8_dev_vs_test")
    dev = (F.mj or {}).get("dev") or {}
    if not dev or not F.d:
        print("fig8_dev_vs_test: needs model.json dev rows and the final file, skipped"); return
    fig, ax = plt.subplots(figsize=(6.4, 5.0))
    _rule_lines(ax, ("standard", "high_confidence"))
    lines = ["setting   point     (threshold)                     dev R / P      test R / P"]
    for s in SETTINGS:
        st = ROLE_STYLE[s]
        for pt, mk in (("standard", "o"), ("high_confidence", "s")):
            o = (dev.get(s) or {}).get("operating_points", {}).get(pt)
            cut, e = F.op(s, pt)
            if not (o and e):
                continue
            dx, dy = 100 * o["recall"], 100 * o["precision"]
            tx, ty = v100(e, "r30"), v100(e, "prec2")
            lines.append(f"{s:<9} {'standard' if pt == 'standard' else 'high conf':<9} {'(' + applied(o['t']) + ')':<31}"
                         f"{dx:5.1f} / {dy:4.1f}    {tx[0]:5.1f} / {ty[0]:4.1f}")
            if s == "immediate":
                continue          # within a point of standard on both sets; listed in the table only
            ax.annotate("", xy=(tx[0], ty[0]), xytext=(dx, dy),
                        arrowprops=dict(arrowstyle="->", color=st["color"], lw=1.2, shrinkA=4, shrinkB=5))
            ax.plot(dx, dy, mk, ms=7, mfc="white", mec=st["color"], mew=1.5, zorder=5)
            ax.errorbar(tx[0], ty[0], xerr=err(tx), yerr=err(ty), fmt=mk, ms=7, mfc=st["color"], mec=st["color"],
                        color=st["color"], elinewidth=0.9, capsize=0, zorder=6)
    for s in ("standard", "s2only"):
        ax.plot([], [], "-", color=ROLE_STYLE[s]["color"], label=SETTING_LABEL[s])
    ax.plot([], [], "o", mfc="white", mec="#444", label="dev (open)"); ax.plot([], [], "o", color="#444", label="test (filled, 95% interval)")
    ax.plot([], [], "s", color="#444", label="square: high-confidence point")
    ax.set_xlim(0, 100); ax.set_ylim(0, 100)
    ax.set_xlabel("Recall: polygons >= 1 ha with >= 30% of pixels alerted (%)"); ax.set_ylabel("Area precision, 2-year (%)")
    ax.set_title(f"Locked operating points: dev (training years) against test (SLATS {yr(F.Y)})", loc="left", fontsize=10)
    ax.legend(fontsize=7, loc="upper left", bbox_to_anchor=(1.02, 1.0))
    ax.text(1.04, 0.55, "\n".join(lines), transform=ax.transAxes, fontsize=6.8, family="DejaVu Sans Mono", va="top")
    note("Dev / calibration: 860 uniform windows from <=2023 training years (360 dev_uniform + 500 OOF train_uniform spanning "
         "2019-2023 including drought years), where thresholds were chosen. Test: every pixel of Queensland (2023-24), scored once.")
    note("Immediate is within about one point of standard on both sets and is listed in the table only.")
    res_std = []
    for pt in ("standard", "high_confidence"):
        o = (dev.get("standard") or {}).get("operating_points", {}).get(pt); e = F.op("standard", pt)[1]
        if o and e:
            q = v100(e, "prec2")
            verdict = "meets" if q[0] >= DEV_RULE[pt] else "below"
            res_std.append(f"{POINT_LABEL[pt]} ({applied(o['t'])}): target >= {DEV_RULE[pt]}%, <=2023 pooled {100 * o['precision']:.1f}%, "
                           f"test {q[0]:.1f}% [{q[1]:.1f}-{q[2]:.1f}] ({verdict})")
    if res_std:
        note("Standard setting on the test year: " + "; ".join(res_std) + ".")
    save(fig, "fig8_dev_vs_test", out)


# ------------------------------------------------------------------------------------------------ fig 9
def fig9_trees(a, out):
    plt = plt_setup()
    F = Final(a, "fig9_trees_vs_network")
    devt = load(a.dev_trees, "fig9_trees_vs_network")
    if not any(F.trees(s) for s in SETTINGS):
        print("fig9_trees_vs_network: no tree scores, skipped"); return
    fig, axs = plt.subplots(1, 3, figsize=(10.5, 3.8), sharey=True)
    for ax, s in zip(axs, SETTINGS):
        _rule_lines(ax, ("standard",))
        nb, tb = F.blocks(s), F.trees(s)
        if nb:
            x, y = curve_xy(nb)
            ax.plot(x, y, lw=1.6, label="network (locked ensemble)", **ROLE_STYLE[s])
            for pt, filled in (("standard", True), ("high_confidence", False)):
                e = entry_at(nb, F.cut_of(s, pt))
                if e:
                    ax.plot(v100(e, "r30")[0], v100(e, "prec2")[0], "o" if filled else "s", ms=7, mfc=ROLE_STYLE[s]["color"] if filled else "white",
                            mec=ROLE_STYLE[s]["color"], mew=1.5, zorder=5)
        if tb:
            x, y = curve_xy(tb)
            ax.plot(x, y, color=C["green"], lw=1.6, ls=":", label="LightGBM (baseline 32-feature inputs + same masks)")
            o = ((devt or {}).get("results", {}).get(f"gbt_{s}|fixed") or {}).get("operating_points", {}).get("standard")
            if o:
                e = entry_at(tb, math.ceil(o["t"] * 250 - 1e-9))
                if e:
                    ax.plot(v100(e, "r30")[0], v100(e, "prec2")[0], "D", ms=6, color=C["green"], zorder=5,
                            label=f"LightGBM dev point ({applied(o['t'])})")
        ax.set_xlim(0, 100); ax.set_ylim(0, 100)
        ax.set_title({"standard": "Standard", "immediate": "Immediate", "s2only": "Sentinel-2 only"}[s], loc="left", fontsize=10)
        ax.set_xlabel("Recall, polygons >= 1 ha (%)")
        ax.legend(fontsize=6.5, loc="lower left")
    axs[0].set_ylabel("Area precision, 2-year (%)")
    pop = (F.trees("standard") or {}).get("population", "124 blocks")
    fig.suptitle(f"LightGBM baseline against the network on the same pixels: {pop}, SLATS {yr(F.Y)}", x=0.02, ha="left", fontsize=10)
    note("Both scored on the same block pixels and polygons. LightGBM gets the same Queensland mask layers but the baseline "
         "32-feature, two-season, six-band Sentinel-2 stack")
    note("(features.compute_basic), not the network's 99 features. Network points: locked standard (filled) and "
         "high-confidence (open). LightGBM probabilities are uncalibrated; its points were chosen on dev.")
    save(fig, "fig9_trees_vs_network", out)


# ------------------------------------------------------------------------------------------------ fig 7, 10
def _density(path, fig):
    import numpy as np
    f = p(path)
    if not os.path.exists(f):
        USED.setdefault(fig, []).append(f"MISSING {path}")
        return None
    USED.setdefault(fig, []).append(os.path.relpath(f, REPO))
    d = np.load(f, allow_pickle=False)
    meta = json.loads(str(d["meta"]))
    al = d["alert_px"]
    if al.ndim == 2:
        al = al[None]
    thr = meta.get("thresholds") or [meta.get("threshold")]
    land = d["land_px"] if "land_px" in d.files else d["valid_px"]
    return dict(lon=d["lon_edges"], lat=d["lat_edges"], alert=al, valid=d["valid_px"], land=land, thr=thr, meta=meta)


def _draw_density(ax, D, k, norm, cmap, ol):
    import numpy as np, matplotlib
    va, la = D["valid"], D["land"]
    share = np.where(va > 0, D["alert"][k] / np.maximum(va, 1), np.nan)
    nod = (la > 0) & (va < 0.5 * la)
    mapped = (va > 0) & ~nod
    ax.pcolormesh(D["lon"], D["lat"], np.where(mapped, 1.0, np.nan), cmap=matplotlib.colors.ListedColormap(["#ececec"]),
                  shading="flat", rasterized=True)
    show = np.where(mapped & (share > 0), np.clip(share, norm.vmin, None), np.nan)
    im = ax.pcolormesh(D["lon"], D["lat"], show, cmap=cmap, norm=norm, shading="flat", rasterized=True)
    ax.pcolormesh(D["lon"], D["lat"], np.where(nod, 1.0, np.nan), cmap=matplotlib.colors.ListedColormap([NODATA_COLOR]),
                  shading="flat", rasterized=True)
    if ol:
        for ring in ol.get("qld", []):
            xs, ys = zip(*ring); ax.plot(xs, ys, color="#333", lw=0.6)
        for name, rings in ol.get("holdout", {}).items():
            for ring in rings:
                xs, ys = zip(*ring); ax.plot(xs, ys, color="#333", lw=0.8, ls="--")
    ax.set_aspect(1 / math.cos(math.radians(-20)))
    ax.set_xlim(137.8, 153.8); ax.set_ylim(-29.4, -9.9); ax.grid(False)
    return im, int(nod.sum())


def _legend_patches(ax):
    from matplotlib.patches import Patch
    from matplotlib.lines import Line2D
    h = [Patch(color="#ececec", label="mapped, no alert"), Patch(color=NODATA_COLOR, label="no data on >= half of the land"),
         Line2D([], [], color="#333", lw=0.8, ls="--", label="held-out bioregions")]
    ax.legend(handles=h, fontsize=7, loc="upper right", bbox_to_anchor=(1.0, 1.0))


def _pct_formatter(cb):
    from matplotlib.ticker import FuncFormatter
    cb.ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{100 * v:.3g}%"))
    cb.ax.yaxis.set_minor_formatter(FuncFormatter(lambda v, _: ""))


def _norm_for(Ds, k):
    import numpy as np
    from matplotlib.colors import LogNorm
    nz = np.concatenate([(D["alert"][k] / np.maximum(D["valid"], 1))[(D["valid"] > 0) & (D["alert"][k] > 0)] for D in Ds])
    if not len(nz):
        return LogNorm(1e-5, 1e-2)
    vmax = float(np.percentile(nz, 99.5)); vmin = min(max(vmax / 1000, float(np.percentile(nz, 2))), vmax / 3)
    return LogNorm(vmin, vmax)


def fig7_density(a, out):
    plt = plt_setup()
    import matplotlib
    Y = a.label_year
    D = _density(a.density.format(year=Y), "fig7_density")
    if D is None:
        print("fig7_density: no density file, skipped"); return
    ol = load(a.outline, "fig7_density")
    k = 0
    fig, ax = plt.subplots(figsize=(6.2, 7.0))
    cmap = matplotlib.colormaps["cividis_r"]
    im, nn = _draw_density(ax, D, k, _norm_for([D], k), cmap, ol)
    cb = fig.colorbar(im, ax=ax, shrink=0.55, pad=0.02); _pct_formatter(cb)
    cb.set_label(f"Share of land alerted ({applied(D['thr'][k])}, alerts >= 13 px)", fontsize=8)
    ax.set_xlabel("Longitude"); ax.set_ylabel("Latitude"); _legend_patches(ax)
    ax.set_title(f"Alerts at the standard threshold, SLATS {yr(Y)}, {D['meta'].get('cell_deg', 0.05)}-degree cells", loc="left", fontsize=10)
    note(f"{D['meta'].get('n_rasters')} Sentinel-2 tiles. Share = alerted pixels / pixels with a map in the cell. "
         "Outline: geoBoundaries ADM1 (CC BY 4.0).")
    save(fig, f"fig7_density_{Y}", out)


def fig10_density_years(a, out):
    plt = plt_setup()
    import matplotlib
    Ds = [(Y, _density(a.density.format(year=Y), "fig10_density_years")) for Y in a.density_years]
    Ds = [(Y, D) for Y, D in Ds if D is not None]
    if not Ds:
        print("fig10_density_years: no density files, skipped"); return
    ol = load(a.outline, "fig10_density_years")
    t_hi = a.density_threshold
    ks = [min(range(len(D["thr"])), key=lambda i: abs(D["thr"][i] - t_hi)) for _, D in Ds]
    import matplotlib.colors as mc
    norm = _norm_for([D for _, D in Ds], 0) if False else None
    import numpy as np
    nz = np.concatenate([(D["alert"][k] / np.maximum(D["valid"], 1))[(D["valid"] > 0) & (D["alert"][k] > 0)] for (_, D), k in zip(Ds, ks)])
    vmax = float(np.percentile(nz, 99.5)) if len(nz) else 1e-2
    norm = mc.LogNorm(min(max(vmax / 1000, float(np.percentile(nz, 2)) if len(nz) else 1e-5), vmax / 3), vmax)
    cmap = matplotlib.colormaps["cividis_r"]
    fig, axs = plt.subplots(1, len(Ds), figsize=(3.6 * len(Ds) + 0.8, 4.6))
    axs = np.atleast_1d(axs)
    for ax, (Y, D), k in zip(axs, Ds, ks):
        im, nn = _draw_density(ax, D, k, norm, cmap, ol)
        scored = "scored against SLATS" if Y <= INPUTS["label_year"] else "no SLATS map yet: not scored"
        ax.set_title(f"SLATS year {yr(Y)}\n{scored}", loc="left", fontsize=9)
        ax.set_xticks([140, 145, 150]); ax.tick_params(labelsize=7)
        tot = int(D["alert"][k].sum()) * 0.04
        ax.text(0.98, 0.98, f"{tot / 1e3:,.0f}k ha alerted\n{nn} cells mostly no data", transform=ax.transAxes, fontsize=7, va="top", ha="right")
    from matplotlib.patches import Patch
    from matplotlib.lines import Line2D
    fig.legend(handles=[Patch(color="#ececec", label="mapped, no alert"), Patch(color=NODATA_COLOR, label="no data on >= half of the land in the cell"),
                        Line2D([], [], color="#333", lw=0.8, ls="--", label="held-out bioregions")],
               fontsize=7, loc="lower center", ncol=3, bbox_to_anchor=(0.45, -0.02))
    cb = fig.colorbar(im, ax=list(axs), shrink=0.6, pad=0.015); _pct_formatter(cb)
    cb.set_label(f"Share of land alerted ({applied(Ds[0][1]['thr'][ks[0]])}, high confidence)", fontsize=8)
    fig.suptitle("Alert density at the high-confidence threshold, one colour scale for all three years", x=0.02, ha="left", fontsize=10)
    note("Mask inputs: woody extent & cropping lagged 3 yr in 2023-24 (2021); latest published woody extent (2023) and "
         "seasonal cropping (2024/2025) in 2024-25 & 2025-26. Alerted hectares count pixels of alerts >= 13 px.")
    save(fig, "fig10_density_years", out)


# ------------------------------------------------------------------------------------------------ data steps
def _density_tile(args):
    """Counts for one tile: (cell rows, cell cols, valid, land, [alert per threshold]) per 10x10-pixel block."""
    import numpy as np, rasterio
    from pyproj import Transformer
    from brigalow import postprocess
    f, thr, owner_root, B, lat_e, lon_e = args
    with rasterio.open(f) as d:
        q = d.read(1); tr = d.transform; crs = d.crs
    valid = q != 255
    land = None
    if owner_root:
        op = os.path.join(owner_root, os.path.splitext(os.path.basename(f))[0], "owner.tif")
        if os.path.exists(op):
            with rasterio.open(op) as d:
                land = d.read(1) == 1
    if land is None:
        land = valid
    if not (valid.any() or land.any()):
        return None
    H, W = q.shape; Hp, Wp = -(-H // B) * B, -(-W // B) * B
    bsum = lambda x: np.pad(x, ((0, Hp - H), (0, Wp - W))).reshape(Hp // B, B, Wp // B, B).sum((1, 3))
    v_b = bsum(valid); l_b = bsum(land)
    a_b = [bsum(postprocess.label_alerts(q, t)[0] > 0) for t in thr]
    r, c = np.nonzero((v_b > 0) | (l_b > 0))
    xs, ys = rasterio.transform.xy(tr, (r + 0.5) * B - 0.5, (c + 0.5) * B - 0.5)
    lon, lat = Transformer.from_crs(crs, 4326, always_xy=True).transform(np.asarray(xs), np.asarray(ys))
    i = np.searchsorted(lat_e, lat) - 1; j = np.searchsorted(lon_e, lon) - 1
    ok = (i >= 0) & (i < len(lat_e) - 1) & (j >= 0) & (j < len(lon_e) - 1)
    return (os.path.basename(f), i[ok], j[ok], v_b[r, c][ok], l_b[r, c][ok], [x[r, c][ok] for x in a_b])


def cmd_density(a):
    """Reduce per-tile probability rasters to alerted / valid / land pixel counts on a lon/lat grid (needs rasterio,
    pyproj, scipy). Alerts as the release maps: p >= threshold, 8-connected components >= 13 px
    (postprocess.label_alerts), one count layer per threshold. Land = owned Queensland land from the statewide
    masks/<tile>/owner.tif (value 1) when --owner-root is given, so cells with no data can be shown."""
    import numpy as np
    from brigalow import postprocess
    files = sorted(set(sum((glob.glob(os.path.join(d, "*.tif")) for d in a.prob_dir), [])))
    seen = {}
    for f in files:          # one raster per tile name (several folders may hold the same tile)
        seen.setdefault(os.path.basename(f), f)
    files = sorted(seen.values())
    cd = a.cell_deg
    lon_e = np.round(np.arange(137.5, 154.0 + cd / 2, cd), 6); lat_e = np.round(np.arange(-29.5, -9.5 + cd / 2, cd), 6)
    shp = (len(lat_e) - 1, len(lon_e) - 1)
    thr = list(a.threshold)
    al_g = np.zeros((len(thr),) + shp, np.int64); va_g = np.zeros(shp, np.int64); la_g = np.zeros(shp, np.int64)
    jobs = [(f, thr, a.owner_root, a.block, lat_e, lon_e) for f in files]
    if a.procs > 1:
        from multiprocessing import get_context
        pool = get_context("fork").Pool(a.procs); it = pool.imap_unordered(_density_tile, jobs)
    else:
        pool = None; it = map(_density_tile, jobs)
    for res in it:
        if res is None:
            continue
        name, i, j, v, l, al = res
        np.add.at(va_g, (i, j), v); np.add.at(la_g, (i, j), l)
        for k in range(len(thr)):
            np.add.at(al_g[k], (i, j), al[k])
        print(f"  {name}: valid {int(v.sum())}, land {int(l.sum())}, alert px "
              + ", ".join(f"{t}: {int(x.sum())}" for t, x in zip(thr, al)), flush=True)
    if pool is not None:
        pool.close(); pool.join()
    meta = dict(label_year=a.label_year, thresholds=thr, threshold=thr[0], cell_deg=cd, n_rasters=len(files),
                prob_dir=[os.path.abspath(d) for d in a.prob_dir], owner_root=a.owner_root or None,
                min_px=postprocess.MIN_PX, note=a.note)
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    np.savez_compressed(a.out, lon_edges=lon_e, lat_edges=lat_e, alert_px=al_g, valid_px=va_g, land_px=la_g,
                        meta=np.array(json.dumps(meta)))
    print(f"wrote {a.out}: {len(files)} rasters, valid {int(va_g.sum())} px, land {int(la_g.sum())} px, alert px "
          + ", ".join(f"{t}: {int(x.sum())}" for t, x in zip(thr, al_g)))


def cmd_outline(a):
    """Queensland outline (geoBoundaries gbOpen AUS ADM1, CC BY 4.0, the boundary used for tile selection) and the
    held-out IBRA bioregions clipped to it, as simplified lon/lat rings (needs geopandas)."""
    import geopandas as gpd
    from brigalow import postprocess
    b = gpd.read_file(a.boundary).to_crs(4326)
    col = next(c for c in ("shapeName", "NAME_1", "name") if c in b.columns)
    qld = b[b[col].str.contains("Queensland", case=False)].geometry.union_all()
    g = postprocess.load_ibra(a.ibra)

    def rings(geom):
        geom = geom.simplify(a.simplify)
        out = []
        for poly in getattr(geom, "geoms", [geom]):
            if poly.geom_type == "Polygon" and poly.area > a.min_area:
                out.append([[round(x, 4), round(y, 4)] for x, y in poly.exterior.coords])
        return out
    js = dict(source=f"Queensland: geoBoundaries gbOpen AUS ADM1 (CC BY 4.0); held-out bioregions: IBRA 7 (CC BY 4.0) "
                     f"clipped to it; simplified {a.simplify} deg", qld=rings(qld),
              holdout={n: rings(g[g.bioregion == n].geometry.union_all().intersection(qld)) for n in HOLDOUT})
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    json.dump(js, open(a.out, "w"))
    print(f"wrote {a.out}: {len(js['qld'])} rings")


# ------------------------------------------------------------------------------------------------ main
FIGS = dict(fig1_pr_test=fig1_test, fig3_area_bioregion=fig3_area,
            fig4_attribution=fig4_attribution,
            fig7_density=fig7_density, fig8_dev_vs_test=fig8_dev_vs_test, fig9_trees_vs_network=fig9_trees,
            fig10_density_years=fig10_density_years)


def main(argv=None):
    argv = sys.argv[1:] if argv is None else argv
    if argv and argv[0] in ("density", "outline"):
        ap = argparse.ArgumentParser()
        sp = ap.add_subparsers(dest="cmd")
        d = sp.add_parser("density")
        d.add_argument("--prob-dir", nargs="+", required=True)
        d.add_argument("--threshold", type=float, nargs="+", required=True)
        d.add_argument("--owner-root", default="", help="statewide masks root: <root>/<tile>/owner.tif (1 = owned Queensland land)")
        d.add_argument("--label-year", type=int, required=True); d.add_argument("--out", required=True)
        d.add_argument("--cell-deg", type=float, default=0.05); d.add_argument("--block", type=int, default=10)
        d.add_argument("--note", default=""); d.add_argument("--procs", type=int, default=1)
        o = sp.add_parser("outline")
        o.add_argument("--ibra", default=os.path.join(REPO, "src", "brigalow", "data", "ibra7_qld.gpkg"))
        o.add_argument("--boundary", default="https://github.com/wmgeolab/geoBoundaries/raw/main/releaseData/gbOpen/AUS/ADM1/geoBoundaries-AUS-ADM1.geojson")
        o.add_argument("--simplify", type=float, default=0.01); o.add_argument("--min-area", type=float, default=0.002)
        o.add_argument("--out", default=p(INPUTS["outline"]))
        a = ap.parse_args(argv)
        return cmd_density(a) if a.cmd == "density" else cmd_outline(a)
    ap = argparse.ArgumentParser(description="Brigalow figures")
    for k in ("final", "products", "model_json", "dev_main", "dev_trees", "density", "outline"):
        ap.add_argument("--" + k.replace("_", "-"), default=INPUTS[k])
    ap.add_argument("--density-years", type=int, nargs="*", default=INPUTS["density_years"])
    ap.add_argument("--density-threshold", type=float, default=0.40, help="threshold drawn in fig10 (high confidence)")
    ap.add_argument("--label-year", type=int, default=INPUTS["label_year"])
    ap.add_argument("--only", nargs="*", default=[], help="figure names to draw (default all)")
    ap.add_argument("--out", default=os.path.join(REPO, "figures"))
    a = ap.parse_args(argv)
    for name, fn in FIGS.items():
        if a.only and name not in a.only:
            continue
        print(f"{name}:")
        try:
            fn(a, a.out)
        except Exception as e:
            import traceback
            print(f"  FAILED: {type(e).__name__}: {e}")
            traceback.print_exc()
        for u in USED.get(name, []):
            print(f"    input: {u}")
    if not a.only:
        json.dump(USED, open(os.path.join(a.out, "inputs_used.json"), "w"), indent=1)


if __name__ == "__main__":
    main()