"""Coarsened wheel histories, typed Poisson counts and survivor-weighted localisation."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from math import comb, exp, factorial, log, prod
import json
from localiser12 import tv, push

def poisson(base,other,limit=44):
    # Enumerate all compositions of each total. Its omitted mass has a geometric tail bound.
    def words(k,d):
        if d==1:yield (k,);return
        for x in range(k+1):
            for rest in words(k-x,d-1):yield (x,)+rest
    def pmf(mu,x):return exp(-sum(mu))*prod(r**n/factorial(n) for r,n in zip(mu,x))
    lo=min(log(b/a) for a,b in zip(base,other));hi=max(log(b/a) for a,b in zip(base,other))
    delta=sum(other)-sum(base);full=total=0.;cross=[]
    for k in range(limit+1):
        ds=[pmf(other,x)-pmf(base,x) for x in words(k,len(base))]
        full+=sum(abs(v) for v in ds)/2;total+=abs(sum(ds))/2
        if min(ds)<0<max(ds):cross.append(k)
        if min(abs(k*lo-delta),abs(k*hi-delta))>1e-12:
            assert (min(ds)<0<max(ds))==(k*lo<delta<k*hi)
    tail=sum(exp(-s)*s**(limit+1)/factorial(limit+1)/(1-s/(limit+2)) for s in (sum(base),sum(other)))
    return dict(base=base,other=other,vector_tv=round(full,12),total_tv=round(total,12),
                loss=round(full-total,12),mixed_through_cutoff=cross,cutoff=limit,tail_bound=tail)

def kernel(sites,p,independent,groups=None):
    groups=groups or [[i] for i in range(len(sites))]
    out=defaultdict(F)
    if independent:
        for bits in product((0,1),repeat=len(groups)):
            mask=sum(1<<i for grp,b in zip(groups,bits) if b for i in grp)
            out[mask]+=F((p-1)**sum(bits),p**len(bits))
    else:
        for a in range(p):out[sum(1<<i for i,x in enumerate(sites) if x%p!=a)]+=F(1,p)
    return out

def histories(sites,primes,cuts,independent):
    start=(1<<len(sites))-1;law={((len(sites),),start):F(1)}
    for j,p in enumerate(primes,1):
        local=kernel(sites,p,independent);future=defaultdict(F)
        for (history,old),mass in law.items():
            for mask,w in local.items():
                alive=old&mask
                h=history+(alive.bit_count(),) if j in cuts else history
                future[h,alive]+=mass*w
        law=future
    return push(law,lambda item:item[0])

def count_reader(n,primes,cuts,independent):
    law={((n,),n):F(1)}
    for j,p in enumerate(primes,1):
        future=defaultdict(F)
        for (h,s),mass in law.items():
            outcomes=([(i,F(comb(s,i)*(p-1)**i,p**s)) for i in range(s+1)] if independent
                      else [(s,1-F(s,p))]+([(s-1,F(s,p))] if s else []))
            for i,w in outcomes:
                if w:future[h+(i,) if j in cuts else h,i]+=mass*w
        law=future
    return push(law,lambda item:item[0])

def local_bound():
    sites=(1,11,13,33);old={15:F(1)};ref=old;total=F(0);raw=F(0)
    for p in (5,7,11):
        actual=kernel(sites,p,False);ideal=kernel(sites,p,True,[[0,1],[2,3]] if p==5 else None)
        raw+=tv(actual,ideal)
        def advance(a,k):
            d=defaultdict(F)
            for x,v in a.items():
                for y,w in k.items():d[x&y]+=v*w
            return d
        for x,v in old.items():total+=v*tv(push(actual,lambda y:y&x),push(ideal,lambda y:y&x))
        old=advance(old,actual);ref=advance(ref,ideal)
    assert tv(old,ref)<=total<raw
    return list(map(str,[tv(old,ref),total,raw]))

def expected_doubles(n, blocks, exact=False):
    # Histories are unnecessary for this observable: count labelled h-subsets
    # alive at block entry and lost within it, then invert factorial moments.
    prior=[1]*5
    totals=defaultdict(lambda:[0,0])
    for block in blocks:
        m=len(block)
        ps=[F(1,p) if exact else 1/p for p in block]
        q=0
        for x in ps:q+=(1-q)*x
        y=prior[1]*q
        independent=comb(n,2)*y**2*(1-y)**(n-2)
        exclusive=0
        for h in range(2,min(n,m)+1):
            alive=[0]*h+[1]
            for rate in ps:
                alive=[value*(1-j*rate)+(alive[j+1]*(j+1)*rate if j<h else 0)
                       for j,value in enumerate(alive)]
            exclusive+=(-1)**(h-2)*comb(h,2)*comb(n,h)*prior[h]*alive[0]
        totals[m][0]+=independent;totals[m][1]+=exclusive
        for h in range(1,len(prior)):prior[h]*=prod(1-h*x for x in ps)
    return dict(totals)

def pilots():
    from math import isqrt,sqrt
    sieve=bytearray([1])*200001
    for p in range(2,isqrt(len(sieve)-1)+1):
        if sieve[p]:
            start=p*p;sieve[start::p]=bytes(len(sieve[start::p]))
    out=[]
    for k in (1000,10000,100000):
        n=round(2*sqrt(k*log(k)));ps=[p for p in range(k+1,2*k+1) if sieve[p]]
        blocks=[]
        for j in range(0,len(ps)-5,6):blocks.extend([ps[j:j+2],ps[j+2:j+6]])
        result=expected_doubles(n,blocks)
        out.append(dict(k=k,sites=n,complete_packets=len(blocks)//2,omitted_wheels=len(ps)%6,
                        means_I_S={str(m):[round(x,9) for x in means] for m,means in result.items()}))
    return out

def run():
    primes=(5,7,11,13,17,19);cases=[]
    for n in (2,3,4):
        for cuts in [(2,6),(4,6),(1,2,3,4,5,6)]:
            a,b=[histories(list(range(n)),primes,cuts,ind) for ind in (False,True)]
            assert a==count_reader(n,primes,cuts,False) and b==count_reader(n,primes,cuts,True)
            def double(h):return tuple(int(x-y==2) for x,y in zip(h,h[1:]))
            da,db=push(a,double),push(b,double)
            if cuts==(2,6):
                means=expected_doubles(n,[primes[:2],primes[2:]],True)
                for j,m in enumerate((2,4)):
                    assert means[m]==[sum(x[j]*v for x,v in law.items()) for law in (db,da)]
            cases.append(dict(n=n,cuts=cuts,tv=list(map(str,[tv(a,b),tv(da,db),tv(push(da,sum),push(db,sum))]))))
    temporal=poisson([2/3,8/3],[1/3,2])
    assert 2 in temporal['mixed_through_cutoff'] and temporal['loss']>0
    # For ratios 2 and 4 the log-ratio on total k ranges in [k,2k] in log(2) units.
    # Delta = log(4), attained exactly at both adjacent integer boundaries.
    assert not any(k<2<2*k for k in range(4))
    return dict(mixed_mean_pilots=pilots(),boundary=dict(base_over_log4=["1/2","1/6"],ratios=[2,4],
                              thresholds_equal=[1,2],tv_preserved=True,fisher_sufficient=False),finite=cases,local_exact_weighted_raw=local_bound(),temporal=temporal,
         controls=[poisson(a,b) for a,b in [([1,.5],[2,1.5]),([1,1],[1.5,1.5]),([1,1],[1.1,1.11]),([1,2,1],[2,1,1])]])
if __name__=='__main__':print(json.dumps(run(),indent=2))
