File size: 17,480 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
345
346
347
348
349
350
351
352
#!/usr/bin/env python3
"""Exact adversarial regression suite for the calibration release.

Uses only Python's standard library. Exhaustive assertions concern the finite
families explicitly enumerated here; they do not replace the general proofs.
Run from any working directory: python3 code/verify_robust.py
"""
from fractions import Fraction as F
from itertools import product, combinations
from pathlib import Path
import argparse
import json
import time

from calibration_core import (
    rank, null_basis, restrict_rows, residual_spaces, generic_profile,
    numerical_profile, numerical_table, common_generic_design,
    dense_completion, decode_column, dot, linear_combination, jsonable,
)
from plan_robust_calibration import plan

ROOT = Path(__file__).resolve().parents[1]


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def expect_value_error(thunk, message):
    try:
        thunk()
    except ValueError as exc:
        return str(exc)
    raise AssertionError(message)


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


def reference_rank_2(rows):
    """Independent rank oracle in R^2: no elimination or core rank routine."""
    nonzero = [row for row in rows if row[0] or row[1]]
    if not nonzero:
        return 0
    first = nonzero[0]
    if any(first[0]*v[1] != first[1]*v[0] for v in nonzero[1:]):
        return 2
    return 1


def reference_profile_from_ranks(ranks, dimension, m):
    return [min(m-mask.bit_count() for mask, value in enumerate(ranks)
                if value <= dimension-k) for k in range(1, dimension+1)]


def test_architecture_exhaustion():
    e1, e2, ep, em = [F(1), F(0)], [F(0), F(1)], [F(1), F(1)], [F(1), F(-1)]
    E = [e1, e2]
    names = ["zero", "e1", "e2", "e1_plus_e2", "e1_minus_e2", "full_R2"]
    allowed = [[], [e1], [e2], [ep], [em], [e1, e2]]
    choices = [[[F(0), F(0)]], [e1], [e2], [ep], [em], [e1, e2, ep, em]]
    # Extra scalar spaces force the common design to satisfy several different
    # restrictions, not just all subsets of one two-dimensional restriction.
    family = [E, [e1], [e2], [ep], [em]]
    records = []
    assignments = 0
    exact_subset_checks = 0
    attaining_assignments = 0
    common_rank_checks = 0
    max_search_attempts = 0
    for arch_number, architecture in enumerate(product(range(6), repeat=3)):
        Hs = [allowed[a] for a in architecture]
        theory = generic_profile(E, Hs)
        best_ranks = [0]*8
        best_profile = [0, 0]
        jointly_attaining = []
        n_assign = 0
        for rows in product(*(choices[a] for a in architecture)):
            C = [list(row) for row in rows]
            rr = [reference_rank_2([C[a] for a in range(3) if mask & (1 << a)])
                  for mask in range(8)]
            direct = reference_profile_from_ranks(rr, 2, 3)
            got = numerical_profile(E, C)
            require(got["ranks"] == rr, "numerical ranks differ from determinant oracle")
            require(got["profile"] == direct, "numerical profile differs from deletion oracle")
            require(all(a <= b for a, b in zip(rr, theory["generic_ranks"])),
                    "assignment exceeds claimed generic rank")
            require(all(a <= b for a, b in zip(direct, theory["profile"])),
                    "assignment exceeds claimed profile optimum")
            best_ranks = [max(a, b) for a, b in zip(best_ranks, rr)]
            best_profile = [max(a, b) for a, b in zip(best_profile, direct)]
            if rr == theory["generic_ranks"]:
                require(direct == theory["profile"], "attaining ranks fail profile optimum")
                jointly_attaining.append(C)
            n_assign += 1
            assignments += 1
            exact_subset_checks += 8
        require(best_ranks == theory["generic_ranks"], "finite rank maximum does not attain Rado")
        require(best_profile == theory["profile"], "finite profile maximum does not attain cut")
        require(bool(jointly_attaining), "no assignment jointly attains every subset rank")
        attaining_assignments += len(jointly_attaining)
        selected = common_generic_design(family, Hs, seed=13371337+arch_number,
                                         max_attempts=2000)
        require(selected["status"] == "certified", "common search failed on small exhaustive family")
        max_search_attempts = max(max_search_attempts, selected["attempts"])
        for space in family:
            expected = generic_profile(space, Hs)
            actual = numerical_profile(space, selected["rows"])
            require(actual["ranks"] == expected["generic_ranks"],
                    "common design fails a second subspace's rank profile")
            require(actual["profile"] == expected["profile"],
                    "common design fails a second subspace's deletion profile")
            common_rank_checks += 8
        records.append({"architecture": [names[a] for a in architecture],
                        "candidate_assignments": n_assign,
                        "simultaneous_attainers": len(jointly_attaining),
                        "generic_ranks": theory["generic_ranks"],
                        "generic_profile": theory["profile"],
                        "attaining_matrix": jointly_attaining[0],
                        "common_five_space_matrix": selected["rows"],
                        "common_search_attempts": selected["attempts"]})
    require(len(records) == 216, "wrong architecture count")
    require(assignments == 729, "wrong total finite assignment count")
    return {"status": "passed", "architectures": len(records),
            "finite_assignments": assignments,
            "independent_subset_rank_checks": exact_subset_checks,
            "assignments_attaining_all_subset_ranks": attaining_assignments,
            "common_five_space_designs": len(records),
            "common_design_subset_rank_checks": common_rank_checks,
            "largest_common_search_attempt_count": max_search_attempts,
            "records": records}


def dense_spec(n, r):
    return {"n": n, "edges": [[i, j] for i in range(n) for j in range(i+1, n)],
            "trusted_rows": [], "sensor_spaces": [identity(n) for _ in range(r)],
            "erasures": 1, "errors": 1, "seed": 13371337}


def test_dense_faults():
    spec = dense_spec(4, 6)
    supports, spaces = residual_spaces(4, spec["edges"], [])
    require(list(map(len, spaces)) == [3, 2, 1, 0], "complete-DAG dimensions wrong")
    C, search = dense_completion(spaces, 6)
    profiles = [numerical_profile(E, C) for E in spaces]
    require([p["profile"] for p in profiles] == [[4, 5, 6], [5, 6], [6], []],
            "dense MDS deletion profile wrong")
    coeffs = [[F(1, 3), F(-2), F(5, 7)], [F(2), F(-1, 2)], [F(-3, 5)]]
    vectors = [linear_combination(z, E, 4) for z, E in zip(coeffs, spaces)]
    errors = [F(-7, 3), F(1), F(5, 2)]
    scenarios = 0
    decodes = 0
    for erased in [()] + [(a,) for a in range(6)]:
        available = [a for a in range(6) if a not in erased]
        corruptions = [(None, F(0))] + [(a, value) for a in available for value in errors]
        for bad, value in corruptions:
            scenarios += 1
            for j, (E, vector) in enumerate(zip(spaces, vectors)):
                y = [dot(row, vector) for row in C]
                if bad is not None:
                    y[bad] += (j+1)*value
                for a in erased:
                    y[a] = None
                decoded = decode_column(E, C, y, erased=erased, max_errors=1)
                require(decoded == vector, "dense erased/corrupted recovery failed")
                decodes += 1
    require(scenarios == 115 and decodes == 345, "wrong dense fault test count")
    # The data at one fewer channel have two exact explanations under the same
    # erasure/error budgets. This checks the lower bound, not only success.
    C5, _ = dense_completion(spaces, 5)
    cert5 = numerical_profile(spaces[0], C5)
    require(cert5["distance"] == 3, "below-threshold distance should be three")
    witness = cert5["witnesses"][0]
    vector = witness["surviving_kernel_basis"][0]
    encoded = [dot(row, vector) for row in C5]
    support = [a for a, value in enumerate(encoded) if value]
    require(len(support) == 3, "lower-bound witness is not minimum support")
    erased, bad0, bad1 = support
    y = [F(0)]*5
    y[bad0] = encoded[bad0]
    y[erased] = None
    require(sum(y[a] != 0 for a in range(5) if a != erased) == 1,
            "zero model needs more than one error")
    require(sum(y[a] != encoded[a] for a in range(5) if a != erased) == 1,
            "alternative model needs more than one error")
    reject = expect_value_error(
        lambda: decode_column(spaces[0], C5, y, erased=(erased,), max_errors=1),
        "decoder accepted nonunique below-threshold data")
    return {"status": "passed", "residual_dimensions": list(map(len, spaces)),
            "six_channel_matrix": C, "construction_steps": search,
            "profiles": [p["profile"] for p in profiles],
            "tested_error_amplitudes": errors, "fault_scenarios": scenarios,
            "successful_column_decodes": decodes,
            "below_threshold": {"channels": 5, "matrix": C5,
                                "distance": 3, "alternative_vector": vector,
                                "encoded_difference": encoded,
                                "erased": [erased], "attack_for_zero": [bad0],
                                "attack_for_alternative": [bad1], "common_data": y,
                                "decoder_rejection": reject}}


def spark_exact(A):
    """Enumerate dependent column sets; n+1 denotes full column rank."""
    n = len(A[0]) if A else 0
    for size in range(1, n+1):
        for S in combinations(range(n), size):
            sub = [[row[a] for a in S] for row in A]
            if rank(sub, size) < size:
                local = null_basis(sub, size)[0]
                vector = [F(0)]*n
                for a, value in zip(S, local):
                    vector[a] = value
                require(any(vector), "zero spark witness")
                require(all(dot(row, vector) == 0 for row in A), "invalid spark witness")
                return size, vector
    return n+1, None


def star_spec(A, erasures=0, errors=0):
    leaves = len(A[0])
    n = leaves+1
    return {"n": n, "edges": [[0, i] for i in range(1, n)],
            "trusted_rows": [[F(0)]+list(row) for row in A],
            "sensor_spaces": [[[F(0)]+row] for row in identity(leaves)],
            "erasures": erasures, "errors": errors, "seed": 13371337}


def star_report(A):
    spec = star_spec(A)
    supports, spaces = residual_spaces(spec["n"], spec["edges"], spec["trusted_rows"])
    C = [H[0] for H in spec["sensor_spaces"]]
    require(all(not E for E in spaces[1:]), "star has unexpected non-root ambiguity")
    actual = numerical_profile(spaces[0], C)
    spark, witness = spark_exact(A)
    require(actual["distance"] == spark, "causal star distance differs from spark")
    require(generic_profile(spaces[0], spec["sensor_spaces"])["profile"] == actual["profile"],
            "fixed coordinate architecture profile mismatch")
    return {"parity_matrix": A, "spark": spark, "spark_witness": witness,
            "causal_vertices": spec["n"], "residual_dimension": len(spaces[0]),
            "causal_distance": actual["distance"], "profile": actual["profile"]}


def test_stars_and_coefficients():
    A = [[F(1), F(0), F(1), F(1)], [F(0), F(1), F(1), F(-1)]]
    n = 4
    dup = [row+[F(0)]*n for row in A]
    dup += [row+[-x for x in row] for row in identity(n)]
    first, second = star_report(A), star_report(dup)
    require(first["spark"] == 3 and second["spark"] == 6, "spark doubling wrong")
    require(first["profile"] == [3, 4] and second["profile"] == [6, 8],
            "duplicated generalized weights wrong")
    original_kernel = null_basis(A, 4)
    expected_dup = [v+v for v in original_kernel]
    duplicate_kernel = null_basis(dup, 8)
    require(rank(expected_dup+duplicate_kernel, 8) == len(original_kernel),
            "duplicated parity kernel is not diagonal copy of original")
    generic = [[F(1)]*4, [F(1), F(2), F(3), F(4)]]
    exceptional = [[F(1)]*4, [F(1), F(1), F(3), F(4)]]
    require([[bool(x) for x in row] for row in generic] ==
            [[bool(x) for x in row] for row in exceptional], "patterns differ")
    third, fourth = star_report(generic), star_report(exceptional)
    require(third["causal_distance"] == 3 and fourth["causal_distance"] == 2,
            "same-pattern exceptional cancellation was not detected")
    return {"status": "passed", "spark_three": first, "duplicated_spark_six": second,
            "same_pattern_generic": third, "same_pattern_exceptional": fourth}


def test_decoder_regression():
    E = identity(2)
    C = identity(2)
    # Before the fix, the zero-error branch supplied zero and all one-error
    # branches were silently skipped for lack of rank. The decoder returned
    # zero despite whole affine families of other feasible explanations.
    message = expect_value_error(
        lambda: decode_column(E, C, [0, 0], max_errors=1),
        "rank-deficient feasible families must cause non-identifiability")
    require("non-identifiable feasible family" in message,
            "regression did not exercise the rank-deficient-family branch")
    require(decode_column(E, C, [F(3, 2), F(-7, 4)], max_errors=0) == [F(3, 2), F(-7, 4)],
            "ordinary exact decoding was broken")
    messages = {
        "negative_error_budget": expect_value_error(
            lambda: decode_column(E, C, [0, 0], max_errors=-1), "negative errors accepted"),
        "wrong_observation_length": expect_value_error(
            lambda: decode_column(E, C, [0]), "wrong observation count accepted"),
        "erasure_out_of_range": expect_value_error(
            lambda: decode_column(E, C, [0, 0], erased=(2,)), "invalid erasure accepted"),
    }
    return {"status": "passed", "nonidentifiability_regression": message,
            "input_validation": messages, "checks": 5}


def write_examples():
    folder = ROOT / "examples"
    folder.mkdir(exist_ok=True)
    A = [[F(1), F(0), F(1), F(1)], [F(0), F(1), F(1), F(-1)]]
    dup = [row+[F(0)]*4 for row in A]
    dup += [row+[-x for x in row] for row in identity(4)]
    specs = {
        "dense_complete_four": dense_spec(4, 6),
        "dense_complete_four_below_threshold": dense_spec(4, 5),
        "star_spark_three": star_spec(A, errors=1),
        "star_spark_six": star_spec(dup, erasures=1, errors=2),
        "same_pattern_generic": star_spec([[F(1)]*4, [F(1), F(2), F(3), F(4)]], errors=1),
        "same_pattern_exceptional": star_spec([[F(1)]*4, [F(1), F(1), F(3), F(4)]], errors=1),
    }
    reports = []
    expected = [True, False, True, True, True, False]
    for (name, spec), should_work in zip(specs.items(), expected):
        (folder / (name+".json")).write_text(json.dumps(jsonable(spec), indent=2)+"\n")
        certificate = plan(jsonable(spec))
        require(certificate["requested_tolerance_possible"] is should_work,
                "planner returns wrong feasibility on "+name)
        require(certificate["design"]["status"] == "certified", "planner design search failed")
        (folder / (name+"_certificate.json")).write_text(json.dumps(certificate, indent=2)+"\n")
        reports.append({"input": name+".json", "certificate": name+"_certificate.json",
                        "requested_tolerance_possible": should_work,
                        "optimal_distance": certificate["optimal_architecture_distance"]})
    return reports


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=ROOT / "results" / "robust_results.json")
    args = parser.parse_args()
    started = time.monotonic()
    result = {"status": "passed", "arithmetic": "fractions.Fraction; exact rational checks",
              "seed": 13371337,
              "scope": "finite exhaustive regression and witness checks, not formal proof-assistant certification",
              "architecture_exhaustion": test_architecture_exhaustion(),
              "dense_fault_recovery": test_dense_faults(),
              "causal_stars": test_stars_and_coefficients(),
              "decoder_regression": test_decoder_regression(),
              "planner_examples": write_examples()}
    result["elapsed_seconds"] = round(time.monotonic()-started, 3)
    args.output.parent.mkdir(exist_ok=True, parents=True)
    args.output.write_text(json.dumps(jsonable(result), indent=2)+"\n")
    summary = {"status": result["status"], "architectures": 216, "candidate_assignments": 729,
               "independent_subset_rank_checks": result["architecture_exhaustion"]["independent_subset_rank_checks"],
               "common_design_subset_rank_checks": result["architecture_exhaustion"]["common_design_subset_rank_checks"],
               "fault_scenarios": result["dense_fault_recovery"]["fault_scenarios"],
               "successful_column_decodes": result["dense_fault_recovery"]["successful_column_decodes"],
               "planner_examples": len(result["planner_examples"]),
               "elapsed_seconds": result["elapsed_seconds"], "output": str(args.output)}
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()