"""Exact block-orbit transport certificates for arbitrary catalogue sizes. Each internal edge removes one exponent unit from the upper block and adds it to the lower block. After averaging over permutations within the two blocks, it is a nonnegative sum of ordered monomial differences. Flow conservation therefore certifies an identity, not a sampled inequality. """ import argparse import gzip import hashlib import json import math import sys import time from collections import Counter, deque from functools import lru_cache from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts')) from certify import orbit_shapes @lru_cache(None) def partitions(degree, length, cap=None): if cap is None: cap = degree if length == 0: return ((),) if degree == 0 else () if length == 1: return ((degree,),) if degree <= cap else () result = [] for first in range(min(degree, cap), -1, -1): if degree - first > (length - 1) * first: continue for rest in partitions(degree - first, length - 1, first): result.append((first,) + rest) return tuple(result) def orbit_size(exponents, cut): numerator = math.factorial(cut) * math.factorial(len(exponents) - cut) denominator = math.prod(math.factorial(count) for group in (exponents[:cut], exponents[cut:]) for count in Counter(group).values()) assert numerator % denominator == 0 return numerator // denominator def kernel_states(capacity, support, cut): degree = capacity * (capacity + 1) + 2 - support shapes = orbit_shapes(capacity, support) # This identity also checks the reflected-cut symmetry used in the proof. for shape, scores in shapes.items(): assert sum(scores.get(e, 0) for e in shape) == 0 states = [upper + lower for upper_degree in range(degree + 1) for upper in partitions(upper_degree, cut) for lower in partitions(degree - upper_degree, support - cut)] masses = [] for exponents in states: scores = shapes.get(tuple(sorted(exponents, reverse=True)), {}) coefficient = sum(scores.get(e, 0) for e in exponents[:cut]) masses.append(coefficient * orbit_size(exponents, cut)) assert sum(masses) == 0 return degree, states, masses class IntegerFlow: def __init__(self, size): self.graph = [[] for _ in range(size)] def add(self, source, target, capacity): assert capacity > 0 a, b = self.graph[source], self.graph[target] a.append([target, capacity, len(b), capacity]) b.append([source, 0, len(a) - 1, 0]) def solve(self, source, sink, target_flow): graph = self.graph total = 0 while True: levels = [-1] * len(graph) levels[source] = 0 queue = deque([source]) while queue: u = queue.popleft() for v, capacity, _, _ in graph[u]: if capacity and levels[v] < 0: levels[v] = levels[u] + 1 queue.append(v) if levels[sink] < 0: return total cursor = [0] * len(graph) def augment(u, amount): if u == sink: return amount while cursor[u] < len(graph[u]): edge = graph[u][cursor[u]] v, available, reverse, _ = edge if available and levels[v] == levels[u] + 1: sent = augment(v, min(amount, available)) if sent: edge[1] -= sent graph[v][reverse][1] += sent return sent cursor[u] += 1 return 0 while amount := augment(source, target_flow): total += amount def is_transfer(source, target, cut): return (len(source) == len(target) and sum(source) == sum(target) and sum(source[:cut]) - sum(target[:cut]) == 1 and all(a >= b for a, b in zip(source[:cut], target[:cut])) and all(a <= b for a, b in zip(source[cut:], target[cut:]))) def mass_digest(states, masses): digest = hashlib.sha256() for exponents, mass in zip(states, masses): if mass: digest.update((','.join(map(str, exponents)) + ':' + str(mass) + '\n').encode()) return digest.hexdigest() def certify(capacity, support, cut, certificate_dir): start = time.monotonic() degree, states, masses = kernel_states(capacity, support, cut) index = {e: i for i, e in enumerate(states)} source, sink = len(states), len(states) + 1 total = sum(mass for mass in masses if mass > 0) assert total > 0 network = IntegerFlow(sink + 1) internal_edges = 0 for u, exponents in enumerate(states): if masses[u] > 0: network.add(source, u, masses[u]) elif masses[u] < 0: network.add(u, sink, -masses[u]) for a in sorted(set(exponents[:cut])): if a == 0: continue for b in sorted(set(exponents[cut:])): upper, lower = list(exponents[:cut]), list(exponents[cut:]) upper.remove(a) upper.append(a - 1) lower.remove(b) lower.append(b + 1) target = tuple(sorted(upper, reverse=True) + sorted(lower, reverse=True)) network.add(u, index[target], total) internal_edges += 1 sent = network.solve(source, sink, total) if sent != total: # A forward-closed set with positive net mass is an exact obstruction # to this restricted transport cone, not to Zipf monotonicity. reachable = {source} queue = deque([source]) while queue: u = queue.popleft() for v, residual, _, _ in network.graph[u]: if residual and v not in reachable: reachable.add(v) queue.append(v) assert sink not in reachable selected = {u for u in reachable if u < len(states)} for u in selected: assert all(v in selected for v, _, _, initial in network.graph[u] if v < len(states) and initial) net_mass = sum(masses[u] for u in selected) assert net_mass == total - sent > 0 # Record the maximal generators of this forward-closed set. has_predecessor = set() for u in selected: has_predecessor.update(v for v, _, _, initial in network.graph[u] if v < len(states) and initial) generators = sorted(states[u] for u in selected - has_predecessor) return {'capacity': capacity, 'support': support, 'cut': cut, 'degree': degree, 'states': len(states), 'flow': sent, 'required_flow': total, 'deficiency': net_mass, 'closed_set_size': len(selected), 'generators': generators, 'nonzero_masses_in_closed_set': [ [states[u], masses[u]] for u in sorted(selected) if masses[u]], 'passed': False, 'seconds': time.monotonic() - start} name = f'C{capacity}-m{support}-l{cut}.jsonl.gz' certificate_dir.mkdir(parents=True, exist_ok=True) path = certificate_dir / name balances = [0] * len(states) digest = hashlib.sha256() count = 0 header = {'capacity': capacity, 'support': support, 'cut': cut, 'degree': degree, 'mass_sha256': mass_digest(states, masses)} with gzip.open(path, 'wt', encoding='utf-8') as output: output.write(json.dumps(header, separators=(',', ':')) + '\n') for u in range(len(states)): for v, remaining, _, initial in network.graph[u]: if v >= len(states) or not initial or remaining == initial: continue amount = initial - remaining assert amount > 0 and is_transfer(states[u], states[v], cut) balances[u] += amount balances[v] -= amount line = json.dumps([states[u], states[v], amount], separators=(',', ':')) + '\n' output.write(line) digest.update(line.encode()) count += 1 assert balances == masses, 'Polynomial coefficient identity failed' return {**header, 'states': len(states), 'internal_edges': internal_edges, 'transported_mass': total, 'positive_flows': count, 'flow_sha256': digest.hexdigest(), 'certificate_file': name, 'seconds': time.monotonic() - start, 'passed': True} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--max-capacity', type=int, default=5) parser.add_argument('--case', help='Run one capacity:support:cut triple') parser.add_argument('--certificate-dir', type=Path, default=Path('work/zipf-transport')) parser.add_argument('--out', type=Path, default=Path(__file__).parent / 'results/transport_certificates.json') args = parser.parse_args() records = [] # Maximal support 2C+1 is proved analytically. Other cuts follow by reflection. cases = ([tuple(map(int, args.case.split(':')))] if args.case else [(capacity, support, cut) for capacity in range(1, args.max_capacity + 1) for support in range(capacity + 1, 2 * capacity + 1) for cut in range(1, support // 2 + 1)]) for capacity, support, cut in cases: result = certify(capacity, support, cut, args.certificate_dir) records.append(result) print(json.dumps(result), flush=True) args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(json.dumps({'max_capacity_requested': args.max_capacity, 'records': records}, indent=2) + '\n') if not result['passed']: raise SystemExit('Restricted transport failed; exact obstruction recorded.') if __name__ == '__main__': main()