File size: 7,064 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
"""`brigalow` CLI without network: the Sentinel-2 pipeline (statewide.process_tile) and the model are replaced by
stand-ins that write a synthetic probability tile, so the orchestration, mosaic, alerts and run record are tested."""
import json, os, sys
import numpy as np
import pandas as pd
import pytest

from brigalow import cli, statewide
from brigalow.tiles import TILE_PX, TILE_RES

TILES = cli.default_tiles()


class FakeInfer:
    mode = "none"; crop = 128; members = [object()]
    thresholds = {"s2only": {"standard": 0.4, "high_confidence": 0.8}}


class FakePredictor:
    def __init__(self, *a, **k):
        self.p = FakeInfer(); self.device = "cpu"; self.stride = 96; self.lag = None


def fake_process_tile(row, tiles, Y, pred, out_path, masks, bbox_ll=None, threads=16, **k):
    """Probability 0.04 on needed pixels, a 6x6 px blob of 0.9 at the box centre, 255 elsewhere."""
    from pyproj import Transformer
    need = statewide.needed_mask(row, tiles, masks, bbox_ll)
    q = np.full((TILE_PX, TILE_PX), 255, np.uint8); q[need] = 10
    lon, lat = (bbox_ll[0] + bbox_ll[2]) / 2, (bbox_ll[1] + bbox_ll[3]) / 2
    x, y = Transformer.from_crs(4326, int(row["epsg"]), always_xy=True).transform(lon, lat)
    r, c = int((row["y1"] - y) / TILE_RES), int((x - row["x0"]) / TILE_RES)
    q[r - 3:r + 3, c - 3:c + 3] = np.where(need[r - 3:r + 3, c - 3:c + 3], 225, 255)
    statewide.write_prob(row, q, out_path)
    dates = {str(b): ["2025-07-10", "2025-08-04"] for b in range(121)}
    return dict(tile=row["tile"], dates={"before": {"dates": {k: ["2024-06-20"] for k in dates}}, "after": {"dates": dates}},
                valid_need_share=1.0, rx_gb_total=0.0, need_px=int(need.sum()))


@pytest.fixture
def interior_box():
    t = pd.read_parquet(TILES)
    r = t[t.tile == "55KDQ"].iloc[0]
    return (r.lon_c - 0.02, r.lat_c - 0.02, r.lon_c + 0.02, r.lat_c + 0.02)


def test_predict_s2only_fallback(tmp_path, monkeypatch, interior_box, capsys):
    """No key, no --tern-root, mirror unreachable: falls back to Sentinel-2 only and says why."""
    monkeypatch.delenv("TERN_API_KEY", raising=False)
    monkeypatch.setenv("BRIGALOW_MASK_MIRROR", "http://127.0.0.1:9/")
    monkeypatch.setattr(statewide, "Predictor", FakePredictor)
    monkeypatch.setattr(statewide, "process_tile", fake_process_tile)
    out = tmp_path / "out"
    rec = cli.predict_area(interior_box, 2025, out, weights="fake.onnx")
    txt = capsys.readouterr().out
    assert "could not be reached" in txt and "Sentinel-2-only setting" in txt and "Contains modified Copernicus Sentinel data 2024, 2025" in txt
    assert rec["setting"] == "s2only" and rec["threshold"] == 0.4 and rec["alerts"] == 1 and rec["alerts_high"] == 1
    assert sorted(os.listdir(out)) == ["alerts.geojson", "alerts.gpkg", "probability.tif", "run.json", "tiles"]
    import rasterio, geopandas as gpd
    with rasterio.open(out / "probability.tif") as s:
        q = s.read(1)
        assert s.crs.to_epsg() == 32755 and s.tags(ns="IMAGE_STRUCTURE").get("LAYOUT") == "COG"
        assert (q == 225).sum() == 36 and ((q == 10) | (q == 225)).mean() > 0.9
    a = gpd.read_file(out / "alerts.gpkg")
    assert len(a) == 1 and a.area_ha[0] == pytest.approx(1.44) and a.confidence[0] == "high"
    assert a.after_dates[0] == "2025-07-10,2025-08-04" and a.tiles[0] == "55KDQ"
    assert json.load(open(out / "run.json"))["notes"]


def test_main_returns_none(monkeypatch, tmp_path, interior_box):
    """Console scripts pass main()'s return value to sys.exit: it must be None."""
    monkeypatch.delenv("TERN_API_KEY", raising=False)
    monkeypatch.setenv("BRIGALOW_MASK_MIRROR", "http://127.0.0.1:9/")
    monkeypatch.setattr(statewide, "Predictor", FakePredictor)
    monkeypatch.setattr(statewide, "process_tile", fake_process_tile)
    bb = ",".join(map(str, interior_box))
    assert cli.main(["predict", "--bbox", bb, "--label-year", "2025", "--out", str(tmp_path / "o"), "--weights", "x.onnx"]) is None


def test_input_checks(tmp_path):
    with pytest.raises(SystemExit, match="W,S,E,N"):
        cli.predict_area((147, -22, 146, -21), 2025, tmp_path, weights="x")
    with pytest.raises(SystemExit, match="small areas"):
        cli.predict_area((140, -25, 146, -20), 2025, tmp_path, weights="x")
    with pytest.raises(SystemExit, match="has not ended"):
        cli.predict_area((146.5, -22.7, 146.51, -22.69), 2099, tmp_path, weights="x")


def test_thresholds_for():
    nested = {"standard": {"standard": 0.3, "high_confidence": 0.6}, "s2only": {"standard": 0.4, "high_confidence": None}}
    assert cli.thresholds_for(nested, "standard") == (0.3, 0.6)
    assert cli.thresholds_for(nested, "s2only") == (0.4, None)
    assert cli.thresholds_for({"standard": 0.02}, "immediate") == (0.02, None)
    assert cli.thresholds_for({}, "standard") == (None, None)


def test_select_tiles_interior_and_outside(interior_box):
    t = pd.read_parquet(TILES)
    assert cli.select_tiles(t, interior_box).tile.tolist() == ["55KDQ"]
    assert len(cli.select_tiles(t, (130.0, -25.0, 130.05, -24.95))) == 0      # Northern Territory


def test_no_torch_import_on_onnx_path():
    """The CLI modules must not import torch at module level (laptop install: onnxruntime only)."""
    import subprocess
    code = ("import sys; sys.modules['torch'] = None\n"
            "import brigalow.cli, brigalow.statewide, brigalow.infer, brigalow.postprocess, brigalow.tern\n"
            "print('ok')")
    r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
                       env={**os.environ, "PYTHONPATH": os.path.join(os.path.dirname(__file__), "..", "src")})
    assert r.returncode == 0 and r.stdout.strip() == "ok", r.stderr


def test_model_dir_uses_onnx_without_torch():
    """`brigalow predict --weights weights/brigalow` must work with onnxruntime only (README: PyTorch is not needed)."""
    import subprocess
    w = os.path.join(os.path.dirname(__file__), "..", "weights", "brigalow")
    mj = os.path.join(w, "model.json")
    if not os.path.exists(mj):
        pytest.skip("weights/brigalow not present")
    meta = json.load(open(mj))
    members = meta.get("members", [])
    first = (members[0].get("onnx") or members[0].get("pt")) if (members and isinstance(members[0], dict)) else (members[0] if members else "")
    if not first or not os.path.exists(os.path.join(w, first)):
        pytest.skip("weights/brigalow ONNX binaries not present locally")
    pytest.importorskip("onnxruntime")
    code = ("import sys; sys.modules['torch'] = None\n"
            "from brigalow import infer\n"
            f"p = infer.load({w!r})\n"
            "print(type(p.members[0]).__name__, len(p.members), p.stride)")
    r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
                       env={**os.environ, "PYTHONPATH": os.path.join(os.path.dirname(__file__), "..", "src")})
    exp = ["_OnnxMember", str(len(members)), str(meta["inference"]["stride"])]
    assert r.returncode == 0 and r.stdout.split() == exp, r.stdout + r.stderr