"""Validation against references and theory (not just behaviour tests).""" import itertools import numpy as np import pytest from robotics.bench import trackA, trackB from robotics.swarm import fusion def test_our_dawid_skene_matches_crowdkit_reference(): pytest.importorskip("crowdkit") from robotics.swarm.crowd import crowdkit (Ph, yh, _), (P, y, _) = trackA.synthetic(n=400, seed=3) ours = fusion.dawid_skene(np.vstack([Ph, P]), P)[0] > 0 # same data as the reference (hist + eval) ref = crowdkit(Ph, P, "DawidSkene")[0] > 0 assert np.mean(ours == ref) >= 0.90 assert abs(np.mean(ours == y) - np.mean(ref == y)) < 0.03 @pytest.mark.parametrize("attack", ["bias", "collude", "noise", "two_faced", "drift"]) @pytest.mark.parametrize("F", [1, 2, 3]) def test_wmsr_safety_on_complete_graph(attack, F): """W-MSR theorem (LeBlanc et al. 2013): with F-local adversaries on a sufficiently robust graph (here complete, n=12 >= 3F+1), every honest state stays inside the convex hull (per coordinate) of the honest initial states, whatever the Byzantine robots send.""" w = trackB.World(n=12, k=11, F=F, attack=attack, seed=F) w.A = ~np.eye(12, dtype=bool) target = np.array([5.0, 5.0]) m = w.measure(target) honest = ~w.byz lo, hi = m[honest].min(0), m[honest].max(0) x = m.copy() for rnd in range(15): new = x.copy() for i in np.flatnonzero(honest): nb = np.flatnonzero(w.A[i]) vals = np.array([w.lie(j, i, x[j], target, "eval", rnd) if w.byz[j] else x[j] for j in nb]) new[i] = trackB._wmsr(x[i], vals, F) x = new assert np.all(x[honest] >= lo - 1e-9) and np.all(x[honest] <= hi + 1e-9) def test_race_s_is_invariant_to_monotone_miscalibration(): """Rank-Gauss makes RACE-S invariant to any strictly increasing distortion of an agent's scores.""" (Ph, yh, _), (P, y, _) = trackA.synthetic(n=300, seed=4) a = fusion.race_s(Ph, P, 0)[0] > 0 Ph2, P2 = Ph.copy(), P.copy() Ph2[:, 2], P2[:, 2] = Ph[:, 2] ** 3, P[:, 2] ** 3 b = fusion.race_s(Ph2, P2, 0)[0] > 0 assert np.mean(a == b) >= 0.98