"""Mass conservation and sampling budgets for paired data-diversity fits.""" import copy import json 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")) import diversity_mass as mass FAMILIES = {"a": "fa", "a-extra": "fa", "b": "fb", "held": "fh"} def records(): return [ dict(name="a1", sample_id="20", group="a", split="original-role", target=np.array([[1, 1, 1, 0, 255]], dtype=np.uint8)), dict(name="a2", sample_id="30", group="a", split="original-role", target=np.array([[1, 255]], dtype=np.uint8)), dict(name="b1", sample_id="10", group="b", split="original-role", target=np.array([[1, 0, 0, 0, 255]], dtype=np.uint8)), ] def test_mass_is_equal_per_class_family_and_supported_frame_not_pixel_count(): original = records() out, weights, audit = mass.prepare(original, "fh", FAMILIES) assert [r["sample_id"] for r in out] == ["10", "20", "30"] np.testing.assert_allclose(weights["a1"], [[1 / 24, 1 / 24, 1 / 24, 1 / 4, 0]]) np.testing.assert_allclose(weights["a2"], [[1 / 8, 0]]) np.testing.assert_allclose(weights["b1"], [[1 / 4, 1 / 12, 1 / 12, 1 / 12, 0]]) assert audit["total_mass"] == pytest.approx(1) assert [r["mass"] for r in audit["classes"]] == pytest.approx([0.5, 0.5]) assert all(r["mass"] == pytest.approx(0.25) for r in audit["family_classes"]) assert {r["name"]: r["mass"] for r in audit["frames"]} == pytest.approx( {"a1": 3 / 8, "a2": 1 / 8, "b1": 1 / 2} ) assert json.loads(json.dumps(audit)) == audit for r in out: assert r["split"] == "original-role" assert weights[r["name"]].dtype == np.float64 assert (weights[r["name"]][r["target"] != 255] > 0).all() assert not weights[r["name"]][r["target"] == 255].any() def test_bg_only_frame_redistributes_only_its_family_background_mass(): old = records() added = dict(name="new", sample_id="40", group="a-extra", split="regression", target=np.array([[0, 0, 255]], dtype=np.uint8)) _, before, ba = mass.prepare(old, "fh", FAMILIES) out, after, aa = mass.prepare(old + [added], "fh", FAMILIES) for r in old: np.testing.assert_array_equal(before[r["name"]][r["target"] == 1], after[r["name"]][r["target"] == 1]) np.testing.assert_array_equal(before["b1"], after["b1"]) assert after["a1"][0, 3] == pytest.approx(1 / 8) np.testing.assert_allclose(after["new"], [[1 / 16, 1 / 16, 0]]) assert [r["mass"] for r in ba["classes"]] == pytest.approx( [r["mass"] for r in aa["classes"]] ) assert [r["mass"] for r in ba["family_classes"]] == pytest.approx( [r["mass"] for r in aa["family_classes"]] ) assert next(r for r in out if r["name"] == "new")["group"] == "a-extra" assert next(r for r in out if r["name"] == "new")["split"] == "regression" def test_no_input_mutation_and_permutation_independence(): source = records() previous = copy.deepcopy(source) out, weights, audit = mass.prepare(source, "fh", FAMILIES) other, ww, aa = mass.prepare(source[::-1], "fh", dict(reversed(list(FAMILIES.items())))) assert audit == aa assert [r["sample_id"] for r in other] == [r["sample_id"] for r in out] for r, old in zip(source, previous, strict=True): np.testing.assert_array_equal(r["target"], old["target"]) np.testing.assert_array_equal(weights[r["name"]], ww[r["name"]]) out[0]["target"][:] = 255 out[0]["group"] = "changed" np.testing.assert_array_equal(source[2]["target"], previous[2]["target"]) assert source[2]["group"] == "b" @pytest.mark.parametrize("fault", [ "held", "duplicate-name", "duplicate-id", "missing-group", "missing-family", "one-class-family", "one-class-global", "unknown-only", "bad-label", "float", "nan", "infinity", "empty-target", "one-dimensional", "missing-target", "empty", "missing-held-map", "bad-mapping", "blank-id", ]) def test_invalid_admissions_fail_closed(fault): rows, mapping = records(), dict(FAMILIES) if fault == "held": rows[0]["group"] = "held" elif fault == "duplicate-name": rows[1]["name"] = rows[0]["name"] elif fault == "duplicate-id": rows[1]["sample_id"] = rows[0]["sample_id"] elif fault == "missing-group": del mapping["a"] elif fault == "missing-family": mapping["extra-unseen-group"] = "extra-family" elif fault == "one-class-family": rows[2]["target"][rows[2]["target"] == 1] = 0 elif fault == "one-class-global": for r in rows: r["target"][r["target"] == 1] = 0 elif fault == "unknown-only": rows[0]["target"][:] = 255 elif fault == "bad-label": rows[0]["target"][0, 0] = 2 elif fault in ("float", "nan", "infinity"): rows[0]["target"] = rows[0]["target"].astype(float) rows[0]["target"][0, 0] = {"float": 1.0, "nan": np.nan, "infinity": np.inf}[fault] elif fault == "empty-target": rows[0]["target"] = np.empty((0, 2), dtype=np.uint8) elif fault == "one-dimensional": rows[0]["target"] = rows[0]["target"].reshape(-1) elif fault == "missing-target": del rows[0]["target"] elif fault == "empty": rows = [] elif fault == "missing-held-map": del mapping["held"] elif fault == "bad-mapping": mapping["a"] = None elif fault == "blank-id": rows[0]["sample_id"] = "" with pytest.raises(ValueError): mass.prepare(rows, "fh", mapping) @pytest.mark.parametrize("budget,frames", [(10, 3), (10240, 12), (10240, 14), (9216, 11), (8, 8), (7, 1)]) def test_quotas_exact_budget_positive_and_fair_over_a_full_cycle(budget, frames): cycle = np.stack([mass.quotas(budget, frames, step) for step in range(frames)]) assert cycle.dtype == np.int64 and (cycle > 0).all() np.testing.assert_array_equal(cycle.sum(axis=1), np.full(frames, budget)) np.testing.assert_array_equal(cycle.sum(axis=0), np.full(frames, budget)) assert cycle.max() - cycle.min() <= 1 np.testing.assert_array_equal(mass.quotas(budget, frames, 0), mass.quotas(budget, frames, frames)) def test_remainder_wraps_and_arms_have_equal_total_draws(): np.testing.assert_array_equal(mass.quotas(11, 4, 3), [3, 3, 2, 3]) np.testing.assert_array_equal(mass.quotas(11, 4, 4), [3, 3, 3, 2]) for step in range(20): assert mass.quotas(10240, 10, step).sum() == mass.quotas(10240, 14, step).sum() np.testing.assert_array_equal(mass.quotas(np.int64(5), np.int64(2), np.int64(1)), [2, 3]) @pytest.mark.parametrize("args", [ (0, 1, 0), (2, 3, 0), (2, 0, 0), (2, -1, 0), (4, 2, -1), (3.0, 2, 0), (3, 2.0, 0), (3, 2, 0.0), (True, 1, 0), (3, True, 0), (3, 2, False), (np.nan, 2, 0), (np.inf, 2, 0), (2**63, 2, 0), ]) def test_invalid_quotas_rejected(args): with pytest.raises(ValueError): mass.quotas(*args)