Download code/observable_certificates.py from PureOne/Nhairun-Exact-Complexity: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/PureOne/Nhairun-Exact-Complexity/resolve/main/code/observable_certificates.py
- Command line
-
hf download hf://datasets/PureOne/Nhairun-Exact-Complexity/code/observable_certificates.py
-
curl -L -o observable_certificates.py https://huggingface.co/datasets/PureOne/Nhairun-Exact-Complexity/resolve/main/code/observable_certificates.py
10.7 kB
| #!/usr/bin/env python3 | |
| """Exact rational certificates for observable rank and quotient guarantees. | |
| This module implements the constructive algebraic parts of the observable-rank | |
| proof and the norm/mismatch certificates. The maximum-volume basis enumerates | |
| rank-sized subsets: its running time is polynomial for FIXED variation rank. | |
| The multivariate matching optimizer is specified in the manuscript; this module | |
| does not replace it by a permutation enumeration or claim to implement it. | |
| """ | |
| from fractions import Fraction as F | |
| from itertools import combinations | |
| def dot(a,b): | |
| return sum((F(x)*F(y) for x,y in zip(a,b)),F(0)) | |
| def matvec(a,x): | |
| return [dot(row,x) for row in a] | |
| def transpose(a): | |
| return [list(row) for row in zip(*a)] | |
| def matmul(a,b): | |
| bt=transpose(b) | |
| return [[dot(row,col) for col in bt] for row in a] | |
| def subtract(a,b): | |
| return [[F(x)-F(y) for x,y in zip(ra,rb)] for ra,rb in zip(a,b)] | |
| def determinant(a): | |
| a=[[F(x) for x in row] for row in a] | |
| n=len(a); value=F(1) | |
| for i in range(n): | |
| pivot=next((j for j in range(i,n) if a[j][i]),None) | |
| if pivot is None:return F(0) | |
| if pivot!=i: | |
| a[i],a[pivot]=a[pivot],a[i];value=-value | |
| d=a[i][i];value*=d | |
| for j in range(i+1,n): | |
| f=a[j][i]/d | |
| for k in range(i+1,n):a[j][k]-=f*a[i][k] | |
| a[j][i]=F(0) | |
| return value | |
| def solve(a,b): | |
| n=len(a) | |
| if not n:return [] | |
| a=[[F(x) for x in row]+[F(v)] for row,v in zip(a,b)] | |
| for i in range(n): | |
| pivot=next((j for j in range(i,n) if a[j][i]),None) | |
| if pivot is None:raise ValueError('singular linear system') | |
| a[i],a[pivot]=a[pivot],a[i] | |
| d=a[i][i];a[i]=[x/d for x in a[i]] | |
| for j in range(n): | |
| if j==i:continue | |
| f=a[j][i] | |
| a[j]=[x-f*y for x,y in zip(a[j],a[i])] | |
| return [row[-1] for row in a] | |
| def gram(vectors): | |
| return [[dot(x,y) for y in vectors] for x in vectors] | |
| def is_psd(a): | |
| """Exact PSD test by symmetric positive-pivot Schur complements.""" | |
| a=[[F(x) for x in row] for row in a] | |
| n=len(a) | |
| if any(len(row)!=n for row in a):return False | |
| if any(a[i][j]!=a[j][i] for i in range(n) for j in range(n)): | |
| return False | |
| while a: | |
| n=len(a) | |
| if any(a[i][i]<0 for i in range(n)):return False | |
| pivot=next((i for i in range(n) if a[i][i]>0),None) | |
| if pivot is None:return all(not x for row in a for x in row) | |
| order=[pivot]+[i for i in range(n) if i!=pivot] | |
| a=[[a[i][j] for j in order] for i in order] | |
| d=a[0][0] | |
| a=[[a[i][j]-a[i][0]*a[0][j]/d | |
| for j in range(1,n)] for i in range(1,n)] | |
| return True | |
| def norm_bound(x,bound): | |
| bound=F(bound) | |
| return bound>=0 and dot(x,x)<=bound*bound | |
| def operator_norm_bound(a,bound): | |
| bound=F(bound) | |
| if bound<0 or not a:return False | |
| n=len(a[0]) | |
| if any(len(row)!=n for row in a):return False | |
| ata=matmul(transpose(a),a) | |
| residual=[[bound*bound*(i==j)-ata[i][j] | |
| for j in range(n)] for i in range(n)] | |
| return is_psd(residual) | |
| def maximum_gram_basis(vectors): | |
| """Return a rational maximum-Gram-volume basis and all coordinates.""" | |
| vectors=[[F(x) for x in v] for v in vectors] | |
| if not vectors:raise ValueError('nonempty vector list required') | |
| m=len(vectors[0]) | |
| if any(len(v)!=m for v in vectors):raise ValueError('dimension mismatch') | |
| independent=[] | |
| for v in vectors: | |
| if determinant(gram(independent+[v]))>0:independent.append(v) | |
| r=len(independent) | |
| if not r:return dict(rank=0,basis=[],coordinates=[[] for _ in vectors], | |
| gram=[],maximum_gram_determinant=F(1)) | |
| candidates=list(dict.fromkeys(tuple(v) for v in vectors if any(v))) | |
| best=None;bestdet=F(-1) | |
| for choice in combinations(candidates,r): | |
| value=determinant(gram(choice)) | |
| if value>bestdet:best=list(choice);bestdet=value | |
| g=gram(best) | |
| coordinates=[solve(g,[dot(b,v) for b in best]) for v in vectors] | |
| assert all(abs(x)<=1 for c in coordinates for x in c) | |
| return dict(rank=r,basis=[list(b) for b in best],coordinates=coordinates, | |
| gram=g,maximum_gram_determinant=bestdet) | |
| def compress_assignment(a,edges): | |
| """Compress observed edge variations; preserve exact squared objectives.""" | |
| a=[F(x) for x in a];n=len(edges);m=len(a) | |
| if not n or any(len(row)!=n for row in edges): | |
| raise ValueError('edges must be a nonempty square array of vectors') | |
| edges=[[[F(x) for x in v] for v in row] for row in edges] | |
| if any(len(v)!=m for row in edges for v in row): | |
| raise ValueError('vector dimension mismatch') | |
| if any(not norm_bound(v,1) for row in edges for v in row): | |
| raise ValueError('the theorem requires edge-vector norms at most one') | |
| reference=[row[0] for row in edges] | |
| variations=[[x-y for x,y in zip(v,reference[p])] | |
| for p,row in enumerate(edges) for v in row] | |
| result=maximum_gram_basis(variations) | |
| constant=[a[j]+sum(reference[p][j] for p in range(n)) for j in range(m)] | |
| flat=result.pop('coordinates') | |
| coordinates=[flat[p*n:(p+1)*n] for p in range(n)] | |
| result.update(size=n,ambient_dimension=m,constant=constant, | |
| coordinates=coordinates, | |
| constant_squared=dot(constant,constant), | |
| cross=[dot(b,constant) for b in result['basis']]) | |
| return result | |
| def compressed_objective(model,order): | |
| r=model['rank'] | |
| total=[sum(model['coordinates'][p][i][j] for p,i in enumerate(order)) | |
| for j in range(r)] | |
| return (model['constant_squared']+2*dot(model['cross'],total) | |
| +dot(total,matvec(model['gram'],total))) | |
| def assignment_residual(a,edges,order): | |
| return [F(x)+sum(F(edges[p][i][j]) for p,i in enumerate(order)) | |
| for j,x in enumerate(a)] | |
| def rounded_encoding(model,epsilon): | |
| """Carry-free scalar costs for the matching primitive in the proof.""" | |
| epsilon=F(epsilon);n=model['size'];r=model['rank'] | |
| if not 0<epsilon<=1:raise ValueError('epsilon must be in (0,1]') | |
| if not r:return dict(rank=0,delta=F(0),base=1,costs=[[0]*n for _ in range(n)], | |
| minima=[],vector_costs=[[[] for _ in range(n)] for _ in range(n)], | |
| degree=0,coordinate_degree=[]) | |
| delta=epsilon/(32*r*n) | |
| rounded=[[[int(F(x)//delta) for x in coord] for coord in row] | |
| for row in model['coordinates']] | |
| minima=[[min(rounded[p][i][j] for i in range(n)) for j in range(r)] | |
| for p in range(n)] | |
| costs=[[[rounded[p][i][j]-minima[p][j] for j in range(r)] | |
| for i in range(n)] for p in range(n)] | |
| degrees=[sum(max(costs[p][i][j] for i in range(n)) for p in range(n)) | |
| for j in range(r)] | |
| base=max(degrees)+1 | |
| encoded=[[sum(costs[p][i][j]*base**j for j in range(r)) | |
| for i in range(n)] for p in range(n)] | |
| return dict(rank=r,delta=delta,base=base,costs=encoded, | |
| minima=[sum(row[j] for row in minima) for j in range(r)], | |
| vector_costs=costs,degree=sum(max(row) for row in encoded), | |
| coordinate_degree=degrees) | |
| def decode_cost(value,base,rank): | |
| digits=[] | |
| for _ in range(rank): | |
| digits.append(value%base);value//=base | |
| if value:raise ValueError('encoded total exceeds supplied rank') | |
| return digits | |
| def rounded_residual(model,encoding,order): | |
| r=model['rank'];out=model['constant'][:] | |
| if not r:return out | |
| q=sum(encoding['costs'][p][i] for p,i in enumerate(order)) | |
| digits=decode_cost(q,encoding['base'],r) | |
| coordinates=[encoding['delta']*(x+y) | |
| for x,y in zip(encoding['minima'],digits)] | |
| for j,b in enumerate(model['basis']): | |
| out=[x+coordinates[j]*y for x,y in zip(out,b)] | |
| return out | |
| def execute(matrices,increments,initial,order): | |
| x=[F(v) for v in initial] | |
| for i in order: | |
| x=[u+F(v) for u,v in zip(matvec(matrices[i],x),increments[i])] | |
| return x | |
| def quotient_certificate(matrices,increments,response,quotient_increments, | |
| readout,initial,quotient_initial,target,rho, | |
| kappa=F(0),eta=F(0),eta0=F(0)): | |
| """Validate supplied rational bounds and return the uniform certificate. | |
| q_N bounds every observation mismatch. 4*q_N bounds objective mismatch; | |
| eps+8*q_N bounds true regret after eps-additive quotient optimization. | |
| """ | |
| rho=F(rho);kappa=F(kappa);eta=F(eta);eta0=F(eta0) | |
| n=len(matrices) | |
| if not n or not 0<=rho<1 or min(kappa,eta,eta0)<0: | |
| raise ValueError('invalid contraction or mismatch constants') | |
| if len(increments)!=n or len(quotient_increments)!=n: | |
| raise ValueError('request count mismatch') | |
| d=len(initial);r=len(quotient_initial) | |
| if len(target)!=r or len(readout)!=r or any(len(row)!=d for row in readout): | |
| raise ValueError('readout dimension mismatch') | |
| if len(response)!=r or any(len(row)!=r for row in response): | |
| raise ValueError('quotient response dimension mismatch') | |
| if any(len(m)!=d or any(len(row)!=d for row in m) for m in matrices): | |
| raise ValueError('hidden response dimension mismatch') | |
| if any(len(b)!=d for b in increments) or any(len(c)!=r for c in quotient_increments): | |
| raise ValueError('increment dimension mismatch') | |
| if not operator_norm_bound(readout,1) or not operator_norm_bound(response,rho): | |
| raise ValueError('readout or quotient norm bound failed') | |
| if not all(norm_bound(x,1) for x in (initial,quotient_initial,target)): | |
| raise ValueError('initial-state or target norm bound failed') | |
| ac=matmul(response,readout) | |
| for m,b,c in zip(matrices,increments,quotient_increments): | |
| if not operator_norm_bound(m,rho):raise ValueError('hidden norm bound failed') | |
| if not norm_bound(b,1-rho) or not norm_bound(c,1-rho): | |
| raise ValueError('increment norm bound failed') | |
| if not operator_norm_bound(subtract(matmul(readout,m),ac),kappa): | |
| raise ValueError('observable response defect bound failed') | |
| if not norm_bound([x-F(y) for x,y in zip(matvec(readout,b),c)],eta): | |
| raise ValueError('observable increment defect bound failed') | |
| if not norm_bound([x-F(y) for x,y in zip(matvec(readout,initial),quotient_initial)],eta0): | |
| raise ValueError('initial observation mismatch bound failed') | |
| q=rho**n*eta0+(kappa+eta)*(1-rho**n)/(1-rho) | |
| return dict(requests=n,hidden_dimension=d,observed_dimension=r, | |
| terminal_mismatch=q,objective_mismatch=4*q, | |
| regret_transfer=8*q,exact_closure=(kappa==eta==eta0==0)) | |