"""python3 -B blind_marks_136.py results.json. Requires NumPy, SciPy, Sessions 108/114 source/layout helpers."""
import json,sys
from pathlib import Path
from collections import defaultdict
import numpy as np
from scipy.special import expit
from scipy.optimize import minimize
from next_rune_114 import layout,TRAIN,TEST
from known_marks_114 import layout as solved_layout
from fixed_stream_133_135 import solved
def counts(blocks):
    A=np.zeros(841,int);J=A.copy()
    for _,_,j,x in blocks:
        pair=x[:-1]*29+x[1:];A+=np.bincount(pair,minlength=841);J+=np.bincount(pair[j==1],minlength=841)
    return A.reshape(29,29),J.reshape(29,29)
def fit(blocks):
    a,j=counts(blocks);p=float(j.sum()/a.sum());b=np.log(p/(1-p));I=np.eye(29)
    lam=np.r_[0.,np.ones(59)*5,np.ones(841)*20]
    def linear(w):return w[0]+w[1:30,None]+w[None,30:59]+w[59]*I+w[60:].reshape(29,29)
    def fg(w):
        h=linear(w);g=a*expit(h)-j
        return np.sum(a*np.logaddexp(0,h)-j*h)+.5*np.dot(lam*w,w),np.r_[g.sum(),g.sum(1),g.sum(0),np.trace(g),g.ravel()]+lam*w
    opt=minimize(fg,np.r_[b,np.zeros(900)],jac=True,method='L-BFGS-B',options=dict(ftol=1e-13,gtol=1e-7,maxiter=600))
    assert opt.success and max(abs(opt.jac))<.01
    return b,linear(opt.x)
def quartile(scores,y):
    # Give all tied edges at the cutoff the same fractional weight.
    n=len(y);k=int(np.ceil(n/4));v=np.partition(scores,-k)[-k];w=scores>v;t=scores==v
    return float((sum(y[w])+(k-sum(w))*np.mean(y[t]))/k)
def score(train,test,rng=None,draws=0):
    b,t=fit(train);parts=defaultdict(lambda:[0,0,0.]);sim=np.zeros(draws);ss=[];yy=[]
    for g,pg,j,x in test:
        h=t[x[:-1],x[1:]];z=(h-b)/np.log(2);base=float((np.logaddexp(0,b)-np.logaddexp(0,h)).sum()/np.log(2));gain=base+np.dot(j,z)
        parts[g][0]+=len(j);parts[g][1]+=int(sum(j));parts[g][2]+=gain;ss.extend(h);yy.extend(j)
        if draws:
            # Correlate all cyclic label rotations with the frozen log-odds for this page block.
            corr=np.fft.irfft(np.fft.rfft(z)*np.conj(np.fft.rfft(j)),n=len(j))
            assert abs(corr[0]-np.dot(j,z))<1e-8 and abs(corr[1%len(j)]-np.dot(np.roll(j,1),z))<1e-8
            sim+=base+corr[rng.integers(len(j),size=draws)]
    gain=sum(v[2] for v in parts.values());n=len(yy);ngood=sum(v[2]>0 for v in parts.values())
    out=dict(bits=gain,edges=n,joins=int(sum(yy)),train_rate=float(expit(b)),positive=ngood,by_group=dict(parts),top_precision=quartile(np.array(ss),np.array(yy)),prevalence=np.mean(yy),per_edge=gain/n)
    if draws:
        ge=int(sum(sim>=gain-1e-8));p=(ge+1)/(draws+1);out.update(ge=ge,p=p,null_range=np.quantile(sim,[.025,.975],method='inverted_cdf').tolist(),passed=bool(gain>0 and ngood>=3 and p<=.05))
    return out
def split(L):
    tr=[b for b in L if b[0] in TRAIN];p={b[1] for b in tr};te=[b for b in L if b[0] in TEST and b[1] not in p];return tr,te,sorted(p&{b[1] for b in L if b[0] in TEST})
def synthetic(L,rng,f):
    out=[]
    for g,pg,j,x in L:
        n=len(x);inc=rng.integers(29,size=n);inc[1:][(j==1)&(rng.random(n-1)<f)]=7
        out.append((g,pg,j,np.cumsum(inc)%29))
    return out
def known(L):
    f={}
    for s in sorted({v[0] for v in L}):
        out=score([v for v in L if v[0]!=s],[v for v in L if v[0]==s]);f[s]=[out[k] for k in ['edges','joins','bits','top_precision','prevalence']]
    bits=sum(v[2] for v in f.values());positive=sum(v[2]>0 for v in f.values())
    return dict(bits=bits,positive=positive,by_group=f,edges=sum(v[0] for v in f.values()),joins=sum(v[1] for v in f.values()),calibration=bool(bits>0 and positive>=5))
def run():
    L=layout();tr,te,overlap=split(L);res=score(tr,te,np.random.default_rng(3301136),9999)
    res.update(train_pages=len({r[1] for r in tr}),test_pages=len({r[1] for r in te}),overlap_pages=overlap)
    solved();P,C=solved_layout();ps=known(P);cs=known(C)
    checks={}
    for k,f in [('planted',.4),('null',0.)]:
        arr=[]
        for i in range(16):
            a,b,_=split(synthetic(L,np.random.default_rng(136700+i+(0 if f else 100)),f));v=score(a,b,np.random.default_rng(136900+i),999);arr.append([v['bits'],v['p'],v['positive'],v['passed']])
        checks[k]=arr
    pa=sum(v[-1] for v in checks['planted']);nu=sum(v[-1] for v in checks['null'])
    return dict(primary=res,known_plain=ps,known_print=cs,controls=checks,planted_pass=pa,null_pass=nu,calibrated=pa>=12 and nu<=2 and ps['calibration'],final_pass=bool(pa>=12 and nu<=2 and ps['calibration'] and res['passed']))
if __name__=='__main__':Path(sys.argv[1]).write_text(json.dumps(run(),separators=(',',':'),default=lambda x:x.item())+'\n')
