File size: 13,165 Bytes
33e9f46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""Exact conditional-memory certificates for finite positive branch models.

The model is known.  A compact state receives externally supplied branch labels;
it does not, unless separately certified, predict their probabilities.
"""
from __future__ import annotations
from dataclasses import dataclass
from itertools import combinations
from typing import Sequence
import numpy as np
import sympy as sp
from scipy.optimize import linprog


def pairs(n: int) -> list[tuple[int, int]]:
    if n < 2:
        raise ValueError("Ambient dimension must be at least two.")
    return list(combinations(range(n), 2))


def wedge(a: sp.Matrix, b: sp.Matrix) -> sp.Matrix:
    a, b = sp.Matrix(a), sp.Matrix(b)
    if a.rows != 1 or b.shape != a.shape:
        raise ValueError("Wedge arguments must be equal-length rows.")
    return sp.Matrix([[a[i]*b[j] - a[j]*b[i] for i,j in pairs(a.cols)]])


def compound2(T: sp.Matrix) -> sp.Matrix:
    T = sp.Matrix(T)
    if T.rows != T.cols or T.rows < 2:
        raise ValueError("A square matrix of order at least two is required.")
    ij = pairs(T.rows)
    return sp.Matrix([[T[i,k]*T[j,l]-T[i,l]*T[j,k]
                       for k,l in ij] for i,j in ij])


def row_basis(F: sp.Matrix) -> sp.Matrix:
    F = sp.Matrix(F)
    if F.rows == 0:
        return F
    inds = F.T.rref()[1]
    return F[list(inds), :] if inds else sp.zeros(0, F.cols)


@dataclass(frozen=True)
class Ratio:
    numerator: sp.Matrix
    denominator: sp.Matrix
    word: tuple[int, ...]


@dataclass
class ExteriorCertificate:
    normalizer: sp.Matrix
    readouts: tuple[sp.Matrix, ...]
    seeds: tuple[Ratio, ...]
    branches: tuple[sp.Matrix, ...]
    ratios: list[Ratio]
    R: sp.Matrix
    transports: list[sp.Matrix]
    depth: int

    def signature_exact(self, x: sp.Matrix) -> sp.Matrix:
        x = sp.Matrix(x)
        self._validate_state(x)
        out = []
        for r in self.ratios:
            den = (r.denominator*x)[0]
            if den <= 0:
                raise ValueError("A stored denominator is nonpositive.")
            out.append((r.numerator*x)[0]/den)
        return sp.Matrix(out)

    def _validate_state(self, x: sp.Matrix) -> None:
        if x.shape != (self.normalizer.cols, 1):
            raise ValueError("Incorrect state shape.")
        if (self.normalizer*x)[0] != 1 or any(v < 0 for v in x):
            raise ValueError("Expected an exactly normalized simplex state.")

    def fiber_matrix(self, z: Sequence) -> sp.Matrix:
        if len(z) != len(self.ratios):
            raise ValueError("Incorrect signature dimension.")
        rows = [r.numerator-sp.sympify(v)*r.denominator
                for r,v in zip(self.ratios,z)]
        return sp.Matrix.vstack(*rows) if rows else sp.zeros(0, self.normalizer.cols)

    def reconstruct_fiber_float(self, z: Sequence[float]) -> np.ndarray:
        """Find any simplex representative; numerical, not an exact certificate."""
        L = self.fiber_matrix(z)
        eq = np.array(sp.Matrix.vstack(self.normalizer,L),dtype=float)
        rhs = np.zeros(eq.shape[0]); rhs[0] = 1.0
        res = linprog(np.zeros(eq.shape[1]), A_eq=eq, b_eq=rhs,
                      bounds=(0,None), method="highs")
        if not res.success or np.max(np.abs(eq@res.x-rhs))>1e-7:
            raise ValueError("No numerically certified feasible representative.")
        return res.x

    def update_float(self, z: Sequence[float], branch: int) -> np.ndarray:
        if branch < 0 or branch >= len(self.branches):
            raise ValueError("Unknown branch.")
        x = self.reconstruct_fiber_float(z)
        T = np.array(self.branches[branch], dtype=float)
        y = T@x
        if np.sum(y) <= 0:
            raise ValueError("Impossible branch.")
        y /= np.sum(y)
        return np.array([float(np.array(r.numerator,dtype=float).ravel()@y /
                               (np.array(r.denominator,dtype=float).ravel()@y))
                         for r in self.ratios])

    def verify(self) -> bool:
        """Check both directions: seed coverage, genuine orbit rows, closure.

        Instrument probability normalization is an additional model obligation;
        this checker permits a library containing outcomes of several actions.
        """
        try:
            n = self.normalizer.cols
            if self.normalizer != sp.ones(1,n) or n < 2:
                return False
            if len(self.branches) != len(self.transports) or not self.branches:
                return False
            if self.R.shape != (len(self.ratios), n*(n-1)//2):
                return False
            if self.R.rank() != self.R.rows:
                return False
            if any(T.shape != (n,n) or any(v <= 0 for v in T)
                   for T in self.branches):
                return False
            for seed in self.seeds:
                if (seed.numerator.shape != (1,n) or
                    seed.denominator.shape != (1,n) or seed.word or
                    any(v <= 0 for v in seed.denominator)):
                    return False
                if sp.Matrix.vstack(self.R,wedge(seed.numerator,
                                                seed.denominator)).rank() != self.R.rows:
                    return False
            for i,r in enumerate(self.ratios):
                if (r.numerator.shape != (1,n) or
                    r.denominator.shape != (1,n) or
                    any(v <= 0 for v in r.denominator) or
                    wedge(r.numerator,r.denominator) != self.R[i,:]):
                    return False
                if any(a < 0 or a >= len(self.branches) for a in r.word):
                    return False
                genuine = False
                for seed in self.seeds:
                    beta, alpha = seed.numerator, seed.denominator
                    # Words are chronological; row products are reverse ordered.
                    for a in reversed(r.word):
                        beta, alpha = beta*self.branches[a], alpha*self.branches[a]
                    if beta == r.numerator and alpha == r.denominator:
                        genuine = True
                        break
                if not genuine:
                    return False
            for T,H in zip(self.branches,self.transports):
                if H.shape != (self.R.rows,self.R.rows):
                    return False
                if self.R*compound2(T) != H*self.R:
                    return False
            return True
        except (ValueError, TypeError, IndexError):
            return False


def compile_exterior(branches: Sequence[sp.Matrix],
                     readouts: Sequence[sp.Matrix]) -> ExteriorCertificate:
    """Wrapper for ordinary affine mandatory readouts."""
    if not branches:
        raise ValueError("At least one branch is required.")
    n=sp.Matrix(branches[0]).rows
    seeds=[Ratio(sp.Matrix(f),sp.ones(1,n),()) for f in readouts]
    return compile_ratios(branches,seeds)


def compile_ratios(branches: Sequence[sp.Matrix],
                   seeds: Sequence[Ratio]) -> ExteriorCertificate:
    """Exact closure for linear-fractional mandatory readouts.

    All denominators must be strictly positive on the entire simplex. Branches
    are known strictly positive matrices. Instrument normalization is separate.
    """
    if not branches:
        raise ValueError("At least one branch is required.")
    Ts = tuple(sp.Matrix(T) for T in branches)
    n = Ts[0].rows
    for T in Ts:
        if T.shape != (n,n) or any(x <= 0 for x in T):
            raise ValueError("Branches must be square and strictly positive.")
    fs = tuple(sp.Matrix(r.numerator) for r in seeds)
    for r in seeds:
        if r.word:
            raise ValueError("Initial readouts must have empty provenance words.")
        if r.numerator.shape != (1,n) or r.denominator.shape != (1,n):
            raise ValueError("Readout rows have wrong dimensions.")
        if any(x<=0 for x in r.denominator):
            raise ValueError("Denominator must be positive on the full simplex.")
    e = sp.ones(1,n)
    ratios: list[Ratio] = []
    R = sp.zeros(0,n*(n-1)//2)
    def admit(beta,alpha,word):
        nonlocal R
        r=wedge(beta,alpha)
        if sp.Matrix.vstack(R,r).rank() > R.rows:
            R=sp.Matrix.vstack(R,r)
            ratios.append(Ratio(beta,alpha,word))
    for r in seeds:
        admit(r.numerator,r.denominator,r.word)
    cursor=0
    while cursor < len(ratios):
        r=ratios[cursor]; cursor+=1
        for a,T in enumerate(Ts):
            admit(r.numerator*T,r.denominator*T,(a,)+r.word)
    Hs=[]
    for T in Ts:
        target=R*compound2(T)
        if R.rows:
            hrows=[R.T.gauss_jordan_solve(target[i,:].T)[0].T
                   for i in range(R.rows)]
            H=sp.Matrix.vstack(*hrows)
        else:
            H=sp.zeros(0,0)
        Hs.append(H)
    cert=ExteriorCertificate(e,fs,tuple(seeds),Ts,ratios,R,Hs,
                             max((len(r.word) for r in ratios),default=0))
    if not cert.verify():
        raise ArithmeticError("Internal closure verification failed.")
    return cert


def snapshot_space(cert: ExteriorCertificate) -> sp.Matrix:
    """Least affine initial-information space for the conditional contract.

    Unlike affine_closure, these coordinates need not update from themselves.
    """
    rows=[cert.normalizer]
    for r in cert.ratios:
        rows.extend([r.numerator,r.denominator])
    return row_basis(sp.Matrix.vstack(*rows))


def factor_two_fixture(r: int):
    """r independent ratios, exactly 2r affine snapshot scalars, reset future."""
    if r<1: raise ValueError("Positive rank required.")
    n=2*r+1; e=sp.ones(1,n); E=sp.eye(n)
    beta=[E[2*j,:]-E[n-1,:] for j in range(r)]
    alpha=[e+sp.Rational(1,4)*(E[2*j+1,:]-E[n-1,:]) for j in range(r)]
    seeds=[Ratio(b,a,()) for b,a in zip(beta,alpha)]
    return compile_ratios([sp.ones(n)/n],seeds)


def affine_closure(branches: Sequence[sp.Matrix], initial: sp.Matrix) -> sp.Matrix:
    """Least fixed affine self-updating space, using reset-or-invariance."""
    W=row_basis(initial)
    n=W.cols
    if sp.Matrix.vstack(W,sp.ones(1,n)).rank()!=W.rows:
        raise ValueError("Normalizer is missing.")
    while True:
        extra=[W*T for T in branches if (W*T).rank()>1]
        new=row_basis(sp.Matrix.vstack(W,*extra))
        if new.rows==W.rows:
            return W
        W=new


def hadamard_exact(n: int) -> sp.Matrix:
    if n<4 or n & (n-1):
        raise ValueError("Use a power of two n >= 4.")
    H=sp.Matrix([[1]])
    while H.rows<n:
        H=sp.Matrix.vstack(sp.Matrix.hstack(H,H),sp.Matrix.hstack(H,-H))
    return H


@dataclass
class Family:
    n: int
    F: sp.Matrix
    LA: sp.Matrix
    LB: sp.Matrix
    A: sp.Matrix
    B: sp.Matrix
    delta: sp.Rational
    c: sp.Rational = sp.Rational(1,2)
    tau: sp.Rational = sp.Rational(1,4)
    gamma: sp.Rational = sp.Rational(1,8)
    kappa: sp.Rational = sp.Rational(1,8)

    def signature(self,x: sp.Matrix) -> sp.Matrix:
        z=self.F*sp.Matrix(x)
        if z[0]!=1:
            raise ValueError("Not normalized.")
        return sp.Matrix([z[1], z[2]/(1+self.tau*z[3])])

    def compact_step(self, state: Sequence, label: int) -> sp.Matrix:
        if label==0:
            return sp.Matrix([self.gamma*state[1],self.kappa*state[1]])
        if label==1:
            return sp.zeros(2,1)
        raise ValueError("Unknown label.")


def separation_family(n: int, delta=0) -> Family:
    F=hadamard_exact(n)
    c,tau,g,k=map(sp.Rational,[sp.Rational(1,2),sp.Rational(1,4),
                              sp.Rational(1,8),sp.Rational(1,8)])
    delta=sp.Rational(delta)
    if not (0<=delta<sp.Rational(1,8)):
        raise ValueError("Require 0 <= delta < 1/8.")
    lam=sp.Rational(1,8*n)
    LA=sp.zeros(n); LB=sp.zeros(n)
    LA[0,0]=c; LA[0,3]=c*tau
    LA[1,2]=c*g; LA[2,2]=c*k
    LB[0,0]=1-c; LB[0,3]=-c*tau
    LB[1,3]=delta
    for j in range(3,n-1): LB[j,j+1]=lam
    A=F.T*LA*F/n; B=F.T*LB*F/n
    return Family(n,F,LA,LB,A,B,delta,c,tau,g,k)


def normalize(T: sp.Matrix,x: sp.Matrix) -> sp.Matrix:
    y=T*x; p=sum(y)
    if p<=0: raise ValueError("Nonpositive branch mass.")
    return y/p


def jacobian_rank(cert: ExteriorCertificate, x: sp.Matrix) -> int:
    z=cert.signature_exact(x)
    return cert.fiber_matrix(z).rank()


def reconstruct_hidden_from_B_readouts(n: int, observations: Sequence,
                                        delta) -> sp.Matrix:
    """Recover initial coordinates z3..z(n-1) after the rank-one rewrite.

    observation[t] = mandatory f after t+1 consecutive B outcomes.
    Exact arithmetic; small delta/late observations can be ill-conditioned.
    """
    delta=sp.sympify(delta)
    if delta<=0 or len(observations)!=n-3:
        raise ValueError("Need positive delta and n-3 successive B readouts.")
    d0=sp.Rational(1,2); d1=sp.Rational(1,8); lam=sp.Rational(1,8*n)
    P=sp.Integer(1); out=[]
    for t,y in enumerate(observations):
        a=sp.simplify(d0*y/(delta+d1*y))
        out.append(sp.simplify(a*P/lam**t))
        P=sp.simplify(P*(d0-d1*a))
    return sp.Matrix(out)