A unified geometry of private navigation and observable projection · Chapter 24 of 24

21. Reproducibility appendix

Save the following code as a Python file and run it with Python 3. It uses only the standard library. It does not access enrollment data, external accounts, or network services.

"""Exact finite verification for the unified geometric formalization.
Run with Python 3; standard library only. General proofs remain in the manuscript.
"""
from collections import Counter, defaultdict
from fractions import Fraction
from itertools import combinations, permutations, product


def vxor(a, b):
    return tuple(x ^ y for x, y in zip(a, b))


alphabet = tuple(range(4))
targets = list(product(alphabet, repeat=2))
vocabularies = list(permutations(range(2)))
words = list(product(range(2), repeat=4))
cells = [
    ({0, 1}, {2, 3}),
    ({0, 2}, {1, 3}),
    ({0, 1}, {2, 3}),
    ({0, 2}, {1, 3}),
]
positions = (0, 0, 1, 1)


def member_signature(s):
    return tuple(next(i for i, cell in enumerate(partition)
                      if s[j] in cell)
                 for partition, j in zip(cells, positions))


def raw_signature(s, phi):
    return tuple(phi[i] for i in member_signature(s))


credentials = [(s, phi) for s in targets for phi in vocabularies]
fibers = defaultdict(list)
weights = {c: (c[0][0] + 1) * (c[0][1] + 2) * (c[1][0] + 1)
           for c in credentials}
weight_total = sum(weights.values())
priors = {c: Fraction(w, weight_total) for c, w in weights.items()}
joint = defaultdict(Fraction)
for c in credentials:
    raw = raw_signature(*c)
    for mask in words:
        y = vxor(raw, mask)
        fibers[y].append((c, mask))
        joint[c, y] += priors[c] / len(words)

for y in words:
    assert len(fibers[y]) == len(credentials)
    assert {c for c, mask in fibers[y]} == set(credentials)
    for c in credentials:
        assert joint[c, y] == priors[c] / len(words)

slice_checks = 0
for y in words:
    for phi in vocabularies:
        for mask in words:
            hits = [(c, m) for c, m in fibers[y]
                    if c[1] == phi and m == mask]
            assert len(hits) == 1
            slice_checks += 1

accepted_checks = 0
for s in targets:
    for phi in vocabularies:
        inv = {value: index for index, value in enumerate(phi)}
        for mask in words:
            for y in words:
                decoded = tuple(inv[a] for a in vxor(y, mask))
                acc = all(s[j] in partition[i]
                          for j, partition, i in zip(positions, cells, decoded))
                if acc:
                    survivors = [a for a in targets
                                 if member_signature(a) == decoded]
                    assert survivors == [s]
                    accepted_checks += 1
print(f"Core: 512 credential-mask states; exact nonuniform-prior factorization; "
      f"{slice_checks} private intersections; {accepted_checks} accepted recoveries.")

actual_s, actual_phi, actual_mask = (2, 1), (1, 0), (1, 0, 1, 1)
assert member_signature(actual_s) == (1, 0, 0, 1)
assert raw_signature(actual_s, actual_phi) == (0, 1, 1, 0)
assert vxor(raw_signature(actual_s, actual_phi), actual_mask) == (1, 1, 0, 1)
# A missing phase leaves an accepted answer compatible with two symbols.
assert {a for a in alphabet if a in cells[0][1]} == {2, 3}
print("Worked example and missing-separation counterexample passed.")


def matrix_rank_mod(entries, q):
    a = [list(entries[:2]), list(entries[2:])]
    rank = 0
    for col in range(2):
        pivot = next((i for i in range(rank, 2) if a[i][col] % q), None)
        if pivot is None:
            continue
        a[rank], a[pivot] = a[pivot], a[rank]
        scale = pow(a[rank][col], -1, q)
        a[rank] = [(v * scale) % q for v in a[rank]]
        for row in range(2):
            if row != rank:
                c = a[row][col]
                a[row] = [(v - c * u) % q
                          for v, u in zip(a[row], a[rank])]
        rank += 1
    return rank


def matvec(entries, x, q):
    return ((entries[0] * x[0] + entries[1] * x[1]) % q,
            (entries[2] * x[0] + entries[3] * x[1]) % q)


affine_fibers = affine_slices = 0
q = 3
plane = list(product(range(q), repeat=2))
for entries in product(range(q), repeat=4):
    rank = matrix_rank_mod(entries, q)
    for y in plane:
        fiber = [(x, m) for x in plane for m in plane
                 if tuple((a + b) % q
                          for a, b in zip(matvec(entries, x, q), m)) == y]
        assert len(fiber) == q ** 2
        affine_fibers += 1
        for m in plane:
            hit_count = sum(mm == m for x, mm in fiber)
            assert hit_count in (0, q ** (2 - rank))
            affine_slices += 1
print(f"Affine geometry: 81 matrices; {affine_fibers} fibers; "
      f"{affine_slices} slice intersections passed.")

# The previously developed circular suite follows.


from collections import Counter
from itertools import combinations, permutations, product
from math import gcd


def signatures(h, b, counts, vocabulary=None):
    vocabulary = tuple(range(h)) if vocabulary is None else vocabulary
    phases = [r for r, n in enumerate(counts) for _ in range(n)]
    return [
        tuple(vocabulary[((a - r) % (h * b)) // b] for r in phases)
        for a in range(h * b)
    ], phases


def add(x, y, h):
    return tuple((a + b) % h for a, b in zip(x, y))


def sub(x, y, h):
    return tuple((a - b) % h for a, b in zip(x, y))


def generated_group(generators, h, m):
    subgroup = {(0,) * m}
    for g in generators:
        subgroup = {add(u, tuple(k * a % h for a in g), h)
                    for u in subgroup for k in range(h)}
    return subgroup


schedule_count = 0
distance_pairs = 0
for h in range(2, 7):
    for b in range(1, 6):
        for counts in product(range(4), repeat=b):
            code, phases = signatures(h, b, counts)
            distances = [sum(x != y for x, y in zip(u, v))
                         for u, v in combinations(code, 2)]
            assert min(distances) == min(counts), (h, b, counts)
            for a in range(h * b):
                expected = tuple(int(r == a % b) for r in phases)
                assert sub(code[a], code[(a - 1) % (h * b)], h) == expected
            schedule_count += 1
            distance_pairs += len(distances)
print(f"Distance and boundary identities: {schedule_count} schedules, "
      f"{distance_pairs} target pairs passed.")

vocabulary_cases = 0
for h in range(2, 6):
    for b in range(1, 4):
        for counts in [(1,) * b, (2,) * b,
                       tuple(0 if r == 0 else 1 for r in range(b))]:
            for vocabulary in permutations(range(h)):
                code, phases = signatures(h, b, counts, vocabulary)
                m = len(phases)
                increments = [sub(code[a], code[a - 1], h)
                              for a in range(h * b)]
                subgroup = generated_group(increments, h, m)
                active = [r for r, n in enumerate(counts) if n]
                expected = {
                    tuple(dict(zip(active, values))[r] for r in phases)
                    for values in product(range(h), repeat=len(active))
                }
                assert subgroup == expected, (h, b, counts, vocabulary)
                assert all(set(add(w, z, h) for z in subgroup) == expected
                           for w in code)
                vocabulary_cases += 1
print(f"Difference subgroup and exact privacy support: "
      f"{vocabulary_cases} schedule/vocabulary cases passed.")

# Check all probability laws with integer weights 0, 1, 2 in the smallest
# repeated-phase space. A law is private iff constant on subgroup cosets.
h, b, counts = 2, 1, (2,)
code, phases = signatures(h, b, counts)
ambient = list(product(range(h), repeat=2))
subgroup = {(0, 0), (1, 1)}
law_count = 0
for weights in product(range(3), repeat=len(ambient)):
    if not sum(weights):
        continue
    mu = dict(zip(ambient, weights))
    private = all(
        mu[sub(y, code[0], h)] == mu[sub(y, word, h)]
        for y in ambient for word in code
    )
    invariant = all(mu[y] == mu[add(y, u, h)]
                    for y in ambient for u in subgroup)
    assert private == invariant
    law_count += 1
print(f"Mask-law classification: all {law_count} nonzero small weighted laws passed.")

# Correct one error and one erasure for H=2, b=2, four copies of each phase.
code, phases = signatures(2, 2, (4, 4))
recovery_cases = 0
for truth, word in enumerate(code):
    for erased in range(len(word)):
        candidates = [None] + [j for j in range(len(word)) if j != erased]
        for flipped in candidates:
            received = list(word)
            if flipped is not None:
                received[flipped] ^= 1
            received[erased] = None
            matches = [
                a for a, other in enumerate(code)
                if sum(r is not None and r != v
                       for r, v in zip(received, other)) <= 1
            ]
            assert matches == [truth]
            recovery_cases += 1
print(f"One substitution plus one erasure: {recovery_cases} unique-recovery cases passed.")

# A pre-mask error can be correctable and still leak through a mask-invariant
# within-phase difference. This is an intentional counterexample.
code, phases = signatures(2, 2, (3, 3))
for target in (0, 1):
    raw = list(code[target])
    if target == 1:
        raw[0] ^= 1
    for phase_masks in product(range(2), repeat=2):
        mask = tuple(phase_masks[r] for r in phases)
        released = add(raw, mask, 2)
        assert released[0] ^ released[1] == target
        matches = [a for a, w in enumerate(code)
                   if sum(x != y for x, y in zip(raw, w)) <= 1]
        assert matches == [target]
print("Boundary example: secret-dependent pre-mask error is recoverable but leaks.")

# Explicit ten-symbol example.
code, phases = signatures(2, 5, (1,) * 5)
print("Ten-symbol canonical signatures:")
for a, word in enumerate(code):
    print(a, "".join(map(str, word)))