"""Exact finite histories and independent checks of the persistent-twin limit.
No third-party package is required. A mark records the width/time band of a block.
"""
from collections import defaultdict
from decimal import Decimal as D, localcontext
from fractions import Fraction as F
from itertools import combinations, product
from math import comb, isqrt, log, prod, sqrt
import json
from localiser12 import tv, push

WHEELS=(5,7,11,13,17,19)
def subsets(mask):
    part=mask
    while True:
        yield part
        if part==0:break
        part=(part-1)&mask

def partition(sites,p,anchor):
    excluded={x%p for x in anchor}
    groups=defaultdict(int)
    for i,x in enumerate(sites):
        if x%p not in excluded:groups[x%p]|=1<<i
    return list(groups.values()),p-len(excluded)

def one_wheel(sites,p,anchor,mechanism):
    groups,q=partition(sites,p,anchor)
    laws=defaultdict(F)
    if mechanism=='S':
        laws[0]+=1-F(len(groups),q)
        for g in groups:laws[g]+=F(1,q)
    else:
        for bits in product((0,1),repeat=len(groups)):
            mask=sum(g for g,hit in zip(groups,bits) if hit)
            laws[mask]+=F((q-1)**(len(groups)-sum(bits)),q**len(groups))
    return {mask:v for mask,v in laws.items() if v}

def block_by_draws(sites,primes,anchor,mechanism,initial):
    law={initial:F(1)}
    for p in primes:
        new=defaultdict(F)
        for mask,v in law.items():
            for hit,w in one_wheel(sites,p,anchor,mechanism).items():new[mask & ~hit]+=v*w
        law=new
    return law

def block_by_survival(sites,primes,anchor,mechanism,initial):
    # Joint survival probabilities multiply across wheels. Invert the subset lattice.
    moments={}
    for part in subsets(initial):
        prob=F(1)
        for p in primes:
            groups,q=partition(sites,p,anchor)
            n=sum(bool(g & part) for g in groups)
            prob*=1-F(n,q) if mechanism=='S' else (1-F(1,q))**n
        moments[part]=prob
    law={}
    for keep in subsets(initial):
        v=sum((-1)**extra.bit_count()*moments[extra|keep] for extra in subsets(initial^keep))
        assert v>=0
        if v:law[keep]=v
    assert sum(law.values())==1
    return law

def finite(sites,anchor,widths):
    all_sites=(1<<len(sites))-1;laws=[]
    for mech in ('S','J'):
        histories={(all_sites,):F(1)};offset=0
        for width in widths:
            primes=WHEELS[offset:offset+width];offset+=width
            kernels={}
            for mask in {h[-1] for h in histories}:
                k=block_by_draws(sites,primes,anchor,mech,mask)
                assert k==block_by_survival(sites,primes,anchor,mech,mask)
                kernels[mask]=k
            new=defaultdict(F)
            for h,v in histories.items():
                for keep,w in kernels[h[-1]].items():new[h+(keep,)]+=v*w
            histories=new
        counts=push(histories,lambda h:tuple(v.bit_count() for v in h))
        def marks(h):
            return tuple(sum(h[j]-h[j+1]==2 for j,t in enumerate(widths) if t==m) for m in sorted(set(widths)))
        doubles=push(counts,marks);laws.append([histories,counts,doubles,push(doubles,sum)])
    distances=[tv(a,b) for a,b in zip(*laws)]
    assert all(a>=b for a,b in zip(distances,distances[1:]))
    return list(map(str,distances))

def local_defect(sites,p,anchor):
    groups,q=partition(sites,p,anchor);n=len(sites)
    assert q>=n
    protected=n-sum(g.bit_count() for g in groups);sizes=[g.bit_count() for g in groups if g.bit_count()>1]
    b=F(1,q);singletons=[1<<j for j in range(n)]
    base_s={0:1-n*b,**{g:b for g in singletons}}
    base_j={x:b**x.bit_count()*(1-b)**(n-x.bit_count()) for x in range(1<<n)}
    predicted=[b*(protected+sum(sizes)),1-(1-b)**protected*prod(b**g+(1-b)**g for g in sizes)]
    assert predicted==[tv(one_wheel(sites,p,anchor,m),d) for m,d in [('S',base_s),('J',base_j)]]
    return list(map(str,predicted))

def mass_rates(gamma,bands,lam=D(2)):
    # Rows are ordered by time band and then width.
    result=[]
    for lo,hi in bands:
        a,b=D(lo),D(hi);K=1/a-1/b;H=(b/a).ln()
        for m in (2,4):
            share=D(m)/6
            genuine=share*lam**2*K/2;twin=share*D(gamma)*H
            result.append((genuine*(m-1)+twin,genuine*m+twin))
    return result

def variation(rows,limit=32):
    # Truncate each total degree, bounding both omitted Poisson tails.
    totals=[sum(r[j] for r in rows) for j in (0,1)]
    def weights(mu):
        a=[(-mu).exp()]
        for k in range(1,limit+2):a.append(a[-1]*mu/k)
        return a
    tables=[[weights(mu) for mu in r] for r in rows]
    def folded(i,left,a,b):
        if i==len(tables):return abs(a-b)
        w1,w2=tables[i]
        return sum(folded(i+1,left-h,a*w1[h],b*w2[h]) for h in range(left+1))
    value=folded(0,limit,D(1),D(1))/2
    tail=sum(weights(mu)[-1]/(1-mu/(limit+2)) for mu in totals)/2
    return [str(value.quantize(D('1e-13'))),float(tail)]

def threshold_control():
    # Likelihood S/J bounds on fibres. The equal-prior example of AT.V9
    # preserves TV, but changing the threshold to sqrt(2) splits the k=2 fibre.
    # Here log(L) in units log(2) ranges from k-2 through 2k-2.
    spans={str(k):[k-2,2*k-2] for k in (1,2,3)}
    assert not any(lo<0<hi for lo,hi in spans.values())
    assert spans["2"][0]<F(1,2)<spans["2"][1]
    return spans

def class_losses(nc,b,prior):
    m=len(b)
    moments={}
    for h in range(1,m+1):
        alive=[0]*h+[1]
        for x in b:
            alive=[v*(1-z*x)+(alive[z+1]*(z+1)*x if z<h else 0) for z,v in enumerate(alive)]
        moments[h]=comb(nc,h)*prior[h]*alive[0]
    h1,h2=[sum((-1)**(h-t)*comb(h,t)*moments[h] for h in range(t,m+1)) for t in (1,2)]
    y=prior[1]*(1-prod(1-x for x in b))
    j1=nc*y*(1-y)**(nc-1);j2=comb(nc,2)*y*y*(1-y)**(nc-2)
    return (h1,h2),(j1,j2)

def mean_control():
    span=prod(WHEELS);sites=(0,1,2,span);nc=3;ns=2;nt=1
    prior=[F(1)]*5;law={m:{15:F(1)} for m in ('S','J')}
    out=[]
    for block in [WHEELS[:2],WHEELS[2:]]:
        b=[F(1,p) for p in block]
        for mech,(one,two) in zip(('S','J'),class_losses(nc,b,prior)):
            new=defaultdict(F);ref=F(0)
            for initial,v in law[mech].items():
                for dest,mass in block_by_survival(sites,block,(),mech,initial).items():
                    new[dest]+=v*mass
                    if initial.bit_count()-dest.bit_count()==2:ref+=v*mass
            predicted=one*F(nt,nc)+two*F(comb(ns,2),comb(nc,2))
            assert ref==predicted
            out.append(str(ref));law[mech]=new
        for h in range(1,5):prior[h]*=prod(1-h*x for x in b)
    return out

def finite_means(k,lam,gamma):
    """Use finite factorial moments of the number of classes killed in a block.
    Conditional on that number, class identities are uniformly distributed."""
    bound=2*k;mark=bytearray([1])*(bound+1)
    for p in range(2,isqrt(bound)+1):
        if mark[p]:mark[p*p::p]=bytes(len(mark[p*p::p]))
    total=round(lam*sqrt(k*log(k)));nt=round(gamma*log(k));ns=total-2*nt;nc=ns+nt
    assert ns>=4
    prior=[1.0]*5;means=[]
    for lo,hi in ((k,3*k//2),(3*k//2,2*k)):
        ps=[p for p in range(lo+1,hi+1) if mark[p]];res={m:[0.,0.] for m in (2,4)}
        for j in range(0,len(ps),6):
            for m,start in ((2,j),(4,j+2)):
                block=ps[start:min(start+m,j+6)]
                if not block:continue
                b=[1/p for p in block]
                if j+6<=len(ps):
                    (h1,h2),(j1,j2)=class_losses(nc,b,prior)
                    for i,(one,two) in enumerate(((h1,h2),(j1,j2))):
                        res[m][i]+=one*nt/nc+two*comb(ns,2)/comb(nc,2)
                for h in range(1,5):prior[h]*=prod(1-h*x for x in b)
        means.extend([[round(x,9) for x in res[m]] for m in (2,4)])
    return dict(k=k,total_sites=total,singletons=ns,twins=nt,mean_S_J=means)

def run():
    span=prod(WHEELS);profiles={'distinct':(0,1,2,3),'isolated':(0,1,2,5),'persistent':(0,1,2,span)}
    cases=[];defects=[];classes={}
    for name,sites in profiles.items():
        for anchor in ((),(4,),(5,)):
            classes[name+str(anchor)]=[dict(p=p,q=partition(sites,p,anchor)[1],
                active_masks=partition(sites,p,anchor)[0]) for p in WHEELS]
            for p in WHEELS:
                defects.append(dict(profile=name,p=p,anchor=anchor,S_J=local_defect(sites,p,anchor)))
            for widths in ((1,5),(3,3),(1,2),(2,3)):
                cases.append(dict(profile=name,anchor=anchor,widths=widths,tv=finite(sites,anchor,widths)))
    bands=[('1','1.5'),('1.5','2')];whole=[('1','2')]
    with localcontext() as ctx:
        ctx.prec=48
        gamma_shift=1/D(2).ln()
        pooled=mass_rates(0,whole);other=mass_rates(gamma_shift,whole)
        assert max(abs(s-j) for (s,_),(_,j) in zip(other,pooled))<D('1e-44')
        split0=mass_rates(0,bands);split_adjusted=mass_rates(gamma_shift,bands)
        shifted=[(a[0],b[1]) for a,b in zip(split_adjusted,split0)]
        assert shifted[0][0]<shifted[0][1] and shifted[2][0]>shifted[2][1]
        stats={}
        for name,rows in [('no_twins',pooled),('known_twins',mass_rates(1,whole)),('split_known_twins',mass_rates(1,bands)),('matched_split',shifted)]:
            stats[name]=dict(rates_S_J=[[round(float(x),10) for x in row] for row in rows],tv=variation(rows))
    return dict(moment_control=mean_control(),exact_cases=cases,classes=classes,local_defects=defects,threshold_log2=threshold_control(),
                limiting=stats,matched_pooled_tv=0,compensating_twin_density=float(gamma_shift),
                finite_means=[finite_means(k,2,1) for k in (1000,10000,100000)])
if __name__=='__main__':print(json.dumps(run(),indent=2))
