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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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""Constant-ray rectangular packet maps and exact augmentation decoding.

Python 3.10+, standard library only. Geometry and payload fields can differ.
The finite packet iteration requires matching characteristic; the direct
rectangular Gaussian decoder does not. Packet matrices need not commute.

The small oblique quotient has (q-1)*L rows and (q-1)*ell columns. Its ordinary
left inverse is applied to radial groups. The error operator is nilpotent in
at most 1+r*(d-1)*(p-1) sweeps; for affine-basis slabs the bound is 1+d*(p-1).
"""

from affine_core import Field, inverse, matvec, rank


def left_inverse(matrix, field):
    """Return D with D*matrix=I; reject deficient column rank.

    Select independent rows by elimination on the transpose, then invert only
    that square minor. For an a-by-b matrix, a>=b, this costs O(a*b*b).
    """
    a = len(matrix)
    b = len(matrix[0]) if a else 0
    if any(len(row) != b for row in matrix):
        raise ValueError("ragged matrix")
    if not b:
        return []
    if a < b:
        raise ValueError("matrix has fewer rows than columns")
    work = [[matrix[i][j] for i in range(a)] for j in range(b)]
    selected = []
    r = 0
    for col in range(a):
        pivot = next((i for i in range(r, b) if work[i][col]), None)
        if pivot is None:
            continue
        work[r], work[pivot] = work[pivot], work[r]
        scale = field.inv(work[r][col])
        work[r] = [field.mul(scale, x) for x in work[r]]
        for i in range(r + 1, b):
            factor = work[i][col]
            if factor:
                work[i] = [
                    field.sub(x, field.mul(factor, y))
                    for x, y in zip(work[i], work[r])
                ]
        selected.append(col)
        r += 1
        if r == b:
            break
    if r != b:
        raise ValueError("matrix does not have full column rank")
    minor_inverse = inverse([matrix[i] for i in selected], field)
    result = [[0] * a for _ in range(b)]
    for row in range(b):
        for j, col in enumerate(selected):
            result[row][col] = minor_inverse[row][j]
    return result


def solve_full_column(matrix, rhs, field):
    """Solve a full-column-rank rectangular system and check consistency."""
    if len(matrix) != len(rhs):
        raise ValueError("right-hand side length mismatch")
    result = matvec(left_inverse(matrix, field), rhs, field)
    if matvec(matrix, result, field) != list(rhs):
        raise ValueError("inconsistent rectangular system")
    return result


def polynomial_matrix(weight, source_length, parity_length):
    """L-by-ell convolution matrix of a scalar polynomial modulo T**L."""
    if source_length < 1 or parity_length < source_length:
        raise ValueError("require 1 <= source_length <= parity_length")
    if len(weight) > parity_length:
        raise ValueError("polynomial exceeds parity precision")
    padded = list(weight) + [0] * (parity_length - len(weight))
    return [
        [padded[u - v] if u >= v else 0 for v in range(source_length)]
        for u in range(parity_length)
    ]


def _prime_span_dimension(vectors, geometry_field):
    """F_p-rank of vectors in the polynomial coordinate representation of F_q."""
    p, r = geometry_field.p, geometry_field.n
    expanded = [
        [(x // (p ** k)) % p for x in vector for k in range(r)]
        for vector in vectors
    ]
    return rank(expanded, Field(p))


class MatrixCodec:
    """Systematic encoder with a constant L-by-ell matrix on each listed ray.

    Geometry is an affine_core.Geometry, whose default rays are 0,e_1,...,e_d.
    A geometry with a different spanning rays list is also supported. Zero ray
    matrices are permitted. Packets are lists/tuples of field element labels.
    """

    def __init__(self, geometry, coefficient, matrices):
        if len(matrices) != len(geometry.rays) or not matrices:
            raise ValueError("one packet matrix per listed ray is required")
        L = len(matrices[0])
        ell = len(matrices[0][0]) if L else 0
        if not 1 <= ell <= L:
            raise ValueError("packet dimensions must satisfy 1 <= ell <= L")
        for matrix in matrices:
            if len(matrix) != L or any(len(row) != ell for row in matrix):
                raise ValueError("all ray matrices must have the same dimensions")
            if any(x not in range(coefficient.q) for row in matrix for x in row):
                raise ValueError("invalid coefficient-field matrix entry")
        self.g, self.f = geometry, coefficient
        self.ell, self.b, self.L = ell, ell, L
        self.A = tuple(tuple(tuple(row) for row in matrix) for matrix in matrices)
        self._sites = set(geometry.sites)
        self._data = set(geometry.data)
        self._prepared = {}

    @classmethod
    def from_polynomials(
        cls, geometry, coefficient, source_length, parity_length, weights
    ):
        """Represent any polynomial assignment, including singular leading terms."""
        matrices = [
            polynomial_matrix(weight, source_length, parity_length)
            for weight in weights
        ]
        result = cls(geometry, coefficient, matrices)
        result.weights = tuple(
            tuple(weight) + (0,) * (parity_length - len(weight))
            for weight in weights
        )
        return result

    def _valid_packet(self, packet, size):
        return len(packet) == size and all(x in range(self.f.q) for x in packet)

    def encode(self, source):
        if set(source) != self._data:
            raise ValueError("source addresses must be precisely the data set")
        if any(not self._valid_packet(x, self.ell) for x in source.values()):
            raise ValueError("invalid source packet")
        out = {site: list(packet) for site, packet in source.items()}
        out.update({site: [0] * self.L for site in self.g.parity})
        for site, packet in source.items():
            for j, matrix in enumerate(self.A):
                parity_site = self.g.project(site, j)
                contribution = matvec(matrix, packet, self.f)
                out[parity_site] = [
                    self.f.add(x, y)
                    for x, y in zip(out[parity_site], contribution)
                ]
        return out

    def block_matrix(self, plan):
        """Direct physical-coordinate matrix, independent of the quotient decoder."""
        h = len(plan["missing"])
        result = [[0] * (h * self.ell) for _ in range(h * self.L)]
        for j in plan["active"]:
            matrix = self.A[j]
            for row, col in enumerate(plan["maps"][j]):
                for u in range(self.L):
                    for v in range(self.ell):
                        a, b = row * self.L + u, col * self.ell + v
                        result[a][b] = self.f.add(result[a][b], matrix[u][v])
        return result

    def _radial_matrix(self, active, gamma):
        gf = self.g.f
        reference = active[0]
        cs = list(range(1, gf.q))
        positions = {c: i for i, c in enumerate(cs)}
        ratios = {j: gf.div(gamma[reference], gamma[j]) for j in active}
        result = [[0] * (len(cs) * self.ell) for _ in range(len(cs) * self.L)]
        for i, c in enumerate(cs):
            for j in active:
                k = positions[gf.mul(ratios[j], c)]
                for u in range(self.L):
                    for v in range(self.ell):
                        row, col = i * self.L + u, k * self.ell + v
                        result[row][col] = self.f.add(result[row][col], self.A[j][u][v])
        return result

    def _slab_matrix(self, active):
        return [
            [self.f.sum(self.A[j][u][v] for j in active) for v in range(self.ell)]
            for u in range(self.L)
        ]

    def certificate(self, method="augmentation"):
        """Return an exact universal certificate or its first failing orientation.

        Augmentation checks one small quotient per normal class in matched
        characteristic. Direct certification checks every physical hyperplane
        and works in any coding characteristic, at a greater computational cost.
        """
        if method not in ("augmentation", "direct"):
            raise ValueError("unknown certification method")
        if method == "augmentation" and self.f.p != self.g.f.p:
            raise ValueError("augmentation certification requires matching characteristic")
        checked = 0
        if method == "direct":
            for normal, offset in self.g.hyperplanes():
                plan = self.g.plan(normal, offset)
                columns = len(plan["missing"]) * self.ell
                if rank(self.block_matrix(plan), self.f) != columns:
                    return {
                        "universal": False, "method": method, "checked": checked + 1,
                        "normal": normal, "offset": offset,
                    }
                checked += 1
        else:
            for normal in self.g.normal_classes():
                a, beta = normal[:-1], normal[-1]
                gamma = [
                    self.g.f.add(beta, self.g.dot(a, w)) for w in self.g.rays
                ]
                active = [j for j, value in enumerate(gamma) if value]
                if not active:
                    return {
                        "universal": False, "method": method, "checked": checked + 1,
                        "normal": normal, "reason": "all rays inactive",
                    }
                matrix = (
                    self._radial_matrix(active, gamma) if any(a)
                    else self._slab_matrix(active)
                )
                if rank(matrix, self.f) != len(matrix[0]):
                    return {
                        "universal": False, "method": method, "checked": checked + 1,
                        "normal": normal, "reason": "deficient augmentation rank",
                    }
                checked += 1
        return {"universal": True, "method": method, "checked": checked}

    def certified(self, method="augmentation"):
        return self.certificate(method)["universal"]

    def residual(self, observed, plan):
        missing = set(plan["missing"])
        needed = (self._data - missing) | set(plan["live"])
        if not needed.issubset(observed):
            raise ValueError("erasures extend outside the supplied containing hyperplane")
        for site, packet in observed.items():
            if site not in self._sites:
                raise ValueError("invalid observed address")
            size = self.L if site[-1] == 0 else self.ell
            if not self._valid_packet(packet, size):
                raise ValueError("invalid observed packet")
        rows = {site: i for i, site in enumerate(plan["live"])}
        result = [list(observed[site]) for site in plan["live"]]
        for site in self.g.data:
            if site in missing:
                continue
            for j, matrix in enumerate(self.A):
                row = rows.get(self.g.project(site, j))
                if row is not None:
                    contribution = matvec(matrix, observed[site], self.f)
                    result[row] = [
                        self.f.sub(x, y) for x, y in zip(result[row], contribution)
                    ]
        return result

    def prepare(self, normal, offset):
        """Prepare an ordinary small quotient left inverse and radial grouping."""
        if self.f.p != self.g.f.p:
            raise ValueError("finite augmentation decoding requires matching characteristic")
        key = (tuple(normal), offset)
        if key in self._prepared:
            return self._prepared[key]
        plan = self.g.plan(normal, offset)
        h = len(plan["missing"])
        if not h:
            prepared = {
                "plan": plan, "h": 0, "groups": [], "B0": [], "D0": [],
                "bound": 0, "row_for_source": [], "relative_maps": {},
            }
            self._prepared[key] = prepared
            return prepared
        active = plan["active"]
        reference = active[0]
        # Align equation rows so the reference ray is the identity; unknown
        # packets retain their original missing-source order.
        row_for_source = [None] * h
        for row, col in enumerate(plan["maps"][reference]):
            row_for_source[col] = row
        relative_maps = {
            j: [plan["maps"][j][row_for_source[i]] for i in range(h)]
            for j in active
        }
        a = plan["normal"][:-1]
        if any(a):
            pivot = next(i for i, x in enumerate(a) if x)
            cs = list(range(1, self.g.q))
            radial_position = {c: i for i, c in enumerate(cs)}
            grouping = {}
            # On the lost hyperplane, the omitted horizontal coordinate is
            # determined by the free coordinates and c. Relative rays translate
            # free coordinates and send c to gamma_ref/gamma_j * c.
            for i, site in enumerate(plan["missing"]):
                tangent = tuple(x for k, x in enumerate(site[:-1]) if k != pivot)
                grouping.setdefault(tangent, [None] * len(cs))[
                    radial_position[site[-1]]
                ] = i
            groups = list(grouping.values())
            if any(None in group for group in groups):
                raise AssertionError("incomplete radial group")
            B0 = self._radial_matrix(active, plan["gamma"])
            bound = 1 + self.g.f.n * (self.g.d - 1) * (self.f.p - 1)
        else:
            groups = [[i] for i in range(h)]
            B0 = self._slab_matrix(active)
            base = self.g.rays[reference]
            differences = [
                tuple(self.g.f.sub(x, y) for x, y in zip(self.g.rays[j], base))
                for j in active
            ]
            e = _prime_span_dimension(differences, self.g.f)
            bound = 1 + e * (self.f.p - 1)
        D0 = left_inverse(B0, self.f)
        prepared = {
            "plan": plan, "h": h, "groups": groups, "B0": B0, "D0": D0,
            "bound": bound, "row_for_source": row_for_source,
            "relative_maps": relative_maps,
        }
        self._prepared[key] = prepared
        return prepared

    def apply_aligned(self, prepared, source_packets):
        """Apply M after reference row alignment, also useful for operator audits."""
        h = prepared["h"]
        if len(source_packets) != h:
            raise ValueError("source array length mismatch")
        if not h:
            return []
        result = [[0] * self.L for _ in range(h)]
        for j in prepared["plan"]["active"]:
            matrix = self.A[j]
            for row, col in enumerate(prepared["relative_maps"][j]):
                contribution = matvec(matrix, source_packets[col], self.f)
                result[row] = [
                    self.f.add(x, y) for x, y in zip(result[row], contribution)
                ]
        return result

    def apply_left_inverse(self, prepared, residual_packets):
        """Apply the small ordinary D0 separately on each tangent fiber."""
        result = [[0] * self.ell for _ in range(prepared["h"])]
        for group in prepared["groups"]:
            flat = [x for i in group for x in residual_packets[i]]
            values = matvec(prepared["D0"], flat, self.f)
            for k, i in enumerate(group):
                result[i] = values[k * self.ell:(k + 1) * self.ell]
        return result

    def error_step(self, prepared, source_packets):
        """Apply I-D0*M; its advertised power vanishes for a certified cut."""
        correction = self.apply_left_inverse(
            prepared, self.apply_aligned(prepared, source_packets)
        )
        return [
            [self.f.sub(x, y) for x, y in zip(packet, delta)]
            for packet, delta in zip(source_packets, correction)
        ]

    def solve_prepared(self, prepared, residual_packets):
        """Solve from surviving-parity order, returning missing-source order."""
        h = prepared["h"]
        if len(residual_packets) != h:
            raise ValueError("residual array length mismatch")
        if not h:
            return []
        rhs = [residual_packets[i] for i in prepared["row_for_source"]]
        values = [[0] * self.ell for _ in range(h)]
        for _ in range(prepared["bound"]):
            applied = self.apply_aligned(prepared, values)
            residual = [
                [self.f.sub(x, y) for x, y in zip(packet, image)]
                for packet, image in zip(rhs, applied)
            ]
            delta = self.apply_left_inverse(prepared, residual)
            values = [
                [self.f.add(x, y) for x, y in zip(packet, step)]
                for packet, step in zip(values, delta)
            ]
        return values

    def decode(self, observed, normal, offset, method="nilpotent", verify=True):
        """Recover the complete source from a full or partial hyperplane erasure."""
        if method not in ("nilpotent", "gaussian"):
            raise ValueError("unknown decoder")
        plan = self.g.plan(normal, offset)
        rhs = self.residual(observed, plan)
        h = len(plan["missing"])
        if not h:
            values, bound, quotient_shape = [], 0, [0, 0]
        elif method == "gaussian":
            flat = solve_full_column(
                self.block_matrix(plan), [x for packet in rhs for x in packet], self.f
            )
            values = [flat[i * self.ell:(i + 1) * self.ell] for i in range(h)]
            bound, quotient_shape = None, None
        else:
            prepared = self.prepare(normal, offset)
            values = self.solve_prepared(prepared, rhs)
            bound = prepared["bound"]
            quotient_shape = [len(prepared["B0"]), len(prepared["B0"][0])]
        missing = set(plan["missing"])
        source = {
            site: list(observed[site]) for site in self.g.data if site not in missing
        }
        source.update(zip(plan["missing"], values))
        if verify:
            rebuilt = self.encode(source)
            if any(rebuilt[site] != list(packet) for site, packet in observed.items()):
                raise ValueError("surviving equations are inconsistent")
        return source, {
            "method": method,
            "unknown_packets": h,
            "source_symbols_per_packet": self.ell,
            "parity_symbols_per_packet": self.L,
            "iterations": bound,
            "small_quotient_shape": quotient_shape,
            "dense_global_solve": method == "gaussian" and h > 0,
        }


def noncommuting_binary_four():
    """Explicit four-bit triple whose nonzero GF(4)-linear sums are nonsingular."""
    return [
        [[int(i == j) for j in range(4)] for i in range(4)],
        [[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0]],
        [[0, 1, 1, 1], [1, 1, 1, 0], [1, 1, 0, 0], [1, 0, 0, 0]],
    ]