File size: 14,502 Bytes
6773986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Exact rational checks of the inverse-gauge measurement/reconstruction bridge.

Run: python3 code/verify_bridge.py

Matrix inversion and causal response checks are implemented independently of
calibration_core. The optional exact error-decoding integration uses the release
decoder, with the reference algebra checked separately here. These are finite
internal checks, not proof-assistant or external mathematical certification.
"""

from fractions import Fraction as F
from pathlib import Path
import argparse
import json

from calibration_core import decode_column, residual_spaces, jsonable


ROOT = Path(__file__).resolve().parents[1]
COUNTS = {"assertions": 0, "intervention_contexts": 0,
          "decoded_nonzero_space_columns": 0}


def require(condition, message):
    COUNTS["assertions"] += 1
    if not condition:
        raise AssertionError(message)


def mat(rows):
    return [[F(x) for x in row] for row in rows]


def zeros(n, m):
    return [[F(0) for _ in range(m)] for _ in range(n)]


def eye(n):
    return [[F(int(i == j)) for j in range(n)] for i in range(n)]


def add(A, B):
    if len(A) != len(B) or any(len(a) != len(b) for a, b in zip(A, B)):
        raise ValueError("addition dimension mismatch")
    return [[a+b for a, b in zip(x, y)] for x, y in zip(A, B)]


def neg(A):
    return [[-x for x in row] for row in A]


def sub(A, B):
    return add(A, neg(B))


def mul(A, B):
    if not A or not B or len(A[0]) != len(B):
        raise ValueError("multiplication dimension mismatch")
    if any(len(row) != len(A[0]) for row in A):
        raise ValueError("ragged left matrix")
    if any(len(row) != len(B[0]) for row in B):
        raise ValueError("ragged right matrix")
    return [[sum((A[i][k]*B[k][j] for k in range(len(B))), F(0))
             for j in range(len(B[0]))] for i in range(len(A))]


def inverse(A):
    """Independent Gauss-Jordan inversion over Fraction."""
    n = len(A)
    if any(len(row) != n for row in A):
        raise ValueError("inverse needs a square matrix")
    aug = [list(row)+ident for row, ident in zip(A, eye(n))]
    for col in range(n):
        pivot = next((i for i in range(col, n) if aug[i][col]), None)
        if pivot is None:
            raise ValueError("singular matrix")
        aug[col], aug[pivot] = aug[pivot], aug[col]
        scale = aug[col][col]
        aug[col] = [x/scale for x in aug[col]]
        for row in range(n):
            if row != col and aug[row][col]:
                scale = aug[row][col]
                aug[row] = [x-scale*y for x, y in zip(aug[row], aug[col])]
    return [row[n:] for row in aug]


def determinant(A):
    """Separate exact determinant for checking spanning intervention rows."""
    n = len(A)
    if any(len(row) != n for row in A):
        raise ValueError("determinant needs a square matrix")
    B = [list(row) for row in A]
    result = F(1)
    for c in range(n):
        p = next((i for i in range(c, n) if B[i][c]), None)
        if p is None:
            return F(0)
        if p != c:
            B[c], B[p] = B[p], B[c]
            result = -result
        v = B[c][c]
        result *= v
        for i in range(c+1, n):
            scale = B[i][c]/v
            for j in range(c+1, n):
                B[i][j] -= scale*B[c][j]
    return result


def row_support(A):
    return [i for i, row in enumerate(A) if any(row)]


def frobenius_squared(A):
    return sum((x*x for row in A for x in row), F(0))


def complete_reference(n):
    """Complete ordered DAG with all reference edge coefficients equal to one."""
    return [[F(1) if i == j else F(-1) if i > j else F(0)
             for j in range(n)] for i in range(n)]


def assert_complete_strict(B, name):
    n = len(B)
    require(all(B[i][i] == 1 for i in range(n)), name+": diagonal changed")
    require(all(B[i][j] == 0 for i in range(n) for j in range(i+1, n)),
            name+": forbidden graph entry appeared")
    require(all(B[i][j] != 0 for i in range(n) for j in range(i)),
            name+": required causal edge vanished")


def assert_pattern(A, n, name):
    require(all(A[i][j] == 0 for i in range(n) for j in range(i, n)),
            name+": not strictly lower triangular")


def test_model(n, N, F0, C, trusted=None):
    B0 = complete_reference(n)
    T0 = inverse(B0)
    U = add(eye(n), N)
    Uinv = inverse(U)
    Q = sub(Uinv, eye(n))
    Btrue = mul(B0, U)
    Ftrue = mul(F0, U)
    Ttrue = inverse(Btrue)
    A0 = mul(F0, T0)
    D = mul(C, Ttrue)
    Y = sub(mul(D, B0), C)
    N2 = mul(N, N)

    require(mul(U, Uinv) == eye(n), "independent inverse check failed")
    require(mul(Uinv, U) == eye(n), "independent inverse reverse check failed")
    require(mul(B0, T0) == eye(n), "reference inverse check failed")
    require(mul(Ftrue, Ttrue) == A0, "baseline aligned mixing not preserved")
    require(all(any(A0[i][k] for i in range(len(A0))) for k in range(n)),
            "aligned operator has an invisible innovation column")
    require(Y == mul(C, Q), "inverse-gauge linear observation identity failed")
    require(Y != mul(C, N), "example failed to reject forward-gauge substitution")
    require(Q != neg(N), "example has no nonzero higher-order inverse term")
    require(Y != mul(C, neg(N)), "measurement failed to expose quadratic inverse term")
    require(sub(inverse(add(eye(n), Q)), eye(n)) == N,
            "inverse-gauge involution failed")
    require(mul(B0, inverse(add(eye(n), Q))) == Btrue,
            "causal coefficient reconstruction failed")
    require(mul(F0, inverse(add(eye(n), Q))) == Ftrue,
            "observation-map reconstruction failed")
    assert_pattern(N, n, "N")
    assert_pattern(Q, n, "Q")
    assert_pattern(N2, n, "N squared")
    require(any(any(row) for row in N2), "quadratic witness is zero")
    assert_complete_strict(B0, "reference")
    assert_complete_strict(Btrue, "true")

    power = eye(n)
    polynomial_inverse = eye(n)
    for exponent in range(1, n):
        power = mul(power, N)
        polynomial_inverse = add(polynomial_inverse,
                                 power if exponent % 2 == 0 else neg(power))
    require(mul(power, N) == zeros(n, n), "nilpotence bound failed")
    require(polynomial_inverse == Uinv, "finite inverse polynomial failed")

    if trusted is not None:
        require(mul(trusted, N) == zeros(len(trusted), n), "M N nonzero")
        require(mul(trusted, Q) == zeros(len(trusted), n), "inverse lost trusted constraints")
        require(mul(trusted, N2) == zeros(len(trusted), n), "product lost trusted constraints")
        require(mul(trusted, U) == trusted, "trusted rows not fixed by forward gauge")
        require(mul(trusted, Uinv) == trusted, "trusted rows not fixed by inverse gauge")
        require(mul(trusted, T0) == mul(trusted, Ttrue),
                "trusted calibrated readout baseline responses differ")

    context_records = []
    for k in range(1, n):
        rows = [[F(t)**j/F(10) for j in range(k)] for t in range(1, k+1)]
        require(determinant(rows) != 0, "incoming intervention family not rich")
        for local in rows:
            delta0 = local+[F(0)]*(n-k)
            delta = mul([delta0], U)[0]
            require(all(delta[j] == 0 for j in range(k, n)),
                    "transported intervention left parent space")
            require(all(delta[j] != 0 for j in range(k)),
                    "transported dense incoming change lost strict support")
            original = [list(row) for row in B0]
            original[k] = [x-y for x, y in zip(original[k], delta0)]
            candidate = [list(row) for row in Btrue]
            candidate[k] = [x-y for x, y in zip(candidate[k], delta)]
            require(candidate == mul(original, U), "intervened gauge identity failed")
            assert_complete_strict(original, "reference intervention")
            assert_complete_strict(candidate, "true intervention")
            original_inverse = inverse(original)
            candidate_inverse = inverse(candidate)
            require(mul(F0, original_inverse) == mul(Ftrue, candidate_inverse),
                    "aligned intervention responses differ")
            require(mul([delta0], inverse(add(eye(n), Q)))[0] == delta,
                    "control reconstructed from Q differs")
            if trusted is not None:
                require(mul(trusted, original_inverse) == mul(trusted, candidate_inverse),
                        "trusted readout intervention responses differ")
            COUNTS["intervention_contexts"] += 1
            context_records.append({"target": k, "reference_change": delta0,
                                    "true_change": delta, "response_equality": True})

    return {"vertices": n, "baseline_B0": B0, "reference_F0": F0,
            "aligned_A0": A0, "forward_N": N, "N_squared": N2,
            "inverse_Q": Q, "true_B": Btrue, "true_F": Ftrue,
            "new_C": C, "aligned_new_D": D, "observed_Y": Y,
            "trusted_M": trusted, "interventions": context_records}


def three_node_example():
    a, b, c = F(1, 10), F(1, 7), F(1, 9)
    N = mat([[0, 0, 0], [a, 0, 0], [b, c, 0]])
    record = test_model(3, N, mat([[1, 2, 3]]), mat([[1, 2, 3], [2, 1, 4]]))
    Q = record["inverse_Q"]
    require(Q == mat([[0, 0, 0], [-a, 0, 0], [-b+c*a, -c, 0]]),
            "three-node explicit inverse formula failed")
    require(-Q[2][0]+Q[2][1]*Q[1][0] == b,
            "three-node quadratic parameter recovery failed")
    require(-Q[2][0] != b, "first-order-only reconstruction unexpectedly exact")
    record["quadratic_correction"] = c*a
    record["first_order_b_estimate"] = -Q[2][0]
    record["exact_b"] = b
    return record


def four_node_trusted_example():
    a, b, c = F(1, 20), F(1, 30), F(1, 40)
    N = mat([[0, 0, 0, 0], [a, 0, 0, 0],
             [b, c, 0, 0], [-a-b, -c, 0, 0]])
    M = mat([[1, 1, 1, 1]])
    C = [[F(t)**j for j in range(4)] for t in range(2, 7)]
    record = test_model(4, N, mat([[1, 2, 3, 4], [2, -1, 1, 1]]), C, M)
    B0, D, Q = record["baseline_B0"], record["aligned_new_D"], record["inverse_Q"]
    T0 = inverse(B0)
    H = zeros(5, 4)
    H[1] = [F(3, 7), F(-2, 5), F(1, 11), F(4, 9)]
    W = mat([[F(1, 1000), F(-1, 900), 0, F(1, 700)],
             [0, 0, 0, 0],
             [F(-1, 1100), 0, F(1, 1300), 0],
             [0, F(1, 1400), F(-1, 1500), F(1, 1600)],
             [0, 0, 0, 0]])
    transformed_H, transformed_W = mul(H, B0), mul(W, B0)
    Ytilde = sub(mul(add(add(D, H), W), B0), C)
    require(Ytilde == add(add(mul(C, Q), transformed_H), transformed_W),
            "corrupted/noisy mixing-to-discrepancy identity failed")
    require(row_support(transformed_H) == row_support(H) == [1],
            "invertible right multiplication changed attack row support")
    require(row_support(transformed_W) == row_support(W),
            "invertible right multiplication changed noise row support")
    require(mul(transformed_H, T0) == H, "attack pullback identity failed")
    require(mul(transformed_W, T0) == W, "noise pullback identity failed")
    noise_sq = frobenius_squared(W)
    transformed_sq = frobenius_squared(transformed_W)
    conservative_upper_sq = noise_sq*frobenius_squared(B0)
    require(transformed_sq <= conservative_upper_sq,
            "conservative exact Frobenius amplification bound failed")

    edges = [(i, j) for i in range(4) for j in range(i+1, 4)]
    supports, spaces = residual_spaces(4, edges, M)
    require(list(map(len, spaces)) == [2, 1, 0, 0],
            "trusted residual dimensions differ from independent expectation")
    require(supports == [[1, 2, 3], [2, 3], [3], []],
            "complete-four surrounded pattern differs")
    exact_corrupted = sub(mul(add(D, H), B0), C)
    erased = (4,)
    decoded = zeros(4, 4)
    for j, E in enumerate(spaces):
        if E:
            observations = [exact_corrupted[a][j] if a not in erased else None
                            for a in range(5)]
            value = decode_column(E, C, observations, erased=erased, max_errors=1)
            require(value == [Q[i][j] for i in range(4)],
                    "operator-bridge sparse-error decode failed")
            for i in range(4):
                decoded[i][j] = value[i]
            COUNTS["decoded_nonzero_space_columns"] += 1
        else:
            require(all(Q[i][j] == 0 for i in range(4)),
                    "known-zero ambiguity column is not zero")
    require(decoded == Q, "decoded full inverse gauge differs from truth")
    require(mul(B0, inverse(add(eye(4), decoded))) == record["true_B"],
            "decoded causal coefficient reconstruction failed")
    residual = sub(exact_corrupted, mul(C, decoded))
    require([a for a in row_support(residual) if a not in erased] == [1],
            "decoded explanation lacks the stipulated shared error support")
    record["row_fault_mapping"] = {
        "attack_in_D": H, "attack_in_Y": transformed_H,
        "bounded_noise_in_D": W, "bounded_noise_in_Y": transformed_W,
        "attack_rows_before_and_after": [1],
        "noise_rows_before_and_after": row_support(W),
        "noise_frobenius_squared": noise_sq,
        "transformed_noise_frobenius_squared": transformed_sq,
        "conservative_upper_squared_using_B0_Frobenius": conservative_upper_sq,
        "note": "This exact rational inequality uses ||B0||_F as a conservative upper bound on ||B0||_op."
    }
    record["exact_decode"] = {
        "erasures": list(erased), "corrupted_rows": [1],
        "bounded_noise_for_this_decode": 0,
        "residual_dimensions": list(map(len, spaces)),
        "decoded_Q": decoded,
        "causal_reconstruction_exact": True
    }
    return record


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=ROOT / "results" / "bridge_results.json")
    args = parser.parse_args()
    report = {"status": "passed", "arithmetic": "fractions.Fraction",
              "scope": "finite internal exact checks; no external or proof-assistant certification",
              "three_node_quadratic": three_node_example(),
              "complete_four_trusted": four_node_trusted_example()}
    report["counts"] = dict(COUNTS)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(jsonable(report), indent=2)+"\n")
    print(json.dumps({"status": "passed", **COUNTS, "output": str(args.output)}, indent=2))


if __name__ == "__main__":
    main()