"""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: /prob//.tif, uint8 round(p*250), 255 = no data or not owned by the tile, plus .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_.gpkg, alerts_.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/.tif the probability rasters as cloud-optimised GeoTIFFs with overviews (native UTM grid) probability__utm.vrt one mosaic per UTM zone (tiles of a zone share the 20 m grid, no resampling) probability_.gti.gpkg GDAL raster tile index over all tiles (GDAL >= 3.9 opens it as one raster, warping the zones on the fly) brigalow_.qgs QGIS project: all zone mosaics (colour ramp) + the alerts; opens in one step summary_.csv / .md alerts and hectares by bioregion and confidence class tiles_.csv per tile: mapped area, alerts, dates README_.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 (/masks//{fire,woody}_.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""" probability/{r['tile']}.tif 1 255 """) wkt = CRS.from_epsg(epsg).to_wkt().replace("&", "&").replace("<", "<").replace(">", ">") xml = f""" {wkt} {x0:.6f}, {TILE_RES:.1f}, 0.0, {y1:.6f}, 0.0, {-TILE_RES:.1f} probability = value / 250; 255 = no data{Y} 255 Gray Brigalow clearing probability x 250, label year {Y} {chr(10).join(src)} """ 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("&", "&").replace("<", "<").replace(">", ">").replace('"', """) def _srs(epsg): """QGIS with WKT (QGIS ignores an authid-only element for the project CRS).""" from pyproj import CRS return (f'{_esc(CRS.from_epsg(epsg).to_wkt())}' f'{epsg}EPSG:{epsg}') 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'') ramp = "\n ".join(items) layers, tree = [], [] sym = lambda name, colour, width="0.5": f""" """ def vlayer(lid, fname, lname, title, checked, renderer): tree.append(f'') layers.append(f""" {lid} ./{fname}|layername={lname} {title} {_srs(4326)} ogr {renderer} """) single = lambda colour, width: f""" {sym("0", colour, width)} """ 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""" {sym("0", "200,0,0,255")} {sym("1", "255,160,0,255")} """) for epsg, p in vrts: f = os.path.basename(p); rid = f[:-4] tree.append(f'') layers.append(f""" {rid} ./{f} Probability {Y} UTM {epsg % 100} {_srs(epsg)} gdal {ramp} """) xml = f""" Brigalow clearing alerts, label year {Y} {_srs(3577)} {chr(10).join(' ' + t for t in tree).strip()} {chr(10).join(layers)} false 1 """ 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/.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.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` | `