"""Certify a continuum factor-box model using outward integer convolutions. Compile fixed_cap22_product.c first, as described in README.md. All endpoint, parity, normalization and mass bounds in the verdict are rational. """ from argparse import ArgumentParser from ctypes import CDLL, c_int, c_int64 from fractions import Fraction as F from itertools import product from math import prod from pathlib import Path import json import numpy as np HERE=Path(__file__).resolve().parent SCALE=10**8 LIB=CDLL(str(HERE/'fixed_cap22_product.so')) ARR=np.ctypeslib.ndpointer(dtype=np.int64,ndim=1,flags='C_CONTIGUOUS') LIB.cell_product.argtypes=[ARR,ARR,c_int,c_int64,c_int,ARR] LIB.cell_product.restype=c_int def conv(a,b,ceil): n=len(a) out=np.zeros(n+1,dtype=np.int64) code=LIB.cell_product(np.ascontiguousarray(a),np.ascontiguousarray(b),n,SCALE,ceil,out) if code:raise ArithmeticError(f'digit, allocation or range failure {code}') return out def test_product(): rng=np.random.default_rng(762) for n in (8,23,71,257): a=rng.integers(0,8*SCALE,n,dtype=np.int64) b=rng.integers(0,8*SCALE,n,dtype=np.int64) a[:n//5]=0;b[-n//5:]=0 for up in (0,1): v=conv(a,b,up) for i in range(1,n+1): z=sum(int(a[j])*int(b[i-1-j]) for j in range(i)) assert v[i]==(z+up*(n*SCALE-1))//(n*SCALE) print('direct integer convolution oracle passed',flush=True) def cell(h): lo,hi=h return np.minimum(lo[:-1],lo[1:]),np.maximum(hi[:-1],hi[1:]) def posconv(a,b): return conv(a[0],b[0],0),conv(a[1],b[1],1) def fraciv(v): return F(int(v[0]),SCALE),F(int(v[1]),SCALE) def plus(x,y,k=1): return (x[0]+k*y[0],x[1]+k*y[1]) if k>=0 else (x[0]+k*y[1],x[1]+k*y[0]) def imul(x,y): p=[a*b for a in x for b in y] return min(p),max(p) def sub(a,b): return tuple(x-y for x,y in zip(a,b)) def leq(a,b): return all(x<=y for x,y in zip(a,b)) def parts(r): return product(*(range(a+1) for a in r)) def total(r,cuts): return sum(a*b for a,b in zip(r,cuts)) def ratarray(vlo,vhi,x,y): # integer rectangle times an exact rational interval. All four products # use Python arbitrary-precision arithmetic if signed int64 is too small. def mul(a,b): num,den=b.numerator,b.denominator maxa=max(abs(int(a.min())),abs(int(a.max()))) if maxa*abs(num)>=2**61 or den>=2**61: arr=a.astype(object) else:arr=a return arr*num,den lows=[]; highs=[] for a in (vlo,vhi): for b in (x,y): num,den=mul(a,b) low=num//den; high=-((-num)//den) assert min(int(low.min()),int(high.min()))> -2**60 assert max(int(low.max()),int(high.max()))<2**60 lows.append(np.asarray(low,dtype=np.int64)) highs.append(np.asarray(high,dtype=np.int64)) return np.minimum.reduce(lows),np.maximum.reduce(highs) def verify(path,M): data=json.loads(Path(path).read_text()) c={tuple(map(int,k.split(','))):F(str(v)) for k,v in data['coefficients'].items()} cut=[F(z,data['denominator'])*M for z in data['cuts']] assert all(x.denominator==1 for x in cut) cuts=list(map(int,cut)); k=len(cuts)-1; half=M//2 assert cuts[-1]==half and 2*half==M zero=(0,)*k vs=sorted({v for r in c for v in parts(r)},key=lambda v:(sum(v),v)) idx=np.arange(M,dtype=np.int64) K={}; raw={} zeros=np.zeros(M+1,dtype=np.int64) for v in vs: if v==zero:continue i=next(i for i in range(k) if v[i]) u=list(v);u[i]-=1;u=tuple(u) if u==zero: lo=np.zeros(M,dtype=np.int64);hi=lo.copy() ix=idx[cuts[i]:cuts[i+1]] lo[ix]=SCALE*M//(ix+1);hi[ix]=-((-SCALE*M)//ix) K[v]=lo,hi else: unit=tuple(int(j==i) for j in range(k)) lo,hi=posconv(K[u],K[unit]) raw[v]=lo//v[i],-((-hi)//v[i]) K[v]=cell(raw[v]) L={zero:(zeros,zeros)}; T={} big=0 for d in vs: if d==zero:continue # Nontrivial density above 1/2 needs at least two unobserved factors. if sum(d)==1 or total(d,cuts[1:])<=half: L[d]=(zeros,zeros);T[d]=(0,0);continue lo,hi=raw[d]; lo=lo.copy();hi=hi.copy() t=plus((int(lo[-1]),int(hi[-1])),(int(lo[-1]),int(hi[-1])),(-1)**sum(d)) for v in parts(d): if v==zero or v==d or total(v,cuts[:-1])>=half:continue w=sub(d,v) if total(w,cuts[1:])<=half:continue b0,b1=K[w];b0=b0.copy();b1=b1.copy();b0[:half]=0;b1[:half]=0 val=posconv(K[v],(b0,b1)) lo,hi=plus((lo,hi),val,(-1)**sum(v)) t=plus(t,(int(val[0][-1]),int(val[1][-1])),(-2)**sum(v)) big+=1 L[d]=(lo,hi);T[d]=t # Correction direction is one free box. Its ordinary extension is used # with the same coefficient. Re-solving the one empty signed row is exact. t0=(F(0),F(0)) for r,x in c.items():t0=plus(t0,fraciv(T[r]),x) g=max(c,key=lambda r:min(abs(int(T[r][0])),abs(int(T[r][1]))) if not T[r][0]<=0<=T[r][1] else 0) den=fraciv(T[g]);assert den[0]*den[1]>0 ts=imul((-t0[1],-t0[0]),(1/den[1],1/den[0])) interval={r:(x,x) for r,x in c.items()} interval[g]=plus(interval[g],ts) f1=(F(0),F(0)) for r,iv in interval.items(): lo,hi=L[r] f1=plus(f1,imul(iv,fraciv((lo[-1],hi[-1]))),-1) print('mesh',M,'boxes',len(c),'nontrivial convolution pairs',big,'parity direction',g,flush=True) print('empty signed interval',tuple(map(float,t0)),'correction',tuple(map(float,ts)),'prime',tuple(map(float,f1)),flush=True) assert f1[1]<0 flo=min(F(0),*(iv[0] for iv in interval.values())) fhi=max(F(0),*(iv[1] for iv in interval.values())) obs=0 for z in vs: 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 # Measure-zero artificial bin boundaries can be assigned consistently # when lifting. We bound both traces on every open feasible cell. lo=np.zeros(i1-i0+1,dtype=np.int64);hi=lo.copy() for r,iv in interval.items(): if not leq(z,r):continue a,b=L[sub(r,z)] u,v=ratarray(a[i0:i1+1],b[i0:i1+1],*iv) assert max(abs(int(lo.min())),abs(int(hi.max())))<2**57 lo-=v;hi-=u low,high=cell((lo,hi)) ix=idx[i0:i1] lim=max(abs(int(low.min())),abs(int(high.max()))) assert M*lim<2**62 lb=int(np.minimum(ix*low,(ix+1)*low).min()) ub=int(np.maximum(ix*high,(ix+1)*high).max()) flo=min(flo,F(lb,M*SCALE));fhi=max(fhi,F(ub,M*SCALE));obs+=len(ix) C=F(str(data['target'])) cap=1+fhi/(-f1[1]) print('observed cells',obs,'nonprime envelope',float(flo),float(fhi),'cap upper',float(cap),flush=True) print('exact lower reserve',flo-f1[1],'exact cap reserve',C-cap,flush=True) ok=flo>f1[1] and cap