"""Exact common mass under one/two deleted residue classes; product model checks."""
from collections import Counter
from fractions import Fraction as F
from itertools import combinations,product
from math import prod
import json

def kernels(xs,p,h,anchors):
    domain=set(range(p))-{a%p for a in anchors}
    subsets=list(combinations(sorted(domain),h))
    wheel=Counter()
    for blocked in subsets:wheel[tuple(x%p not in blocked for x in xs)]+=F(1,len(subsets))
    independent={m:prod(1-F(h,p) if v else F(h,p) for v in m) for m in product((False,True),repeat=len(xs))}
    return wheel,independent

def variation(a,b):
    return sum(abs(a.get(k,0)-b.get(k,0)) for k in a.keys()|b.keys())/2

def test(xs,ps,h,anchors):
    P,Q=kernels(xs,ps[0],h,anchors);joint=[{},{}];bound=variation(P,Q);loss=0;bad=0
    for a in P.keys()|Q.keys():
        p,q=P.get(a,0),Q.get(a,0)
        K,L=kernels([x for x,ok in zip(xs,a) if ok],ps[1],h,anchors)
        bound+=min(p,q)*variation(K,L)
        for b in K.keys()|L.keys():
            k,l=K.get(b,0),L.get(b,0)
            joint[0][a,b]=p*k;joint[1][a,b]=q*l
            slack=min(p*k,q*l)-min(p,q)*min(k,l)
            assert (slack>0)==(min(p,q,k,l)>0 and (p-q)*(k-l)<0)
            loss+=slack;bad+=int(slack>0)
    true=variation(*joint);assert bound-true==loss
    return dict(sites=xs,primes=ps,h=h,anchors=anchors,tv=str(true),upper=str(bound),slack=str(loss),discordant=bad)

def rare():
    # Groups have s petals with one common centre, disjoint between groups.
    q=F(1,8);entries=[]
    for size in (1,2,4,8,16,32,64):
        n=64//size
        empty=(1-q*(1-(1-q)**size))**n
        entries.append([size,n,str(1-empty)])
    return entries

def cluster():
    # Equal marginal q in both laws. The count of empty groups is compared
    # to the entire labelled sample, then to the vector of group counts.
    groups=[(2,F(1,5)),(3,F(1,7)),(2,F(1,4))]
    q=F(1,4);P={};Q={};group_laws=[]
    for n,e in groups:
        r=q/(1-e);pair=[]
        for shared in (True,False):
            law={}
            for bits in product((0,1),repeat=n):
                k=sum(bits)
                law[bits]=((1-e)*r**k*(1-r)**(n-k)+e*(k==0)) if shared else q**k*(1-q)**(n-k)
            pair.append(law)
        group_laws.append(pair)
    for paths in product(*(pair[0] for pair in group_laws)):
        for out,idx in [(P,0),(Q,1)]:out[paths]=prod(pair[idx][word] for pair,word in zip(group_laws,paths))
    def project(law,fn):
        v=Counter()
        for key,p in law.items():v[fn(key)]+=p
        return v
    by_count=lambda z:tuple(map(sum,z))
    empty=lambda z:sum(sum(w)==0 for w in z)
    whole=variation(P,Q);by=variation(project(P,by_count),project(Q,by_count));short=variation(project(P,empty),project(Q,empty))
    assert whole==by and short<whole
    return dict(labelled=str(whole),group_counts=str(by),empty_count=str(short))

if __name__=='__main__':
    v=[test(xs,p,h,a) for xs in [(0,3,5),(0,15,30),(1,4,8),(1,6,9)] for p in [(3,5),(5,3)]
       for h in (1,2) for a in [(),(11,)]]
    print(json.dumps(dict(histories=v,sharp=sum(r['slack']=='0' for r in v),petals=rare(),heterogeneous=cluster()),indent=2))
