"""Compare proposals after an equal number of fresh dyadic decisions, in separate processes."""
from fractions import Fraction as F
from pathlib import Path
from time import perf_counter
import json,sys,subprocess
import decouverte30 as geo
from relations31 import guesses

def trial(laws,bits,method):
    laws=[list(map(F,r)) for r in laws];cache={};stats={'decision':0.,'proposal':0.,'verification':0.}
    decision=geo.decide
    def memo(laws,e):
        if e not in cache:
            tic=perf_counter();cache[e]=decision(laws,e);stats['decision']+=perf_counter()-tic
        return cache[e]
    a,b=F(0),F(1);memo(laws,a);memo(laws,b)
    for _ in range(bits):
        m=(a+b)/2
        if memo(laws,m)['feasible']:b=m
        else:a=m
    start=perf_counter()
    if method=='planes':
        geo.decide=memo
        try:
            d=geo.discover(laws,bits);assert d['bracket']==[a,b]
        finally:geo.decide=decision
        pool=[z['coeff'] for z in sorted(d['candidates'],key=lambda z:-len(z['coeff']))]
    else:pool=list(guesses(a,b,bits,4 if len(laws)==2 else 5))
    stats['proposal']=perf_counter()-start;start=perf_counter();winner=None
    for co in pool:
        if geo.certify('budget',dict(laws=laws,bracket=[a,b]),co):
            winner=co;break
    stats['verification']=perf_counter()-start;assert len(cache)==bits+2
    return dict(method=method,bits=bits,distinct=len(cache),bracket=[a,b],proposals=pool,found=winner,times=stats)
def study():
    rows=json.loads(Path(__file__).with_name('relations31.json').read_bytes());out=[]
    for i in (6,18):
        for bits in (36,64):
            for m in ('planes','pslq'):
                z=json.loads(subprocess.check_output([sys.executable,'-B',__file__,str(i),str(bits),m]));out.append(dict(name=rows[i]['name'],**z))
    return out
if __name__=='__main__':
    if len(sys.argv)>1:
        i,b,m=sys.argv[1:];rows=json.loads(Path(__file__).with_name('relations31.json').read_bytes());result=trial(rows[int(i)]['laws'],int(b),m)
    else:result=study()
    print(json.dumps(result,default=str))
