"""Dispersion of prefix variance across invertible dilations of a CRT set."""
from fractions import Fraction
from itertools import combinations
from math import gcd, prod
import json


def moments(local):
    r = prod(local)
    kernel = [r*r-1-6*h*(r-h) for h in range(r)]
    first = Fraction(0)
    second = Fraction(0)
    tables = {}
    for p, values in local.items():
        pairs = [sum((x+h)%p in values for x in values) for h in range(p)]
        orbit = [[pairs[u*h%p] for u in range(1,p)] for h in range(p)]
        tables[p] = [[Fraction(sum(a*b for a,b in zip(x,y)),p-1) for y in orbit] for x in orbit]
    for h in range(r):
        one = prod(Fraction(len(a)*(len(a)-1),p-1) if h%p else len(a) for p,a in local.items())
        first += kernel[h]*one
        for j in range(r):
            joint = prod(tables[p][h%p][j%p] for p in local)
            second += kernel[h]*kernel[j]*joint
    scale = 12*r*r
    mean = first/scale
    return mean,second/scale**2-mean*mean


def direct(local):
    r = prod(local)
    a = [x for x in range(r) if all(x%p in s for p,s in local.items())]
    values = []
    for u in range(1,r):
        if gcd(u,r)!=1:
            continue
        events = {x*u%r for x in a}
        prefix = 0
        discrepancy = []
        for x in range(r):
            discrepancy.append(Fraction(prefix*r-x*len(a),r))
            prefix += x in events
        mean = sum(discrepancy)/r
        values.append(sum((v-mean)**2 for v in discrepancy)/r)
    mean = sum(values)/len(values)
    return mean,sum((v-mean)**2 for v in values)/len(values)


if __name__=="__main__":
    checked = 0
    for k in range(8):
        for subset in combinations(range(7),k):
            local = {7:set(subset)}
            assert moments(local)==direct(local)
            checked += 1
    for small in ({0},{1,2},set()):
        local = {3:small,5:{0,2},2:{1}}
        assert moments(local)==direct(local)
        checked += 1
    examples = {str(s):list(map(str,moments({7:set(s)}))) for s in ((0,1,2),(0,1,3))}
    print(json.dumps({"exact_checks":checked,"mean_and_dispersion":examples},indent=2))
