File size: 34,683 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
"""Release files for one statewide Brigalow map year, from the per-tile probability rasters.

Brigalow, a model that maps woody-vegetation clearing in Queensland, writes one probability raster per Sentinel-2
MGRS tile (brigalow.statewide: <run>/prob/<Y>/<tile>.tif, uint8 round(p*250), 255 = no data or not owned by the tile,
plus <tile>.json with the imagery dates). Tile ownership (design/tiles_qld.parquet, brigalow.tiles) means every 20 m
pixel of the state belongs to exactly one tile. This script makes, in --out:

  alerts_<Y>.gpkg, alerts_<Y>.fgb   alert polygons for the whole state (EPSG:4326), each alert once across tile seams
                                    (brigalow.postprocess: same rule as the scorer; fields documented there and in README)
  probability/<tile>.tif            the probability rasters as cloud-optimised GeoTIFFs with overviews (native UTM grid)
  probability_<Y>_utm<zone>.vrt     one mosaic per UTM zone (tiles of a zone share the 20 m grid, no resampling)
  probability_<Y>.gti.gpkg          GDAL raster tile index over all tiles (GDAL >= 3.9 opens it as one raster, warping
                                    the zones on the fly)
  brigalow_<Y>.qgs                  QGIS project: all zone mosaics (colour ramp) + the alerts; opens in one step
  summary_<Y>.csv / .md             alerts and hectares by bioregion and confidence class
  tiles_<Y>.csv                     per tile: mapped area, alerts, dates
  README_<Y>.md                     what the files are, fields, thresholds, limits, attribution

    python scripts/make_release_maps.py --prob-dir RUN/prob/2025 --label-year 2025 --out release/2025 \
        --model-json weights/brigalow/model.json --setting standard --tern-root /data/tern --procs 8

Resumable: per-tile pieces (--out/work/, intermediate: delete or leave out when publishing) and COGs (probability/)
are kept and skipped when present.
"""
import argparse, datetime as dt, glob, json, os, sys, time, traceback
from concurrent.futures import ProcessPoolExecutor, as_completed

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
import numpy as np

from brigalow import postprocess
from brigalow.tiles import TILE_PX, TILE_RES

QGIS_RAMP = [(0.0, "#ffffcc"), (0.2, "#fed976"), (0.4, "#fd8d3c"), (0.6, "#e31a1c"), (1.0, "#800026")]


# ------------------------------------------------------------------------------------------------ per tile
def tile_layers(row, Y, tern_root=None, masks_root=None):
    """Fire-in-window and woody layers on the tile grid for the alert fields. masks_root = the statewide per-tile masks
    (<root>/masks/<tile>/{fire,woody}_<year>.tif, the scorer's layers); tern_root = local TERN folder (read_layer)."""
    from rasterio.transform import from_origin

    def read(kind, year):
        """The per-tile mask file if present (fast, identical to tern.read_layer by construction), else the TERN raster."""
        if masks_root:
            p = os.path.join(masks_root, "masks", row["tile"], f"{kind}_{year}.tif")
            if os.path.exists(p):
                import rasterio
                with rasterio.open(p) as s:
                    return s.read(1)
        if tern_root:
            try:
                from brigalow import tern
                tr = from_origin(float(row["x0"]), float(row["y1"]), TILE_RES, TILE_RES)
                return tern.read_layer(kind, year, int(row["epsg"]), tr, (TILE_PX, TILE_PX), root=tern_root)
            except Exception:
                return None
        return None
    if not (tern_root or masks_root):
        return {}, []
    used = []
    fire = postprocess.fire_in_window(lambda y: read("fire", y), Y)
    if fire is not None:
        used.append(f"fire {Y - 1}-08..{Y}-09")
    wy = postprocess.woody_year(Y)
    woody = read("woody", wy)
    if woody is not None:
        used.append(f"woody {wy}")
    return {"fire": fire, "woody": woody}, used


def do_tile(path, row, Y, thr, high, out, tern_root, masks_root):
    import rasterio
    name = row["tile"]
    pp = os.path.join(out, "work", f"pieces_{name}.parquet"); sp = os.path.join(out, "work", f"stats_{name}.json")
    ph = os.path.join(out, "work", f"pieces_hi_{name}.parquet")
    cp = os.path.join(out, "probability", f"{name}.tif")
    if os.path.exists(pp) and os.path.exists(sp) and os.path.exists(cp):
        st = json.load(open(sp))
        if high is None or (os.path.exists(ph) and "alert_px_high" in st):
            return st
        # only the high-confidence pass is missing (maps built before the high-confidence main layer)
        with rasterio.open(path) as s:
            q = s.read(1); tr = s.transform
        jp = path[:-4] + ".json"
        info = json.load(open(jp)) if os.path.exists(jp) else {}
        layers, _ = tile_layers(row, Y, tern_root, masks_root)
        hp = postprocess.tile_pieces(q, tr, int(row["epsg"]), high, high, layers, tile=name, tile_info=info)
        hp.to_parquet(ph + ".tmp"); os.replace(ph + ".tmp", ph)
        st.update(alert_px_high=int(((q >= postprocess.cut(high)) & (q != 255)).sum()), pieces_high=len(hp))
        json.dump(st, open(sp + ".tmp", "w")); os.replace(sp + ".tmp", sp)
        return st
    t0 = time.time()
    with rasterio.open(path) as s:
        q = s.read(1); tr = s.transform; crs = s.crs
        if s.width != TILE_PX or abs(tr.c - float(row["x0"])) > 0.01 or abs(tr.f - float(row["y1"])) > 0.01:
            raise RuntimeError(f"{name}: grid differs from the tile table")
    jp = path[:-4] + ".json"
    info = json.load(open(jp)) if os.path.exists(jp) else {}
    layers, used = tile_layers(row, Y, tern_root, masks_root)
    pieces = postprocess.tile_pieces(q, tr, int(row["epsg"]), thr, high, layers, tile=name, tile_info=info)
    pieces.to_parquet(pp + ".tmp"); os.replace(pp + ".tmp", pp)
    if high is not None:
        hp = postprocess.tile_pieces(q, tr, int(row["epsg"]), high, high, layers, tile=name, tile_info=info)
        hp.to_parquet(ph + ".tmp"); os.replace(ph + ".tmp", ph)
    postprocess.write_cog(q, cp, crs, tr, tags=dict(scale="probability = value / 250; 255 = no data / not owned by this tile",
                                                     tile=name, label_year=str(Y), model="Brigalow"))
    d = info.get("dates", {})
    dates = {p: sorted({x for v in d.get(p, {}).get("dates", {}).values() for x in v}) for p in ("before", "after")}
    st = dict(tile=name, epsg=int(row["epsg"]), mapped_km2=round(float((q != 255).sum()) * 4e-4, 2),
              alert_px=int(((q >= postprocess.cut(thr)) & (q != 255)).sum()), pieces=len(pieces),
              alert_px_high=int(((q >= postprocess.cut(high)) & (q != 255)).sum()) if high is not None else None,
              pieces_high=len(hp) if high is not None else None,
              before_first=(dates["before"] or [""])[0], before_last=(dates["before"] or [""])[-1],
              after_first=(dates["after"] or [""])[0], after_last=(dates["after"] or [""])[-1],
              n_dates_before=len(dates["before"]), n_dates_after=len(dates["after"]), layers=used,
              setting=info.get("setting", ""), mask_source=info.get("mask_source", ""),
              need_px=int(info.get("need_px", 0) or 0), valid_px=int(info.get("valid_px", (q != 255).sum()) or 0),
              mask_years=json.dumps(info.get("mask_years", {}), sort_keys=True), seconds=round(time.time() - t0, 1))
    json.dump(st, open(sp + ".tmp", "w")); os.replace(sp + ".tmp", sp)
    return st


# ------------------------------------------------------------------------------------------------ mosaics
def zone_vrts(out, Y, rows):
    """One VRT per EPSG (UTM zone): tiles of one zone sit on one 20 m lattice, so SimpleSource placement is exact.
    ComplexSource with NODATA 255 so a tile's not-owned pixels never cover its neighbour's owned pixels."""
    from pyproj import CRS
    paths = []
    for epsg in sorted({int(r["epsg"]) for r in rows}):
        rs = [r for r in rows if int(r["epsg"]) == epsg]
        x0 = min(float(r["x0"]) for r in rs); y1 = max(float(r["y1"]) for r in rs)
        x1 = max(float(r["x0"]) + TILE_PX * TILE_RES for r in rs); y0 = min(float(r["y1"]) - TILE_PX * TILE_RES for r in rs)
        W = int(round((x1 - x0) / TILE_RES)); H = int(round((y1 - y0) / TILE_RES))
        src = []
        for r in sorted(rs, key=lambda r: r["tile"]):
            dx = (float(r["x0"]) - x0) / TILE_RES; dy = (y1 - float(r["y1"])) / TILE_RES
            if abs(dx - round(dx)) > 1e-6 or abs(dy - round(dy)) > 1e-6:
                raise RuntimeError(f"tile {r['tile']} is not on the zone's 20 m lattice")
            src.append(f"""    <ComplexSource>
      <SourceFilename relativeToVRT="1">probability/{r['tile']}.tif</SourceFilename>
      <SourceBand>1</SourceBand>
      <SourceProperties RasterXSize="{TILE_PX}" RasterYSize="{TILE_PX}" DataType="Byte" BlockXSize="512" BlockYSize="512" />
      <SrcRect xOff="0" yOff="0" xSize="{TILE_PX}" ySize="{TILE_PX}" />
      <DstRect xOff="{int(round(dx))}" yOff="{int(round(dy))}" xSize="{TILE_PX}" ySize="{TILE_PX}" />
      <NODATA>255</NODATA>
    </ComplexSource>""")
        wkt = CRS.from_epsg(epsg).to_wkt().replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
        xml = f"""<VRTDataset rasterXSize="{W}" rasterYSize="{H}">
  <SRS dataAxisToSRSAxisMapping="1,2">{wkt}</SRS>
  <GeoTransform>{x0:.6f}, {TILE_RES:.1f}, 0.0, {y1:.6f}, 0.0, {-TILE_RES:.1f}</GeoTransform>
  <Metadata><MDI key="scale">probability = value / 250; 255 = no data</MDI><MDI key="label_year">{Y}</MDI></Metadata>
  <VRTRasterBand dataType="Byte" band="1">
    <NoDataValue>255</NoDataValue>
    <ColorInterp>Gray</ColorInterp>
    <Description>Brigalow clearing probability x 250, label year {Y}</Description>
{chr(10).join(src)}
  </VRTRasterBand>
</VRTDataset>
"""
        p = os.path.join(out, f"probability_{Y}_utm{epsg % 100}.vrt")
        open(p, "w").write(xml)
        paths.append((epsg, p))
    return paths


def gti_index(out, Y, rows):
    """GDAL GTI raster tile index (GDAL >= 3.9): footprints + relative paths + per-tile SRS; opens as one raster in
    EPSG:3577 at 20 m, warped on the fly. Also usable as a plain footprint layer."""
    import geopandas as gpd
    from shapely import wkt
    p = os.path.join(out, f"probability_{Y}.gti.gpkg")
    g = gpd.GeoDataFrame(dict(location=[f"probability/{r['tile']}.tif" for r in rows], tile=[r["tile"] for r in rows],
                              srs=[f"EPSG:{int(r['epsg'])}" for r in rows]),
                         geometry=[wkt.loads(r["footprint_wkt"]) for r in rows], crs=4326).to_crs(3577)
    if os.path.exists(p):
        os.remove(p)
    g.to_file(p, layer="tiles", driver="GPKG",
              layer_metadata={"RESX": "20", "RESY": "20", "SRS": "EPSG:3577", "DATA_TYPE": "Byte", "BAND_COUNT": "1",
                              "NODATA": "255", "LOCATION_FIELD": "location", "SRS_BEHAVIOR": "REPROJECT",
                              "RESAMPLING": "nearest", "SORT_FIELD": "tile"})
    return p


def _esc(s):
    return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


def _srs(epsg):
    """QGIS <spatialrefsys> with WKT (QGIS ignores an authid-only element for the project CRS)."""
    from pyproj import CRS
    return (f'<spatialrefsys nativeFormat="Wkt"><wkt>{_esc(CRS.from_epsg(epsg).to_wkt())}</wkt>'
            f'<srid>{epsg}</srid><authid>EPSG:{epsg}</authid></spatialrefsys>')


def qgis_project(out, Y, vrts, alerts_file, thr, high, cand_file=None):
    """A small QGIS 3 project: zone mosaics with a probability colour ramp (values below the alert threshold
    transparent), the main alert layer (on) and, if given, the standard-threshold candidates (off), project CRS
    EPSG:3577."""
    lo = postprocess.cut(thr)
    items = []
    for v, c in QGIS_RAMP:
        val = max(lo, int(round(v * 250)))
        items.append(f'<item alpha="255" value="{val}" label="{val / 250:.2f}" color="{c}"/>')
    ramp = "\n              ".join(items)
    layers, tree = [], []
    sym = lambda name, colour, width="0.5": f"""<symbol type="fill" name="{name}" alpha="1" clip_to_extent="1" force_rhr="0">
            <layer class="SimpleLine" enabled="1" pass="0" locked="0">
              <Option type="Map">
                <Option type="QString" name="line_color" value="{colour}"/>
                <Option type="QString" name="line_width" value="{width}"/>
                <Option type="QString" name="line_width_unit" value="MM"/>
              </Option>
            </layer>
          </symbol>"""

    def vlayer(lid, fname, lname, title, checked, renderer):
        tree.append(f'<layer-tree-layer expanded="1" checked="{"Qt::Checked" if checked else "Qt::Unchecked"}" id="{lid}" '
                    f'name="{title}" source="./{fname}|layername={lname}" providerKey="ogr"><customproperties/></layer-tree-layer>')
        layers.append(f"""<maplayer type="vector" geometry="Polygon" wkbType="MultiPolygon" hasScaleBasedVisibilityFlag="0">
      <id>{lid}</id>
      <datasource>./{fname}|layername={lname}</datasource>
      <layername>{title}</layername>
      <srs>{_srs(4326)}</srs>
      <provider encoding="UTF-8">ogr</provider>
      {renderer}
    </maplayer>""")
    single = lambda colour, width: f"""<renderer-v2 type="singleSymbol" forceraster="0" symbollevels="0" enableorderby="0">
        <symbols>
          {sym("0", colour, width)}
        </symbols>
      </renderer-v2>"""
    if cand_file:
        vlayer(f"alerts_{Y}", alerts_file, "alerts", f"Alerts {Y} (high confidence)", True, single("200,0,0,255", "0.6"))
        vlayer(f"candidates_{Y}", cand_file, "candidates", f"Candidates {Y} (standard threshold, lower confidence)", False,
               single("255,160,0,255", "0.3"))
    else:
        vlayer(f"alerts_{Y}", alerts_file, "alerts", f"Alerts {Y}", True, f"""<renderer-v2 type="categorizedSymbol" attr="confidence" forceraster="0" symbollevels="0" enableorderby="0">
        <categories>
          <category symbol="0" value="high" label="high confidence" render="true"/>
          <category symbol="1" value="standard" label="standard" render="true"/>
        </categories>
        <symbols>
          {sym("0", "200,0,0,255")}
          {sym("1", "255,160,0,255")}
        </symbols>
      </renderer-v2>""")
    for epsg, p in vrts:
        f = os.path.basename(p); rid = f[:-4]
        tree.append(f'<layer-tree-layer expanded="0" checked="Qt::Checked" id="{rid}" name="Probability {Y} UTM {epsg % 100}" source="./{f}" providerKey="gdal"><customproperties/></layer-tree-layer>')
        layers.append(f"""<maplayer type="raster" hasScaleBasedVisibilityFlag="0">
      <id>{rid}</id>
      <datasource>./{f}</datasource>
      <layername>Probability {Y} UTM {epsg % 100}</layername>
      <srs>{_srs(epsg)}</srs>
      <provider>gdal</provider>
      <pipe>
        <rasterrenderer type="singlebandpseudocolor" band="1" opacity="1" alphaBand="-1" classificationMin="{lo}" classificationMax="250" nodataColor="">
          <rastershader>
            <colorrampshader colorRampType="INTERPOLATED" classificationMode="1" clip="1" minimumValue="{lo}" maximumValue="250">
              {ramp}
            </colorrampshader>
          </rastershader>
        </rasterrenderer>
        <brightnesscontrast brightness="0" contrast="0" gamma="1"/>
        <huesaturation saturation="0" grayscaleMode="0" colorizeOn="0"/>
        <rasterresampler maxOversampling="2"/>
      </pipe>
    </maplayer>""")
    xml = f"""<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
<qgis projectname="Brigalow {Y}" version="3.22.0">
  <homePath path=""/>
  <title>Brigalow clearing alerts, label year {Y}</title>
  <projectCrs>
    {_srs(3577)}
  </projectCrs>
  <layer-tree-group>
    <customproperties/>
    {chr(10).join('    ' + t for t in tree).strip()}
  </layer-tree-group>
  <projectlayers>
    {chr(10).join(layers)}
  </projectlayers>
  <properties>
    <Paths><Absolute type="bool">false</Absolute></Paths>
    <SpatialRefSys><ProjectionsEnabled type="int">1</ProjectionsEnabled></SpatialRefSys>
  </properties>
</qgis>
"""
    p = os.path.join(out, f"brigalow_{Y}.qgs")
    open(p, "w").write(xml)
    return p


# ------------------------------------------------------------------------------------------------ README
def readme(out, Y, a, thr, high, stats, al, summ, files, layer_note, cand=None):
    sy = f"{Y - 1}-{str(Y)[2:]}"
    bf = sorted(s["before_first"] for s in stats if s["before_first"]); bl = sorted(s["before_last"] for s in stats if s["before_last"])
    af = sorted(s["after_first"] for s in stats if s["after_first"]); alst = sorted(s["after_last"] for s in stats if s["after_last"])
    mapped = sum(s["mapped_km2"] for s in stats)
    nh = int((al.confidence == "high").sum()) if len(al) else 0
    two = cand is not None and cand is not al
    hp = (postprocess.cut(high) - 0.5) / 250 if high is not None else None
    sp = (postprocess.cut(thr) - 0.5) / 250
    if two:
        nc, hc = len(cand), (cand.area_ha.sum() if len(cand) else 0)
        nch = int(cand.contains_high.sum()) if "contains_high" in cand else 0
        alerts_txt = (f"- Main layer `alerts_{Y}` (high confidence, p >= {hp:.3f}): **{len(al):,}** alerts covering "
                      f"**{al.area_ha.sum() if len(al) else 0:,.0f} ha**.\n"
                      f"- Candidates `candidates_{Y}` (standard threshold, p >= {sp:.3f}; lower confidence): {nc:,} polygons "
                      f"covering {hc:,.0f} ha, {nch:,} of which contain a high-confidence alert.")
    else:
        alerts_txt = f"- Alerts: **{len(al):,}** covering **{al.area_ha.sum() if len(al) else 0:,.0f} ha** ({nh:,} high confidence)."
    yrs = sorted({d[:4] for d in bf + bl + af + alst})
    banner = f"\n> **{a.banner}**\n" if a.banner else ""
    thr_src = ("the model's operating points for this setting, chosen on development data from the training years only"
               if a.model_json and a.threshold is None and a.high_threshold is None else
               "given on the command line, not the model's dev-chosen operating points")
    sumtab = postprocess.md_table(summ) if len(summ) else "(no alerts)"
    need = sum(s.get("need_px", 0) for s in stats); valid = sum(s.get("valid_px", 0) for s in stats)
    cov_txt = f" ({100 * valid / need:.3f}% of the state land pixels had a clear view in both periods)" if need else ""
    my = [json.loads(m) for m in sorted({s.get("mask_years", "{}") for s in stats}) if m != "{}"]
    if my and a.setting != "s2only":
        w = "/".join(sorted({str(m.get("woody")) for m in my})); c = "/".join(sorted({str(m.get("crop")) for m in my}))
        mask_txt = (f"SLATS woody extent {w}, cropping maps {c}, Queensland fire scars from August {Y - 2} to "
                    f"{'September ' + str(Y) + ' (inside the window)' if a.setting == 'standard' else 'July ' + str(Y - 1)}")
    else:
        mask_txt = "none (Sentinel-2 only)" if a.setting == "s2only" else "not recorded"
    return f"""# Brigalow clearing map, SLATS year {sy} (label year {Y})
{banner}
Brigalow, a model that maps woody-vegetation clearing in Queensland, from 9-band, 3-season Sentinel-2 imagery
at 20 m. This folder holds its map for the SLATS year {sy}: clearing between the dry season of {Y - 1} and the dry
season of {Y} (the official SLATS window runs August {Y - 1} to August {Y}). It is model output, not the official
Queensland map.

- Model: {a.model_name or ('Brigalow v1 (`weights/brigalow/model.json` in https://huggingface.co/-1/Brigalow-QLD-v1)' if a.model_json else 'given thresholds')}; setting: **{a.setting}**{f' ({a.setting_note})' if a.setting_note else ''}.
- Alert threshold {thr:g} (probability), high-confidence threshold {high if high is not None else 'none'}; {thr_src}.
  The probability rasters store round(p x 250), and an alert pixel is a stored value of at least ceil(t x 250), so
  {thr:g} is applied as p >= {(postprocess.cut(thr) - 0.5) / 250:.3f}{'' if high is None else f' and {high:g} as p >= {(postprocess.cut(high) - 0.5) / 250:.3f}'}
  (the 2023-24 test was scored with the same rule).
- Imagery: Sentinel-2 L2A (Element 84 Earth Search). "Before" dates {bf[0] if bf else '?'} to {bl[-1] if bl else '?'},
  "after" dates {af[0] if af else '?'} to {alst[-1] if alst else '?'}; up to 4 clear dates per dry-season period (3 in the wet season), chosen per 20 km block.
- Area mapped: {mapped:,.0f} km2 of Queensland land on {len(stats)} Sentinel-2 tiles{cov_txt}. Pixels without a
  clear view in either period are 255 (no data), and no alert can be there.
- Mask inputs ({a.setting} setting): {mask_txt}.
{alerts_txt}
- Built {dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%d %H:%M UTC')} by `scripts/make_release_maps.py`.
- Model and code: https://huggingface.co/-1/Brigalow-QLD-v1 ; the Queensland input layers as used:
  https://huggingface.co/datasets/-1/Brigalow-QLD-inputs ; questions and error reports: hello@trajectorylabs.com.au.

## Files

| file | what |
|---|---|
| `alerts_{Y}.gpkg`, `alerts_{Y}.fgb` | **the main map**: high-confidence alert polygons, EPSG:4326 (WGS 84), one row per alert |
| `candidates_{Y}.gpkg`, `candidates_{Y}.fgb` | lower-confidence candidates: alert polygons at the standard threshold (includes the areas of the main alerts), EPSG:4326 |
| `probability/<tile>.tif` | probability rasters, one per Sentinel-2 MGRS tile, native UTM 20 m grid, cloud-optimised GeoTIFF with overviews; value = probability x 250, 255 = no data or not this tile's pixel |
| `probability_{Y}_utm<zone>.vrt` | mosaic of the tiles of one UTM zone (zones 53-56) |
| `probability_{Y}.gti.gpkg` | GDAL raster tile index over all tiles (GDAL 3.9 or later opens it as one raster in EPSG:3577) |
| `brigalow_{Y}.qgs` | QGIS project with all mosaics, the main alerts (shown) and the candidates (hidden): open this file |
| `summary_{Y}.csv`, `summary_{Y}.md` | alerts and hectares by layer, bioregion and confidence class |
| `tiles_{Y}.csv` | per tile: area mapped, alert pixels, imagery dates |

Each 20 m pixel of Queensland belongs to exactly one tile (the tile in which it lies deepest), so nothing is counted
twice. An alert that crosses a tile seam is one polygon (pieces meeting at a seam are merged before the size rule).

## Alert polygons

An alert is a group of touching pixels (8-connected) with probability at or above a threshold, at least 13 pixels
(0.52 ha). This is the rule the evaluation uses. Polygons follow pixel edges, simplified by at most 10 m (half a pixel).

- **Main layer, `alerts_{Y}`**: alerts delineated at the high-confidence threshold ({high if high is not None else '-'},
  applied as p >= {hp if hp is not None else 0:.3f}). In the statewide 2023-24 test this layer found 76.2% of the official
  SLATS clearing patches of 1 ha or more (82.1% of patches ≥ 5 ha), and 88.8% of its area counted as inside official clearing
  (80.5% strict label-year only; 78.0% without the 20 m tolerance around each official polygon).
- **Candidates, `candidates_{Y}`**: alerts at the standard threshold ({thr:g}, applied as p >= {sp:.3f}), a higher-recall
  screening layer. In the statewide 2023-24 test it found 94.0% of the official clearing patches (94.5% of patches ≥ 5 ha),
  with 55.7% of its area counted as inside official clearing (46.3% strict label-year; 42.4% without the 20 m tolerance).
  Use it to look for smaller or lower-contrast clearing that the high-confidence layer may have missed.

Fields (both layers):

| field | meaning |
|---|---|
| `alert_id` | `<label year>-<tile>-<n>` (main layer: `<label year>-<tile>-H<n>`) |
| `label_year`, `slats_year` | {Y}, "{sy}" |
| `area_ha` | pixels x 0.04 ha (the 20 m pixel count; the simplified polygon's own area differs slightly) |
| `n_px` | number of 20 m pixels |
| `prob_mean`, `prob_max` | mean and highest probability in the alert |
| `confidence` | `high` if at least 13 of its pixels reach the high-confidence threshold, else `standard` (always `high` in the main layer) |
| `candidate_id` | main layer only: the `alert_id` of the candidate polygon that contains it |
| `contains_high` | candidates only: true if it contains a high-confidence alert of the main layer |
| `fire_share` | share of its pixels on a Queensland fire scar first detected between August {Y - 1} and September {Y} (empty if not computed) |
| `woody_share` | share of its pixels mapped as woody in the SLATS woody extent {postprocess.woody_year(Y)} (empty if not computed) |
| `bioregion` | IBRA 7 bioregion of a point inside the polygon |
| `before_dates`, `after_dates` | Sentinel-2 dates used where the alert's highest-probability pixel is |
| `tiles` | Sentinel-2 tile(s) it lies on |

{layer_note}

Why WGS 84: the Sentinel-2 grids are WGS 84 / UTM, GeoJSON requires WGS 84, and one CRS for every file avoids
mistakes. WGS 84 and GDA2020 differ by about 1.8 m in Australia today, a tenth of a pixel.

## Summary by layer, bioregion and confidence

{sumtab}

## Limits

- An alert is a detected change in woody vegetation, not a finding of unlawful clearing. The model knows nothing
  about vegetation categories, permits, exemptions or land tenure.
- This is a model's estimate, not the official SLATS map; the official map for {sy} may differ. Check alerts against
  imagery before acting on any of them. Measured accuracy (SLATS 2023-24) is in the technical report.
- Do not compare these hectares with SLATS hectares: these are counts of 20 m pixels; SLATS reports edited polygons.
- False alerts come mostly from fire, cropping and pasture cycles, flooding, drought and dieback. `fire_share` and
  `woody_share` help to spot some of them; they are hints, not filters.
- Clearing after the last "after" date, or under persistent cloud, is not mapped. Thinning and slow change may be
  missed. Small alerts near the 0.52 ha minimum are less reliable.
- The probability is calibrated on development data from the training years; it is not a guaranteed frequency for
  every region or year.

## Licence and credit

The maps are released under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Credit "Brigalow (Trajectory
Labs), version 1" and keep the data credit below. All of these data have been modified (resampled, combined, or turned into
model inputs and outputs).

- Clearing labels and woody extent: (c) State of Queensland (Department of the Environment, Tourism, Science and
  Innovation) 2026, Statewide Landcover and Trees Study (SLATS), CC BY 4.0.
- Fire scars: (c) State of Queensland (Department of Environment and Science) 2023, Sentinel-2 fire scar mapping,
  CC BY 4.0.
- Crop mapping: (c) State of Queensland (Department of Natural Resources and Mines, Manufacturing and Regional and
  Rural Development) 2026, CC BY 4.0.
- Those three layers were read from the TERN data store. Data was sourced from Terrestrial Ecosystem Research Network
  (TERN) infrastructure, which is enabled by the Australian Government's National Collaborative Research
  Infrastructure Strategy (NCRIS).
- Imagery: Contains modified Copernicus Sentinel data {', '.join(yrs)}.
- Bioregions: IBRA Version 7.0, Commonwealth of Australia, CC BY 4.0.

The data come without warranty. This is not an official map and the data owners have not endorsed it.
"""


# ------------------------------------------------------------------------------------------------ main
def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--prob-dir", required=True, help="folder of <tile>.tif (+ <tile>.json) for one year")
    ap.add_argument("--label-year", type=int, required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--tiles", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "design", "tiles_qld.parquet"))
    ap.add_argument("--model-json", default="", help="model.json carrying the dev operating points")
    ap.add_argument("--setting", default="standard", choices=["standard", "immediate", "s2only"])
    ap.add_argument("--setting-note", default="")
    ap.add_argument("--model-name", default="")
    ap.add_argument("--threshold", type=float, default=None); ap.add_argument("--high-threshold", type=float, default=None)
    ap.add_argument("--tern-root", default="", help="local TERN folder for fire_share / woody_share")
    ap.add_argument("--masks-root", default="", help="statewide data root with masks/<tile>/ (alternative to --tern-root)")
    ap.add_argument("--ibra", default="", help="IBRA 7 zip / shapefile / gpkg (default: the packaged Queensland copy)")
    ap.add_argument("--procs", type=int, default=4)
    ap.add_argument("--only", default="", help="comma-separated tiles (tests)")
    ap.add_argument("--banner", default="", help="warning line shown at the top of the README (e.g. for test builds)")
    a = ap.parse_args()
    import pandas as pd, geopandas as gpd
    from brigalow.cli import thresholds_for, default_ibra
    Y = a.label_year
    thr, high = (None, None)
    if a.model_json:
        thr, high = thresholds_for(json.load(open(a.model_json)).get("thresholds"), a.setting)
    thr = a.threshold if a.threshold is not None else thr
    high = a.high_threshold if a.high_threshold is not None else high
    if thr is None:
        sys.exit("no alert threshold: give --model-json (with thresholds) or --threshold")
    os.makedirs(os.path.join(a.out, "work"), exist_ok=True); os.makedirs(os.path.join(a.out, "probability"), exist_ok=True)
    tiles = pd.read_parquet(a.tiles)
    files = sorted(p for p in glob.glob(os.path.join(a.prob_dir, "*.tif")) if not p.endswith(".tmp.tif"))
    names = [os.path.basename(p)[:-4] for p in files]
    if a.only:
        keep = set(a.only.split(",")); files = [p for p, n in zip(files, names) if n in keep]; names = [n for n in names if n in keep]
    unknown = [n for n in names if n not in set(tiles.tile)]
    if unknown:
        sys.exit(f"tiles not in the tile table: {unknown[:5]}")
    rows = {n: tiles[tiles.tile == n].iloc[0].to_dict() for n in names}
    print(f"{len(files)} tiles, label year {Y}, threshold {thr}, high {high}, {a.procs} processes", flush=True)
    t0 = time.time(); stats, errors = [], []
    with ProcessPoolExecutor(a.procs) as ex:
        fut = {ex.submit(do_tile, p, rows[n], Y, thr, high, a.out, a.tern_root or None, a.masks_root or None): n for p, n in zip(files, names)}
        for f in as_completed(fut):
            n = fut[f]
            try:
                st = f.result(); stats.append(st)
                print(f"ok  {n}: {st['pieces']} pieces, {st['mapped_km2']:.0f} km2, {st['seconds']} s", flush=True)
            except Exception:
                errors.append(n); print(f"ERR {n}\n{traceback.format_exc()[-1500:]}", flush=True)
    if errors:
        sys.exit(f"{len(errors)} tiles failed: {errors}; rerun to retry (finished tiles are kept)")
    stats.sort(key=lambda s: s["tile"])
    print(f"tiles done in {time.time() - t0:.0f} s; merging pieces across seams ...", flush=True)
    def layer(prefix, t, tag):
        parts = [gpd.read_parquet(os.path.join(a.out, "work", f"{prefix}_{n}.parquet")) for n in sorted(names)]
        parts = [p for p in parts if len(p)]
        pcs = gpd.GeoDataFrame(pd.concat(parts, ignore_index=True), crs=postprocess.ALBERS) if parts else \
            postprocess.tile_pieces(np.full((2, 2), 255, np.uint8), None, 4326, t)
        mg = postprocess.merge_pieces(pcs)
        return pcs, postprocess.finalise(mg, Y, ibra=ibra, id_tag=tag)
    ibra_path = a.ibra or default_ibra()
    ibra = postprocess.load_ibra(ibra_path) if ibra_path else None
    pieces, cand = layer("pieces", thr, "")                       # standard threshold: the candidates layer
    n_border = int(pieces.border.astype(bool).sum()) if len(pieces) else 0
    if high is not None:
        pieces_hi, al = layer("pieces_hi", high, "H")             # high-confidence threshold: the main layer
        al, cand = postprocess.link_layers(al, cand)
    else:
        pieces_hi, al = pieces, cand
    postprocess.write_vectors(al, os.path.join(a.out, f"alerts_{Y}"), formats=("gpkg", "fgb"))
    if high is not None:
        postprocess.write_vectors(cand, os.path.join(a.out, f"candidates_{Y}"), formats=("gpkg", "fgb"), layer="candidates")
    summ = pd.concat([postprocess.summary_table(al).assign(layer=f"alerts_{Y} (high confidence)")] +
                     ([postprocess.summary_table(cand).assign(layer=f"candidates_{Y} (standard threshold)")] if high is not None else []),
                     ignore_index=True)
    summ = summ[["layer"] + [c for c in summ.columns if c != "layer"]]
    summ.to_csv(os.path.join(a.out, f"summary_{Y}.csv"), index=False)
    open(os.path.join(a.out, f"summary_{Y}.md"), "w").write(postprocess.md_table(summ) + "\n" if len(summ) else "(no alerts)\n")
    pd.DataFrame(stats).to_csv(os.path.join(a.out, f"tiles_{Y}.csv"), index=False)
    rr = [rows[n] for n in sorted(names)]
    vrts = zone_vrts(a.out, Y, rr)
    gti = gti_index(a.out, Y, rr)
    qgs = qgis_project(a.out, Y, vrts, f"alerts_{Y}.gpkg", thr, high,
                       cand_file=f"candidates_{Y}.gpkg" if high is not None else None)
    used = sorted({u for s in stats for u in s["layers"]})
    note = (f"fire_share and woody_share were computed from: {', '.join(used)}." if used else
            "fire_share and woody_share are empty in this build: no Queensland layers were given.")
    if ibra is None:
        note += " bioregion is empty: no IBRA layer was given."
    open(os.path.join(a.out, f"README_{Y}.md"), "w").write(readme(a.out, Y, a, thr, high, stats, al, summ, files, note, cand))
    merged_n = lambda g: int(g.tiles.str.contains(r"\+").sum()) if len(g) else 0
    rec = dict(label_year=Y, tiles=len(names), alerts=len(al), alert_ha=round(float(al.area_ha.sum()) if len(al) else 0, 2),
               pieces_high=len(pieces_hi), merged_alerts=merged_n(al),
               alerts_linked_to_candidate=int(al.candidate_id.notna().sum()) if "candidate_id" in al else None,
               candidates=len(cand), candidate_ha=round(float(cand.area_ha.sum()) if len(cand) else 0, 2),
               candidates_containing_high=int(cand.contains_high.sum()) if "contains_high" in cand else None,
               pieces=len(pieces), border_pieces=n_border, merged_candidates=merged_n(cand),
               threshold=thr, high_threshold=high, setting=a.setting, layers=used, seconds=round(time.time() - t0, 1),
               outputs=sorted(os.listdir(a.out)))
    json.dump(rec, open(os.path.join(a.out, f"build_{Y}.json"), "w"), indent=1)
    print(json.dumps(rec), flush=True)


if __name__ == "__main__":
    main()