File size: 6,426 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
#!/usr/bin/env python3
"""Optional publication figures; requires numpy and matplotlib.

The exact regression suite remains standard-library only. Figures 1 and 2
read executed exact result files. Figure 3 uses floating-point singular values
to illustrate a proved conditioning counterexample; it is not a rank proof.
"""
from pathlib import Path
from itertools import combinations
import json
import os
import tempfile

ROOT = Path(__file__).resolve().parents[1]
os.environ.setdefault("MPLCONFIGDIR", str(Path(tempfile.gettempdir()) / "eve-aithrael-matplotlib"))
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

PALETTE = ["#007F86", "#B46B22", "#8B3B64", "#25364D"]
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                     "axes.titlesize": 13, "axes.labelsize": 10,
                     "axes.spines.top": False, "axes.spines.right": False,
                     "axes.edgecolor": "#76818B", "axes.labelcolor": "#25364D",
                     "text.color": "#25364D", "xtick.color": "#526170",
                     "ytick.color": "#526170", "grid.color": "#E4E8EC",
                     "figure.facecolor": "white", "savefig.facecolor": "white",
                     "pdf.fonttype": 42, "ps.fonttype": 42})


def save(fig, name):
    folder = ROOT / "figures"
    folder.mkdir(exist_ok=True)
    target = folder / (name+".pdf")
    fig.savefig(target, bbox_inches="tight", metadata={"Title": name.replace("_", " "),
               "Author": "Eve, OpenAI AI assistant; prepared for Maciej Nowicki"})
    preview = ROOT.parent / "work" / "figure_previews"
    preview.mkdir(parents=True, exist_ok=True)
    fig.savefig(preview / (name+".png"), dpi=155, bbox_inches="tight")
    plt.close(fig)
    return {"file": str(target.relative_to(ROOT)), "bytes": target.stat().st_size}


def main():
    results_path = ROOT / "results" / "robust_results.json"
    results = json.loads(results_path.read_text())
    assert results["status"] == "passed"
    outputs = []
    profiles = results["dense_fault_recovery"]["profiles"]
    fig, ax = plt.subplots(figsize=(7.0, 4.4), layout="constrained")
    for j, profile in enumerate(profiles):
        if profile:
            ax.plot(range(1, len(profile)+1), profile, marker="o", linewidth=2.1,
                    markersize=7, color=PALETTE[j], label=f"Column {j}: dimension {len(profile)}")
    ax.axhline(3, color="#677381", linestyle=(0, (4, 3)), linewidth=1.1)
    ax.text(1.04, 3.16, "One erasure + one arbitrary error: distance must exceed 3", fontsize=9)
    ax.set(xlabel="Surviving ambiguity dimension k", ylabel="Minimum channels removed",
           title="Complete four-node DAG: exact failure profiles",
           xlim=(0.9, 3.12), ylim=(2.7, 6.45), xticks=[1, 2, 3], yticks=[3, 4, 5, 6])
    ax.grid(axis="y")
    ax.legend(loc="lower right", frameon=False, bbox_to_anchor=(1.0, 0.18))
    outputs.append(save(fig, "complete_four_failure_profiles"))

    cases = results["causal_stars"]
    distances = [cases["same_pattern_generic"]["causal_distance"],
                 cases["same_pattern_exceptional"]["causal_distance"]]
    assert distances == [3, 2]
    fig, ax = plt.subplots(figsize=(7.0, 4.5), layout="constrained")
    bars = ax.bar([0, 1], distances, width=0.52, color=[PALETTE[0], PALETTE[2]])
    ax.bar_label(bars, labels=["Distance 3", "Distance 2"], padding=7, fontsize=12)
    ax.axhline(3, color="#677381", linestyle=(0, (4, 3)), linewidth=1.0)
    ax.text(1.39, 3.12, "Minimum for one\narbitrary error", ha="right", va="bottom", fontsize=9)
    ax.set(xticks=[0, 1], xticklabels=["Distinct column ratios\nSecond row: 1, 2, 3, 4",
                                     "Repeated column ratio\nSecond row: 1, 1, 3, 4"],
           ylabel="Exact channel distance", title="Identical entry supports, different robustness",
           ylim=(0, 4.15), xlim=(-0.55, 1.55), yticks=[0, 1, 2, 3, 4])
    ax.text(0, 0.18, "Corrects one error", ha="center", va="bottom", color="white", fontsize=10)
    ax.text(1, 0.18, "Cannot correct one error", ha="center", va="bottom", color="white", fontsize=9)
    ax.grid(axis="y", zorder=0)
    ax.set_axisbelow(True)
    outputs.append(save(fig, "same_support_coefficient_dependence"))

    epsilons = np.logspace(-6, 0, 31)
    parameters = np.arange(1, 6, dtype=float)
    margins = []
    for eps in epsilons:
        C = np.column_stack((np.ones(5), 1+eps*parameters))/(2+eps*parameters)[:, None]
        assert np.all(C > 0) and np.max(np.abs(C.sum(axis=1)-1)) < 1e-14
        margin = min(float(np.linalg.svd(C[list(K)], compute_uv=False)[-1])
                     for K in combinations(range(5), 2))
        assert margin > 0
        margins.append(margin)
    fig, ax = plt.subplots(figsize=(7.0, 4.4), layout="constrained")
    ax.loglog(epsilons, margins, color=PALETTE[0], marker="o", markersize=3.6, linewidth=1.8)
    ax.set(xlabel="Separation parameter epsilon", ylabel="Worst retained-row singular value",
           title="Optimal exact correction can be poorly conditioned")
    ax.grid(which="major", alpha=0.9)
    ax.text(0.04, 0.96, "5 positive convex-average channels; every pair independent\n"
            "Exact distance = 4 for every epsilon > 0\n"
            "Retain any 2 rows after the combined fault budget",
            transform=ax.transAxes, va="top", fontsize=9,
            bbox={"facecolor": "white", "edgecolor": "#E4E8EC", "pad": 7})
    outputs.append(save(fig, "normalized_conditioning_margin"))
    data = {"source": "results/robust_results.json",
            "exact_complete_four_profiles": profiles,
            "exact_equal_support_distances": distances,
            "conditioning_example": {
                "status": "floating-point illustration of a separately proved formula",
                "rows": "(1, 1+epsilon*a)/(2+epsilon*a), a=1,...,5",
                "known_erasures": 1, "arbitrary_errors": 1, "combined_budget": 3,
                "rows_retained": 2, "exact_distance_for_positive_epsilon": 4,
                "epsilon": epsilons.tolist(), "minimum_singular_value": margins},
            "figures": outputs}
    target = ROOT / "results" / "figure_data.json"
    target.write_text(json.dumps(data, indent=2)+"\n")
    print(json.dumps({"status": "created", "figures": outputs,
                      "data": str(target.relative_to(ROOT))}, indent=2))


if __name__ == "__main__":
    main()