#!/usr/bin/env python3
"""combo_match.py - whole-picture matching. Library entry = an indexed SUBSET (size<=R) of base spectra (from discoveries.jsonl ladders);
its composite spectrum = equal-weight sum + floor.  Match = exhaustive exact-gamma-likelihood score of the FULL composite vs the measured
spectrum (one free gain).  bits = log2(#combinations)+6.  Controls: same procedure with single-pole Lorentz base / random smooth base.
Real-time: neighbour-move tracker (swap/add/drop one member) vs per-frame exhaustive vs direct knots."""
import json, math, itertools, numpy as np
from fractions import Fraction
rng=np.random.default_rng(21); G=48; fn=np.geomspace(.004,.45,G); M=32; R=5; FLOOR=.02
LAD=[]
for line in open('discoveries.jsonl'):
    r=json.loads(line); rho,gam=Fraction(r['rho']),Fraction(r['gamma'])
    if rho>1 and gam>1 and r['n']>=3: tf=r['transfer_function']; LAD.append(([float(Fraction(s)) for s in tf['numerator']],[float(Fraction(s)) for s in tf['denominator']]))
def lad_pow(rec,fhi):
    sc=2*np.pi*fhi/0.15; x=2j*np.pi*fn/sc; p=lambda c:sum(a*x**i for i,a in enumerate(c))
    with np.errstate(all='ignore'): return np.maximum(np.abs(p(rec[0])/p(rec[1]))**2,1e-30)
def norm(S): return S/S.mean(0 if S.ndim==2 and S.shape[0]==G else -1,keepdims=True) if False else S/S.mean(axis=-1,keepdims=True)
cand_lad=[]
for rec in LAD:
    for fh in np.geomspace(.01,.4,12): s=lad_pow(rec,fh); cand_lad+=[s,1/s]
fc=np.geomspace(.003,.5,1200); lor=1/(1+(fn[None]/fc[:,None])**2); cand_lor=np.vstack([lor,1-lor+1e-3])
def rs():
    k=np.sort(rng.uniform(0,1,5)); v=rng.normal(0,10,5); x=(np.log(fn)-np.log(fn[0]))/(np.log(fn[-1])-np.log(fn[0])); return 10**(np.interp(x,np.r_[0,k,1],np.r_[v[0],v,v[-1]])/10)
cand_rnd=np.array([rs() for _ in range(2400)])
def farthest(C,m):
    L=np.log(norm(np.array(C))); L=L-L.mean(1,keepdims=True); ch=[0]; d=np.sum((L-L[0])**2,1)
    for _ in range(m-1): i=int(np.argmax(d)); ch.append(i); d=np.minimum(d,np.sum((L-L[i])**2,1))
    return norm(np.array(C)[ch])
BASES={'exact ladders (discoveries.jsonl)':farthest(cand_lad,M),'single-pole Lorentz':farthest(cand_lor,M),'random smooth':farthest(cand_rnd,M)}
COMBOS=[np.array(list(itertools.combinations(range(M),r)),dtype=np.int32) for r in range(1,R+1)]
NC=sum(len(c) for c in COMBOS); BITS=math.log2(NC)+6
print(f"base spectra M={M} per dictionary; combinations of size<=({R}): {NC:,} -> {math.log2(NC):.1f} bits + 6 gain = {BITS:.1f} bits per library match\n")
def best_combo(B,y,chunk=20000,topk=1):
    best=(1e30,None,None)
    for ci,idx in enumerate(COMBOS):
        for s0 in range(0,len(idx),chunk):
            ii=idx[s0:s0+chunk]; S=B[ii].sum(1)+FLOOR; g=np.mean(y[None]/S,1); score=np.sum(np.log(S),1)+G*np.log(g)
            j=int(np.argmin(score))
            if score[j]<best[0]: best=(score[j],ii[j],g[j]*S[j])
    return best[1],best[2]
def rms_db(m,t): return float(np.sqrt(np.mean((10*np.log10(np.maximum(m,1e-30)/t))**2)))
def knots(y,bits):
    q=max(2,int(bits)//4); idx=np.linspace(0,G-1,q).round().astype(int); L=10*np.log10(y); st=3.0; Lq=np.round(np.clip(L[idx],L.max()-48,L.max())/st)*st
    return 10**(np.interp(np.arange(G),idx,Lq)/10)
def target(kind):
    n=40 if kind.startswith('1/f') else 3; f_c=np.exp(rng.uniform(np.log(.004),np.log(.4),n)); wts=np.exp(rng.normal(0,.6 if n==40 else 1.2,n))
    if n==40: wts=wts*f_c
    y=sum(w_/(1+(fn/c)**2) for w_,c in zip(wts,f_c)); y=y/y.mean()+.02
    if 'interf' in kind:
        for c in rng.uniform(.01,.3,2): y=y+0.6*np.exp(-0.5*((np.log10(fn)-np.log10(c))/.045)**2)*y.mean()
    return y
print("[1] STATIC: whole-picture match.  error = RMS dB of matched composite vs the TRUE spectrum;  'meas' rows: match is made to a gamma(m=8)-noisy measurement\n")
N=8; res={}
for kind in ('1/f (40 relaxations)','3 relaxations','3 relaxations + 2 narrow interferers'):
    print(f" target: {kind}")
    print(f"   {'matched to':16}"+"".join(f"{k[:28]:>31}" for k in BASES)+f"{'direct knots @%.0f bits'%BITS:>26}")
    for mode in ('truth','noisy meas'):
        errs={k:[] for k in BASES}; kb=[]; raw=[]
        for _ in range(N):
            y=target(kind); meas=y if mode=='truth' else y*rng.gamma(8,1/8,G)
            for k,B in BASES.items(): _,mod=best_combo(B,meas); errs[k].append(rms_db(mod,y))
            kb.append(rms_db(knots(meas,BITS),y)); raw.append(rms_db(meas,y))
        print(f"   {mode:16}"+"".join(f"{np.mean(errs[k]):31.2f}" for k in BASES)+f"{np.mean(kb):26.2f}"+(f"   (raw meas err {np.mean(raw):.2f})" if mode!='truth' else ""),flush=True)
    print()
# ------------------------------------------------ real-time
print("[2] REAL-TIME: 150 frames, 3 drifting relaxations, noisy per-frame measurement (gamma m=8, ~1.5 dB).  tracker = neighbour moves (swap/add/drop one member)\n")
T=150
def truth(fc_,w_): y=sum(wi/(1+(fn/np.exp(c))**2) for wi,c in zip(w_,fc_)); return y/y.mean()+.02
def score_of(B,mem,y):
    S=B[list(mem)].sum(0)+FLOOR; g=np.mean(y/S); return np.sum(np.log(S))+G*np.log(g),g*S
def neighbours(mem):
    mem=tuple(mem); out=[]
    for a in mem:
        if len(mem)>1: out.append(tuple(sorted(set(mem)-{a})))
        for b in range(M):
            if b not in mem: out.append(tuple(sorted((set(mem)-{a})|{b})))
    if len(mem)<R: out+=[tuple(sorted(set(mem)|{b})) for b in range(M) if b not in mem]
    return out
print(f"   {'method':38}{'meas err':>10}{'model err vs truth':>20}{'bits/frame':>12}{'changes':>9}")
for name,B in BASES.items():
    r2=np.random.default_rng(3); fcs=np.log(np.array([.01,.05,.2])); w_=np.array([1.,.6,.3]); mem=None; bits=0; eT=[]; eM=[]; ch=0; gq=None
    for t in range(T):
        fcs=fcs+r2.normal(0,.03,3); w_=np.abs(w_*np.exp(r2.normal(0,.04,3))); y=truth(fcs,w_); meas=y*r2.gamma(8,1/8,G)
        if mem is None: ids,_=best_combo(B,meas); mem=tuple(sorted(ids)); bits+=math.log2(NC); ch+=1
        sc,mod=score_of(B,mem,meas); cands=neighbours(mem); best=(sc,mem)
        for c in cands:
            s_,_m=score_of(B,c,meas)
            if s_<best[0]-1.5: best=(s_,c)
        if best[1]!=mem: mem=best[1]; bits+=math.log2(len(cands)+1); ch+=1; sc,mod=score_of(B,mem,meas)
        else: bits+=1
        gdb=round(10*np.log10(np.mean(meas/(B[list(mem)].sum(0)+FLOOR)))/1.5)
        if gq is None or gdb!=gq: bits+=3; gq=gdb
        eT.append(rms_db(mod,y)); eM.append(rms_db(meas,y))
    print(f"   {('tracker, '+name)[:38]:38}{np.mean(eM):10.2f}{np.mean(eT):20.2f}{bits/T:12.1f}{ch:9d}",flush=True)
