"""Exact variance on all local mask pairs. All arithmetic in the certificate is integral."""
from fractions import Fraction as F
from math import isqrt
from itertools import combinations, product
from math import gcd,prod
import json


def kernel(n,h):
    return n*n-1-6*h*(n-h)


def auto(p,subset):
    return [sum((x+h)%p in subset for x in subset) for h in range(p)]


def subsets(p):
    for size in range(p+1):
        for points in combinations(range(p),size):
            yield set(points)


def variance_numerator(r,events):
    # Variance over ALL strict prefix thresholds 0,...,r-1, denominator r**4.
    count = total = squares = 0
    for x in range(r):
        discrepancy = r*count-x*len(events)
        total += discrepancy
        squares += discrepancy*discrepancy
        count += x in events
    return r*squares-total*total


def orbit(local):
    r = prod(local)
    base = [x for x in range(r) if all(x%p in a for p,a in local.items())]
    tables = {p:auto(p,a) for p,a in local.items()}
    ks = [kernel(r,h) for h in range(r)]
    values = {}
    for u in range(1,r):
        if gcd(u,r)>1:
            continue
        v = pow(u,-1,r)
        num = variance_numerator(r,{u*x%r for x in base})
        green = sum(k*prod(b[(v*h)%p] for p,b in tables.items()) for h,k in enumerate(ks))
        assert 12*num == green*r*r
        values[v] = green  # = 12*r*r*V
    return values


def check_projection(local,values):
    # Test the conditional expectation identity used in the global proof.
    r = prod(local)
    for p,a in local.items():
        s = r//p
        bp = auto(p,a)
        factors = [(q,F(len(t)*(len(t)-1),q-1)) for q,t in local.items() if q!=p]
        for v in range(1,p):
            conditional = [k for u,k in values.items() if u%p==v]
            rhs = F(0)
            for flags in product((False,True),repeat=len(factors)):
                d = prod(q for (q,_),on in zip(factors,flags) if on)
                coeff = prod(len(local[q])-c if on else c for (q,c),on in zip(factors,flags))
                fp = sum(kernel(p,y)*bp[d*v*y%p] for y in range(p))
                rhs += coeff * ((s*d)*fp + (d*d-1)*(s//d)*len(a)**2)
            assert F(sum(conditional),len(conditional)) == rhs


def census(p,q):
    rows = {k:dict(pairs=0,zero=0,dilations=0) for k in ("proper","full_nonempty","empty")}
    examples = {}
    for a,b in product(subsets(p),subsets(q)):
        local = {p:a,q:b}
        values = orbit(local)
        flat = all(len(set(auto(mod,subset)[1:]))==1 for mod,subset in local.items())
        zero = len(set(values.values()))==1
        kind = "empty" if not a or not b else "proper" if len(a)<p and len(b)<q else "full_nonempty"
        assert zero == (kind=="empty" or flat),(a,b)
        row = rows[kind]
        row["pairs"] += 1
        row["zero"] += int(zero)
        row["dilations"] += len(values)
        if kind=="proper" and not zero and "positive" not in examples:
            vs = [F(v,12*(p*q)**2) for v in values.values()]
            mean = sum(vs)/len(vs)
            spread = sum((v-mean)**2 for v in vs)/len(vs)
            examples["positive"] = dict(masks=[sorted(a),sorted(b)],minimum=str(min(vs)),
                                        maximum=str(max(vs)),dispersion=str(spread))
    return dict(primes=[p,q],counts=rows,examples=examples)


def local_determinant(p):
    # Columns are opposite nonzero differences; rows are multipliers modulo sign.
    reps = range(1,(p+1)//2)
    matrix = [[2*kernel(p,pow(v,-1,p)*y % p) for y in reps] for v in reps]
    previous = sign = 1
    for k in range(len(matrix)-1):
        pivot_row = next((i for i in range(k,len(matrix)) if matrix[i][k]),None)
        if pivot_row is None:
            return 0
        if pivot_row != k:
            matrix[k],matrix[pivot_row] = matrix[pivot_row],matrix[k]
            sign *= -1
        pivot = matrix[k][k]
        for i in range(k+1,len(matrix)):
            for j in range(k+1,len(matrix)):
                value = matrix[i][j]*pivot - matrix[i][k]*matrix[k][j]
                quotient,rem = divmod(value,previous)
                assert rem == 0
                matrix[i][j] = quotient
        previous = pivot
    return sign*matrix[-1][-1]


def experiment():
    projections = [{3:{0,1},5:{0,1},7:{0,1,3}},{2:{1},5:set(range(5)),7:{0,1,2}},
                   {3:set(),5:{0,1}},{5:{0,1},7:{0,1,2,3,4,5}},{11:{0,1,3},13:{0,1,5,6}}]
    for local in projections:
        check_projection(local,orbit(local))
    dets = {p:local_determinant(p) for p in range(3,48,2) if all(p%q for q in range(2,isqrt(p)+1))}
    assert all(dets.values())
    return dict(censuses=[census(3,5),census(5,7)],local_determinants=dets,projection_models=len(projections),
                projection_values=sum(sum(p-1 for p in x) for x in projections))


if __name__=="__main__":
    print(json.dumps(experiment(),indent=2))
