"""Eliminate the radius between the two observed vertex branches of the B-weight sweep."""
from fractions import Fraction as F
import json,sympy as S
from pathlib import Path
from verifier29 import rows_at
from verifier30 import rows,PROBES
from decouverte30 import discover
from projecteur29 import determinants,t
from poids31 import sample
s=S.Symbol('s')

def branch(z):
    r=sample(z);laws=r['certificate']['laws'];j=r['region'];d=discover(laws,20)
    px,py=PROBES[j];probe=F(px,4),F(py,4)
    symbolic=[laws[0],[1/(21+s),(9+s)/(21+s),7/(21+s),4/(21+s)],laws[2]]
    chosen=[];ids=[]
    source=next(c['source'] for c in d['candidates'] if c['coeff']==r['certificate']['coeff'])
    which=next(z[0] for z in source if isinstance(z,list) and 'vertex contact' in z[-1])
    for h in d['supports'][which]:
        found=next(((i,k) for i,law in enumerate(laws) for k,(p,_) in enumerate(rows([law],j)) if p==h),None)
        if found is None:continue
        i,k=found;values=list(rows_at([symbolic[i]],probe,t))[k];o,x,y,w=values
        scale=(21+s) if i==1 else 1
        chosen.append(tuple(S.cancel(scale*a) for a in (x-o,y-o,w-x-y+o,o)));ids.append([i,k])
    assert len(chosen)==3
    D,U,V,W=determinants(chosen);H=S.factor(D*W-U*V)
    target=S.Poly.from_list(r['certificate']['coeff'],t)
    for poly,_ in S.factor_list(H)[1]:
        if S.degree(poly,t)>0 and S.rem(poly.subs(s,S.Rational(z)),target.as_expr(),t)==0:
            return poly,ids
    raise ValueError(H)
def study():
    path=json.loads(Path(__file__).with_name('poids31.json').read_bytes())
    left,right=sorted(map(F,path['transitions'][0]['interval']))
    p,ids=branch(left);q,jds=branch(right);res=S.factor(S.resultant(p,q,t));roots=[]
    for h,_ in S.factor_list(res)[1]:
        f=S.Poly(h,s)
        if f.count_roots(S.Rational(left),S.Rational(right)):
            for (a,b),_ in f.intervals(eps=S.Rational(1,2**32)):
                if a>=left and b<=right:roots.append(dict(coeff=[int(v) for v in f.primitive()[1].all_coeffs()],interval=list(map(str,(a,b)))))
    return dict(bracket=[left,right],events=[ids,jds],branches=[str(p),str(q)],resultant=str(res),roots=roots)
if __name__=='__main__':print(json.dumps(study(),default=str))
