Neiru-Siha-II / research /certificates.py
PureOne's picture
Release Neiru Siha II research dataset
19591f3 verified
Raw History Blame Contribute Delete
12.2 kB
#!/usr/bin/env python3
"""Exact rational certificates for finite equal-weight selection rules.
Public API
----------
verify_upper_certificate(p, n, counts, lottery_weights, C, rules=None)
Checks that every supplied count vector is legal, the lottery weights are
nonnegative and sum to one, and
sum_j lambda_j (c_j/n-p)(c_j/n-p)^T <= C (diag(p)-p p^T).
A valid certificate guarantees some supported selection has normalized
squared mean error at most C, for EVERY geometry with these masses.
verify_lower_certificate(p, n, G, tau, rules=None,
admissible_counts=None, max_states=500000)
Checks G >= 0, G p = 0, sum_i p_i G_ii = 1, and q^T G q >= tau
for EVERY legal q=c/n. The complete rule-constrained set is enumerated.
If admissible_counts is supplied, its coverage is checked against that set;
omitting even one admissible count vector invalidates the certificate.
A valid certificate gives a realizable unit-variance geometry in dimension
at most len(p)-1 whose best legal selection error is at least tau.
positive_semidefinite(matrix)
Checks a symmetric rational matrix by exact Schur complements, including
singular matrices with zero pivots. No eigenvalue tolerances are used.
Rules match selection.py: optional integer lower/upper arrays and linear rows
{'a': [...], 'sense': '<=' | '>=' | '==', 'rhs': rational} acting on counts.
Rationals are int, Fraction, or strings; Python binary floats and bools are
rejected. JSON decimal tokens are parsed directly as Fraction by the CLI.
Malformed input raises ValueError. A mathematically invalid certificate returns
{'valid': False, 'reason': ...}. Validity is never inferred from a sampled set.
CLI: python certificates.py certificate.json [--output checked.json]
JSON kind is 'upper' or 'lower'; remaining keys match the corresponding API.
"""
from fractions import Fraction as F
from math import comb
from pathlib import Path
import argparse
import json
def rational(value):
if isinstance(value,bool) or isinstance(value,float):
raise ValueError('Use exact integer, Fraction, or rational-string inputs; binary floats and bools are rejected')
if isinstance(value,F):
return value
if isinstance(value,int):
return F(value)
if isinstance(value,str):
try:
return F(value)
except (ValueError,ZeroDivisionError) as exc:
raise ValueError('Invalid rational string') from exc
raise ValueError('Unsupported rational input type')
def integer(value,label,positive=False):
if isinstance(value,bool) or not isinstance(value,int):
raise ValueError(label+' must be an integer')
if positive and value<=0:
raise ValueError(label+' must be positive')
return value
def matrix_input(matrix):
if not isinstance(matrix,(list,tuple)) or not matrix:
raise ValueError('A nonempty square matrix is required')
m=len(matrix)
if any(not isinstance(row,(list,tuple)) or len(row)!=m for row in matrix):
raise ValueError('Matrix must be square')
return [[rational(x) for x in row] for row in matrix]
def positive_semidefinite(matrix):
"""Exact PSD decision; zero diagonal with nonzero row is indefinite."""
a=matrix_input(matrix)
size=len(a)
if any(a[i][j]!=a[j][i] for i in range(size) for j in range(i)):
return {'valid':False,'reason':'Matrix is not symmetric','dimension':size}
pivots=[]
zeros=0
while a:
pivot=a[0][0]
if pivot<0:
return {'valid':False,'reason':'Negative exact Schur pivot',
'pivot_index':len(pivots),'pivot':str(pivot),'dimension':size}
if pivot==0:
if any(a[0][j] for j in range(1,len(a))):
return {'valid':False,'reason':'Zero Schur pivot has a nonzero off-diagonal entry',
'pivot_index':len(pivots),'dimension':size}
zeros+=1
a=[row[1:] for row in a[1:]]
else:
a=[[a[i][j]-a[i][0]*a[0][j]/pivot
for j in range(1,len(a))] for i in range(1,len(a))]
pivots.append(str(pivot))
return {'valid':True,'dimension':size,'rank':size-zeros,
'zero_pivots':zeros,'schur_pivots':pivots}
def setup(p,n,rules):
integer(n,'n',positive=True)
if not isinstance(p,(list,tuple)) or not p:
raise ValueError('p must be a nonempty probability vector')
p=[rational(x) for x in p]
m=len(p)
if any(x<=0 for x in p) or sum(p)!=1:
raise ValueError('p must contain strictly positive exact probabilities summing to one')
rules={} if rules is None else rules
if not isinstance(rules,dict):
raise ValueError('rules must be a dictionary')
lower=rules.get('lower',[0]*m)
upper=rules.get('upper',[n]*m)
if not isinstance(lower,(list,tuple)) or not isinstance(upper,(list,tuple)) or len(lower)!=m or len(upper)!=m:
raise ValueError('Count bounds must match p')
lower=[integer(x,'lower bound') for x in lower]
upper=[integer(x,'upper bound') for x in upper]
rows=[]
linear=rules.get('linear',[])
if not isinstance(linear,(list,tuple)):
raise ValueError('linear rules must be an array')
for row in linear:
if not isinstance(row,dict) or not all(key in row for key in ('a','sense','rhs')):
raise ValueError('Invalid linear count rule')
if not isinstance(row['a'],(list,tuple)) or len(row['a'])!=m:
raise ValueError('Linear coefficient vector must match p')
if row['sense'] not in ('<=','>=','=='):
raise ValueError('Unknown linear rule comparison')
rows.append(([rational(a) for a in row['a']],row['sense'],rational(row['rhs'])))
return p,(lower,upper,rows)
def count_input(count,m,n):
if not isinstance(count,(list,tuple)) or len(count)!=m:
raise ValueError('Count vector must match p')
count=tuple(integer(x,'count') for x in count)
if any(x<0 for x in count) or sum(count)!=n:
raise ValueError('Count vector must be nonnegative and sum to n')
return count
def obeys(count,compiled_rules):
lower,upper,rows=compiled_rules
if any(c<lo or c>hi for c,lo,hi in zip(count,lower,upper)):
return False
for a,sense,rhs in rows:
value=sum(x*c for x,c in zip(a,count))
if ((sense=='<=' and value>rhs) or (sense=='>=' and value<rhs)
or (sense=='==' and value!=rhs)):
return False
return True
def compositions(n,m,prefix=()):
if m==1:
yield prefix+(n,)
else:
for first in range(n+1):
yield from compositions(n-first,m-1,prefix+(first,))
def quadratic(matrix,vector):
return sum(vector[i]*matrix[i][j]*vector[j]
for i in range(len(vector)) for j in range(len(vector)))
def verify_upper_certificate(p,n,counts,lottery_weights,C,rules=None):
p,compiled=setup(p,n,rules)
m=len(p)
C=rational(C)
if C<0:
return {'valid':False,'kind':'upper','reason':'Upper coefficient is negative'}
if not isinstance(counts,(list,tuple)) or not counts:
raise ValueError('At least one supported count vector is required')
if not isinstance(lottery_weights,(list,tuple)) or len(counts)!=len(lottery_weights):
raise ValueError('Lottery weights must match the supported counts')
lottery=[rational(w) for w in lottery_weights]
if any(w<0 for w in lottery) or sum(lottery)!=1:
return {'valid':False,'kind':'upper','reason':'Lottery weights must be nonnegative and sum exactly to one'}
legal=[]
for index,count in enumerate(counts):
count=count_input(count,m,n)
if not obeys(count,compiled):
return {'valid':False,'kind':'upper','reason':'Supported count violates a selection rule',
'count_index':index,'count':list(count)}
legal.append(count)
moment=[[F(0) for _ in p] for _ in p]
for count,weight in zip(legal,lottery):
delta=[F(c,n)-w for c,w in zip(count,p)]
for i in range(m):
for j in range(m):
moment[i][j]+=weight*delta[i]*delta[j]
residual=[[C*((p[i] if i==j else 0)-p[i]*p[j])-moment[i][j]
for j in range(m)] for i in range(m)]
psd=positive_semidefinite(residual)
result={'valid':psd['valid'],'kind':'upper','coefficient':str(C),
'supported_counts':len(legal),'matrix_check':psd,
'covariance_equality':all(x==0 for row in residual for x in row)}
if not psd['valid']:
result['reason']='Exact matrix domination fails'
return result
def verify_lower_certificate(p,n,G,tau,rules=None,admissible_counts=None,max_states=500000):
p,compiled=setup(p,n,rules)
m=len(p)
G=matrix_input(G)
if len(G)!=m:
raise ValueError('Gram dimension must match p')
tau=rational(tau)
integer(max_states,'max_states',positive=True)
states=comb(n+m-1,m-1)
if states>max_states:
raise ValueError(f'Complete enumeration requires {states} count states; limit is {max_states}')
psd=positive_semidefinite(G)
if not psd['valid']:
return {'valid':False,'kind':'lower','reason':'Gram matrix is not positive semidefinite','matrix_check':psd}
if any(sum(G[i][j]*p[j] for j in range(m)) for i in range(m)):
return {'valid':False,'kind':'lower','reason':'Gram matrix is not centered: Gp is nonzero'}
variance=sum(p[i]*G[i][i] for i in range(m))
if variance!=1:
return {'valid':False,'kind':'lower','reason':'Gram variance is not exactly one','variance':str(variance)}
supplied=None
if admissible_counts is not None:
if not isinstance(admissible_counts,(list,tuple)):
raise ValueError('admissible_counts must be a list or tuple')
supplied=set()
for index,count in enumerate(admissible_counts):
count=count_input(count,m,n)
if not obeys(count,compiled):
return {'valid':False,'kind':'lower','reason':'Supplied admissible count violates a rule',
'count_index':index,'count':list(count)}
if count in supplied:
return {'valid':False,'kind':'lower','reason':'Supplied admissible count set contains duplicates'}
supplied.add(count)
feasible=0
minimum=None
minimizer=None
for count in compositions(n,m):
if not obeys(count,compiled):
continue
feasible+=1
if supplied is not None and count not in supplied:
return {'valid':False,'kind':'lower','reason':'Supplied count set omits a legal selection',
'missing_count':list(count),'complete_set_verified':False}
value=quadratic(G,[F(c,n) for c in count])
if minimum is None or value<minimum:
minimum,minimizer=value,count
if not feasible:
return {'valid':False,'kind':'lower','reason':'Rules admit no selection; no finite minimax claim is certified',
'enumerated_states':states,'feasible_states':0}
result={'valid':minimum>=tau,'kind':'lower','coefficient':str(tau),
'minimum_error':str(minimum),'minimizer':list(minimizer),
'enumerated_states':states,'feasible_states':feasible,
'complete_set_verified':True,'gram_rank':psd['rank'],'matrix_check':psd}
if minimum<tau:
result['reason']='A legal count vector has error below the claimed lower coefficient'
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('input',type=Path)
parser.add_argument('--output',type=Path)
args=parser.parse_args()
data=json.loads(args.input.read_text(),parse_float=F)
kind=data.pop('kind',None)
if kind=='upper':
result=verify_upper_certificate(**data)
elif kind=='lower':
result=verify_lower_certificate(**data)
else:
raise ValueError("Certificate kind must be 'upper' or 'lower'")
rendered=json.dumps(result,indent=2)+'\n'
if args.output:
args.output.write_text(rendered)
else:
print(rendered,end='')
if __name__=='__main__':
main()