"""Independent dense elimination and finite-payload checks (BSD-3-Clause).""" from itertools import combinations import unittest import model def dense_rank(rows, width): a = [[(row >> col) & 1 for col in range(width)] for row in rows] pivot = 0 for col in range(width): found = next((i for i in range(pivot, len(a)) if a[i][col]), None) if found is None: continue a[pivot], a[found] = a[found], a[pivot] for i in range(pivot+1, len(a)): if a[i][col]: a[i] = [x ^ y for x, y in zip(a[i], a[pivot])] pivot += 1 return pivot class Liber8tionTests(unittest.TestCase): def test_all_device_pairs_with_independent_dense_elimination(self): count = 0 for k in range(2, 9): matrix = model.rows(k) for erased in combinations(range(k+2), 2): survivors = model.surviving(matrix, erased) self.assertEqual(model.rank(survivors), 8*k) self.assertEqual(dense_rank(survivors, 8*k), 8*k) count += 1 self.assertEqual(count, 161) def test_each_q_matrix_and_pair_sum_are_invertible(self): blocks = [[(r >> (8*d)) & 255 for r in model.rows(8)[72:]] for d in range(8)] for block in blocks: self.assertEqual(dense_rank(block, 8), 8) for a, b in combinations(blocks, 2): self.assertEqual(dense_rank([x ^ y for x, y in zip(a,b)], 8), 8) def test_all_k2_payloads_have_distinct_parity_pairs(self): # Direct XOR equations for the k=2 example, without integer-row dot products. seen = set() for payload in range(1 << 16): a, b = payload & 255, payload >> 8 p = a ^ b q = 0 for row, col in enumerate((7,3,0,2,6,1,5,4)): bit = ((a >> row) ^ (b >> col)) & 1 if row == 4: bit ^= (b >> 7) & 1 q |= bit << row seen.add(p | (q << 8)) dot = sum(((r & payload).bit_count() % 2) << i for i,r in enumerate(model.rows(2)[16:])) self.assertEqual(dot, p | (q << 8)) self.assertEqual(len(seen), 65536) def test_density_and_update_histogram(self): for k in range(2,9): c = model.configuration(k) self.assertEqual(c["codingMatrixOnes"], 17*k-1) self.assertEqual(c["directEncodingXors"], 17*(k-1)) self.assertEqual(c["parityUpdateCounts"], {"two": 7*k+1, "three": k-1}) self.assertEqual(model.configuration(8)["meanParityUpdates"], "135/64") self.assertEqual(model.targets(8,15), [("P",7),("Q",0),("Q",4)]) def test_missing_extra_coefficient_is_detected(self): broken = model.rows(2) broken[28] ^= 1 << 15 self.assertLess(dense_rank(model.surviving(broken,(0,1)),16),16) self.assertEqual(model.results()["negativeControl"]["survivorRank"],15) def test_reject_invalid_inputs(self): for k in (True, False, 0, 1, 9, -1, 2.0, "2", None): with self.assertRaises(ValueError): model.rows(k) for coordinate in (True, -1, 64, 1.0, None): with self.assertRaises(ValueError): model.targets(8, coordinate) for row in (-1, True, "1"): with self.assertRaises(ValueError): model.rank([row]) if __name__ == "__main__": unittest.main()