"""brigalow.postprocess on synthetic rasters (no network, a few seconds).""" import json import numpy as np import pytest from rasterio.transform import from_origin from brigalow import postprocess as pp from brigalow import scoring EPSG = 32755 TR = from_origin(500000.0, 7500000.0, 20.0, 20.0) def blob(q, r, c, h, w, v): q[r:r + h, c:c + w] = v return q def test_cut_matches_scorer(): try: from brigalow.statewide_score import prob_cuts except Exception as e: # pragma: no cover - the scorer's own imports pytest.skip(f"statewide_score not importable: {e}") ts = [0.002, 0.02, 0.05, 0.3, 0.5, 0.6, 0.95, 0.123] assert [pp.cut(t) for t in ts] == prob_cuts(ts) def test_alert_rule_equals_scoring_clean_alerts(): rng = np.random.default_rng(0) q = (rng.random((300, 300)) ** 6 * 250).astype(np.uint8) q[rng.random((300, 300)) < 0.05] = 255 for t in (0.05, 0.3, 0.6): lab, size, border = pp.label_alerts(q, t) ref = scoring.clean_alerts((q >= pp.cut(t)) & (q != 255)) assert np.array_equal(lab > 0, ref) assert (size >= pp.MIN_PX).all() and not border.any() def test_size_rule_connectivity_and_nodata(): q = np.zeros((60, 60), np.uint8) blob(q, 5, 5, 3, 4, 200) # 12 px -> dropped blob(q, 20, 5, 1, 13, 200) # 13 px -> kept for k in range(13): # 13 px touching only diagonally -> one 8-connected alert q[30 + k, 30 + k] = 200 blob(q, 50, 40, 4, 4, 255) # no data never alerts lab, size, _ = pp.label_alerts(q, 0.5) assert sorted(size.tolist()) == [13, 13] def test_pieces_fields_and_finalise(): q = np.zeros((200, 200), np.uint8) blob(q, 10, 10, 10, 10, 120) # 100 px, prob 0.48, standard blob(q, 50, 50, 5, 5, 230) # 25 px, prob 0.92, high blob(q, 52, 52, 1, 1, 250) fire = np.zeros_like(q); fire[10:15, 10:20] = 1 # half of alert 1 woody = np.full_like(q, 2); woody[50:55, 50:55] = 1 # alert 2 on non-woody info = {"dates": {"before": {"dates": {"0": ["2024-07-01", "2024-06-11"]}}, "after": {"dates": {"0": ["2025-08-01"]}}}} p = pp.tile_pieces(q, TR, EPSG, 0.3, 0.8, {"fire": fire, "woody": woody}, tile="55KXX", tile_info=info) assert len(p) == 2 and p.crs.to_epsg() == pp.ALBERS m = pp.merge_pieces(p) a = pp.finalise(m, 2025) assert list(a.columns[:-1]) == pp.FIELDS and a.crs.to_epsg() == 4326 a = a.sort_values("n_px", ascending=False).reset_index(drop=True) assert a.n_px.tolist() == [100, 25] assert a.area_ha.tolist() == [4.0, 1.0] assert a.confidence.tolist() == ["standard", "high"] assert a.prob_mean[0] == pytest.approx(0.48) and a.prob_max[1] == pytest.approx(1.0) assert a.fire_share.tolist() == [0.5, 0.0] and a.woody_share.tolist() == [1.0, 0.0] assert a.before_dates[0] == "2024-06-11,2024-07-01" and a.after_dates[0] == "2025-08-01" assert a.slats_year[0] == "2024-25" and a.alert_id[0].startswith("2025-55KXX-") assert a.geometry.is_valid.all() and set(a.geom_type) <= {"Polygon", "MultiPolygon"} # polygon area ~ pixel area (simplification moves edges by at most 10 m) area = a.to_crs(pp.ALBERS).geometry.area / 1e4 assert np.allclose(area, a.area_ha, rtol=0.25) def test_no_layers_gives_empty_shares(): q = blob(np.zeros((40, 40), np.uint8), 5, 5, 5, 5, 200) a = pp.finalise(pp.merge_pieces(pp.tile_pieces(q, TR, EPSG, 0.5)), 2024) assert len(a) == 1 and np.isnan(a.fire_share[0]) and np.isnan(a.woody_share[0]) and a.bioregion[0] is None def test_seam_merge_same_zone(): """Two tiles of one zone side by side (shared 20 m lattice). An alert split 12 + 12 px across the seam is one 24 px alert; a 12 px piece one pixel away from the seam on the other side stays separate and is dropped.""" W = 100 qa = np.full((80, W), 255, np.uint8); qa[:, :50] = 0 # tile A owns columns < 50 qb = np.full((80, W), 255, np.uint8); qb[:, 50:] = 0 # tile B (same grid here) owns the rest blob(qa, 10, 44, 2, 6, 200); blob(qb, 10, 50, 2, 6, 200) # 12 + 12 px meeting at the seam blob(qa, 40, 44, 2, 6, 200); blob(qb, 40, 51, 2, 6, 200) # 12 + 12 px, one pixel gap: not one alert pa = pp.tile_pieces(qa, TR, EPSG, 0.5, tile="A"); pb = pp.tile_pieces(qb, TR, EPSG, 0.5, tile="B") assert pa.border.all() and pb.border.all() import pandas as pd, geopandas as gpd m = pp.merge_pieces(gpd.GeoDataFrame(pd.concat([pa, pb], ignore_index=True), crs=pp.ALBERS)) assert len(m) == 1 and m.n_px.iloc[0] == 24 and m.tile.iloc[0] == "A+B" assert m.geometry.iloc[0].geom_type == "Polygon" # the seam gap is closed, one part a = pp.finalise(m, 2025) assert a.tiles[0] == "A+B" and a.area_ha[0] == pytest.approx(0.96) def test_seam_merge_tolerance(): """merge_pieces joins border pieces of different tiles within SEAM_TOL_M only.""" import geopandas as gpd from shapely.geometry import box def piece(x0, tile, n=8): return dict(tile=tile, n_px=n, prob_sum=n * 0.8, prob_max=0.9, high_px=0, fire_px=0.0, fire_known=np.nan, woody_px=0.0, woody_known=np.nan, before_dates="", after_dates="", border=True, rep_r=0, rep_c=0, geometry=box(x0, 0, x0 + 40, 80)) g = gpd.GeoDataFrame([piece(0, "A"), piece(50, "B"), # 10 m gap (zone seam): merged piece(1000, "A"), piece(1065, "B"), # 25 m gap: separate (each 8 px, dropped) piece(2000, "A", 20), piece(2045, "A")], # same tile never merged geometry="geometry", crs=pp.ALBERS) m = pp.merge_pieces(g) assert sorted(m.n_px.tolist()) == [16, 20] def test_bioregion_and_summary(tmp_path): import geopandas as gpd from shapely.geometry import box q = np.zeros((100, 100), np.uint8); blob(q, 10, 10, 5, 5, 200); blob(q, 60, 60, 5, 5, 240) a = pp.tile_pieces(q, TR, EPSG, 0.5, 0.9) lon, lat = gpd.GeoSeries(a.geometry, crs=pp.ALBERS).to_crs(4326).representative_point().iloc[0].coords[0] ibra = gpd.GeoDataFrame(dict(bioregion=["Brigalow Belt North"]), geometry=[box(lon - 0.001, lat - 0.001, lon + 0.001, lat + 0.001)], crs=4326) f = pp.finalise(pp.merge_pieces(a), 2025, ibra=ibra) assert sorted(f.bioregion.tolist()) == ["", "Brigalow Belt North"] s = pp.summary_table(f) allrows = s[s.bioregion == "All"] assert allrows.alerts.sum() == 2 and allrows.hectares.sum() == pytest.approx(2.0) assert "| bioregion |" in pp.md_table(s) paths = pp.write_vectors(f, str(tmp_path / "alerts"), formats=("gpkg", "fgb", "geojson")) for p in paths: r = gpd.read_file(p) assert len(r) == 2 and r.crs.to_epsg() == 4326 and set(pp.FIELDS) <= set(r.columns) gj = json.load(open(tmp_path / "alerts.geojson")) assert gj["features"][0]["geometry"]["type"] in ("Polygon", "MultiPolygon") def test_write_cog(tmp_path): import rasterio q = np.full((1200, 1100), 255, np.uint8); q[100:900, 100:1000] = 100 p = str(tmp_path / "x.tif") pp.write_cog(q, p, f"EPSG:{EPSG}", TR, tags={"scale": "probability = value / 250"}) with rasterio.open(p) as s: assert s.nodata == 255 and s.dtypes[0] == "uint8" and s.block_shapes[0] == (512, 512) assert s.overviews(1) and s.tags(ns="IMAGE_STRUCTURE").get("LAYOUT") == "COG" assert np.array_equal(s.read(1), q) def test_to_u8_and_fire_window(): q = pp.to_u8(np.array([[0.0, 0.5, 1.0, np.nan]], np.float32)) assert q.tolist() == [[0, 125, 250, 255]] rasters = {2024: np.array([[8, 7, 0, 254]], np.uint8), 2025: np.array([[0, 9, 10, 0]], np.uint8)} f = pp.fire_in_window(lambda y: rasters.get(y), 2025) assert f.tolist() == [[1, 1, 0, 255]] # Aug 2024 in, Sep 2025 in, Oct 2025 out, not assessed -> unknown assert pp.woody_year(2024) == 2023 and pp.woody_year(2026) == 2023 and pp.woody_year(2021) == 2020