"""Run with python3 treeOS_LOG_reflection_test.py. All arithmetic is exact.""" from collections import Counter from random import Random Q, S = 339949771344778, 10**15 DEPTH = 23 def terminal(d, n): for _ in range(n): d = (Q * d) // S return d def threshold(target, n): """Smallest source with terminal >= target, by inverse inequalities.""" for _ in range(n): target = -((-S * target) // Q) return target def forward_threshold(target, n): """Compute the same threshold by forward evaluations and binary search.""" lo, hi = -1, 1 while terminal(lo, n) >= target: lo *= 2 while terminal(hi, n) < target: hi *= 2 while hi - lo > 1: mid = (lo + hi) // 2 if terminal(mid, n) < target: lo = mid else: hi = mid return hi def test(): if not __debug__: raise RuntimeError("Run without -O so assertions are enabled.") n = DEPTH cuts = {} for target in (-2, -1, 0, 1): t = threshold(target, n) assert t == forward_threshold(target, n) assert terminal(t - 1, n) == target - 1 and terminal(t, n) == target cuts[target] = t # Intersect the ordinary zero fiber with each reflected fiber. lo, hi = cuts[0], cuts[1] - 1 classes = [] for z in (0, -1, -2): first = max(lo, 1 - cuts[z + 1]) last = min(hi, -cuts[z]) assert first <= last for d in (first, last): assert (terminal(d, n), terminal(-d, n)) == (0, z) classes.append((first, last, z)) assert classes == [(0, 0, 0), (1, 32524186965, -1), (32524186966, 64283265547, -2)] counts = [last - first + 1 for first, last, _ in classes] assert sum(counts) == hi - lo + 1 == 64283265548 assert (sum(counts) - 1).bit_length() == 36 for (first, last, z), count in zip(classes, counts): print(f"{first:,}..{last:,} -> {z}: {count:,} sources") canonical = Counter() for d in range(32768): y, z = terminal(d, n), terminal(-d, n) assert (y, z) == (0, -int(d > 0)) canonical[z] += 1 print("Canonical histogram:", dict(canonical)) # Test a streaming encoder. Its state is only y and the two-bit gap. # Cross-check the receiver against direct evaluation on the negated input. rng = Random(23) sources = list(range(-4096, 4097)) sources += [rng.randrange(-(1 << 512), 1 << 512) for _ in range(256)] seen = [set() for _ in range(129)] for d in sources: y, z, gap = d, -d, 0 for depth in range(1, 129): y, r = divmod(Q * y, S) gap = (r + Q * gap + S - 1) // S z = (Q * z) // S assert gap in (0, 1, 2) and -y - gap == z seen[depth].add(gap) assert seen[1] == {0, 1} print(f"Streaming reflection: {len(sources) * 128:,} comparisons passed") # Certify sharpness on the same y=0 for every tested depth >= 2. for depth in range(2, 129): witnesses = (0, 1, threshold(1, depth) - 1) assert all(terminal(d, depth) == 0 for d in witnesses) assert [terminal(-d, depth) for d in witnesses] == [0, -1, -2] print("All three outcomes realized at every depth 2..128") print("PASS") if __name__ == "__main__": test()