"""Verify a fixed-cap table on the complete continuous factor simplex.""" import argparse import json from fractions import Fraction as F from pathlib import Path from itertools import combinations_with_replacement import numpy as np from intervals import (SCALE,cell,conv,fraciv,imul,leq,parts,plus, posconv,ratarray,sub,test_product,total) from storage import IntervalStore def signedconv(signed,positive): lo,hi=signed;p,q=positive a=conv(np.maximum(lo,0),p,0)-conv(np.maximum(-lo,0),q,1) b=conv(np.maximum(hi,0),q,1)-conv(np.maximum(-hi,0),p,0) return a,b def interval_product(x,y,div): maxi=lambda arr:max(abs(int(arr.min())),abs(int(arr.max()))) wide=max(map(maxi,x))*max(map(maxi,y))>=2**61 p=[(a.astype(object) if wide else a)*b for a in x for b in y] lo=np.minimum.reduce(p)//div;hi=-((-np.maximum.reduce(p))//div) assert max(maxi(lo),maxi(hi))<2**59 return np.asarray(lo,dtype=np.int64),np.asarray(hi,dtype=np.int64) def add(x,y,k=1): # All summands are outward integer bounds in units of SCALE. assert max(max(abs(int(a.min())),abs(int(a.max()))) for a in x)<2**58 assert max(max(abs(int(a.min())),abs(int(a.max()))) for a in y)*abs(k)<2**58 return plus(x,y,k) def twice_box(step,gap): return tuple(np.r_[np.zeros(gap,dtype=np.int64),v[gap:]] for v in step) def meshkernels(cuts,cols,M,keep): vs=sorted({v for r in cols for v in parts(r)},key=lambda v:(sum(v),v)) kk=len(cuts)-1; zz=(0,)*kk K=IntervalStore();raw=IntervalStore() zero=np.zeros(M+1,dtype=np.int64);zzgrid=(zero,zero) for v in vs[1:]: i=next(i for i in range(kk) if v[i]); u=list(v);u[i]-=1;u=tuple(u) if u==zz: lo=np.zeros(M,dtype=np.int64);hi=lo.copy() ix=np.arange(cuts[i],cuts[i+1]) lo[ix]=SCALE*M//(ix+1);hi[ix]=-((-SCALE*M)//ix) K[v]=lo,hi else: e=tuple(int(o==i) for o in range(kk)) a,b=posconv(K[u],K[e]);raw[v]=a//v[i],-((-b)//v[i]) K[v]=cell(raw[v]) L=IntervalStore();L[zz]=zzgrid;Tend={zz:(0,0)};T=IntervalStore() for d in vs[1:]: if sum(d)==1 or total(d,cuts[1:])<=M//2: raw.pop(d,None);L[d]=zzgrid;Tend[d]=(0,0) if d in keep:T[d]=zzgrid continue fv=raw.pop(d) l=fv t=add(fv,fv,(-1)**sum(d)) if d in keep else None te=plus((int(fv[0][-1]),int(fv[1][-1])),(int(fv[0][-1]),int(fv[1][-1])),(-1)**sum(d)) for v in parts(d): if v==zz or v==d or total(v,cuts[:-1])>=M//2:continue w=sub(d,v) if total(w,cuts[1:])<=M//2:continue cv=posconv(K[v],twice_box(K[w],M//2)) l=add(l,cv,(-1)**sum(v)) te=plus(te,(int(cv[0][-1]),int(cv[1][-1])),(-2)**sum(v)) if t is not None:t=add(t,cv,(-2)**sum(v)) L[d]=l;Tend[d]=te if t is not None:T[d]=t return vs,K,L,Tend,T def rmq(lo,hi): low=[lo];high=[hi];width=1 while width*2<=len(lo): low.append(np.minimum(low[-1][:-width],low[-1][width:])) high.append(np.maximum(high[-1][:-width],high[-1][width:])) width*=2 def query(a,b): assert np.all(b>=a) and np.all(a>=0) and np.all(b 0 and M % 2 == 0 and M <= 2**21 co={tuple(map(int,s.split(','))):F(str(v)) for s,v in dat['coefficients'].items()} cuts=[F(z*M,dat['denominator']) for z in dat['cuts']] assert all(x.denominator==1 for x in cuts) cuts=list(map(int,cuts)) small=int(dat.get('small_bins',1)) assert 0 < small < len(cuts)-1 eta,alpha,half=cuts[0],cuts[small],M//2 assert cuts[-1]==half assert 0 < eta and all(x < y for x, y in zip(cuts, cuts[1:])) assert all(len(r) == len(cuts)-1 and min(r) >= 0 for r in co) zero=tuple(0 for _ in cuts[1:]) units=[tuple(int(i==j) for i in range(len(zero))) for j in range(small)] for r in co: # Physical observers survive every fragmentation of a giant. # This support excludes two observed factors of total below alpha. least=[lower for n,lower in zip(r[:small],cuts) for _ in range(min(n,2))] assert len(least)<2 or least[0]+least[1]>=alpha keep={sub(r,units[j]) for r in co for j in range(small) if r[j]} vs,K,L,te,T=meshkernels(cuts,co,M,keep) del K # R_j is the exponential kernel of j rough components, ignoring their # subdivision into coefficient bins in the scalar correction profile. assert dat['profile']=='23' prof={2:1,3:-1} jmax=max(prof) _,R0,L0,_,T0=meshkernels([alpha,half],[(jmax,)],M,{(j,) for j in prof}) R={j:R0[(j,)] for j in range(1,jmax+1)} LR={j:L0[(j,)] for j in range(jmax+1)} ix=np.arange(eta,alpha);res=M-ix-1 # Use the entire residual cell [1-(i+1)/M,1-i/M]. num=(np.zeros(len(ix),dtype=np.int64),np.zeros(len(ix),dtype=np.int64)) den=(np.zeros(len(ix),dtype=np.int64),np.zeros(len(ix),dtype=np.int64)) for side in range(small): active=slice(cuts[side]-eta,cuts[side+1]-eta) local_res=res[active] local=(num[0][active],num[1][active]) for r,c in co.items(): if not r[side]:continue a,b=cell(T[sub(r,units[side])]) local=add(local,ratarray(a[local_res],b[local_res],c,c),-1) num[0][active],num[1][active]=local for j,w in prof.items(): a,b=cell(T0[(j,)]) den=add(den,(a[res],b[res]),w) assert den[0].min()>0 # SCALE * (integer / integer) is below int64 by an explicit test. assert max(np.max(np.abs(v)) for v in num)<2**61//SCALE candlo=[a*SCALE//b for a in num for b in den] candhi=[-((-a*SCALE)//b) for a in num for b in den] h=(np.minimum.reduce(candlo),np.maximum.reduce(candhi)) hquery=rmq(*h) H0=(np.zeros(M,dtype=np.int64),np.zeros(M,dtype=np.int64)) assert max(abs(int(v)).bit_length() for side in h for v in (side.min(),side.max())) + M.bit_length() < 63 H0[0][ix]=np.minimum(h[0]*M//ix,h[0]*M//(ix+1)) H0[1][ix]=np.maximum(-((-h[1]*M)//ix),-((-h[1]*M)//(ix+1))) print('mesh',M,'free coefficients',len(co),'diagonal',den[0].min()/SCALE,den[1].max()/SCALE, 'h enclosure',h[0].min()/SCALE,h[1].max()/SCALE,flush=True) # One tagged kernel h(x)/x, and j untagged rough components. J={0:H0};JG={} for j in range(1,jmax+1): JG[j]=signedconv(H0,R[j]);J[j]=cell(JG[j]) zeroa=np.zeros(M+1,dtype=np.int64);zeroiv=(zeroa,zeroa) psi={0:zeroiv};th={0:(0,0)} for j in range(1,jmax+1): l=JG[j];t=add(JG[j],JG[j],(-1)**(j+1)) for v in range(1,j): # J_{j-v} may be signed, so take it as signed argument. u=signedconv(twice_box(J[j-v],half),R[v]) l=add(l,u,(-1)**v);t=add(t,u,(-2)**v) for v in range(j+1): if j-v<2:continue u=signedconv(J[v],twice_box(R[j-v],half)) l=add(l,u,-(-1)**v);t=add(t,u,-2*(-2)**v) psi[j]=l;th[j]=(int(t[0][-1]),int(t[1][-1])) maxb=M//(2*alpha) ordinary={};pinned={} for b in range(maxb+1): o=zeroiv;p=zeroiv for j,w in prof.items(): if j0 else -1) for r in rough_boxes if te[r][0]>0 or te[r][1]<0} else: g=max(rough_boxes,key=lambda r:min(abs(v) for v in te[r]) if te[r][0]*te[r][1]>0 else 0) direction={g:1} den=(F(0),F(0)) for r,d in direction.items(): den=plus(den,fraciv(te[r]),d) assert den[0]*den[1]>0 ts=imul((-tglobal[1],-tglobal[0]),(1/den[1],1/den[0])) iv={r:(v,v) for r,v in co.items()} for r,d in direction.items(): iv[r]=plus(iv[r],ts,d) prime=fraciv((ordinary[0][0][-1],ordinary[0][1][-1])) if direction_mode=='aligned': response=(F(0),F(0)) for r,c in co.items(): h0,h1=L[r] endpoint=fraciv((h0[-1],h1[-1])) prime=plus(prime,endpoint,c) if r in direction: response=plus(response,endpoint,direction[r]) prime=plus(prime,imul(ts,response)) descriptor=f'{len(direction)} aligned rough boxes' else: for r,c in iv.items(): prime=plus(prime,imul(c,fraciv((L[r][0][-1],L[r][1][-1])))) descriptor=g prime=(-prime[1],-prime[0]) print('empty parity correction',descriptor,tuple(map(float,ts)),'prime',tuple(map(float,prime)),flush=True) assert prime[1]<0 # Include all feasible free boxes, also those with zero stored coefficient. # Every surviving constant is in co. All additional free profiles have # exactly one tagged small part and two or three rough components. A # giant observation must occur in a stored or tagged free profile. free=set(co) for side in range(small): for count in prof: for rough in combinations_with_replacement(range(small,len(zero)),count): vec=list(units[side]) for j in rough:vec[j]+=1 free.add(tuple(vec)) allv=sorted({z for r in free for z in parts(r)},key=lambda z:(sum(z),z)) flo=F(0);fhi=F(0);worst=None;highest=None for r in allv: if not total(r,cuts[:-1])fhi:highest=(r, "free") flo=min(flo,a);fhi=max(fhi,b) print('free interval',float(flo),float(fhi),flush=True) obs=0 for z in allv: if z==zero or total(z,cuts[:-1])>=half:continue i0=max(half,M-total(z,cuts[1:]));i1=M-total(z,cuts[:-1]) if i1<=i0:continue ys=np.arange(i0,i1);ng=len(ys);v0=np.zeros(ng+1,dtype=np.int64) grid=(v0,v0);b=sum(z[small:]) if not any(z[:small]):grid=tuple(t[i0:i1+1] for t in ordinary[b]) response=(v0,v0) for r,cer in iv.items(): if leq(z,r): a,e=L[sub(r,z)] block=(a[i0:i1+1],e[i0:i1+1]) if direction_mode=='aligned' and r in direction: response=add(response,block,direction[r]) cer=(co[r],co[r]) grid=add(grid,ratarray(*block,*cer)) if direction_mode=='aligned' and (np.any(response[0]) or np.any(response[1])): grid=add(grid,ratarray(*response,*ts)) val=cell(grid) if sum(z[:small])==1: # A cell with only a boundary-touching x may be included by # either trace at eta or alpha. Enclosing extra traces is valid. side=z[:small].index(1) lower,upper=cuts[side:side+2] xl=np.maximum(lower,M-(ys+1)-total(z[small:],cuts[small+1:])) xh=np.minimum(upper,M-ys-total(z[small:],cuts[small:-1])) ok=xl<=xh if not np.any(ok):continue ys=ys[ok];val=tuple(t[ok] for t in val) xl=np.clip(xl[ok]-1,lower,upper-1)-eta xh=np.clip(xh[ok],lower,upper-1)-eta hp=hquery(xl,xh);p=cell(pinned[b]) boost=interval_product(hp,(p[0][ys],p[1][ys]),SCALE) val=add(val,boost) # Giant value is minus y times the bracket. low,high=interval_product((-val[1],-val[0]),(ys,ys+1),M) lb=F(int(low.min()),SCALE);ub=F(int(high.max()),SCALE) if lbfhi:highest=(z,float(ys[int(np.argmax(high))]/M)) flo=min(flo,lb);fhi=max(fhi,ub);obs+=len(ys) cap=1+fhi/(-prime[1]) print('observed cells',obs,'nonprime interval',float(flo),float(fhi),'worst lower',worst,'cap upper',float(cap),flush=True) print('highest upper location',highest,flush=True) print('exact positivity reserve',flo-prime[1],'exact cap reserve',target-cap,flush=True) print('cap bound as a rational',cap,flush=True) ok=flo>prime[1] and cap