File size: 16,858 Bytes
54f300b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""Sparse affine-hyperplane recovery by twisted binary convolution.

Physical addresses are (u, c), with u a d-bit integer, c in {0,1};
c=1 stores a scalar source in GF(2**m), c=0 stores scalar parity.
All arithmetic is exact. This is a reference codec, not a storage protocol.
"""
from itertools import product

from affine_core import Field, inverse


def dot(a, b):
    return (a & b).bit_count() & 1


def binary_apply(rows, value):
    return sum(dot(row, value) << j for j, row in enumerate(rows))


def binary_inverse(rows):
    d = len(rows)
    matrix = [[(row >> j) & 1 for j in range(d)] for row in rows]
    inv = inverse(matrix, Field(2))
    return [sum(x << j for j, x in enumerate(row)) for row in inv]


def binary_transpose(rows):
    return [sum(((rows[j] >> i) & 1) << j for j in range(len(rows)))
            for i in range(len(rows))]


def independent_binary_basis(values, dimension):
    """Extend independent bit-vector labels to the requested dimension."""
    chosen, span = [], {0}
    for value in values:
        if value in span:
            raise ValueError("dependent initial field elements")
        chosen.append(value)
        span |= {x ^ value for x in tuple(span)}
    if len(chosen) > dimension:
        raise ValueError("too many initial elements")
    candidate = 1
    while len(chosen) < dimension:
        if candidate not in span:
            chosen.append(candidate)
            span |= {x ^ candidate for x in tuple(span)}
        candidate += 1
    return chosen


def optimal_kernel(d, field):
    """Alphabet-optimal construction; support ceil(3*d/2), for d>=2.

Returns (T, kernel), with T represented by binary row masks. The support
count is an achieved bound, not a general minimum-support theorem.
"""
    if field.p != 2 or d < 1:
        raise ValueError("binary characteristic and positive dimension required")
    if d == 1:
        if field.n < 2:
            raise ValueError("dimension one requires at least GF(4)")
        return [1], {0: 1, 1: 2}
    blocks = (d + 1) // 2
    if field.n < blocks:
        raise ValueError("alphabet degree below the exact existence threshold")
    rows, kernel = [0] * d, {}
    if d % 2 == 0:
        basis = [1 << i for i in range(blocks)]
        basis[0] = 1
        for value in basis[1:]:
            basis[0] ^= value
        offset, weights = 0, basis
    else:
        alpha = 2
        square = field.mul(alpha, alpha)
        lam, v = square ^ alpha, 1 ^ square
        basis = independent_binary_basis([lam, v], blocks)
        nu = v
        for value in basis[2:]:
            nu ^= value
        kernel.update({1: lam, 2: nu, 4: lam ^ nu, 5: square, 6: nu})
        rows[:3] = [1, 3, 6]
        offset, weights = 3, basis[2:]
    for i, weight in enumerate(weights):
        j = offset + 2*i
        a, b = 1 << j, 1 << (j+1)
        kernel[a] = kernel[b] = kernel[a ^ b] = weight
        rows[j], rows[j+1] = b, a ^ b
    if any(not x for x in kernel.values()):
        raise AssertionError("construction unexpectedly contains a zero weight")
    # rows is R=T^{-t} on normal vectors.
    transform = binary_transpose(binary_inverse(rows))
    return transform, kernel


class TwistedCodec:
    def __init__(self, d, field, transform, kernel):
        if field.p != 2 or not isinstance(d, int) or d < 1:
            raise ValueError("positive dimension and characteristic two required")
        self.d, self.f, self.n = d, field, 1 << d
        if len(transform) != d or any(x not in range(self.n) for x in transform):
            raise ValueError("invalid binary transform")
        self.transform = tuple(transform)
        self.inverse_transform = tuple(binary_inverse(transform))
        if any(w not in range(self.n) or a not in range(field.q)
               for w, a in kernel.items()):
            raise ValueError("invalid kernel entry")
        self.kernel = {w: a for w, a in kernel.items() if a}
        self.forward = [binary_apply(transform, u) for u in range(self.n)]
        self.backward = [binary_apply(self.inverse_transform, z) for z in range(self.n)]
        self.normal_transform = binary_transpose(self.inverse_transform)
        self.sigma = field.sum(self.kernel.values())
        self._plan_cache = {}

    @classmethod
    def optimal(cls, d, field=None):
        """Explicit alphabet-optimal family; its support need not be minimal."""
        if field is None:
            field = Field(2, 2 if d == 1 else (d+1)//2)
        transform, kernel = optimal_kernel(d, field)
        return cls(d, field, transform, kernel)

    @classmethod
    def minimum_support_example(cls,d):
        """Finite exact examples attaining both optima in dimensions 2..6."""
        if d==2:
            return cls.optimal(2)
        cases={
            3:([1,1,3,2],[2,4,3]),
            4:([1,3,1,3,1],[7,10,9,12]),
            5:([4,6,3,7,2,5],[14,7,17,25,2]),
            6:([3,7,5,4,2,2,4],[14,28,32,20,7,63]),
        }
        if d not in cases:
            raise ValueError("finite examples are supplied only for d=2..6")
        weights,normal_rows=cases[d]
        degree=(d+1)//2
        field=Field(2,degree,[1,1,1] if degree==2 else [1,1,0,1])
        kernel={0:weights[0]}|{1<<i:weights[i+1] for i in range(d)}
        return cls(d,field,binary_transpose(binary_inverse(normal_rows)),kernel)

    def quadratic(self, a):
        """Evaluate a^t S T^{-t}a using exact sparse moment sums."""
        b = binary_apply(self.normal_transform, a)
        ma = mb = mixed = 0
        for w, coefficient in self.kernel.items():
            aw, bw = dot(a, w), dot(b, w)
            if aw:
                ma ^= coefficient
            if bw:
                mb ^= coefficient
            if aw and bw:
                mixed ^= coefficient
        return self.f.mul(self.sigma, mixed) ^ self.f.mul(ma, mb)

    def certificate(self):
        """Exhaustive small moment certificate, independent of packet values."""
        if not self.sigma:
            return {"valid": False, "failure": "zero augmentation", "normal": 0}
        for a in range(1, self.n):
            if not self.quadratic(a):
                return {"valid": False, "failure": "zero quadratic value", "normal": a}
        return {"valid": True, "normal_checks": self.n-1,
                "support": len(self.kernel), "alphabet_size": self.f.q}

    def obstruction(self):
        """Return a bad hyperplane and a nonzero invisible source difference.

        A valid encoder returns None. A rejected encoder receives an exact
        collision witness over its original coding field, not an extension.
        """
        certificate = self.certificate()
        if certificate["valid"]:
            return None
        if not self.sigma:
            return {"plane":(0,1,1),"difference":[1]*self.n,
                    "reason":"zero augmentation"}
        a = certificate["normal"]
        b = binary_apply(self.normal_transform,a)
        difference = [0]*self.n
        if a == b:
            halves = [0,0]
            for w,value in self.kernel.items():
                halves[dot(a,w)] ^= value
            zero_half = next(i for i,x in enumerate(halves) if x == 0)
            plane = (a,1 ^ zero_half,0)
            for u in range(self.n):
                if self.on((u,1),plane):
                    difference[u]=1
        else:
            plane=(a,0,0)
            table=[[0,0],[0,0]]
            for w,value in self.kernel.items():
                table[dot(b,w)][dot(a,w)^1] ^= value
            row=next((r for r in table if any(r)),None)
            vector=[row[1],row[0]] if row is not None else [1,0]
            assert any(vector) and all(self.f.sum(self.f.mul(x,y) for x,y in zip(r,vector))==0
                                      for r in table)
            for u in range(self.n):
                z=self.forward[u]
                if dot(b,z)==0:
                    difference[u]=vector[dot(a,z)]
        assert any(difference)
        return {"plane":plane,"difference":difference,"reason":"zero quadratic value"}

    def on(self, address, plane):
        u, c = address
        a, beta, tau = plane
        return (dot(a, u) ^ (beta & c)) == tau

    def hyperplanes(self):
        for a in range(self.n):
            for beta in (0, 1):
                if a or beta:
                    for tau in (0, 1):
                        yield a, beta, tau

    def containing_hyperplane(self, erased):
        """Infer a containing hyperplane from erased physical addresses."""
        erased = list(erased)
        if any(not isinstance(s, tuple) or len(s) != 2 or
               s[0] not in range(self.n) or s[1] not in (0, 1) for s in erased):
            raise ValueError("invalid erased address")
        if not erased:
            return 0, 1, 0
        rows = [u | (c << self.d) | (1 << (self.d+1)) for u, c in erased]
        width, pivot_cols, r = self.d+2, [], 0
        for col in range(width):
            pivot = next((i for i in range(r, len(rows)) if (rows[i] >> col) & 1), None)
            if pivot is None:
                continue
            rows[r], rows[pivot] = rows[pivot], rows[r]
            for i in range(len(rows)):
                if i != r and (rows[i] >> col) & 1:
                    rows[i] ^= rows[r]
            pivot_cols.append(col)
            r += 1
            if r == len(rows):
                break
        free = next((c for c in range(width) if c not in pivot_cols), None)
        if free is None:
            raise ValueError("erased set is not contained in an affine hyperplane")
        vector = 1 << free
        for row, col in zip(rows, pivot_cols):
            if dot(row, vector):
                vector |= 1 << col
        a = vector & (self.n-1)
        beta, tau = (vector >> self.d) & 1, (vector >> (self.d+1)) & 1
        if not (a or beta) or not all(self.on(s, (a,beta,tau)) for s in erased):
            raise AssertionError("invalid inferred hyperplane")
        return a, beta, tau

    def encode(self, source):
        if len(source) != self.n or any(x not in range(self.f.q) for x in source):
            raise ValueError("one valid source scalar per data site required")
        parity, mul = [0]*self.n, self.f.multiplication
        for u, value in enumerate(source):
            if value:
                z = self.forward[u]
                for w, coefficient in self.kernel.items():
                    parity[z ^ w] ^= mul[coefficient][value]
        return {(u,1): x for u,x in enumerate(source)} | {(v,0): y for v,y in enumerate(parity)}

    def _plan(self, plane):
        plane = tuple(plane)
        if plane in self._plan_cache:
            return self._plan_cache[plane]
        if len(plane) != 3:
            raise ValueError("plane must be (normal,beta,offset)")
        a, beta, tau = plane
        if a not in range(self.n) or beta not in (0,1) or tau not in (0,1) or not (a or beta):
            raise ValueError("invalid affine hyperplane")
        missing = [u for u in range(self.n) if self.on((u,1), plane)]
        live = [v for v in range(self.n) if not self.on((v,0), plane)]
        plan = {"missing": missing, "missing_set": set(missing), "live": live,
                "live_set": set(live), "plane": plane}
        if a == 0:
            plan["kind"] = "slab" if missing else "parity"
        else:
            b = binary_apply(self.normal_transform, a)
            s, t = tau ^ beta, tau ^ 1
            if a == b:
                group = [w for w in range(self.n) if not dot(a,w)]
                z0 = next(z for z in range(self.n) if dot(b,z) == s)
                v0 = next(v for v in range(self.n) if dot(a,v) == t)
                kernel = {w ^ v0 ^ z0: value for w,value in self.kernel.items()
                          if not dot(a, w ^ v0 ^ z0)}
                delta = self.f.sum(kernel.values())
                plan.update(kind="coincident", group=group, sources=[z0], targets=[v0],
                            kernels=[[kernel]], delta=delta)
            else:
                group = [w for w in range(self.n) if not dot(a,w) and not dot(b,w)]
                zs = [next(z for z in range(self.n) if dot(a,z) == i and dot(b,z) == s)
                      for i in (0,1)]
                vs = [next(v for v in range(self.n) if dot(a,v) == t and dot(b,v) == i)
                      for i in (0,1)]
                kernels = [[{} for _ in (0,1)] for _ in (0,1)]
                for w, value in self.kernel.items():
                    row, col = dot(b,w) ^ s, dot(a,w) ^ t
                    shift = w ^ vs[row] ^ zs[col]
                    assert not dot(a,shift) and not dot(b,shift)
                    kernels[row][col][shift] = value
                aug = [[self.f.sum(h.values()) for h in row] for row in kernels]
                delta = self.f.mul(aug[0][0],aug[1][1]) ^ self.f.mul(aug[0][1],aug[1][0])
                plan.update(kind="independent", group=group, sources=zs, targets=vs,
                            kernels=kernels, delta=delta)
            if not plan["delta"]:
                raise ValueError("singular recovery cut")
        self._plan_cache[plane] = plan
        return plan

    def _convolve(self, kernel, values, group):
        mul = self.f.multiplication
        result = {w: 0 for w in group}
        for shift, coefficient in kernel.items():
            row = mul[coefficient]
            for w in group:
                result[w] ^= row[values[w ^ shift]]
        return result

    def decode(self, observed, plane=None, verify=True):
        if any(not isinstance(s,tuple) or len(s) != 2 or s[0] not in range(self.n)
               or s[1] not in (0,1) or value not in range(self.f.q)
               for s,value in observed.items()):
            raise ValueError("invalid observed address or scalar")
        if plane is None:
            erased = [(u,c) for u in range(self.n) for c in (0,1) if (u,c) not in observed]
            plane = self.containing_hyperplane(erased)
        plan = self._plan(plane)
        missing, live = plan["missing_set"], plan["live_set"]
        if any((u,1) not in observed for u in range(self.n) if u not in missing) or any(
                (v,0) not in observed for v in live):
            raise ValueError("erasures extend outside the containing hyperplane")
        residual = {v: observed[(v,0)] for v in live}
        mul = self.f.multiplication
        for u in range(self.n):
            if u not in missing:
                value, z = observed[(u,1)], self.forward[u]
                if value:
                    for w, coefficient in self.kernel.items():
                        v = z ^ w
                        if v in live:
                            residual[v] ^= mul[coefficient][value]
        source = [0 if u in missing else observed[(u,1)] for u in range(self.n)]
        kind = plan["kind"]
        layers = 0
        if kind == "slab":
            if not self.sigma:
                raise ValueError("singular all-data slab")
            values = self._convolve(self.kernel,residual,range(self.n))
            scale = self.f.inv(self.f.mul(self.sigma,self.sigma))
            for z, value in values.items():
                source[self.backward[z]] = mul[scale][value]
            layers = 1
        elif kind in ("coincident","independent"):
            group, kernels = plan["group"], plan["kernels"]
            ys = [{w: residual[v ^ w] for w in group} for v in plan["targets"]]
            if kind == "coincident":
                xs = [self._convolve(kernels[0][0],ys[0],group)]
                layers = 1
            else:
                h00,h01 = kernels[0]
                h10,h11 = kernels[1]
                p0,q0 = self._convolve(h11,ys[0],group),self._convolve(h01,ys[1],group)
                p1,q1 = self._convolve(h10,ys[0],group),self._convolve(h00,ys[1],group)
                adj = [{w:p0[w]^q0[w] for w in group},{w:p1[w]^q1[w] for w in group}]
                xs = []
                for values in adj:
                    left = self._convolve(h00,self._convolve(h11,values,group),group)
                    right = self._convolve(h01,self._convolve(h10,values,group),group)
                    xs.append({w:left[w]^right[w] for w in group})
                layers = 3
            scale = self.f.inv(self.f.mul(plan["delta"],plan["delta"]))
            for z0, values in zip(plan["sources"],xs):
                for w,value in values.items():
                    source[self.backward[z0 ^ w]] = mul[scale][value]
        if verify:
            rebuilt = self.encode(source)
            if any(rebuilt[s] != value for s,value in observed.items()):
                raise ValueError("surviving observations are inconsistent")
        return source, {"kind":kind,"convolution_layers":layers,
                        "missing_data":len(missing),"live_parity":len(live),
                        "plane":list(plane)}