File size: 16,974 Bytes
3b80460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproduce component-frontier constructions and algebraic certificates.

All n=3..60, K=1..n+2, and 2n cyclic deletion offsets are checked. Complete
offset coverage follows an independently checked geometric rotation identity;
actual interval unions are checked at every sampled normal for the base offset.
The classical regular-polygon SMT theorem is an explicit proof dependency,
not a numerical conclusion of this script.
"""

from __future__ import annotations

import json
import math
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

from complexity_frontier import (
    PI, STEINER_DEPENDENCY, side_length, frontier_length, frontier_lower_bounds,
    regular_vertices, construction, graph_component_count,
    connected_repair_cost, repair_segments, penalized_optimum, joint_penalty_limit,
)
from finite_audit import alternating_polygon, missed_length_at_angle, maximal_required_gap

HERE = Path(__file__).resolve().parent


def verify():
    records = []
    offset_case_count = 0
    maxima = {"length_error": 0.0, "sampled_missed_length": 0.0,
              "sampled_required_gap": 0.0, "lower_bound_formula_error": 0.0,
              "rotation_equivariance_error": 0.0, "repair_length_error": 0.0,
              "repair_steiner_lower_bound_error": 0.0}
    for n in range(3, 61):
        vertices = regular_vertices(n)
        indices = np.arange(2 * n)
        d = side_length(n)
        rotations = []
        # Validate every vertex and hence every possible retained edge under
        # each cyclic offset. This is independent of the deletion subset.
        for offset in range(2 * n):
            phi = offset * PI / n
            rotation = np.array([[math.cos(phi), -math.sin(phi)],
                                  [math.sin(phi), math.cos(phi)]])
            error = float(np.max(np.abs(vertices @ rotation.T
                                         - vertices[(indices + offset) % (2 * n)])))
            assert error < 3e-14
            maxima["rotation_equivariance_error"] = max(maxima["rotation_equivariance_error"], error)
            # The entire normal grid is permuted by the same rotation.
            normals = np.mod(np.arange(n) * PI / n + phi, PI)
            expected = np.arange(n) * PI / n
            nearest_grid_error = np.min(np.abs(
                (normals[:, None] - expected[None, :] + PI / 2) % PI - PI / 2), axis=1)
            assert float(nearest_grid_error.max()) < 3e-14
            rotations.append(error)
        for budget in range(1, n + 3):
            q = min(budget, n)
            base = construction(n, budget, offset=1)
            length = float(np.linalg.norm(base["segments"][:, 1]
                                           - base["segments"][:, 0], axis=1).sum())
            expected = frontier_length(n, budget)
            length_error = abs(length - expected)
            lower = frontier_lower_bounds(n, budget)
            lower_error = abs(lower["combined_bound"] - expected)
            normals = np.arange(n) * PI / n
            missed = max(missed_length_at_angle(base["segments"], theta) for theta in normals)
            gap = max(maximal_required_gap(base["segments"], theta) for theta in normals)
            assert length_error < 2e-12 and lower_error < 2e-12
            assert missed < 2e-10 and gap < 2e-10
            # Check every offset combinatorially; the rotation identity above
            # transfers each full interval-union certificate to that offset.
            for offset in range(2 * n):
                shifted = construction(n, budget, offset)
                removed = shifted["deleted_edge_indices"]
                assert len(set(map(int, removed))) == q
                assert np.all(removed % 2 == offset % 2)
                retained = set(map(int, shifted["retained_edge_indices"]))
                opposite_parity = {j for j in range(2 * n) if j % 2 != offset % 2}
                assert opposite_parity.issubset(retained)
                assert graph_component_count(n, shifted["retained_edge_indices"]) == q
                # Exact integer edge accounting, separate from geometric float tests.
                assert len(retained) == 2 * n - q
                assert len(retained) + (q - 1) == 2 * n - 1
                offset_case_count += 1
            maxima["length_error"] = max(maxima["length_error"], length_error)
            maxima["sampled_missed_length"] = max(maxima["sampled_missed_length"], missed)
            maxima["sampled_required_gap"] = max(maxima["sampled_required_gap"], gap)
            maxima["lower_bound_formula_error"] = max(maxima["lower_bound_formula_error"], lower_error)
            records.append({"n": n, "K": budget, "realized_components": q,
                            "side_length": d, "formula_length": expected,
                            "measured_length": length,
                            "projection_lower_bound": lower["projection_bound"],
                            "component_steiner_lower_bound": lower["component_steiner_bound"],
                            "combined_lower_bound": lower["combined_bound"],
                            "max_base_sample_missed_length": missed,
                            "max_base_sample_gap": gap,
                            "verified_cyclic_offsets": 2 * n})
        alternating = alternating_polygon(n)
        added = repair_segments(n)
        repaired = np.concatenate((alternating, added), axis=0)
        added_length = float(np.linalg.norm(added[:, 1] - added[:, 0], axis=1).sum())
        total = float(np.linalg.norm(repaired[:, 1] - repaired[:, 0], axis=1).sum())
        steiner_minimum = (2 * n - 1) * d
        error = abs(added_length - connected_repair_cost(n))
        lower_error = abs(total - steiner_minimum)
        assert error < 2e-12 and lower_error < 2e-12
        assert graph_component_count(n, [j for j in range(2 * n) if j != 1]) == 1
        maxima["repair_length_error"] = max(maxima["repair_length_error"], error)
        maxima["repair_steiner_lower_bound_error"] = max(maxima["repair_steiner_lower_bound_error"], lower_error)
    return records, offset_case_count, maxima


def make_figure():
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                         "axes.titlesize": 12, "axes.labelsize": 10})
    fig, axes = plt.subplots(3, 2, figsize=(12.6, 12.8))
    fig.patch.set_facecolor("#f8fafc")
    for ax in axes.ravel():
        ax.set_facecolor("white")
        ax.spines[["top", "right"]].set_visible(False)
    ax = axes[0, 0]
    example = construction(12, 3, offset=1)
    theta = np.linspace(0, 2 * PI, 601)
    ax.plot(np.cos(theta), np.sin(theta), ls="--", lw=1, color="#94a3b8")
    palette = ["#2563eb", "#8b5cf6", "#0891b2"]
    # Colors identify the three connected polygonal paths after deleting edges1,3,5.
    for index, segment in zip(example["retained_edge_indices"], example["segments"]):
        group = 0 if index == 2 else (1 if index == 4 else 2)
        ax.plot(segment[:, 0], segment[:, 1], lw=4, color=palette[group],
                solid_capstyle="round")
    for index in example["deleted_edge_indices"]:
        points = example["vertices"][[index, (index + 1) % 24]]
        ax.plot(points[:, 0], points[:, 1], ls=":", color="#dc2626", lw=1.8)
    ax.set_aspect("equal"); ax.set_xlim(-1.12, 1.12); ax.set_ylim(-1.12, 1.12)
    ax.set_title("A. Exact construction: $n=12$, $K=3$", loc="left", fontweight="bold")
    ax.set_xlabel("$x$"); ax.set_ylabel("$y$")
    ax.text(0.04, 0.03, "Delete three edges of one parity.\nRetain every required contact vertex.",
            transform=ax.transAxes, fontsize=8, color="#475569",
            bbox={"facecolor": "white", "edgecolor": "none", "alpha": .9})

    ax = axes[0, 1]
    for n, color in zip([8, 16, 32, 64], ["#94a3b8", "#0891b2", "#8b5cf6", "#2563eb"]):
        budgets = np.arange(1, int(1.3 * n) + 1)
        values = [frontier_length(n, int(k)) / PI for k in budgets]
        ax.plot(budgets / n, values, color=color, lw=2, label=f"$n={n}$")
    ax.axhline(1, color="#64748b", ls="--", lw=1)
    ax.axvline(1, color="#cbd5e1", ls=":", lw=1)
    ax.set_xlim(0, 1.25); ax.set_ylim(.96, 2.04)
    ax.set_xlabel("Relative component budget $K/n$")
    ax.set_ylabel("Exact sampled optimum / $\\pi$")
    ax.set_title("B. The sharp complexity / length frontier", loc="left", fontweight="bold")
    ax.legend(frameon=False, fontsize=8)
    ax.grid(alpha=.15)

    ax = axes[1, 0]
    counts = np.arange(3, 257)
    for k, color in zip([1, 2, 4, 8], ["#2563eb", "#8b5cf6", "#0891b2", "#64748b"]):
        ax.plot(counts, [frontier_length(int(n), k) for n in counts], lw=2,
                color=color, label=f"Fixed $K={k}$")
    ax.axhline(2 * PI, ls="--", color="#dc2626", lw=1.5, label="Limit: $2\\pi$")
    ax.set_xscale("log", base=2); ax.set_xlim(3, 256); ax.set_ylim(2.9, 6.5)
    ax.set_xlabel("Audited normal count $n$")
    ax.set_ylabel("Total length")
    ax.set_title("C. Fixed component budgets restore the full limit", loc="left", fontweight="bold")
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    ax.grid(alpha=.15)
    ax = axes[2, 0]
    n = 16
    d = side_length(n)
    scaled = np.linspace(0, 2.1, 501)
    connected = np.array([penalized_optimum(n, float(t * d))["connected_branch"]
                           / (n * d) for t in scaled])
    alternating = np.array([penalized_optimum(n, float(t * d))["alternating_branch"]
                             / (n * d) for t in scaled])
    ax.plot(scaled, alternating, color="#2563eb", lw=1.8,
            label="$n$-component branch")
    ax.plot(scaled, connected, color="#8b5cf6", lw=1.8,
            label="Connected branch")
    ax.plot(scaled, np.minimum(connected, alternating), color="#0f172a", lw=2.7,
            ls="--", label="Exact penalized optimum")
    ax.axvline(1, color="#dc2626", ls=":", lw=1.4)
    ax.scatter([1], [2], s=35, color="#dc2626", zorder=5)
    ax.set_xlim(0, 2.1); ax.set_ylim(.95, 2.2)
    ax.set_xlabel("Component penalty / side length $\\lambda/d$")
    ax.set_ylabel("$J_n(\\lambda)/(nd)$")
    ax.set_title("E. Exact penalty transition at $\\lambda=d$", loc="left", fontweight="bold")
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    ax.grid(alpha=.15)

    ax = axes[2, 1]
    scaled_cost = np.linspace(0, 2 * PI, 501)
    for n, color in zip([8, 32, 128], ["#94a3b8", "#8b5cf6", "#2563eb"]):
        values = [penalized_optimum(n, float(c / n))["value"] for c in scaled_cost]
        ax.plot(scaled_cost / PI, values, lw=1.9, color=color, label=f"$n={n}$")
    ax.plot(scaled_cost / PI, [joint_penalty_limit(float(c)) for c in scaled_cost],
            color="#0f172a", lw=2.6, ls="--", label="$\\min(2\\pi,\\pi+c)$")
    ax.axvline(1, color="#dc2626", lw=1.2, ls=":")
    ax.set_xlim(0, 2); ax.set_ylim(2.95, 6.55)
    ax.set_xlabel("Scaled penalty $c/\\pi=n\\lambda/\\pi$")
    ax.set_ylabel("Penalized optimum $J_n(c/n)$")
    ax.set_title("F. Joint limit with $n\\lambda\\to c$", loc="left", fontweight="bold")
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    ax.grid(alpha=.15)

    ax = axes[1, 1]
    selected = np.array([n * side_length(int(n)) for n in counts])
    repairs = np.array([connected_repair_cost(int(n)) for n in counts])
    ax.plot(counts, selected, color="#2563eb", lw=2.4, label="Alternating audit length")
    ax.plot(counts, repairs, color="#dc2626", lw=2.4, label="Exact minimum connection repair")
    ax.axhline(PI, color="#64748b", ls="--", lw=1.3, label="Each tends to $\\pi$")
    ax.set_xscale("log", base=2); ax.set_xlim(3, 256); ax.set_ylim(1.9, 3.3)
    ax.set_xlabel("Audited normal count $n$")
    ax.set_ylabel("Length")
    ax.set_title("D. Connecting the sampled optimum costs another $\\pi$", loc="left", fontweight="bold")
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    ax.grid(alpha=.15)
    fig.suptitle("Component complexity controls the exact audit frontier",
                  x=.055, y=1.01, ha="left", fontsize=17, fontweight="bold", color="#0f172a")
    fig.tight_layout(h_pad=2.4, w_pad=2.5, rect=(0, .035, 1, .985))
    fig.text(.055, .005,
        "Interior finite-angle model: $L(n,K)=[2n-\\min(K,n)]\\,2\\sin(\\pi/(2n))$. "
        "The lower bound uses the classical regular-polygon Steiner theorem (Du-Hwang-Weng,1987).\n"
        "No unrestricted opaque-disk optimum or numerical proof of that Steiner theorem is claimed.",
        fontsize=9, color="#475569", linespacing=1.6)
    directory = HERE / "figures"
    directory.mkdir(exist_ok=True)
    fig.savefig(directory / "complexity_frontier.png", dpi=185,
                bbox_inches="tight", facecolor=fig.get_facecolor())
    fig.savefig(directory / "complexity_frontier.pdf", bbox_inches="tight",
                facecolor=fig.get_facecolor())
    plt.close(fig)


def verify_penalties():
    cases = []
    maximum_error = 0.0
    for n in range(3, 61):
        d = side_length(n)
        penalties = [factor * d for factor in [0, .25, .75, 1, 1.25, 2, 5]]
        penalties += [.02, .1, .5]
        for penalty in penalties:
            exact = penalized_optimum(n, penalty)
            objectives = np.array([frontier_length(n, k) + penalty * k
                                     for k in range(1, n + 1)])
            error = abs(float(objectives.min()) - exact["value"])
            assert error < 2e-12
            maximum_error = max(maximum_error, error)
            for k in exact["minimizing_component_counts"]:
                assert abs(objectives[k - 1] - exact["value"]) < 2e-12
            if penalty == d:
                assert len(exact["minimizing_component_counts"]) == n
                assert float(np.ptp(objectives)) < 2e-12
            cases.append({"n": n, "penalty": penalty,
                          "threshold": d, "value": exact["value"],
                          "phase": exact["phase"], "enumeration_error": error})
    limits = []
    for c in [0, .5 * PI, PI, 1.5 * PI, 2 * PI]:
        sequence = [{"n": 2**power,
                     "value": penalized_optimum(2**power, c / 2**power)["value"]}
                    for power in range(2, 15)]
        target = joint_penalty_limit(c)
        assert abs(sequence[-1]["value"] - target) < 3e-4
        limits.append({"scaled_penalty_c": c, "limit": target, "sequence": sequence})
    fixed = []
    for penalty in [.01, .1, 1.0]:
        n = 32768
        value = penalized_optimum(n, penalty)["value"]
        target = 2 * PI + penalty
        assert abs(value - target) < 2e-4
        fixed.append({"fixed_penalty": penalty, "n": n,
                      "value": value, "limit": target})
    return {"case_count": len(cases), "maximum_enumeration_error": maximum_error,
            "cases": cases, "joint_limit_sequences": limits,
            "fixed_positive_penalty_checks": fixed}


def main():
    records, offsets, maxima = verify()
    penalties = verify_penalties()
    make_figure()
    report = {"status": "PASS", "n_range": [3, 60],
        "component_budget_range": "K=1,...,n+2 for each n",
        "base_family_count": len(records), "all_cyclic_offset_case_count": offsets,
        "offset_validation": "All edge subsets and graph components checked explicitly; geometric rotation equivariance transfers complete base sampled-interval-union certificates to every cyclic offset.",
        "scope": "Exact component-budget frontier for interior uniform-normal audits.",
        "arithmetic": "Exact integer edge counts plus geometric analytic formulas evaluated in float64.",
        "proof_dependency": STEINER_DEPENDENCY,
        "not_claimed": ["Independent proof or numerical verification of the Steiner minimum tree theorem",
                        "The unrestricted fully opaque disk optimum",
                        "Interval-arithmetic certification"],
        "max_observed_errors": maxima,
        "fixed_budget_limit": "2*pi for each fixed positive integer K",
        "repair_cost_formula": "(n-1)*2*sin(pi/(2*n))",
        "repair_cost_limit": "pi",
        "penalty_formula": "J_n(lambda)=min((2*n-1)*d+lambda,n*d+n*lambda)",
        "penalty_threshold": "lambda=d=2*sin(pi/(2*n))",
        "joint_penalty_limit": "If lambda_n->0 and n*lambda_n->c, J_n(lambda_n)->min(2*pi,pi+c)",
        "fixed_positive_penalty_limit": "2*pi+lambda",
        "penalty_verification": penalties,
        "versions": {"numpy": np.__version__, "matplotlib": matplotlib.__version__},
        "cases": records}
    (HERE / "COMPLEXITY_VERIFICATION.json").write_text(json.dumps(report, indent=2) + "\n")
    summary = {key: report[key] for key in ["status", "base_family_count",
          "all_cyclic_offset_case_count", "max_observed_errors"]}
    summary["penalty_case_count"] = penalties["case_count"]
    summary["max_penalty_enumeration_error"] = penalties["maximum_enumeration_error"]
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()