Download code/scalar_ordering.py from PureOne/Nhairun-Exact-Complexity: direct link, hf CLI and curl.
- Browser
- Download file 7.93 kB
-
https://huggingface.co/datasets/PureOne/Nhairun-Exact-Complexity/resolve/main/code/scalar_ordering.py
- Command line
-
hf download hf://datasets/PureOne/Nhairun-Exact-Complexity/code/scalar_ordering.py
-
curl -L -o scalar_ordering.py https://huggingface.co/datasets/PureOne/Nhairun-Exact-Complexity/resolve/main/code/scalar_ordering.py
7.93 kB
| #!/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 0<rho<1: | |
| raise ValueError('rho must be strictly between zero and one') | |
| n=len(values); N=2*n | |
| r,s=rho.numerator,rho.denominator | |
| weights=[r**(N-p)*s**(p-1) for p in range(1,N+1)] | |
| W=sum(weights); base=W+1 | |
| gaps=[weights[2*i+1]-weights[2*i] for i in range(n)] | |
| H=prod(gaps) | |
| data=[a*H//g for a,g in zip(values,gaps)] | |
| D=2*max(weights)*sum(data) | |
| Q=2*D+1 | |
| markers=[base**i for i in range(n)] | |
| target=Q*sum(markers[i]*(weights[2*i]+weights[2*i+1]) for i in range(n)) | |
| raw=[] | |
| for marker,c in zip(markers,data): | |
| raw.extend([Q*marker+c,Q*marker-c]) | |
| bias=F(target,W) | |
| shifted=[F(v)-bias for v in raw] | |
| R=1+ceil_fraction(2*max(abs(v) for v in shifted)/(1-rho)) | |
| centers=[v/((1-rho)*R) for v in shifted] | |
| gap=F(1,s**(N-1)*R) | |
| return dict(values=values,rho=rho,n=n,N=N,weights=weights,W=W,base=base, | |
| gaps=gaps,H=H,data=data,D=D,Q=Q,markers=markers,target=target, | |
| raw=raw,bias=bias,R=R,centers=centers,gap=gap) | |
| def endpoint(centers, order, rho=F(1,2), initial=F(0)): | |
| x=F(initial); rho=F(rho) | |
| for j in order: | |
| x=rho*x+(1-rho)*F(centers[j]) | |
| return x | |
| def raw_residual(model, order): | |
| return sum(w*model['raw'][j] for w,j in zip(model['weights'],order))-model['target'] | |
| def determinant_mod(matrix, p): | |
| a=[row[:] for row in matrix] | |
| n=len(a); answer=1 | |
| for i in range(n): | |
| pivot=next((j for j in range(i,n) if a[j][i]%p),None) | |
| if pivot is None:return 0 | |
| if pivot!=i: | |
| a[i],a[pivot]=a[pivot],a[i] | |
| answer=-answer | |
| v=a[i][i]%p | |
| answer=answer*v%p | |
| inv=pow(v,p-2,p) | |
| for j in range(i+1,n): | |
| factor=a[j][i]*inv%p | |
| if factor: | |
| for k in range(i+1,n):a[j][k]=(a[j][k]-factor*a[i][k])%p | |
| a[j][i]=0 | |
| return answer%p | |
| def interpolate_consecutive(values,p): | |
| """Recover coefficients from values at 0,1,...,D, with p>D.""" | |
| 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<D: | |
| following=[0]*(len(basis)+1) | |
| for k,b in enumerate(basis): | |
| following[k]=(following[k]-j*b)%p | |
| following[k+1]=(following[k+1]+b)%p | |
| inverse=pow(j+1,p-2,p) | |
| basis=[x*inverse%p for x in following] | |
| return result | |
| def is_prime(n): | |
| if n<2:return False | |
| if n%2==0:return n==2 | |
| return all(n%d for d in range(3,isqrt(n)+1,2)) | |
| def next_prime(n): | |
| n=max(2,n) | |
| while not is_prime(n):n+=1 | |
| return n | |
| def degree_bound(costs): | |
| if not costs:return 0 | |
| return sum(max((v for v in row if v is not None),default=0) for row in costs) | |
| def coefficient_oracle(costs,p,rng,stats=None): | |
| """Return a subset of the attainable perfect-matching weights. | |
| There are no false positives. Each genuine coefficient vanishes with | |
| probability at most n/|S|, where S is a dyadic subset of the field. | |
| Every label uses a fixed number of independent unbiased random bits. | |
| """ | |
| n=len(costs) | |
| if n==0:return {0} | |
| if any(all(v is None for v in row) for row in costs):return set() | |
| D=degree_bound(costs) | |
| if p<=D:raise ValueError('field is too small') | |
| label_bits=p.bit_length()-1 | |
| labels=[[rng.getrandbits(label_bits) for _ in row] for row in costs] | |
| values=[] | |
| for x in range(D+1): | |
| matrix=[[0 if v is None else labels[i][j]*pow(x,v,p)%p | |
| for j,v in enumerate(row)] for i,row in enumerate(costs)] | |
| values.append(determinant_mod(matrix,p)) | |
| coeff=interpolate_consecutive(values,p) | |
| if stats is not None: | |
| stats['oracle_calls']=stats.get('oracle_calls',0)+1 | |
| stats['determinants']=stats.get('determinants',0)+D+1 | |
| return {q for q,c in enumerate(coeff) if c} | |
| def recover_order(costs,target,p,rng,stats=None): | |
| n=len(costs); columns=list(range(n)); answer=[] | |
| original_target=target | |
| for i in range(n): | |
| chosen=None | |
| for j in columns: | |
| value=costs[i][j] | |
| if value is None or target<value:continue | |
| remainder=target-value | |
| rest=[c for c in columns if c!=j] | |
| minor=[[costs[row][c] for c in rest] for row in range(i+1,n)] | |
| support=coefficient_oracle(minor,p,rng,stats) | |
| if remainder in support: | |
| chosen=j;target=remainder;break | |
| if chosen is None:return None | |
| answer.append(chosen);columns.remove(chosen) | |
| if target or sum(costs[i][j] for i,j in enumerate(answer))!=original_target: | |
| return None | |
| return answer | |
| def approximate_scalar_order(centers,rho=F(1,2),epsilon=F(1,4), | |
| failure_probability=F(1,4),initial=F(0), | |
| target=F(0),rng=None): | |
| """Return a valid order with J <= OPT+epsilon with probability >=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 0<rho<1 or not 0<epsilon<=1 or not 0<beta<1: | |
| raise ValueError('invalid size or approximation parameters') | |
| if any(abs(x)>1 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<best_value:best=order;best_value=value | |
| return dict(order=best,objective=best_value,statistics=stats, | |
| epsilon=epsilon,failure_probability=beta) | |