#!/usr/bin/env python3 """Exact equal-weight mean selection in arbitrary finite dimension. All arithmetic is rational. The unrestricted routine is constructive, not an instance optimizer. Rule-constrained enumeration is an exact small-instance oracle and deliberately does not inherit unrestricted constants. """ from collections import Counter from fractions import Fraction as Q from itertools import combinations_with_replacement import argparse import json from pathlib import Path def rat(value): return value if isinstance(value, Q) else Q(str(value)) def dot(a, b): return sum((x*y for x, y in zip(a, b)), Q(0)) def norm2(a): return dot(a, a) def sub(a, b): return tuple(x-y for x, y in zip(a, b)) def validate_points(points): z = [tuple(map(rat, row)) for row in points] if not z or not z[0] or any(len(row) != len(z[0]) for row in z): raise ValueError('Need nonempty, equally sized coordinate rows') return z def moments(points, weights): d = len(points[0]) mu = tuple(sum((p*x[j] for p,x in zip(weights,points)), Q(0)) for j in range(d)) variance = sum((p*norm2(sub(x,mu)) for p,x in zip(weights,points)), Q(0)) return mu, variance def affine_dependence(points): """Return a nonzero exact affine dependence, or None if independent.""" cols = len(points) rows = len(points[0])+1 a = [[Q(1)]*cols] + [[x[j] for x in points] for j in range(rows-1)] pivots = [] row = 0 for col in range(cols): pivot = next((i for i in range(row, rows) if a[i][col]), None) if pivot is None: continue a[row], a[pivot] = a[pivot], a[row] v = a[row][col] a[row] = [x/v for x in a[row]] for i in range(rows): if i != row and a[i][col]: v = a[i][col] a[i] = [x-v*y for x,y in zip(a[i],a[row])] pivots.append(col) row += 1 if row == rows: break free = next((i for i in range(cols) if i not in pivots), None) if free is None: return None direction = [Q(0)]*cols direction[free] = Q(1) for i,col in enumerate(pivots): direction[col] = -a[i][free] return direction def compress_stream(points): """One pass; preserve the mean and never increase the second moment. At termination, resident original points are affinely independent, hence there are at most r+1 of them when the stream has affine rank r. """ resident = [] count = 0 sums = None second = Q(0) for raw in points: x = tuple(map(rat, raw)) if sums is None: if not x: raise ValueError('Empty coordinate row') sums = [Q(0)]*len(x) if len(x) != len(sums): raise ValueError('Coordinate dimensions differ') resident = [(i,z,p*Q(count,count+1)) for i,z,p in resident] resident.append((count,x,Q(1,count+1))) count += 1 sums = [s+y for s,y in zip(sums,x)] second += norm2(x) while True: direction = affine_dependence([z for _,z,_ in resident]) if direction is None: break if sum(a*norm2(z) for a,(_,z,_) in zip(direction,resident)) > 0: direction = [-a for a in direction] step = min(p/(-a) for a,(_,_,p) in zip(direction,resident) if a < 0) resident = [(i,z,p+step*a) for a,(i,z,p) in zip(direction,resident) if p+step*a > 0] if not count: raise ValueError('Input has no points') mu = tuple(s/count for s in sums) variance = second/count - norm2(mu) return resident, mu, variance, count def coefficient(rank, n): """Proved universal upper coefficient U_r(n), not an unknown sharp value.""" if not isinstance(n,int) or isinstance(n,bool) or n < 1: raise ValueError('n must be a positive integer') if rank < 0: raise ValueError('rank must be nonnegative') if rank == 0: return Q(0) if n == 1: return Q(1) if rank <= 2: return Q(1,2*n-1) pair = max(Q(1,3), Q(rank-1,2*rank)) if n <= rank: return (n-2+4*pair)/n**2 base = (rank-2+4*pair)/rank**2 return rank*base/(n*(1+base)-rank*base) def mean_of_counts(points, counts, n): return tuple(sum((c*points[i][j] for i,c in counts.items()),Q(0))/n for j in range(len(points[0]))) def select_atomic(points, weights, n): """Pair certificate, conditional padding, and exact mass peeling. The support-size parameter r=m-1 makes the theorem valid in any ambient Hilbert space, even if the input support is not affinely independent. """ z = validate_points(points) p = list(map(rat,weights)) if len(z) != len(p) or any(w < 0 for w in p) or sum(p) != 1: raise ValueError('Weights must be probabilities with matching length') if not isinstance(n,int) or isinstance(n,bool) or n < 1: raise ValueError('n must be a positive integer') active = [i for i,w in enumerate(p) if w] rank = len(active)-1 remaining = n frames = [] trace = [] while True: mu,variance = moments(z,p) bound = coefficient(rank,remaining) radius = {i:norm2(sub(z[i],mu)) for i in active} closest = min(active,key=lambda i:(radius[i],i)) if radius[closest] <= bound*variance: counts = Counter({closest:remaining}) trace.append({'step':'repeat','budget':remaining,'index':closest}) break if remaining == 1: raise AssertionError('Nearest-point variance inequality failed') if remaining == 2: pair = min(combinations_with_replacement(active,2), key=lambda ij:(norm2(sub(tuple((a+b)/2 for a,b in zip(z[ij[0]],z[ij[1]])),mu)),ij)) counts = Counter(pair) trace.append({'step':'pair','budget':2,'indices':list(pair)}) break if remaining >= rank+1: hub = max(active,key=lambda i:(p[i],-i)) if p[hub] < Q(1,remaining): raise AssertionError('Peeling mass threshold failed') frames.append(('peel',hub,remaining,None,None)) trace.append({'step':'peel','budget':remaining,'index':hub}) p = [(remaining*w-(1 if i==hub else 0))/(remaining-1) for i,w in enumerate(p)] active = [i for i,w in enumerate(p) if w] else: frames.append(('pad',None,remaining,mu,tuple(active))) trace.append({'step':'pad','budget':remaining}) remaining -= 1 for kind,hub,budget,mu,available in reversed(frames): if kind == 'peel': counts[hub] += 1 else: total = tuple(sum(c*z[i][j] for i,c in counts.items()) for j in range(len(z[0]))) hub = min(available,key=lambda i:(norm2(sub(tuple((s+x)/budget for s,x in zip(total,z[i])),mu)),i)) counts[hub] += 1 return dict(sorted(counts.items())), trace def residual_candidate(points, weights, n): """Floor exact counts and apply the atomic theorem to fractional mass. Fewer than m slots remain. The bound is k^2 U_(s-1)(k) W_q/n^2, where s is the positive residual support size and W_q its variance. """ z = points floor_counts = [int(n*p) for p in weights] residual = [n*p-k for p,k in zip(weights,floor_counts)] k = n-sum(floor_counts) counts = Counter({i:a for i,a in enumerate(floor_counts) if a}) if k == 0: return dict(counts), Q(0) q = [a/k for a in residual] nu,w = moments(z,q) available = [i for i,p in enumerate(q) if p] residual_counts,_ = select_atomic(z,q,k) counts.update(residual_counts) return dict(sorted(counts.items())), Q(k*k,n*n)*coefficient(len(available)-1,k)*w def select(points,n): resident,mu,variance,N = compress_stream(points) z = [x for _,x,_ in resident] p = [w for _,_,w in resident] rank = len(resident)-1 upper = coefficient(rank,n) atomic_mu,atomic_variance = moments(z,p) assert atomic_mu == mu and atomic_variance <= variance rounding_counts,rounding_bound = residual_candidate(z,p,n) rounding_h = mean_of_counts(z,rounding_counts,n) rounding_error = norm2(sub(rounding_h,mu)) if rounding_error <= upper*atomic_variance: counts,h,error,trace = rounding_counts,rounding_h,rounding_error,[] method = 'floor-residual-atomic-selection' else: counts,trace = select_atomic(z,p,n) h = mean_of_counts(z,counts,n) error = norm2(sub(h,mu)) method = 'pair-padding-peeling' assert error <= upper*variance mapped = {resident[i][0]:v for i,v in counts.items()} return {'N':N,'n':n,'ambient_dimension':len(mu),'resident_affine_rank':rank, 'counts':mapped,'mean':[str(v) for v in mu], 'selected_mean':[str(v) for v in h], 'variance':str(variance), 'squared_mean_error':str(error),'guaranteed_upper_coefficient':str(upper), 'full_data_loss_ratio':str(1+error/variance) if variance else '1', 'compressed_indices':[i for i,_,_ in resident], 'compressed_weights':[str(p) for _,_,p in resident], 'compressed_points':[[str(v) for v in x] for _,x,_ in resident], 'compressed_variance':str(atomic_variance), 'residual_rounding_bound':str(rounding_bound), 'selected_method':method,'construction_trace':trace, 'replacement_allowed':True,'is_instance_optimal':False} def compositions(n,m,prefix=()): if m == 1: yield prefix+(n,) else: for k in range(n+1): yield from compositions(n-k,m-1,prefix+(k,)) def exact_rule_selection(points,n,weights=None,rules=None,max_states=500000): """Exhaustive optimum over rational linear count rules and integer caps. Rules: lower/upper per-row count arrays; linear list with a, sense, rhs. A linear row acts on integer counts. This supports exact quotas and costs. Bounds and enumeration cap are enforced before claiming an optimum. """ from math import comb z = validate_points(points) if not isinstance(n,int) or isinstance(n,bool) or n < 1: raise ValueError('n must be a positive integer') m = len(z) states = comb(n+m-1,m-1) if states > max_states: raise ValueError(f'Exact enumeration needs {states} states; limit is {max_states}') p = [Q(1,m)]*m if weights is None else list(map(rat,weights)) if len(p)!=m or any(v<0 for v in p) or sum(p)!=1: raise ValueError('Invalid probability vector') rules = rules or {} lower = rules.get('lower',[0]*m) upper = rules.get('upper',[n]*m) if len(lower)!=m or len(upper)!=m or any(not isinstance(x,int) for x in lower+upper): raise ValueError('Count bounds need integer arrays of matching length') linear = [] for rule in rules.get('linear',[]): a = list(map(rat,rule['a'])) if len(a)!=m or rule['sense'] not in ('<=','>=','=='): raise ValueError('Invalid linear count rule') linear.append((a,rule['sense'],rat(rule['rhs']))) mu,variance = moments(z,p) best = None feasible = 0 for c in compositions(n,m): if any(vhi for v,lo,hi in zip(c,lower,upper)): continue valid = True for a,sense,rhs in linear: v = dot(a,c) if (sense=='<=' and v>rhs) or (sense=='>=' and v