"""Statewide test of the LOCKED model, label year 2024 (SLATS 2023-24), scored with brigalow.statewide_score. Stages (run on the storage server where masks, labels, products and the synced run live): coverage per tile: owned Queensland land pixels (owner.tif == 1) with valid output (!= 255), per setting tiles statewide tile partials for the three network settings on a fine cut grid (no-data = no alert) blocks the 124 evenly placed blocks: LightGBM (gbt_prob) and the network on the SAME pixels report tables -> results_statewide.md / .json, per-polygon detection table Nothing here chooses a threshold: operating points come from the locked model.json; curves are reported whole. python scripts/statewide_report.py coverage --run RUN --root D --out OUT python scripts/statewide_report.py tiles --run RUN --root D --out OUT --procs 3 python scripts/statewide_report.py blocks --run RUN --root D --out OUT --blocks results/baselines/tree_blocks.parquet python scripts/statewide_report.py report --root D --out OUT --model-json weights/brigalow/model.json --products OUTP """ import argparse, glob, json, math, os, subprocess, sys, time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) import numpy as np import pandas as pd Y = 2024 SETTINGS = {"standard": "prob", "immediate": "prob_immediate", "s2only": "prob_s2only"} # fine grid on the uint8 scale (p = cut / 250); contains the locked points 5 (0.02), 63 (0.25), 50 (0.2), 225 (0.9) FINE = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 15, 18, 20, 23, 25, 30, 35, 38, 40, 45, 50, 55, 60, 63, 70, 75, 80, 88, 100, 113, 125, 138, 150, 163, 175, 188, 200, 213, 225, 238, 245, 250] PRODUCTS = ["dist_ann_any", "dist_ann_win", "dist_ann_high", "gfc113_loss", "gfc113_loss_tc10", "dea_lc_w2n"] PRODUCT_LABEL = {"dist_ann_any": "NASA DIST-ANN 2024, any confirmed", "dist_ann_win": "DIST-ANN, dated in the SLATS window", "dist_ann_high": "DIST-ANN, high only", "gfc113_loss": "Hansen GFC v1.13 loss 2023/24", "gfc113_loss_tc10": "Hansen loss, treecover2000 >= 10", "dea_lc_w2n": "DEA Land Cover woody -> non-woody"} def cut_of(t): return int(math.ceil(t * 250 - 1e-9)) def locked_points(model_json): th = json.load(open(model_json))["thresholds"] out = {} for st in SETTINGS: out[st] = {} for k, v in th[st].items(): c = cut_of(v); eff = (c - 0.5) / 250 # stored value round(p*250) >= c <=> p >= (c - 0.5) / 250 lab = f"{v:g}" if abs(eff - v) < 5e-4 else f"{v:g} (applied as p >= {eff:.3f})" out[st][k] = dict(t=v, cut=c, effective_p=round(eff, 4), label=lab) return out def prob_dir(run, setting): return os.path.join(run, SETTINGS[setting], str(Y)) # ---------------------------------------------------------------- coverage def coverage(a): import rasterio rows = [] for op in sorted(glob.glob(os.path.join(a.root, "masks", "*", "owner.tif"))): tile = op.split(os.sep)[-2] with rasterio.open(op) as s: own = s.read(1) == 1 r = dict(tile=tile, land_px=int(own.sum())) for st in SETTINGS: p = os.path.join(prob_dir(a.run, st), tile + ".tif") if os.path.exists(p): with rasterio.open(p) as s: v = s.read(1) r[f"valid_{st}"] = int((own & (v != 255)).sum()) else: r[f"valid_{st}"] = None rows.append(r) d = pd.DataFrame(rows) os.makedirs(a.out, exist_ok=True) d.to_csv(os.path.join(a.out, "coverage_tiles.csv"), index=False) print(d.drop(columns="tile").sum(numeric_only=True)) # ---------------------------------------------------------------- tiles def tiles(a): methods = [] for st in SETTINGS: methods += ["--method", f"net_{st}={prob_dir(a.run, st)}:{','.join(map(str, FINE))}"] cmd = [sys.executable, "-W", "ignore", "-m", "brigalow.statewide_score", "tile", "--root", a.root, "--year", str(Y), "--out", a.out, "--procs", str(a.procs)] + methods + (["--only", a.only] if a.only else []) env = dict(os.environ, PYTHONPATH=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) subprocess.run(cmd, check=True, env=env) # ---------------------------------------------------------------- blocks def blocks(a): import rasterio from rasterio.windows import Window from brigalow.statewide_score import block_inputs, context_from_L, score_raster, save_partial B = pd.read_parquet(a.blocks) def rd(path, b): if not os.path.exists(path): return None with rasterio.open(path) as s: return s.read(1, window=Window(b.col_off, b.row_off, b.size, b.size)) info = [] for bi, b in enumerate(B.itertuples()): L = block_inputs(a.root, b.tile, b.row_off, b.col_off, b.size, Y) cl = np.full((b.size, b.size), bi, np.uint16); rg = np.zeros((b.size, b.size), np.uint8) for st in SETTINGS: net = rd(os.path.join(prob_dir(a.run, st), b.tile + ".tif"), b) tree = rd(os.path.join(a.run, "gbt_prob", st, str(Y), b.tile + ".tif"), b) if net is None or tree is None: info.append(dict(block=b.block, setting=st, missing=True)); continue use = (net != 255) & (tree != 255) # the same pixels for both methods ctx = context_from_L(L, use) for name, r in ((f"net_{st}", net), (f"gbt_{st}", tree)): d = os.path.join(a.out, "blocks", name); os.makedirs(d, exist_ok=True) part = score_raster(ctx, r, FINE, True, cluster=cl, region=rg) save_partial(os.path.join(d, b.block + ".npz"), part, dict(tile=b.tile, block=b.block, method=name)) info.append(dict(block=b.block, setting=st, px=int(use.size), both_valid=int(use.sum()), net_valid=int((net != 255).sum()), tree_valid=int((tree != 255).sum()))) print(f"[blocks] {bi + 1}/{len(B)} {b.block}", flush=True) pd.DataFrame(info).to_csv(os.path.join(a.out, "blocks", "coverage_blocks.csv"), index=False) def _summ(s): k1 = s[">=1ha"]; ar = s["area"] return dict(n=k1["n"], any=k1["any"], r30=k1["r30"], prec2=ar["precision_2yr"], prec1=ar["slats_cur"], alert_ha=ar["alert_ha"]) # ---------------------------------------------------------------- report def fmt(t): from brigalow import scoring return scoring.fmt(t) def report(a): from brigalow import scoring from brigalow.statewide_score import load_partials, reduce_method, Reduced, cell_name from brigalow.evaluate import block_stats from brigalow.statewide_score import matched_rows from brigalow.config import HOLDOUT_BIOREGIONS from brigalow.design import is_dev LP = locked_points(a.model_json) polys = pd.read_parquet(os.path.join(a.root, "labels", f"polys_{Y}.parquet")) regions = json.load(open(os.path.join(a.root, "masks", "regions.json"))) cov = pd.read_csv(os.path.join(a.out, "coverage_tiles.csv")) mj_raw = json.load(open(a.model_json)) locked_utc = mj_raw.get("locked_utc", "unknown") J = {}; md = [f"# Statewide test of the locked model (weights/brigalow), SLATS {Y - 1}-{str(Y)[2:]}\n", "Scored once, wall to wall, with `brigalow.statewide_score` (reproduces `brigalow/scoring.py`; tested). " "Recall: SLATS clearing polygons >= 1 ha with >= 30% of their pixels alerted (also any pixel, and >= 5 ha). " "Precision 2-yr: share of alert area on SLATS clearing of 2023-24 or 2022-23 (2024-25 is not published); " "strict: 2023-24 only; masked: after removing alerts on Queensland fire scars, cropping and non-woody land. " "Alert components under 13 pixels dropped (per tile; a component cut by a tile seam is judged per piece). " "No-data pixels count as no alert. 95% intervals: bootstrap over 1-degree cells (statewide) or blocks. " f"Operating points: the locked model.json thresholds (locked {locked_utc}, chosen strictly on <= 2023 training years before the test).\n", "Run notes: the 2024 run ran across three RTX 5090 machines (shards 0/3, 1/3, 2/3, with shard 0/3 also completing the tail tiles), " "using one uniform fp32 (TF32) multi-setting inference path (verified 99.99% bit-identical to reference fp32 on 55KDQ before the test). " "All 250 tiles completed with 0 permanent failures.\n"] # coverage cv = {} for st in SETTINGS: c = cov[f"valid_{st}"] has = cov.land_px > 0 cv[st] = dict(valid_share=float(c.sum() / cov.land_px.sum()), tiles=int(c.notna().sum()), tiles_below_995=sorted(cov.tile[has & ((c / cov.land_px.clip(lower=1)) < 0.995)].tolist()), tiles_without_qld_land=sorted(cov.tile[~has].tolist())) tot_owned = int(sum(np.load(p)["nodata_px"][1] for p in glob.glob(os.path.join(a.out, "net_standard", "*.npz")))) nd_owned = int(sum(np.load(p)["nodata_px"][0] for p in glob.glob(os.path.join(a.out, "net_standard", "*.npz")))) land = int(cov.land_px.sum()); land_nd = land - int(cov.valid_standard.sum()) cv["note"] = dict(owned_px=tot_owned, owned_nodata_px=nd_owned, qld_land_px=land, qld_land_nodata_px=land_nd, owned_outside_qld_px=tot_owned - land) J["coverage"] = cv md += ["## Coverage\n", "| setting | tiles | share of owned Queensland land pixels with valid output | tiles below 99.5% |", "|---|---|---|---|"] + [f"| {st} | {v['tiles']} | {100 * v['valid_share']:.2f}% | {len(v['tiles_below_995'])} |" for st, v in cv.items() if st in SETTINGS] md += _lowcov_table(a, cov, cv) n_ = cv["note"] md.append(f"\nThe per-method tables below also give a no-data share of ALL owned tile pixels " f"({100 * n_['owned_nodata_px'] / n_['owned_px']:.2f}% for the standard setting). That share is almost all " f"owned pixels outside Queensland land (sea, Northern Territory, New South Wales: {n_['owned_outside_qld_px']:,} " f"of {n_['owned_px']:,} owned pixels), which the model does not map. On Queensland land " f"{n_['qld_land_nodata_px']:,} of {n_['qld_land_px']:,} pixels ({100 * n_['qld_land_nodata_px'] / n_['qld_land_px']:.2f}%) " f"have no output; they count as no alert.\n") # statewide network extras = {} head = ["\n## Headline: network, statewide, locked operating points\n", "| setting | point | threshold | recall >=30% | recall any px | recall >=5 ha | precision 2-yr | precision strict 1-yr | precision masked | alert ha | SLATS ha |", "|---|---|---|---|---|---|---|---|---|---|---|"] slats_ha = float(polys.area_ha.sum()) detail = [] Rs = {f"net_{st}": load_partials(a.out, f"net_{st}") for st in SETTINGS} Rp = {p: load_partials(a.products, p) for p in PRODUCTS if os.path.isdir(os.path.join(a.products, p))} cells_all = sorted(set(polys.cell) | {cell_name(c) for R_, _, _ in list(Rs.values()) + list(Rp.values()) for c, _ in R_.area}) for st in SETTINGS: name = f"net_{st}" R, n, notes = Rs[name] ex = {} dev_cuts = [LP[st]["standard"]["cut"], LP[st]["high_confidence"]["cut"]] ls, js = reduce_method(R, polys, Y, regions, dev_cuts, label=f"{name} ({n} tiles)", extra=ex, cells=cells_all) js["operating_points"] = {k: dict(v, **_row(js, v["cut"])) for k, v in LP[st].items()} js["coverage"] = cv[st]; js["tiles"] = n; js["population"] = "statewide, wall to wall" J[name] = js; extras[name] = ex; detail += ls for k, v in LP[st].items(): e = _row(js, v["cut"]) head.append(f"| {st} | {k} | {v['label']} | {fmt(e['r30'])} | {fmt(e['any'])} | {fmt(e['r30_5ha'])} | {fmt(e['prec2'])} | " f"{fmt(e['prec1'])} | {fmt(e['prec_masked'])} | {e['alert_ha']:.0f} | {slats_ha:.0f} |") md += head # products (same scorer, same polygons, same cells) and matched points prods = {} for p, (R, n, _) in Rp.items(): ex = {} ls, js = reduce_method(R, polys, Y, None, None, label=p, cells=cells_all, extra=ex) js["stats"] = ex["stats"][R.cuts[0]] prods[p] = js J["products"] = {k: {kk: vv for kk, vv in v.items() if kk != "stats"} for k, v in prods.items()} for st in SETTINGS: name = f"net_{st}" ml, mj = matched_rows({name: extras[name]["stats"]}, {PRODUCT_LABEL[p]: v["stats"] for p, v in prods.items()}, [PRODUCT_LABEL[p] for p in prods], name, cells_all, f"{name} vs other free products, statewide: matched points (1-degree cell bootstrap)") md += ml; J.setdefault("vs_products", {})[st] = mj # dev-cell neighbourhood and per-polygon table devn = _dev_neighbourhood(polys, is_dev) pt_all = [] md += ["\n## Recall by distance to dev cells (dev cells and their 8 neighbours vs the rest; locked standard point)\n", "| setting | polygons near dev cells: n, recall >=30% | elsewhere: n, recall >=30% |", "|---|---|---|"] J["dev_neighbourhood"] = {} for st in SETTINGS: name = f"net_{st}"; ex = extras[name] R = None for k, v in LP[st].items(): ci = J[name]["cuts"].index(v["cut"]) t = scoring.poly_table(ex["accs"][ci], ex["pol"]) t = t.merge(polys[["pid", "cell"]], on="pid", how="left") t[f"near_dev"] = t.cell.isin(devn) t1 = t[t.area_ha >= 1] if k == "standard": a_ = scoring.recall(t1[t1.near_dev], "det30"); b_ = scoring.recall(t1[~t1.near_dev], "det30") md.append(f"| {st} | {int(t1.near_dev.sum())}, {fmt(a_)} | {int((~t1.near_dev).sum())}, {fmt(b_)} |") J["dev_neighbourhood"][st] = dict(near=dict(n=int(t1.near_dev.sum()), r30=a_), far=dict(n=int((~t1.near_dev).sum()), r30=b_)) pt_all.append(t[["year", "pid", "area_ha", "bioregion", "cell", "near_dev", "npx", "nal", "det_any", "det30"]] .assign(setting=st, point=k, threshold=v["t"])) pd.concat(pt_all).to_parquet(os.path.join(a.out, "polygon_detection_2024.parquet")) md += _notol_section(a, LP, J) # trees vs network on the 124 blocks md += _blocks_section(a, polys, LP, J) # excluding low-coverage tiles md += _lowcov_section(a, polys, regions, LP, J, cv) md += ["\n# Detailed tables\n"] + detail J["meta"] = dict(run_notes="three RTX 5090 machines (shards 0/3, 1/3, 2/3 + tail rebalance); uniform fp32 (TF32) multi-setting inference path across all 250 tiles; 0 permanent failures", label_year=Y, model=f"weights/brigalow (locked {locked_utc})", thresholds=LP, fine_cuts=FINE, slats_clearing_ha=slats_ha, n_polys_ge1ha=int((polys.area_ha >= 1).sum()), scored=time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime())) md[1:1] = _howto(J, json.load(open(a.model_json)).get("dev", {})) open(a.md, "w").write("\n".join(md) + "\n") json.dump(J, open(a.json, "w"), indent=1, default=float) print("\n".join(md[:60])) def _notol_section(a, LP, J): p = os.path.join(a.out, "diag_notol", "diag_notol.json") if not os.path.exists(p): p = os.path.join(a.root, "score", "diag_notol_2024", "diag_notol.json") if not os.path.exists(p): return ["\n## POST-TEST DIAGNOSTIC: precision without spatial tolerance — not run\n"] d = json.load(open(p))["results"] L = ["\n## POST-TEST DIAGNOSTIC (added after the test, 27 Nov): area precision without spatial tolerance\n", "This changes no threshold and no headline number. The headline rule (the window scorer's, brigalow.scoring) counts an alert pixel as on label-year SLATS clearing if it lies within one 20 m pixel " "of a 2023-24 clearing polygon (3x3 dilation), and as on adjacent-year clearing if a 2022-23 clearing polygon " "touches the pixel at all. Without tolerance, both years count only pixels whose centre is inside a polygon. " "Same alerts, pixels and 1-degree cell bootstrap; the 'headline rule' columns are recomputed here and match the " "tables above. Every method is scored the same way, so the comparison with NASA DIST-ANN stays fair.\n", "| method | point | precision 2-yr, headline rule | precision 2-yr, no tolerance | strict 1-yr, headline rule | strict 1-yr, no tolerance | alert ha |", "|---|---|---|---|---|---|---|"] J["diagnostic_no_tolerance"] = dict(note="post-test diagnostic; no threshold or headline number changed; headline rule = " "3x3 dilation for the label year and all-touched adjacent year (the window scorer's rule)", results={}) names = [(f"net_{st}", st, k, v) for st in SETTINGS for k, v in LP[st].items()] + [("dist_ann_any", None, "single point", dict(cut=1, label="any confirmed"))] for m, st, k, v in names: key = f"{m}@{v['cut']}" if key not in d: continue r = d[key] lab = m if st is None else f"network {st}" L.append(f"| {lab} | {k} {v['label']} | {fmt(r['prec2_tolerant'])} | {fmt(r['prec2_no_tolerance'])} | " f"{fmt(r['prec1_tolerant'])} | {fmt(r['prec1_no_tolerance'])} | {r['alert_ha']:,.0f} |") J["diagnostic_no_tolerance"]["results"][key] = r return L def _lowcov_table(a, cov, cv): """The tiles under 99.5% valid on Queensland land, with a rough location: tile centre and the IBRA region covering most of the tile's Queensland land (region.tif on owned land pixels).""" import rasterio from brigalow.statewide_masks import load_tiles T = load_tiles(a.tiles).set_index("tile") names = json.load(open(os.path.join(a.root, "masks", "regions.json"))) low = cv["standard"]["tiles_below_995"] rows = [] for t in low: r = cov[cov.tile == t].iloc[0]; lon, lat = float(T.loc[t, "lon_c"]), float(T.loc[t, "lat_c"]) with rasterio.open(os.path.join(a.root, "masks", t, "owner.tif")) as f: own = f.read(1) == 1 with rasterio.open(os.path.join(a.root, "masks", t, "region.tif")) as f: reg = f.read(1)[own] reg = reg[reg > 0] br = names[int(np.bincount(reg).argmax()) - 1] if reg.size else "none" where = "Torres Strait islands" if lat > -10.7 else ("Cape York" if lon > 141 and lat > -16.5 and lon < 146 else "") rows.append(dict(tile=t, land_km2=round(r.land_px * 0.0004, 1), valid=float(r.valid_standard / r.land_px), lon=round(lon, 2), lat=round(lat, 2), land_bioregion=br, where=where)) rows.sort(key=lambda x: x["valid"]) cv["low_tiles"] = rows L = [f"\n### Tiles under 99.5% valid on Queensland land ({len(rows)}; all settings identical)\n", "| tile | Queensland land in tile (km2) | share valid | tile centre (lon, lat) | IBRA region of most of its land | note |", "|---|---|---|---|---|---|"] L += [f"| {x['tile']} | {x['land_km2']:,} | {100 * x['valid']:.1f}% | {x['lon']}, {x['lat']} | {x['land_bioregion']} | {x['where']} |" for x in rows] L.append(f"\nTiles {', '.join(cv['standard']['tiles_without_qld_land'])} own no Queensland land under the TERN woody-extent " "land mask (their owned pixels are sea or outside the state); they are not counted " "among the low-coverage tiles. No number changes: they have no land pixels.\n") return L def _howto(J, dev): """'How to read this': the numbers a reader needs, taken from the tables below.""" def p(x): return "not reached" if x is None else f"{100 * x[0]:.1f}" def ci(x): return "not reached" if x is None else f"{100 * x[0]:.1f} [{100 * x[1]:.1f}-{100 * x[2]:.1f}]" S = J["net_standard"]; op = S["operating_points"]; d = dev.get("standard", {}).get("operating_points", {}) sp, hp = op["standard"], op["high_confidence"] best = S.get("best", {}) dist = J["products"]["dist_ann_any"]["curve"][0] vm = next((m for m in J.get("vs_products", {}).get("standard", {}).get("matched", []) if "any confirmed" in m["reference"]), None) bm = J.get("blocks_124", {}).get("matched", {}).get("standard", {}) bb = bm.get("best", {}); hc = next((m for m in bm.get("matched", []) if "high_confidence" in m["reference"]), None) sp_t = sp['t']; sp_c = sp['cut']; sp_eff = (sp_c - 0.5) / 250 hp_t = hp['t']; hp_c = hp['cut']; hp_eff = (hp_c - 0.5) / 250 sp_met = sp['prec2'][0] >= 0.50 hp_met = hp['prec2'][0] >= 0.80 L = ["\n## How to read this (standard setting: woody extent and cropping 3 years old, fire scars to the end of the window)\n", f"1. **Locked standard point ({sp['label']}):** recall {ci(sp['r30'])}% of SLATS clearing polygons >= 1 ha, area precision " f"{ci(sp['prec2'])}% (2-year), {sp['alert_ha']:,.0f} ha alerted against 274,606 ha of SLATS clearing. " f"**{'Meets' if sp_met else 'Misses'} the pre-set 50% precision target.** Threshold chosen strictly on <=2023 training years " f"(pooled 5-yr OOF + dev: recall {100 * d.get('standard', {}).get('recall', float('nan')):.1f}%, precision " f"{100 * d.get('standard', {}).get('precision', float('nan')):.1f}%); statewide it delivers {100 * sp['prec2'][0]:.1f}% precision.", f" The threshold is applied on the stored uint8 maps (`round(p x 250) >= ceil(t x 250)`), so {sp_t:g} is applied as " f"stored value >= {sp_c} (p >= {sp_eff:.3f}), and {hp_t:g} as stored value >= {hp_c} (p >= {hp_eff:.3f}).", f"2. **Locked high-confidence point ({hp['label']}):** recall {ci(hp['r30'])}% ({ci(hp['r30_5ha'])}% on >=5 ha), " f"precision {ci(hp['prec2'])}% (strict 1-yr {ci(hp['prec1'])}%). Pre-set target >= 80% " f"(<=2023 pooled: {100 * d.get('high_confidence', {}).get('precision', float('nan')):.1f}%); statewide " f"{100 * hp['prec2'][0]:.1f}%, {'meeting' if hp_met else 'below'} that target.", f"3. **Whole curve (no threshold choice):** best recall at >= 50% precision {ci(best.get('recall_at_p50'))}; best " f"precision at >= 70% recall {ci(best.get('precision_at_r70'))}. Both are read off the test curve, so they show what " f"the model can do, not what a pre-chosen threshold delivered.", f"4. **NASA DIST-ANN 2024 (any confirmed disturbance):** recall {ci(dist['r30'])}%, precision {ci(dist['prec2'])}%. " + (f"At DIST-ANN's precision the network reaches {p(vm['cand_recall_at_ref_precision'])}% recall; at DIST-ANN's recall " f"it has {p(vm['cand_precision_at_ref_recall'])}% precision." if vm else ""), f"5. **LightGBM (baseline 32-feature inputs + the same masks), 124 evenly placed blocks (same pixels):** best recall at >= 50% precision " f"{ci((bb.get('gbt_standard') or {}).get('recall_at_p50'))} vs the network's {ci((bb.get('net_standard') or {}).get('recall_at_p50'))}. " + (f"At the network's {hp_t:g} point on those blocks ({p(hc['ref_recall'])}% recall, {p(hc['ref_precision'])}% precision) the trees " f"reach {p(hc['cand_recall_at_ref_precision'])}% recall at that precision and {p(hc['cand_precision_at_ref_recall'])}% " f"precision at that recall." if hc else ""), "\nIntervals: 95%, bootstrap over 1-degree cells (statewide) or blocks. 'not reached' = the method has no threshold " "meeting the criterion (shown as null in the JSON).\n"] return L def _cut_txt(js, cut): e = next((e for e in js["curve"] if e["cut"] == cut), None) return "n/a" if e is None else f"recall {100 * e['r30'][0]:.1f}%, precision {100 * e['prec2'][0]:.1f}%" def _row(js, cut): return next(e for e in js["curve"] if e["cut"] == cut) def _dev_neighbourhood(polys, is_dev): cells = set(polys.cell) near = set() for c in cells: lo, la = map(int, c.split("_")) if any(is_dev(f"{lo + dx}_{la + dy}") for dx in (-1, 0, 1) for dy in (-1, 0, 1)): near.add(c) return near def _blocks_section(a, polys, LP, J): from brigalow.statewide_score import load_partials, reduce_method from brigalow.statewide_score import matched_rows B = pd.read_parquet(a.blocks) names = list(B.block) pid_block = {} lines = ["\n## Trees vs network on the 124 evenly placed blocks (same pixels for both; bootstrap over blocks)\n"] covb = pd.read_csv(os.path.join(a.out, "blocks", "coverage_blocks.csv")) ok = covb[covb["px"].notna()] if "px" in covb else covb.iloc[0:0] J["blocks_124"] = {"coverage": {st: float(g.both_valid.sum() / g.px.sum()) for st, g in ok.groupby("setting")}, "blocks_missing": {st: int(g.px.isna().sum()) for st, g in covb.groupby("setting")} if "px" in covb else {}} import rasterio for st in SETTINGS: res = {}; ex = {} for kind in ("net", "gbt"): name = f"{kind}_{st}" R, n, _ = load_partials(os.path.join(a.out, "blocks"), name) if not n: continue pc = _pid_block(a, B) e = {} ls, js = reduce_method(R, polys, Y, None, None, label=f"{name} on {n} blocks", pc=pc, cluster_name=lambda c: names[c], cells=names, extra=e) js["population"] = f"{n} evenly placed 26.88 km blocks" res[name] = js; ex[name] = e J[name if kind == "gbt" else f"{name}_blocks"] = js if len(res) < 2: lines.append(f"(setting {st}: missing)"); continue net, gbt = f"net_{st}", f"gbt_{st}" pts = {f"network {st} @{v['label']} ({k})": ex[net]["stats"][v["cut"]] for k, v in LP[st].items()} ml, mj = matched_rows({gbt: ex[gbt]["stats"], net: ex[net]["stats"]}, pts, list(pts), gbt, names, f"{st}: LightGBM at the network's locked points ({len(names)} blocks)") lines += ml; J["blocks_124"].setdefault("matched", {})[st] = mj lines.append("\nBlock pixels valid for both methods: " + ", ".join(f"{k} {100 * v:.1f}%" for k, v in J["blocks_124"]["coverage"].items())) return lines _PB = {} def _pid_block(a, B): if "pc" in _PB: return _PB["pc"] import rasterio from rasterio.windows import Window pc = {} for b in B.itertuples(): with rasterio.open(os.path.join(a.root, "labels", str(Y), f"{b.tile}_pid.tif")) as s: v = s.read(1, window=Window(b.col_off, b.row_off, b.size, b.size)) for p in np.unique(v[v > 0]).tolist(): pc.setdefault(p, b.block) _PB["pc"] = pc return pc def _lowcov_section(a, polys, regions, LP, J, cv): from brigalow.statewide_score import Reduced, reduce_method lines = ["\n## Excluding tiles under 99.5% coverage (locked points)\n", "| setting | tiles kept | point | recall >=30% | precision 2-yr | alert ha |", "|---|---|---|---|---|---|"] J["excluding_low_coverage"] = {} for st in SETTINGS: drop = set(cv[st]["tiles_below_995"]) R = Reduced(); n = 0 for p in sorted(glob.glob(os.path.join(a.out, f"net_{st}", "*.npz"))): if os.path.basename(p)[:-4] in drop: continue d = np.load(p); R.add({k: d[k] for k in d.files if k != "meta"}); n += 1 if not n: continue # polygons in dropped tiles have zero pixels there and drop out through the 0.6 rule ls, js = reduce_method(R, polys, Y, None, None, label=f"net_{st} without low-coverage tiles") J["excluding_low_coverage"][st] = dict(tiles=n, dropped=sorted(drop), points={k: _row(js, v["cut"]) for k, v in LP[st].items()}) for k, v in LP[st].items(): e = _row(js, v["cut"]) lines.append(f"| {st} | {n} | {k} @{v['label']} | {fmt(e['r30'])} (n {e['n']}) | {fmt(e['prec2'])} | {e['alert_ha']:.0f} |") return lines def main(): ap = argparse.ArgumentParser() ap.add_argument("stage", choices=["coverage", "tiles", "blocks", "report"]) ap.add_argument("--run", default=""); ap.add_argument("--root", default=""); ap.add_argument("--out", required=True) ap.add_argument("--procs", type=int, default=3); ap.add_argument("--only", default="") ap.add_argument("--blocks", default="results/baselines/tree_blocks.parquet") ap.add_argument("--tiles", default="design/tiles_qld.parquet"); ap.add_argument("--model-json", default="weights/brigalow/model.json") ap.add_argument("--products", default=""); ap.add_argument("--md", default="results_statewide.md") ap.add_argument("--json", default="results_statewide.json") a = ap.parse_args() globals()[a.stage](a) if __name__ == "__main__": main()