"""Second-order rigorous enclosures of piecewise functions on the mesh 1/M. Written independently of certificates/intervals.py and convolution.c. Method differs from theirs: they enclose every kernel by STEP functions (cell min/max, first order in 1/M); here every nonnegative kernel is enclosed on each cell [n/M,(n+1)/M) by a LOWER and an UPPER LINEAR function of the local coordinate tau in [0,1]. The convolution of two such piecewise-linear enclosures is computed EXACTLY (as a piecewise cubic) from four exact integer polynomial products (python-flint fmpz_poly) of directed-rounded integer images, and then re-enclosed by linear functions using the exact cubic remainder bounds tau^2 - tau in [-1/4, 0], tau^3 - tau in [-0.385, 0] on [0,1] (max of tau - tau^3 is 2/(3 sqrt 3) = 0.38490 < 0.385). All float work uses IEEE round-to-nearest followed by one nextafter step outward after EVERY operation, so each float bound is a valid bound. Conversions: float->int images by exact ldexp + floor/ceil; int->float by Python's correctly rounded int.__float__ followed by nextafter. """ import numpy as np import flint S = 40 # integer image scale 2^S for convolution inputs C3B = 0.385 # >= max_{[0,1]} (tau - tau^3) = 0.3849001... assert C3B >= 2 / (3 * 3 ** 0.5) + 1e-9 def dn(x): return np.nextafter(x, -np.inf) def up(x): return np.nextafter(x, np.inf) class PL: """Piecewise-linear enclosure on cells off..off+n-1. lo0/lo1 : lower linear piece values at tau=0 and tau=1 of each cell hi0/hi1 : upper linear piece values. nonneg : the enclosed function is known to be >= 0 (lower pieces >= 0).""" __slots__ = ('off', 'lo0', 'lo1', 'hi0', 'hi1', 'nonneg') def __init__(self, off, lo0, lo1, hi0, hi1, nonneg=True): self.off = int(off) self.lo0, self.lo1, self.hi0, self.hi1 = lo0, lo1, hi0, hi1 self.nonneg = nonneg n = len(lo0) assert len(lo1) == n and len(hi0) == n and len(hi1) == n if nonneg and n: assert lo0.min() >= 0 and lo1.min() >= 0, 'nonneg lower pieces' if n: assert np.all(lo0 <= hi0) and np.all(lo1 <= hi1), 'lower <= upper' @property def n(self): return len(self.lo0) @property def end(self): return self.off + self.n def window(self, a, b): """Restriction to cells [a,b) (zero outside own support).""" a = int(a); b = int(b) if b <= a: z = np.zeros(0) return PL(a, z, z, z, z, self.nonneg) out = [np.zeros(b - a) for _ in range(4)] s0, s1 = max(a, self.off), min(b, self.end) if s1 > s0: for o, src in zip(out, (self.lo0, self.lo1, self.hi0, self.hi1)): o[s0 - a:s1 - a] = src[s0 - self.off:s1 - self.off] return PL(a, *out, nonneg=self.nonneg) def trim(self): nz = np.flatnonzero((self.lo0 != 0) | (self.lo1 != 0) | (self.hi0 != 0) | (self.hi1 != 0)) if len(nz) == 0: return self.window(self.off, self.off) return self.window(self.off + nz[0], self.off + nz[-1] + 1) def zero_pl(a, b): z = np.zeros(max(int(b) - int(a), 0)) return PL(a, z, z.copy(), z.copy(), z.copy()) def pl_axpy(acc, x, clo, chi): """acc + c*x for a NONNEGATIVE x and scalar c in [clo,chi] with clo>=0. acc must already cover x's cells (acc is modified in place).""" assert clo >= 0 and chi >= clo and x.nonneg and acc.nonneg if x.n == 0: return acc a, b = x.off - acc.off, x.end - acc.off assert a >= 0 and b <= acc.n, (a, b, acc.n) acc.lo0[a:b] = np.maximum(dn(acc.lo0[a:b] + np.maximum(dn(clo * x.lo0), 0)), 0) acc.lo1[a:b] = np.maximum(dn(acc.lo1[a:b] + np.maximum(dn(clo * x.lo1), 0)), 0) acc.hi0[a:b] = up(acc.hi0[a:b] + up(chi * x.hi0)) acc.hi1[a:b] = up(acc.hi1[a:b] + up(chi * x.hi1)) return acc def float_interval(fr): """Outward float interval of a Fraction (or int).""" f = float(fr) from fractions import Fraction if Fraction(f) == fr: return f, f return float(dn(f)), float(up(f)) def _images(e0, e1, lower): """Integer images (a, b) at scale 2^S: a = value at tau=0, b = slope over the cell. Lower: floor of both endpoints, upper: ceil -- the interpolating line of the rounded endpoints lies below (above) the original line.""" x0 = np.ldexp(e0, S); x1 = np.ldexp(e1, S) assert np.all(np.abs(x0) < 2.0 ** 62) and np.all(np.abs(x1) < 2.0 ** 62) if lower: a = np.floor(x0).astype(np.int64); c = np.floor(x1).astype(np.int64) else: a = np.ceil(x0).astype(np.int64); c = np.ceil(x1).astype(np.int64) return a, c - a def _poly(arr): return flint.fmpz_poly([int(v) for v in arr]) def _coeffs(p, n): c = [int(v) for v in p.coeffs()] c += [0] * (n - len(c)) return np.array(c[:n], dtype=object) def _cubic_ints(F_a, F_b, G_a, G_b): """Exact integer cubic coefficient arrays 6*M*2^(2S)*c_k on output cells 0..nF+nG-1 (relative to F.off+G.off), for the convolution of the two piecewise-linear integer-image functions.""" nF, nG = len(F_a), len(G_a) n = nF + nG pa, pb, pc, pd = _poly(F_a), _poly(F_b), _poly(G_a), _poly(G_b) AC = _coeffs(pa * pc, n); AD = _coeffs(pa * pd, n) BC = _coeffs(pb * pc, n); BD = _coeffs(pb * pd, n) def sh(x): y = np.empty(n, dtype=object); y[0] = 0; y[1:] = x[:-1] return y ACp, ADp, BCp, BDp = sh(AC), sh(AD), sh(BC), sh(BD) C0 = 6 * ACp + 3 * ADp + 3 * BCp + BDp C1 = 6 * AC - 6 * ACp + 3 * BDp C2 = 3 * AD + 3 * BC - 3 * ADp - 3 * BCp - 3 * BDp C3 = BD - BDp return C0, C1, C2, C3 class Cubic: """Piecewise-cubic enclosure: lower cubic sum lo[k] tau^k <= f <= sum hi[k] tau^k on each cell (coefficientwise rounding is valid because tau^k >= 0).""" __slots__ = ('off', 'lo', 'hi') def __init__(self, off, lo, hi): self.off = int(off); self.lo = lo; self.hi = hi @property def n(self): return len(self.lo[0]) @property def end(self): return self.off + self.n def _ints_to_float(C, M, lower): f = np.array([float(v) for v in C], dtype=np.float64) if lower: f = dn(f); f = dn(f / (6.0 * M)); f = dn(np.ldexp(f, -2 * S)) else: f = up(f); f = up(f / (6.0 * M)); f = up(np.ldexp(f, -2 * S)) return f def conv(F, G, M, lim=None): """Exact-arithmetic enclosure of F*G (both nonneg PL) as a Cubic on cells [F.off+G.off, min(F.end+G.end, lim)).""" assert F.nonneg and G.nonneg off = F.off + G.off end = F.end + G.end if lim is not None: end = min(end, lim) if F.n == 0 or G.n == 0 or end <= off: z = np.zeros(0) return Cubic(off, [z] * 4, [z] * 4) n = end - off res = {} for lower in (True, False): Fa, Fb = _images(F.lo0 if lower else F.hi0, F.lo1 if lower else F.hi1, lower) Ga, Gb = _images(G.lo0 if lower else G.hi0, G.lo1 if lower else G.hi1, lower) if lower: # nonnegativity of the integer images of lower pieces assert Fa.min() >= 0 and (Fa + Fb).min() >= 0 and Ga.min() >= 0 and (Ga + Gb).min() >= 0 Cs = _cubic_ints(Fa, Fb, Ga, Gb) res[lower] = [_ints_to_float(C[:n], M, lower) for C in Cs] return Cubic(off, res[True], res[False]) def cubic_cell_bounds(cb): """Bounds of the enclosed function over each whole cell.""" lo, hi = cb.lo, cb.hi p0 = lo[0]; p1 = dn(dn(dn(lo[0] + lo[1]) + lo[2]) + lo[3]) rl = up(up(np.maximum(lo[2], 0) / 4) + up(np.maximum(lo[3], 0) * C3B)) low = dn(np.minimum(p0, p1) - rl) q0 = hi[0]; q1 = up(up(up(hi[0] + hi[1]) + hi[2]) + hi[3]) rh = up(up(np.maximum(-hi[2], 0) / 4) + up(np.maximum(-hi[3], 0) * C3B)) high = up(np.maximum(q0, q1) + rh) return low, high def cubic_right_end(cb): """Bounds of the enclosed function at tau=1 of each cell (exact cubic value).""" lo, hi = cb.lo, cb.hi p1 = dn(dn(dn(lo[0] + lo[1]) + lo[2]) + lo[3]) q1 = up(up(up(hi[0] + hi[1]) + hi[2]) + hi[3]) return p1, q1 def reenclose(cb, nonneg=True): """Linear enclosure per cell of a Cubic enclosure.""" lo, hi = cb.lo, cb.hi rl = up(up(np.maximum(lo[2], 0) / 4) + up(np.maximum(lo[3], 0) * C3B)) e0l = dn(lo[0] - rl) e1l = dn(dn(dn(dn(lo[0] + lo[1]) + lo[2]) + lo[3]) - rl) rh = up(up(np.maximum(-hi[2], 0) / 4) + up(np.maximum(-hi[3], 0) * C3B)) e0h = up(hi[0] + rh) e1h = up(up(up(up(hi[0] + hi[1]) + hi[2]) + hi[3]) + rh) if nonneg: bad = (e0l < 0) | (e1l < 0) e0l = np.where(bad, 0.0, e0l); e1l = np.where(bad, 0.0, e1l) e0h = np.maximum(e0h, 0.0); e1h = np.maximum(e1h, 0.0) return PL(cb.off, e0l, e1l, e0h, e1h, nonneg=nonneg) def pl_to_cubic(F): z = np.zeros(F.n) return Cubic(F.off, [F.lo0.copy(), dn(F.lo1 - F.lo0), z, z.copy()], [F.hi0.copy(), up(F.hi1 - F.hi0), z.copy(), z.copy()]) class CubicAcc: """Accumulator of signed integer-weighted Cubic enclosures on a fixed window.""" def __init__(self, a, b): self.off = int(a); n = max(int(b) - int(a), 0) self.lo = [np.zeros(n) for _ in range(4)] self.hi = [np.zeros(n) for _ in range(4)] def add(self, cb, w): """self += w * cb, w a nonzero integer (exact in float).""" if cb.n == 0: return a = max(cb.off, self.off); b = min(cb.end, self.off + len(self.lo[0])) if b <= a: return i0, i1 = a - self.off, b - self.off j0, j1 = a - cb.off, b - cb.off if w > 0: src_lo, src_hi = cb.lo, cb.hi else: src_lo, src_hi = cb.hi, cb.lo for k in range(4): self.lo[k][i0:i1] = dn(self.lo[k][i0:i1] + dn(w * src_lo[k][j0:j1])) self.hi[k][i0:i1] = up(self.hi[k][i0:i1] + up(w * src_hi[k][j0:j1])) def cubic(self): return Cubic(self.off, self.lo, self.hi) def point_inner(F, G, M): """Bounds of int_0^1 F(s) G(1-s) ds for nonneg PL F, G (exact integers).""" assert F.nonneg and G.nonneg # cell j of F pairs with cell M-1-j of G, G's local coordinate is 1-sigma lo_tot = 0; hi_tot = 0 js = np.arange(F.off, F.end) ms = M - 1 - js ok = (ms >= G.off) & (ms < G.end) if not np.any(ok): return 0.0, 0.0 js = js[ok]; ms = ms[ok] out = [] for lower in (True, False): Fa, Fb = _images((F.lo0 if lower else F.hi0)[js - F.off], (F.lo1 if lower else F.hi1)[js - F.off], lower) Ga, Gb = _images((G.lo0 if lower else G.hi0)[ms - G.off], (G.lo1 if lower else G.hi1)[ms - G.off], lower) # integral over the cell of (a + b s)(c + d (1-s)) ds = ac + ad/2 + bc/2 + bd/6 tot = 0 for a, b, c, d in zip(Fa.tolist(), Fb.tolist(), Ga.tolist(), Gb.tolist()): tot += 6 * a * c + 3 * a * d + 3 * b * c + b * d out.append(tot) lo = float(out[0]); hi = float(out[1]) lo = dn(dn(dn(lo) / (6.0 * M)) * 2.0 ** (-2 * S)); hi = up(up(up(hi) / (6.0 * M)) * 2.0 ** (-2 * S)) return float(dn(lo)), float(up(hi)) def cubic_sub_bounds(cb, ta, tb, sel=None): """Bounds of the enclosed function over tau in [ta, tb] (0<=ta