File size: 11,554 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
#!/usr/bin/env python3
"""Exact rational calibration and fault-tolerance primitives.

The algorithms enumerate channel subsets and are intended as transparent
small-instance certificates, not scalable solvers or raw-data estimators.
All vector-space computations use fractions.Fraction. No third-party package.
"""
from fractions import Fraction as F
from itertools import combinations
import random


def rational_matrix(rows, columns=None):
    out = [[F(x) for x in row] for row in rows]
    if columns is not None and any(len(row) != columns for row in out):
        raise ValueError("inconsistent row width")
    return out


def rref(rows, ncols):
    a = rational_matrix(rows, ncols)
    pivots = []
    k = 0
    for c in range(ncols):
        p = next((i for i in range(k, len(a)) if a[i][c]), None)
        if p is None:
            continue
        a[k], a[p] = a[p], a[k]
        v = a[k][c]
        a[k] = [x / v for x in a[k]]
        for i in range(len(a)):
            if i != k and a[i][c]:
                v = a[i][c]
                a[i] = [x - v*y for x, y in zip(a[i], a[k])]
        pivots.append(c)
        k += 1
        if k == len(a):
            break
    return a, pivots


def rank(rows, ncols):
    return len(rref(rows, ncols)[1])


def row_basis(rows, ncols):
    a, pivots = rref(rows, ncols)
    return a[:len(pivots)]


def null_basis(rows, ncols):
    a, pivots = rref(rows, ncols)
    answer = []
    for free in range(ncols):
        if free in pivots:
            continue
        v = [F(0)]*ncols
        v[free] = F(1)
        for i, p in enumerate(pivots):
            v[p] = -a[i][free]
        answer.append(v)
    return answer


def dot(x, y):
    if len(x) != len(y):
        raise ValueError("dot-product dimension mismatch")
    return sum((a*b for a, b in zip(x, y)), F(0))


def linear_combination(coeff, basis, ambient):
    return [sum((c*v[k] for c, v in zip(coeff, basis)), F(0))
            for k in range(ambient)]


def restrict_rows(rows, basis):
    """Rows composed with a basis stored as ambient row vectors."""
    return [[dot(row, v) for v in basis] for row in rows]


def bits(mask, m):
    return [a for a in range(m) if mask & (1 << a)]


def jsonable(obj):
    if isinstance(obj, F):
        return int(obj) if obj.denominator == 1 else str(obj)
    if isinstance(obj, dict):
        return {str(k): jsonable(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [jsonable(v) for v in obj]
    return obj


def surrounded_supports(n, edges):
    children = [set() for _ in range(n)]
    indegree = [0]*n
    seen = set()
    for u, v in edges:
        if not (0 <= u < n and 0 <= v < n) or u == v or (u, v) in seen:
            raise ValueError("invalid or duplicate directed edge")
        seen.add((u, v)); children[u].add(v); indegree[v] += 1
    queue = [i for i in range(n) if indegree[i] == 0]
    visited = 0
    while queue:
        u = queue.pop(); visited += 1
        for v in children[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)
    if visited != n:
        raise ValueError("graph is not acyclic")
    return [sorted(i for i in children[j] if children[i] <= children[j])
            for j in range(n)]


def residual_spaces(n, edges, trusted_rows):
    M = rational_matrix(trusted_rows, n)
    supports = surrounded_supports(n, edges)
    spaces = []
    for I in supports:
        local = [[row[i] for i in I] for row in M]
        local_basis = null_basis(local, len(I))
        extended = []
        for v in local_basis:
            z = [F(0)]*n
            for i, value in zip(I, v):
                z[i] = value
            extended.append(z)
        spaces.append(extended)
    return supports, spaces


def rado_table(E, channel_spaces):
    """Return r(T) and rho(K) for every channel subset.

    r(T) = dimension of the sum of available restricted row spaces.
    rho(K) = maximal selectable-row rank (classical Rado theorem).
    A subset minimum transform avoids a second nested subset enumeration.
    """
    d, m = len(E), len(channel_spaces)
    W = [restrict_rows(H, E) for H in channel_spaces]
    sums = []
    for mask in range(1 << m):
        rows = [w for a in bits(mask, m) for w in W[a]]
        sums.append(rank(rows, d))
    minima = [sums[mask] - mask.bit_count() for mask in range(1 << m)]
    for a in range(m):
        for mask in range(1 << m):
            if mask & (1 << a):
                minima[mask] = min(minima[mask], minima[mask ^ (1 << a)])
    rho = [mask.bit_count() + minima[mask] for mask in range(1 << m)]
    return {"dimension": d, "sum_ranks": sums, "generic_ranks": rho}


def generic_profile(E, channel_spaces):
    """Exact cut formula for minimum deletions creating k kernel dimensions."""
    table = rado_table(E, channel_spaces)
    d, m = len(E), len(channel_spaces)
    profile, witnesses = [], []
    for k in range(1, d+1):
        candidates = [(m-mask.bit_count()+r-d+k, mask)
                      for mask, r in enumerate(table["sum_ranks"]) if r <= d-k]
        value, cut = min(candidates)
        profile.append(max(0, value))
        witnesses.append({"k": k, "cut_channels": bits(cut, m),
                          "available_rank": table["sum_ranks"][cut],
                          "raw_cut_value": value})
    return {**table, "profile": profile,
            "distance": profile[0] if profile else None, "cut_witnesses": witnesses}


def numerical_table(E, C):
    A = restrict_rows(C, E)
    d, m = len(E), len(C)
    return [rank([A[a] for a in bits(mask, m)], d) for mask in range(1 << m)]


def numerical_profile(E, C):
    d, m = len(E), len(C)
    ranks = numerical_table(E, C)
    values, witnesses = [], []
    ambient = len(E[0]) if E else (len(C[0]) if C else 0)
    A = restrict_rows(C, E)
    for k in range(1, d+1):
        kept = max((mask for mask, r in enumerate(ranks) if r <= d-k),
                   key=lambda mask: (mask.bit_count(), -mask))
        coeffs = null_basis([A[a] for a in bits(kept, m)], d)
        vectors = [linear_combination(c, E, ambient) for c in coeffs]
        removed = [a for a in range(m) if not kept & (1 << a)]
        values.append(len(removed))
        witnesses.append({"k": k, "erased_channels": removed,
                          "surviving_kernel_basis": vectors,
                          "retained_rank": ranks[kept]})
    return {"dimension": d, "profile": values,
            "distance": values[0] if values else None,
            "ranks": ranks, "witnesses": witnesses}


def common_generic_design(spaces, channel_spaces, seed=13371337, max_attempts=2000):
    """Certificate-backed finite search, not a completeness algorithm.

    Every returned matrix attains every theoretical rank for every column and
    channel subset. Failure to find one within max_attempts is inconclusive.
    The mathematical finite-grid existence bound is proved in the manuscript.
    """
    active = [E for E in spaces if E]
    if not active:
        return {"rows": [], "attempts": 0, "rank_checks": 0,
                "status": "already_identified"}
    ambient = len(active[0][0])
    Hs = [row_basis(H, ambient) for H in channel_spaces]
    expected = [rado_table(E, Hs)["generic_ranks"] for E in active]
    rng = random.Random(seed)
    for attempt in range(1, max_attempts+1):
        bound = 2 + attempt//5
        rows = [linear_combination([F(rng.randint(1, bound)) for _ in H], H, ambient)
                for H in Hs]
        got = [numerical_table(E, rows) for E in active]
        if got == expected:
            return {"rows": rows, "attempts": attempt,
                    "rank_checks": len(active)*(1 << len(Hs)), "status": "certified"}
    return {"rows": None, "attempts": max_attempts,
            "rank_checks": 0, "status": "search_exhausted_not_infeasible"}


def dense_completion(spaces, number_rows):
    """Positive integer moment rows with every restriction full spark.

    At each step avoid the finite family of nonzero residual subspaces left
    by subsets of previously chosen rows. The root bound makes the step finite.
    This implementation is exponential in the requested number of channels.
    """
    active = [E for E in spaces if E]
    if not active:
        return [], []
    q = len(active[0][0])
    rows, search_log = [], []
    for h in range(number_rows):
        required = []
        for E in active:
            d = len(E)
            for size in range(min(h, d-1)+1):
                for S in combinations(range(h), size):
                    coeffs = null_basis(restrict_rows([rows[a] for a in S], E), d)
                    V = [linear_combination(c, E, q) for c in coeffs]
                    if V:
                        required.append(V)
        bound = len(required)*max(q-1, 0)+1
        for t in range(1, bound+1):
            row = [F(t)**i for i in range(q)]
            if all(any(dot(row, v) for v in V) for V in required):
                rows.append(row)
                search_log.append({"step": h+1, "families": len(required),
                                   "search_bound": bound, "chosen_t": t})
                break
        else:
            raise AssertionError("polynomial root bound contradicted")
    return rows, search_log


def solve_consistent(rows, rhs, ncols):
    """One rational solution; None if inconsistent. Free variables set to zero."""
    if len(rows) != len(rhs):
        raise ValueError("right-hand side dimension mismatch")
    aug = [list(row)+[F(y)] for row, y in zip(rows, rhs)]
    reduced, pivots = rref(aug, ncols+1)
    if ncols in pivots:
        return None
    x = [F(0)]*ncols
    for i, p in enumerate(pivots):
        x[p] = reduced[i][-1]
    return x


def decode_column(E, C, observations, erased=(), max_errors=0):
    """Exhaustive exact decoder, only for the explicit linear observation model.

    Rejects non-uniqueness instead of returning an arbitrary candidate.
    """
    d, m = len(E), len(C)
    if not E:
        raise ValueError("zero-dimensional case has no column to decode")
    if max_errors < 0:
        raise ValueError("negative error budget")
    if len(observations) != m:
        raise ValueError("observation dimension mismatch")
    erased = set(erased)
    if any(a < 0 or a >= m for a in erased):
        raise ValueError("erased channel index out of range")
    A = restrict_rows(C, E)
    available = [a for a in range(m) if a not in erased]
    solutions = set()
    for size in range(max_errors+1):
        for bad in combinations(available, size):
            kept = [a for a in available if a not in bad]
            coeff = solve_consistent([A[a] for a in kept],
                                     [observations[a] for a in kept], d)
            if coeff is None:
                continue
            # A consistent rank-deficient retained system already supplies
            # infinitely many explanations. Ignoring it can falsely return
            # a unique candidate from another corruption support.
            if rank([A[a] for a in kept], d) < d:
                raise ValueError("decoder found a non-identifiable feasible family")
            mismatches = sum(dot(A[a], coeff) != F(observations[a]) for a in available)
            if mismatches <= max_errors:
                solutions.add(tuple(coeff))
    if len(solutions) != 1:
        raise ValueError("decoder did not find exactly one identifiable candidate")
    coeff = list(next(iter(solutions)))
    return linear_combination(coeff, E, len(E[0]))