import copy import hashlib import sys from pathlib import Path import numpy as np import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning")) from background_admission import add_background, prepare_background from coverage_mass_control import prepare, schedule_digest def review_case(): t = np.full((64, 64), 255, dtype="uint8") t[:5] = 1 t[55:] = 0 protected = np.zeros(t.shape, dtype=bool) protected[25:28, 25:28] = True s = dict( name="sample", split="train", size=[64, 64], rgb_sha256="a" * 64, target_sha256=hashlib.sha256(t.tobytes()).hexdigest(), protected_sha256=hashlib.sha256(protected.tobytes()).hexdigest(), ) review = dict( s, boundary_ignore_px=2, regions=[ dict( id="inside", reason="Visible non-paint interior", polygon=[[128, 128], [384, 128], [384, 384], [128, 384]], ) ], ) return s, review, t, protected def test_background_admission_preserves_known_and_protected_pixels(): s, r, t, p = review_case() before = t.copy() out, added, audit = add_background(s, r, t, p) assert added.any() and not added[p].any() assert np.all(out[p] == 255) assert np.array_equal(out[t != 255], t[t != 255]) assert np.array_equal(out == 1, t == 1) assert not added[16, 16] and added[20, 20] assert audit[0]["protected_excluded"] == 9 assert np.array_equal(t, before) @pytest.mark.parametrize( "bad", ["split", "image", "target", "protected", "margin", "paint", "overlap", "polygon"] ) def test_invalid_or_conflicting_admission_is_rejected(bad): s, r, t, p = review_case() if bad == "split": s["split"] = "regression" if bad == "image": r["rgb_sha256"] = "b" * 64 if bad == "target": t[10, 10] = 0 if bad == "protected": p[30, 30] = True if bad == "margin": r["boundary_ignore_px"] = 0 if bad == "paint": r["regions"][0]["polygon"] = [[0, 0], [512, 0], [512, 512], [0, 512]] if bad == "overlap": r["regions"].append(dict(r["regions"][0], id="second")) if bad == "polygon": r["regions"][0]["polygon"][0] = [-1, 0] with pytest.raises(ValueError): add_background(s, r, t, p) def records(): out = [] for j in range(2): t = np.array([[1, 1, 0, 255], [1, 0, 255, 255]], dtype="uint8") b = t.copy() b[0, 1] = 255 added = np.zeros(t.shape, dtype=bool) added[1, 2:] = True out.append( dict( name=str(j), sample_id=str(j), group=str(j), split="train", target=t, base_target=b, added_background=added, ) ) return out @pytest.mark.parametrize("policy", ["base", "mass", "equal_window"]) def test_negative_mass_conserved_positive_weights_exact_and_order_unchanged(policy): original = records() before = copy.deepcopy(original) rr, weights = prepare(original, policy) out, ww = prepare_background(rr, weights) assert schedule_digest(rr, 7, 120) == schedule_digest(out, 7, 120) for old, new in zip(rr, out, strict=True): n = old["name"] paint = old["target"] == 1 bg = old["target"] == 0 added = old["added_background"] assert np.array_equal(ww[n][paint], weights[n][paint]) assert float(ww[n][new["target"] == 0].sum()) == pytest.approx(float(weights[n][bg].sum())) np.testing.assert_allclose(ww[n][bg], weights[n][bg] * 0.5) assert np.all(new["target"][added] == 0) and not ww[n][new["target"] == 255].any() assert all( np.array_equal(x["target"], y["target"]) for x, y in zip(original, before, strict=True) ) def test_zero_add_is_exact_identity_including_empty_window(): rr = records() for r in rr: r["added_background"][:] = False rr[1]["target"][:] = 255 rr[1]["base_target"][:] = 255 prepared, w = prepare(rr, "base") out, ww = prepare_background(prepared, w) for a, b in zip(prepared, out, strict=True): assert np.array_equal(a["target"], b["target"]) assert np.array_equal(w[a["name"]], ww[a["name"]]) @pytest.mark.parametrize( "bad", ["split", "known", "negative", "nan", "unknown_weight", "empty_bg", "duplicate"] ) def test_invalid_background_weight_inputs_rejected(bad): rr, w = prepare(records(), "mass") if bad == "split": rr[0]["split"] = "test" if bad == "known": rr[0]["added_background"][0, 0] = True if bad == "negative": w["0"][0, 0] = -1 if bad == "nan": w["0"][0, 0] = np.nan if bad == "unknown_weight": w["0"][1, 2] = 1 if bad == "empty_bg": w["0"][rr[0]["target"] == 0] = 0 if bad == "duplicate": rr.append(rr[0]) with pytest.raises(ValueError): prepare_background(rr, w)