#!/usr/bin/env python3 """Exact tests of optimal positive-mask coordinate tomography. Python 3.10+, standard library only. All ranks, sensors, reconstruction and noise certificates use rational arithmetic. The mask-partition routine uses the shortest exchange augmentation for representable matroid partition and checks every returned partition explicitly. No novel matroid algorithm is claimed. The manuscript attributes the partition criterion to Edmonds. """ from collections import deque from fractions import Fraction as F from itertools import product from math import prod import json import random def rank(vectors): """Rank of vectors, each represented as a sequence of rational numbers.""" basis = {} for vector in vectors: row = list(map(F, vector)) for pivot, prior in sorted(basis.items()): if row[pivot]: scalar = row[pivot] row = [a - scalar * b for a, b in zip(row, prior)] pivot = next((i for i, value in enumerate(row) if value), None) if pivot is not None: scalar = row[pivot] basis[pivot] = [value / scalar for value in row] return len(basis) def independent_rows(rows): chosen = [] previous = 0 for i, row in enumerate(rows): current = rank([rows[j] for j in chosen] + [row]) if current > previous: chosen.append(i) previous = current return chosen def solve_linear(rows, rhs): """A consistent linear system, with all nonpivot variables set to zero.""" assert rows and len(rows) == len(rhs) n = len(rows[0]) matrix = [list(map(F, row)) + [F(value)] for row, value in zip(rows, rhs)] pivots = [] lead = 0 for col in range(n): selected = next((i for i in range(lead, len(matrix)) if matrix[i][col]), None) if selected is None: continue matrix[lead], matrix[selected] = matrix[selected], matrix[lead] scalar = matrix[lead][col] matrix[lead] = [value / scalar for value in matrix[lead]] for i in range(len(matrix)): if i != lead and matrix[i][col]: scalar = matrix[i][col] matrix[i] = [a - scalar * b for a, b in zip(matrix[i], matrix[lead])] pivots.append(col) lead += 1 if lead == len(matrix): break for row in matrix: assert any(row[:n]) or row[n] == 0, 'inconsistent linear system' answer = [F(0)] * n for i, col in enumerate(pivots): answer[col] = matrix[i][-1] assert [sum(a * b for a, b in zip(row, answer)) for row in rows] == list(rhs) return answer def inverse(matrix): n = len(matrix) assert all(len(row) == n for row in matrix) columns = [solve_linear(matrix, [F(i == j) for i in range(n)]) for j in range(n)] return [[columns[j][i] for j in range(n)] for i in range(n)] def matvec(matrix, vector): return [sum((F(a) * b for a, b in zip(row, vector)), F(0)) for row in matrix] def coordinate_operator(shape): """Every row sums a coordinate fiber; columns are labeled grid cells.""" points = list(product(*(range(q) for q in shape))) rows, labels = [], [] for axis in range(len(shape)): other_shape = [q for i, q in enumerate(shape) if i != axis] for kept in product(*(range(q) for q in other_shape)): rows.append([int(tuple(x for i, x in enumerate(point) if i != axis) == kept) for point in points]) labels.append((axis, kept)) return points, rows, labels def independent_partition(matrix, channels): """Shortest exchange augmentation; independent sets cover the columns.""" count = len(matrix[0]) columns = [tuple(row[j] for row in matrix) for j in range(count)] groups = [set() for _ in range(channels)] tests = 0 def independent(indices): nonlocal tests tests += 1 return rank([columns[j] for j in sorted(indices)]) == len(indices) for element in range(count): queue = deque([element]) previous = {element: None} terminal = None while queue and terminal is None: current = queue.popleft() for color, group in enumerate(groups): if current in group: continue if independent(group | {current}): terminal = (current, color) break for displaced in sorted(group): if displaced not in previous and independent((group - {displaced}) | {current}): previous[displaced] = (current, color) queue.append(displaced) assert terminal is not None, 'requested channel count does not admit a partition' revised = [group.copy() for group in groups] current, color = terminal revised[color].add(current) while previous[current] is not None: predecessor, color = previous[current] revised[color].remove(current) revised[color].add(predecessor) current = predecessor assert set().union(*revised) == set(range(element + 1)) assert sum(map(len, revised)) == element + 1 assert all(independent(group) for group in revised) groups = revised # Enlarge the first independent set to a basis by moving elements from # the others. Removing an element cannot spoil their independence. full_rank = rank(columns) while len(groups[0]) < full_rank: move = next((element for group in groups[1:] for element in sorted(group) if independent(groups[0] | {element})), None) assert move is not None source = next(j for j in range(1, channels) if move in groups[j]) groups[source].remove(move) groups[0].add(move) assert all(independent(group) for group in groups) return [sorted(group) for group in groups], tests def sensor_plan(matrix, groups, low=F(1, 4), high=F(1)): """Exactly N scalar rows, using one baseline and positive two-level masks.""" assert 0 < low < high n = len(matrix[0]) baseline_rows = independent_rows(matrix) selected = [baseline_rows] masks = [[F(1)] * n] operator = [[F(x) for x in matrix[i]] for i in baseline_rows] for group in groups[1:]: restricted = [[row[j] for j in group] for row in matrix] choices = independent_rows(restricted) assert len(choices) == len(group) selected.append(choices) mask = [high if j in group else low for j in range(n)] masks.append(mask) operator.extend([[F(a) * w for a, w in zip(matrix[i], mask)] for i in choices]) assert len(operator) == n assert rank(operator) == n return {'selected': selected, 'masks': masks, 'operator': operator, 'low': low, 'high': high} def decode(matrix, groups, plan, observations): """Reconstruct from only the N selected scalar measurements.""" n = len(matrix[0]) rb = plan['selected'][0] r = len(rb) base_particular = solve_linear([matrix[i] for i in rb], observations[:r]) full_baseline = matvec(matrix, base_particular) answer = [F(0)] * n pointer = r for group, choices in zip(groups[1:], plan['selected'][1:]): values = observations[pointer:pointer + len(choices)] pointer += len(choices) isolated = [(value - plan['low'] * full_baseline[i]) / (plan['high'] - plan['low']) for value, i in zip(values, choices)] local = solve_linear([[matrix[i][j] for j in group] for i in choices], isolated) for j, value in zip(group, local): answer[j] = value assert pointer == n residual = [full_baseline[i] - sum(F(matrix[i][j]) * answer[j] for group in groups[1:] for j in group) for i in rb] first = solve_linear([[matrix[i][j] for j in groups[0]] for i in rb], residual) for j, value in zip(groups[0], first): answer[j] = value return answer def norm_inf(matrix): return max(sum(abs(x) for x in row) for row in matrix) def case(shape): points, matrix, row_labels = coordinate_operator(shape) n = prod(shape) blind = prod(q - 1 for q in shape) r = n - blind assert rank(matrix) == r channels = (n + r - 1) // r groups, oracle_tests = independent_partition(matrix, channels) assert len(groups[0]) == r assert sum(map(len, groups)) == n plan = sensor_plan(matrix, groups) rng = random.Random(1000 + n) recovered = 0 for _ in range(8): z = [F(rng.randint(1, 80), rng.randint(1, 17)) for _ in points] observations = matvec(plan['operator'], z) assert decode(matrix, groups, plan, observations) == z recovered += 1 # A certified linear-noise bound, with a worst-case perturbation attaining # it: pick the sign of the largest absolute-row-sum inverse row. inv = inverse(plan['operator']) gain = norm_inf(inv) z = [F(i + 2, 7) for i in range(n)] epsilon = min(z) / (10 * gain) worst_row = max(range(n), key=lambda j: sum(abs(x) for x in inv[j])) error = [epsilon * (1 if x > 0 else -1 if x < 0 else 0) for x in inv[worst_row]] observations = matvec(plan['operator'], z) noisy = [a + b for a, b in zip(observations, error)] estimate = decode(matrix, groups, plan, noisy) actual_error = max(abs(a - b) for a, b in zip(estimate, z)) assert actual_error == gain * epsilon assert min(estimate) > 0 # Fewer channels cannot be injective, independently of how masks are # chosen. Sample several positive masks to check the rank obstruction. lower_rank_tests = [] if channels > 1: assert (channels - 1) * r < n for seed in range(3): rg = random.Random(seed) stacked = [] for j in range(channels - 1): weights = [F(1) if j == 0 else F(rg.randint(1, 9)) for _ in points] stacked.extend([[F(a) * w for a, w in zip(row, weights)] for row in matrix]) observed_rank = rank(stacked) assert observed_rank <= (channels - 1) * r < n lower_rank_tests.append(observed_rank) all_temperature_checks = 0 if len(set(shape)) == 1 and len(shape) >= 2: q = shape[0] z0 = [F(2 if sum(point) % q == 0 else 5) for point in points] z1 = [F(2 if sum(point) % q == 1 else 5) for point in points] assert z0 != z1 for row in matrix: values0 = sorted(z0[j] for j, a in enumerate(row) if a) values1 = sorted(z1[j] for j, a in enumerate(row) if a) assert values0 == values1 for power in range(1, q + 3): assert sum(x ** power for x in values0) == sum(x ** power for x in values1) all_temperature_checks += 1 for z in (z0, z1): assert decode(matrix, groups, plan, matvec(plan['operator'], z)) == z return {'shape': list(shape), 'cells': n, 'unmasked_rank': r, 'blind_dimension': blind, 'optimal_channels': channels, 'partition_sizes': list(map(len, groups)), 'partition': groups, 'partition_independence_oracle_calls': oracle_tests, 'scalar_measurements': len(plan['operator']), 'selected_fiber_rows': plan['selected'], 'positive_mask_levels': [str(plan['low']), str(plan['high'])], 'selected_operator_rank': rank(plan['operator']), 'exact_rational_recoveries': recovered, 'inverse_inf_norm': str(gain), 'condition_number_inf': str(norm_inf(plan['operator']) * gain), 'sharp_noise_certificate': True, 'fewer_channel_sample_ranks': lower_rank_tests, 'unmodulated_multiset_power_equalities': all_temperature_checks, 'coded_recovery_of_both_ambiguous_fields': True if all_temperature_checks else None} def main(): cases = [case(shape) for shape in ((3, 3), (4, 4), (3, 3, 3), (2, 3, 4))] cases.extend(case((2,) * dim) for dim in range(1, 6)) return {'status': 'PASS', 'arithmetic': 'exact integers and fractions', 'cases': cases, 'scope': ['Mask channels interrogate the same fixed positive field.', 'Masks are calibrated, externally supplied additional observations.', 'Optimality is within the stated linear exponential-domain sensor model.', 'The matroid partition criterion is established mathematics.', 'No practical image or neural-network superiority is tested.']} if __name__ == '__main__': print(json.dumps(main(), indent=2))