#!/usr/bin/env python3 """Exact scalar reductions and a reference fully polynomial ADDITIVE scheme. All model arithmetic is rational. The approximation routine uses the classical randomized determinant method for exact weighted bipartite matching. It always returns a valid order; its objective guarantee is probabilistic. The elementary implementation is intended for small instances, not as an optimized solver. """ from fractions import Fraction as F from math import prod, isqrt import random def ceil_fraction(x): return -((-x.numerator)//x.denominator) def build_scalar_reduction(values, rho=F(1, 2)): values=list(values) rho=F(rho) if not values or any(not isinstance(a,int) or a<=0 for a in values): raise ValueError('PARTITION values must be positive integers') if not 0D.""" work=[v%p for v in values] D=len(work)-1 if D>=p:raise ValueError('field is too small for interpolation') differences=[] while work: differences.append(work[0]) work=[(work[i+1]-work[i])%p for i in range(len(work)-1)] result=[0]*(D+1) basis=[1] for j,c in enumerate(differences): for k,b in enumerate(basis):result[k]=(result[k]+c*b)%p if j=1-beta. Runtime is polynomial in input bit length, 1/epsilon, and log(1/beta). Default randomness is from SystemRandom. Pass an RNG only for reproducible finite experiments; a fixed seed is not an adversarial probability bound. """ centers=[F(x) for x in centers] n=len(centers);rho=F(rho);epsilon=F(epsilon) beta=F(failure_probability);initial=F(initial);target=F(target) if not n or not 01 for x in centers) or abs(initial)>1 or abs(target)>1: raise ValueError('centers, initial state, and target must lie in [-1,1]') rng=rng or random.SystemRandom() delta=epsilon/(16*n) weights=[(1-rho)*rho**(n-1-i) for i in range(n)] rounded=[[int((w*t)//delta) for t in centers] for w in weights] row_min=[min(row) for row in rounded] costs=[[x-a for x in row] for row,a in zip(rounded,row_min)] offset=sum(row_min) constant=rho**n*initial-target D=degree_bound(costs) p=next_prime(16*n**3*(D+1)+1) repeats=1 while F(1,4)**repeats>beta:repeats+=1 best=list(range(n));best_value=(endpoint(centers,best,rho,initial)-target)**2 stats=dict(degree=D,field_prime=p,repeats=repeats,oracle_calls=0, determinants=0,fallback_rounds=0) for _ in range(repeats): support=coefficient_oracle(costs,p,rng,stats) if support: q=min(support,key=lambda z:(constant+delta*(z+offset))**2) order=recover_order(costs,q,p,rng,stats) else:order=None if order is None: stats['fallback_rounds']+=1;continue assert sorted(order)==list(range(n)) value=(endpoint(centers,order,rho,initial)-target)**2 if value