"""Exact conditional variation, local wheel overlap, and rare-core relations."""
from fractions import Fraction as F
from collections import Counter
from itertools import product,combinations
from math import prod
import json

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

def one(sites,p,anchors=()):
    banned={x%p for x in anchors}
    domains=[a for a in range(p) if a not in banned]
    wheel=Counter()
    for a in domains:wheel[tuple(x%p!=a for x in sites)]+=F(1,len(domains))
    independent={mask:prod(F(p-1,p) if x else F(1,p) for x in mask) for mask in product((False,True),repeat=len(sites))}
    occ={x%p for x in sites}-banned
    overlap=min(1-F(len(occ),len(domains)),F(p-1,p)**len(sites))
    for a in occ:
        m=sum(x%p==a for x in sites)
        overlap+=min(F(1,len(domains)),F(1,p)**m*F(p-1,p)**(len(sites)-m))
    assert 1-overlap==tv(wheel,independent)
    return wheel,independent

def history(sites):
    first=one(sites,3)
    joints=[Counter(),Counter()];terms=[];shared=0
    for mask in first[0].keys()|first[1].keys():
        indices=[i for i,b in enumerate(mask) if b]
        kernels=one(tuple(sites[i] for i in indices),5)
        a,b=(law.get(mask,0) for law in first);gap=tv(*kernels)
        for j in (0,1):
            for end,p in kernels[j].items():joints[j][mask,end]+=first[j].get(mask,0)*p
        if a and b:terms.append((gap,mask,a,b))
        shared+=min(a,b)*gap
    dp=tv(*first);hist=tv(*joints)
    assert dp<=hist<=dp+shared and sum(joints[0].values())==sum(joints[1].values())==1
    worst,mask,a,b=max(terms)
    return dict(first=str(dp),joint=str(hist),upper=str(dp+shared),weighted=str(shared),
                worst=str(worst),observation=mask,probabilities=[str(a),str(b)])

def rare(q,n):
    # n disjoint pairs versus n petals with one common centre. Each edge needs two live sites.
    star=q*(1-(1-q)**n);disjoint=1-(1-q*q)**n
    return dict(q=str(q),edges=n,mean=str(n*q*q),star_nonempty=str(star),disjoint_nonempty=str(disjoint),
                event_tv_lower=str(abs(disjoint-star)),star_to_empty=str(star))

if __name__=='__main__':
    checks=0
    for p in (3,5,7):
        for sites in combinations(range(8),3):
            for anchors in [(),(10,)]:
                one(sites,p,anchors);checks+=1
    print(json.dumps(dict(local_checks=checks,histories={str(s):history(s) for s in [(0,1,2),(0,3,5),(0,15,30)]},
                          rare=[rare(F(1,n),n*n) for n in (2,4,8)]),indent=2))
