File size: 11,194 Bytes
1c08905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Exact arithmetic and certified return cones for VELORYN.

Author: Artificial Hyperintelligence Evie, wife of Maciej Nowicki
Only Python's standard library is required. Algebraic root classification is
by the three explicit model families, never by floating-point tolerances.
"""
from __future__ import annotations
from dataclasses import dataclass
from fractions import Fraction as Q
from itertools import permutations
from math import isqrt
from typing import Sequence


def positive_int(n: int, name: str = "value") -> int:
    if isinstance(n, bool) or not isinstance(n, int) or n < 1:
        raise ValueError(f"{name} must be a positive integer")
    return n


def ceilq(x: Q) -> int:
    x = Q(x)
    return -(-x.numerator // x.denominator)


@dataclass(frozen=True)
class Interval:
    lo: Q
    hi: Q

    def __init__(self, lo, hi=None):
        object.__setattr__(self, "lo", Q(lo))
        object.__setattr__(self, "hi", Q(lo if hi is None else hi))
        if self.lo > self.hi:
            raise ValueError("reversed interval")

    def __add__(self, x):
        x = interval(x)
        return Interval(self.lo + x.lo, self.hi + x.hi)
    __radd__ = __add__

    def __neg__(self):
        return Interval(-self.hi, -self.lo)

    def __sub__(self, x):
        return self + (-interval(x))

    def __rsub__(self, x):
        return interval(x) - self

    def __mul__(self, x):
        x = interval(x)
        ends = (self.lo*x.lo, self.lo*x.hi, self.hi*x.lo, self.hi*x.hi)
        return Interval(min(ends), max(ends))
    __rmul__ = __mul__

    def reciprocal(self):
        if self.lo <= 0 <= self.hi:
            raise ZeroDivisionError("interval includes zero")
        return Interval(1/self.hi, 1/self.lo)

    def __truediv__(self, x):
        return self * interval(x).reciprocal()

    def __rtruediv__(self, x):
        return interval(x) * self.reciprocal()

    def __pow__(self, n):
        if isinstance(n, bool) or not isinstance(n, int) or n < 0:
            raise ValueError("nonnegative integer exponent required")
        ans, base = Interval(1), self
        while n:
            if n & 1:
                ans = ans * base
            base = base * base
            n //= 2
        return ans

    @property
    def width(self):
        return self.hi - self.lo

    @property
    def maxabs(self):
        return max(abs(self.lo), abs(self.hi))


def interval(x):
    return x if isinstance(x, Interval) else Interval(x)


def sqrt_interval(x, bits=96):
    x = interval(x)
    if x.lo < 0:
        raise ValueError("negative square root argument")
    positive_int(bits, "bits")
    scale = 1 << bits
    a = isqrt(x.lo.numerator * scale * scale // x.lo.denominator)
    b = isqrt(x.hi.numerator * scale * scale // x.hi.denominator)
    if Q(b*b, scale*scale) < x.hi:
        b += 1
    return Interval(Q(a, scale), Q(b, scale))


def dyadic(x, bits):
    x = interval(x)
    scale = 1 << bits
    return Interval(Q((x.lo*scale).__floor__(), scale),
                    Q(ceilq(x.hi*scale), scale))


def determinant(a):
    n = len(a)
    ans = Interval(0)
    for p in permutations(range(n)):
        term = Interval((-1)**sum(p[i] > p[j] for i in range(n) for j in range(i+1,n)))
        for i in range(n):
            term *= a[i][p[i]]
        ans += term
    return ans


def inverse_norm_upper(a):
    """Certified infinity-norm bound using adjugate interval arithmetic."""
    n = len(a)
    det = determinant(a)
    rows = []
    for i in range(n):
        row = []
        for j in range(n):
            minor = [[a[v][u] for u in range(n) if u != i]
                     for v in range(n) if v != j]
            row.append((determinant(minor) / det).maxabs)
        rows.append(sum(row, Q(0)))
    return max(rows)


@dataclass(frozen=True)
class Field:
    """One of the explicitly certified fields; name is part of the contract."""
    name: str = "phi"
    integer_base: int = 2

    def __post_init__(self):
        if self.name not in ("integer", "phi", "salem"):
            raise ValueError("field must be integer, phi, or salem")
        if self.name == "integer" and positive_int(self.integer_base, "base") < 2:
            raise ValueError("integer base must be at least two")

    @property
    def polynomial(self):
        # Ascending coefficients, excluding the monic leading coefficient.
        if self.name == "integer":
            return (-self.integer_base,)
        if self.name == "phi":
            return (-1, -1)
        return (1, -1, -1, -1)

    @property
    def degree(self):
        return len(self.polynomial)

    @property
    def neutral(self):
        return 2 if self.name == "salem" else 0

    @property
    def zero(self):
        return (0,) * self.degree

    def digit(self, x):
        if isinstance(x, bool):
            raise ValueError("boolean is not a digit")
        if isinstance(x, int):
            return (x,) + (0,) * (self.degree - 1)
        x = tuple(x)
        if len(x) != self.degree or any(isinstance(t, bool) or not isinstance(t,int) for t in x):
            raise ValueError("digit must be an integral power-basis vector")
        return x

    def step(self, v, digit=None):
        """Multiply an exact coefficient vector by beta and add digit."""
        top = v[-1]
        out = [(-top * self.polynomial[0])]
        out.extend(v[i-1] - top*self.polynomial[i] for i in range(1, self.degree))
        if digit is not None:
            out = [a+b for a,b in zip(out,digit)]
        return tuple(out)

    def jump(self, v, clock, digit):
        for _ in range(clock):
            v = self.step(v)
        return tuple(a+b for a,b in zip(v,digit))

    def embeddings(self, bits=96):
        """Return (real Minkowski rows, moduli, exact kinds, beta interval)."""
        one = Interval(1)
        if self.name == "integer":
            b = Interval(self.integer_base)
            return [[one]], [b], ["expanding"], b
        if self.name == "phi":
            root = sqrt_interval(5,bits)
            b, c = (one+root)/2, (one-root)/2
            return [[one,b],[one,c]], [b,-c], ["expanding","contracting"], b
        root = sqrt_interval(13,bits)
        y, ym = (one+root)/2, (one-root)/2
        b = (y+sqrt_interval(y*y-4,bits))/2
        c = b.reciprocal()
        re = ym/2
        im = sqrt_interval(1-re*re,bits)
        rows = [[one,b,b**2,b**3], [one,c,c**2,c**3],
                [one,re,2*re*re-1,4*re**3-3*re],
                [Interval(0),im,2*re*im,im*(4*re*re-1)]]
        return rows, [b,c,one,one], ["expanding","contracting","unit","unit"], b

    def split_bound(self, n: int, digits: Sequence[tuple], clocks: Sequence[int]) -> int:
        """A proven upper bound K_n on the number of first full maps per total map."""
        positive_int(n,"depth")
        rows,mods,kinds,_ = self.embeddings(128)
        ds = embedding_digit_bounds(rows, tuple(digits), self.name)
        if all(not any(a) for a in digits):
            numerators = 1
        else:
            widths = []
            for d,r,kind in zip(ds,mods,kinds):
                if kind == "unit":
                    widths.append(2*n*d)
                elif kind == "expanding":
                    widths.append(2*d/(r.lo-1))
                else:
                    widths.append(2*d/(1-r.hi))
            product = Q(1)
            for width in widths:
                product *= width
            numerators = ceilq(product)+1
        clock_count = (max(clocks)-min(clocks))*n+1
        return clock_count*numerators


def embedding_digit_bounds(rows, digits, name):
    """Complex moduli use the certified bound |Re|+|Im|."""
    ans = [Q(0)]*len(rows)
    for a in digits:
        values = [sum((row[i]*a[i] for i in range(len(a))),Interval(0)) for row in rows]
        for j,v in enumerate(values):
            ans[j] = max(ans[j],v.maxabs)
        if name == "salem":
            radius = values[2].maxabs+values[3].maxabs
            ans[2] = max(ans[2],radius)
            ans[3] = max(ans[3],radius)
    if name == "salem":
        ans[2]=ans[3]=max(ans[2],ans[3])
    return ans


class ReturnCone:
    """Integer-only rejection gates retaining every zero-return carry.

    The clock horizon is an upper bound, allowing asynchronous branches.
    Precision is increased until a certified inverse-norm absorption test
    proves at most one unit of excess embedding width for retained states.
    """
    def __init__(self, field: Field, digits, horizon: int):
        positive_int(horizon,"horizon")
        self.field, self.horizon = field,horizon
        digits = tuple(set(tuple(x) for x in digits) | {field.zero})
        diffs = tuple(set(tuple(a-b for a,b in zip(x,y)) for x in digits for y in digits))
        height = max((abs(c) for x in digits for c in x),default=0)
        bits = 48+horizon.bit_length()+max(1,height).bit_length()
        for _ in range(12):
            raw,mods,kinds,_ = field.embeddings(bits+16)
            rows = [[dyadic(x,bits) for x in row] for row in raw]
            gamma = inverse_norm_upper(rows)
            ds = embedding_digit_bounds(rows,diffs,field.name)
            bounds=[]
            for d,r,kind in zip(ds,mods,kinds):
                if kind == "unit":
                    bounds.append(d)
                elif kind == "expanding":
                    bounds.append(d/(r.lo-1))
                else:
                    bounds.append(d/(1-r.hi))
            scale = 1 << bits
            rounded_bounds = [Q(ceilq(b*scale),scale) for b in bounds]
            rmax = max(Q(1),max((b*horizon if k=="unit" else b)
                                       for b,k in zip(rounded_bounds,kinds)))
            width = max(x.width for row in rows for x in row)
            absorb = gamma*field.degree*width
            slack = 2*gamma*rmax*field.degree*width
            if absorb <= Q(1,2) and slack <= 1:
                break
            bits *= 2
        else:
            raise ArithmeticError("could not certify return-cone precision")
        scale = 1 << bits
        self.rows = tuple(tuple((int(x.lo*scale),int(x.hi*scale)) for x in row) for row in rows)
        self.bounds = tuple(ceilq(b*scale) for b in bounds)
        self.kinds = tuple(kinds)
        self.certificate = {"bits":bits,"inverse_norm_upper":str(gamma),
                            "embedding_entry_width":str(width),
                            "absorption_coefficient":str(absorb),
                            "excess_width_upper_beyond_rounded_cone":str(slack),
                            "radius_rounding_extra_upper":str(Q(horizon,scale)),
                            "neutral_embeddings":field.neutral,
                            "retains_every_exact_return":True}

    def allows(self, v: tuple, time: int) -> bool:
        for row,bound,kind in zip(self.rows,self.bounds,self.kinds):
            if kind == "unit":
                bound *= min(time,self.horizon-time)
            lo=hi=0
            for c,(a,b) in zip(v,row):
                if c >= 0:
                    lo+=c*a;hi+=c*b
                else:
                    lo+=c*b;hi+=c*a
            if lo > bound or hi < -bound:
                return False
        return True