File size: 8,800 Bytes
1f48ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Figures for the numerical audits of the spectral statements (Claims 1 and 2)."""

from __future__ import annotations

import json
import math
import os

import numpy as np
import pandas as pd
import plotly.graph_objects as go

from analyze import PALETTE, _c, write_fig, linfit

RES = "results"


def main():
    out = {}
    a = pd.read_csv(f"{RES}/audit_spectrum.csv")
    dims = sorted(a["d"].unique())

    # --- lambda1(A*): diverges for quadratic, converges to 6 for truncated -----
    fig = go.Figure()
    for i, d in enumerate(dims):
        q = a[(a["act"] == "quad") & (a["d"] == d)].groupby("delta")["lam1"].mean().reset_index()
        t = a[(a["act"] == "trunc") & (a["M"] == 8.0) & (a["d"] == d)] \
            .groupby("delta")["lam1"].mean().reset_index()
        fig.add_trace(go.Scatter(x=q["delta"], y=q["lam1"], mode="lines+markers",
                                 name=f"quad d={d}", line=dict(color=_c(i, len(dims)), dash="dash")))
        fig.add_trace(go.Scatter(x=t["delta"], y=t["lam1"], mode="lines+markers",
                                 name=f"trunc d={d}", line=dict(color=_c(i, len(dims)))))
    fig.add_hline(y=6, line_dash="dot", line_color="#111",
                  annotation_text="population λ₁ = 6")
    fig.update_layout(title="λ₁(A*) vs δ = n/d — quadratic (dashed) vs truncated M=8 (solid)",
                      xaxis_title="δ = n/d", yaxis_title="λ₁(A*)", xaxis_type="log",
                      yaxis_type="log", template="plotly_white", height=470)
    write_fig(fig, "audit_lam1")

    # --- the eq. (3.13) error: |lam1-6| + |lam2-2| vs the claimed rate ---------
    t = a[(a["act"] == "trunc")].copy()
    t["err"] = (t["lam1"] - 6).abs() + (t["lam2"] - 2).abs()
    t["rate"] = np.exp(-t["M"] / 3) + t["M"] * np.sqrt(t["d"] / t["n"])
    g = t.groupby(["M", "delta", "d"])[["err", "rate"]].mean().reset_index()
    g["C"] = g["err"] / g["rate"]
    g.to_csv(f"{RES}/audit_eq313.csv", index=False)
    fig = go.Figure()
    Ms = sorted(g["M"].unique())
    for i, M in enumerate(Ms):
        s = g[g["M"] == M]
        fig.add_trace(go.Scatter(x=s["rate"], y=s["err"], mode="markers",
                                 marker=dict(size=9, color=_c(i, len(Ms))), name=f"M={M:g}"))
    lim = [float(g["rate"].min()) * 0.8, float(g["rate"].max()) * 1.2]
    for C, dash in ((1.0, "dot"), (0.5, "dash")):
        fig.add_trace(go.Scatter(x=lim, y=[C * lim[0], C * lim[1]], mode="lines",
                                 line=dict(color="#444", dash=dash), name=f"C = {C}"))
    fig.update_layout(
        title="Eq. (3.13) audit: |λ₁−6| + |λ₂−2| vs C(e^(−M/3) + M√(d/n))",
        xaxis_title="e^(−M/3) + M√(d/n)", yaxis_title="|λ₁−6| + |λ₂−2|",
        xaxis_type="log", yaxis_type="log", template="plotly_white", height=470)
    write_fig(fig, "audit_eq313")
    out["eq313_max_C"] = float(g["C"].max())
    out["eq313_max_C_largedelta"] = float(g[g["delta"] >= 16]["C"].max())

    # --- uniform-in-theta BBP --------------------------------------------------
    b = pd.read_csv(f"{RES}/audit_uniform_bbp.csv")
    bt = b[(b["act"] == "trunc") & (b["M"] == 8.0)].copy()
    bt["kind"] = np.where(bt["theta"].str.startswith("random"), "random θ", bt["theta"])
    fig = go.Figure()
    kinds = ["random θ", "theta_star", "adversarial"]
    cols = {"random θ": PALETTE[1], "theta_star": PALETTE[4], "adversarial": PALETTE[6]}
    for k in kinds:
        s = bt[bt["kind"] == k]
        for j, col in enumerate(("lam1", "lam2")):
            fig.add_trace(go.Scatter(
                x=s["delta"], y=s[col], mode="markers",
                marker=dict(size=11, color=cols[k], symbol="circle" if j == 0 else "x"),
                name=f"{k} — λ{j+1}", legendgroup=k, showlegend=True))
    fig.add_hline(y=6, line_dash="dot", line_color="#111")
    fig.add_hline(y=2, line_dash="dot", line_color="#111")
    fig.update_layout(
        title="Uniform-in-θ BBP transition of A(θ): λ₁ (circles) and λ₂ (crosses), truncated M=8",
        xaxis_title="δ = n/d", yaxis_title="eigenvalue of A(θ)", xaxis_type="log",
        template="plotly_white", height=470)
    write_fig(fig, "audit_uniform_bbp")
    s64 = bt[bt["delta"] == 64.0]
    out["bbp_delta64"] = dict(lam1_min=float(s64["lam1"].min()), lam1_max=float(s64["lam1"].max()),
                              lam2_min=float(s64["lam2"].min()), lam2_max=float(s64["lam2"].max()),
                              ov_min=float(s64["sq_overlap_v1"].min()),
                              ov_max=float(s64["sq_overlap_v1"].max()))

    # --- indicator mass -------------------------------------------------------
    c = pd.read_csv(f"{RES}/audit_indicator.csv")
    ct = c[c["act"] == "trunc"].copy()
    ct["kind"] = np.where(ct["theta"].str.startswith("random"), "random θ", ct["theta"])
    fig = go.Figure()
    for i, k in enumerate(["random θ", "theta_star", "adversarial"]):
        s = ct[ct["kind"] == k]
        fig.add_trace(go.Box(x=s["M"], y=s["ratio"], name=k,
                             marker_color=[PALETTE[1], PALETTE[4], PALETTE[6]][i]))
    fig.add_hline(y=1.0, line_dash="dot", line_color="#111",
                  annotation_text="bound with C = 1")
    fig.update_layout(
        title="Uniform indicator-mass bound: measured mass ÷ (e^(−M/2) + √(d/n)·log(n/d))",
        xaxis_title="M", yaxis_title="ratio", template="plotly_white", height=440,
        boxmode="group")
    write_fig(fig, "audit_indicator")
    out["indicator_max_ratio"] = float(ct["ratio"].max())
    out["indicator_max_ratio_adv"] = float(ct[ct["kind"] == "adversarial"]["ratio"].max())

    # --- Theorem 3.2 deficit bound --------------------------------------------
    th = pd.read_csv(f"{RES}/thm32_bound.csv")
    gg = th.groupby(["M", "delta"])[["deficit", "rate", "C_implied"]].mean().reset_index()
    fig = go.Figure()
    Ms = sorted(gg["M"].unique())
    for i, M in enumerate(Ms):
        s = gg[gg["M"] == M]
        fig.add_trace(go.Scatter(x=s["rate"], y=s["deficit"], mode="markers+lines",
                                 marker=dict(size=10, color=_c(i, len(Ms))),
                                 line=dict(color=_c(i, len(Ms))), name=f"M={M:g}"))
    lim = [float(gg["rate"].min()) * 0.9, float(gg["rate"].max()) * 1.1]
    fig.add_trace(go.Scatter(x=lim, y=lim, mode="lines", line=dict(color="#444", dash="dot"),
                             name="C = 1"))
    fig.update_layout(
        title="Theorem 3.2 audit: realised deficit 1 − |⟨θ_∞,θ*⟩| vs e^(−M/2) + (d/n)^(1/5), d=512",
        xaxis_title="e^(−M/2) + (d/n)^(1/5)", yaxis_title="1 − |⟨θ_∞, θ*⟩|",
        xaxis_type="log", yaxis_type="log", template="plotly_white", height=470)
    write_fig(fig, "audit_thm32")
    out["thm32_max_C_Mge4"] = float(th[th["M"] >= 4]["C_implied"].max())
    out["thm32_max_C_all"] = float(th["C_implied"].max())

    # --- smooth vs hard truncation robustness ---------------------------------
    p = f"{RES}/sweep_smooth.csv"
    if os.path.exists(p):
        sm = pd.read_csv(p).groupby(["d", "delta"])["sq_overlap"].mean().reset_index()
        hd = pd.read_csv(f"{RES}/sweep_trunc.csv").groupby(["d", "delta"])["sq_overlap"] \
            .mean().reset_index()
        dims2 = sorted(sm["d"].unique())
        fig = go.Figure()
        for i, d in enumerate(dims2):
            s = sm[sm["d"] == d].sort_values("delta")
            h = hd[hd["d"] == d].sort_values("delta")
            fig.add_trace(go.Scatter(x=s["delta"], y=s["sq_overlap"], mode="lines+markers",
                                     name=f"smooth d={d}", line=dict(color=_c(i, len(dims2)))))
            fig.add_trace(go.Scatter(x=h["delta"], y=h["sq_overlap"], mode="lines",
                                     name=f"hard d={d}",
                                     line=dict(color=_c(i, len(dims2)), dash="dot")))
        fig.update_layout(
            title="Robustness: C^∞ truncation (eq. 3.10, solid) vs hard truncation (eq. 4.3, dotted)",
            xaxis_title="δ = n/d", yaxis_title="squared overlap",
            template="plotly_white", height=470)
        write_fig(fig, "audit_smooth_vs_hard")
        mrg = sm.merge(hd, on=["d", "delta"], suffixes=("_smooth", "_hard"))
        mrg["absdiff"] = (mrg["sq_overlap_smooth"] - mrg["sq_overlap_hard"]).abs()
        mrg.to_csv(f"{RES}/smooth_vs_hard.csv", index=False)
        out["smooth_vs_hard_maxdiff_delta_ge_4"] = float(mrg[mrg["delta"] >= 4]["absdiff"].max())
        out["smooth_vs_hard_meandiff_delta_ge_4"] = float(mrg[mrg["delta"] >= 4]["absdiff"].mean())

    with open(f"{RES}/audit_summary.json", "w") as f:
        json.dump(out, f, indent=2, default=float)
    print(json.dumps(out, indent=2, default=float))


if __name__ == "__main__":
    main()